public void testCommitPreparedTransactions() throws Exception {
    SimpleString recQueue = new SimpleString("BasicXaTestqRec");
    SimpleString sendQueue = new SimpleString("BasicXaTestqSend");

    byte[] globalTransactionId = UUIDGenerator.getInstance().generateStringUUID().getBytes();
    Xid xid = new XidImpl("xa1".getBytes(), 1, globalTransactionId);
    Xid xid2 = new XidImpl("xa2".getBytes(), 1, globalTransactionId);
    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession clientSession = csf.createSession(true, false, false);
    clientSession.createQueue(recQueue, recQueue, null, true);
    clientSession.createQueue(sendQueue, sendQueue, null, true);
    ClientMessage m1 = createTextMessage(clientSession, "");
    m1.putStringProperty("m1", "m1");
    ClientProducer clientProducer = clientSession.createProducer(recQueue);
    clientProducer.send(m1);
    locator.close();

    ServerLocator receiveLocator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory receiveCsf = receiveLocator.createSessionFactory();
    ClientSession receiveClientSession = receiveCsf.createSession(true, false, false);
    ClientConsumer consumer = receiveClientSession.createConsumer(recQueue);

    ServerLocator sendLocator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory sendCsf = sendLocator.createSessionFactory();
    ClientSession sendClientSession = sendCsf.createSession(true, false, false);
    ClientProducer producer = sendClientSession.createProducer(sendQueue);

    receiveClientSession.start(xid, XAResource.TMNOFLAGS);
    receiveClientSession.start();
    sendClientSession.start(xid2, XAResource.TMNOFLAGS);

    ClientMessage m = consumer.receive(5000);
    assertNotNull(m);

    producer.send(m);

    receiveClientSession.end(xid, XAResource.TMSUCCESS);
    sendClientSession.end(xid2, XAResource.TMSUCCESS);

    receiveClientSession.prepare(xid);
    sendClientSession.prepare(xid2);

    HornetQServerControl serverControl = createManagementControl();

    sendLocator.close();
    receiveLocator.close();

    boolean success = serverControl.commitPreparedTransaction(XidImpl.toBase64String(xid));

    success = serverControl.commitPreparedTransaction(XidImpl.toBase64String(xid));

    System.out.println("HornetQServerControlTest.testCommitPreparedTransactions");
  }
Пример #2
0
 private void init() throws YamcsApiException {
   try {
     String username = null;
     String password = null;
     if (invm) {
       locator =
           HornetQClient.createServerLocatorWithoutHA(
               new TransportConfiguration(Protocol.IN_VM_FACTORY));
       sessionFactory = locator.createSessionFactory();
       username = hornetqInvmUser;
       password = hornetqInvmPass;
     } else {
       if (ycd.host != null) {
         Map<String, Object> tcpConfig = new HashMap<String, Object>();
         tcpConfig.put(TransportConstants.HOST_PROP_NAME, ycd.host);
         tcpConfig.put(TransportConstants.PORT_PROP_NAME, ycd.port);
         locator =
             HornetQClient.createServerLocatorWithoutHA(
                 new TransportConfiguration(NettyConnectorFactory.class.getName(), tcpConfig));
         sessionFactory = locator.createSessionFactory();
       } else {
         locator =
             HornetQClient.createServerLocatorWithoutHA(
                 new TransportConfiguration(NettyConnectorFactory.class.getName()));
         sessionFactory = locator.createSessionFactory();
       }
       username = ycd.username;
       password = ycd.password;
     }
     // All sessions are authenticated, a null username translates to
     // guest auth and authz (if allowed by server)
     session =
         sessionFactory.createSession(username, password, false, true, true, preAcknowledge, 1);
     session.start();
   } catch (HornetQException e) {
     // Pass specific HornetQExceptions as our cause, helps identify
     // permissions problems
     try {
       close();
     } catch (HornetQException e1) {
     }
     throw new YamcsApiException(e.getMessage(), e);
   } catch (Exception e) {
     // Pass Exception's cause as our cause.
     System.out.println(e);
     // close everything
     try {
       close();
     } catch (HornetQException e1) {
     }
     throw new YamcsApiException(e.getMessage(), e.getCause());
   }
 }
Пример #3
0
  /**
   * Connects to the yamcs server. This method blocks until a connection is established or some
   * error has occurred, thus this should be called in a separate thread. Hornetq will try
   * indefinitely to establish the connection and also provides automatic re-connection afterwards.
   *
   * @throws Exception if the hornetq session could not be established due to some error
   */
  public void connect() throws Exception {
    for (ConnectionListener cl : connectionListeners) {
      cl.connecting(connParams.getUrl());
    }

    Map<String, Object> tcpConfig = new HashMap<String, Object>();
    tcpConfig.put(TransportConstants.HOST_PROP_NAME, connParams.host);
    tcpConfig.put(TransportConstants.PORT_PROP_NAME, connParams.port);

    locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(NettyConnectorFactory.class.getName(), tcpConfig));

    locator.setInitialConnectAttempts(initialConnectAttempts);
    locator.setReconnectAttempts(reconnectAttempts);
    locator.setRetryInterval(retryInterval);
    locator.setRetryIntervalMultiplier(retryIntervalMultiplier);
    locator.setMaxRetryInterval(maxRetryInterval);
    locator.setAckBatchSize(ackBatchSize);

    sessionFactory = locator.createSessionFactory();

    // TODO Use hornetq auth (like YamcsConnector), or keep anonymous connection?
    session = sessionFactory.createSession(false, true, true, preAcknowledge);
    session.addFailureListener(YamcsAckConnector.this);
    session.start();

    for (ConnectionListener cl : connectionListeners) {
      cl.connected(connParams.getUrl());
    }
  }
Пример #4
0
  @Test
  public void testGetNumberOfBytesPerPage() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    session.createQueue(address, address, true);

    AddressControl addressControl = createManagementControl(address);
    Assert.assertEquals(
        HornetQDefaultConfiguration.getDefaultJournalFileSize(),
        addressControl.getNumberOfBytesPerPage());

    session.close();
    server.stop();

    AddressSettings addressSettings = new AddressSettings();
    addressSettings.setPageSizeBytes(1024);

    server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings);
    server.start();
    ServerLocator locator2 =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    addServerLocator(locator2);
    ClientSessionFactory sf2 = createSessionFactory(locator2);

    session = sf2.createSession(false, true, false);
    session.createQueue(address, address, true);
    Assert.assertEquals(1024, addressControl.getNumberOfBytesPerPage());
  }
Пример #5
0
 protected ServerLocatorInternal getServerLocator() throws Exception {
   ServerLocator locator =
       HornetQClient.createServerLocatorWithHA(
           getConnectorTransportConfiguration(true), getConnectorTransportConfiguration(false));
   addServerLocator(locator);
   return (ServerLocatorInternal) locator;
 }
Пример #6
0
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    configuration = createDefaultConfig();
    configuration.setSecurityEnabled(false);
    server = createServer(true, configuration);
    // start the server
    server.start();

    qs = new AddressSettings();
    qs.setLastValueQueue(true);
    server.getAddressSettingsRepository().addMatch(address.toString(), qs);
    // then we create a client as normal
    locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));

    locator.setBlockOnAcknowledge(true);
    locator.setAckBatchSize(0);
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    clientSession = sessionFactory.createSession(false, true, true);
    clientSessionXa = sessionFactory.createSession(true, false, false);
    clientSession.createQueue(address, qName1, null, true);
  }
  /**
   * Remove any old message queues that have a 0 message count in them. This lets us not worry about
   * changing around the registered listeners.
   */
  private void cleanupOldQueues() {
    log.debug("Cleaning old message queues");
    try {
      String[] queues = hornetqServer.getHornetQServer().getHornetQServerControl().getQueueNames();

      ServerLocator locator =
          HornetQClient.createServerLocatorWithoutHA(
              new TransportConfiguration(InVMConnectorFactory.class.getName()));

      ClientSessionFactory factory = locator.createSessionFactory();
      ClientSession session = factory.createSession(true, true);
      session.start();

      for (int i = 0; i < queues.length; i++) {
        long msgCount = session.queueQuery(new SimpleString(queues[i])).getMessageCount();
        if (msgCount == 0) {
          log.debug(String.format("found queue '%s' with 0 messages. deleting", queues[i]));
          session.deleteQueue(queues[i]);
        } else {
          log.debug(String.format("found queue '%s' with %d messages. kept", queues[i], msgCount));
        }
      }

      session.stop();
      session.close();
    } catch (HornetQException e) {
      log.error("Problem cleaning old message queues:", e);
      throw new RuntimeException(e);
    } catch (Exception e) {
      log.error("Problem cleaning old message queues:", e);
      throw new RuntimeException(e);
    }
  }
  public void testSSL() throws Exception {
    String text = RandomUtil.randomString();

    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    tc.getParams()
        .put(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH);
    tc.getParams()
        .put(
            TransportConstants.KEYSTORE_PASSWORD_PROP_NAME,
            TransportConstants.DEFAULT_KEYSTORE_PASSWORD);

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, true, true);
    session.createQueue(CoreClientOverSSLTest.QUEUE, CoreClientOverSSLTest.QUEUE, false);
    ClientProducer producer = session.createProducer(CoreClientOverSSLTest.QUEUE);

    ClientMessage message = createTextMessage(session, text);
    producer.send(message);

    ClientConsumer consumer = session.createConsumer(CoreClientOverSSLTest.QUEUE);
    session.start();

    Message m = consumer.receive(1000);
    Assert.assertNotNull(m);
    Assert.assertEquals(text, m.getBodyBuffer().readString());
  }
 @Override
 protected ServerLocator createHAServerLocator() {
   ServerLocator locator =
       HornetQClient.createServerLocatorWithHA(
           new DiscoveryGroupConfiguration(
               HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT,
               HornetQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT,
               new UDPBroadcastGroupConfiguration(groupAddress, groupPort, null, -1)));
   locator.setBlockOnNonDurableSend(true);
   locator.setBlockOnDurableSend(true);
   addServerLocator(locator);
   return locator;
 }
Пример #10
0
  public void testConnection(
      final String acceptorHost, final String connectorHost, final boolean mustConnect)
      throws Exception {
    System.out.println(
        "acceptor="
            + acceptorHost
            + ", connector="
            + connectorHost
            + ", mustConnect="
            + mustConnect);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(getHostPropertyKey(), acceptorHost);
    TransportConfiguration acceptorConfig =
        new TransportConfiguration(getAcceptorFactoryClassName(), params);
    Set<TransportConfiguration> transportConfigs = new HashSet<TransportConfiguration>();
    transportConfigs.add(acceptorConfig);

    Configuration config = createDefaultConfig(true);
    config.setAcceptorConfigurations(transportConfigs);
    HornetQServer messagingService = createServer(false, config);
    messagingService.start();

    params = new HashMap<String, Object>();
    params.put(getHostPropertyKey(), connectorHost);
    TransportConfiguration connectorConfig =
        new TransportConfiguration(getConnectorFactoryClassName(), params);

    try {
      ClientSessionFactory sf = HornetQClient.createClientSessionFactory(connectorConfig);

      if (mustConnect) {
        ClientSession session = sf.createSession(false, true, true);
        session.close();
        System.out.println("connection OK");
      } else {
        try {
          sf.createSession(false, true, true);
          Assert.fail(
              "session creation must fail because connector must not be able to connect to the server bound to another network interface");
        } catch (Exception e) {
        }
      }
    } finally {
      if (messagingService != null) {
        messagingService.stop();
      }
    }
  }
  public void testSSLWithIncorrectKeyStorePassword() throws Exception {
    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    tc.getParams()
        .put(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH);
    tc.getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "invalid password");

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    try {
      ClientSessionFactory sf = createSessionFactory(locator);
      Assert.fail();
    } catch (HornetQNotConnectedException se) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }
  }
  // see https://jira.jboss.org/jira/browse/HORNETQ-234
  public void testPlainConnectionToSSLEndpoint() throws Exception {
    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, false);

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    locator.setCallTimeout(2000);
    try {
      createSessionFactory(locator);
      fail("expecting exception");
    } catch (HornetQNotConnectedException se) {
      // ok
    } catch (HornetQConnectionTimedOutException ctoe) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }
  }
  public void testListPreparedTransactionDetails() throws Exception {
    SimpleString atestq = new SimpleString("BasicXaTestq");
    Xid xid = newXID();

    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession clientSession = csf.createSession(true, false, false);
    clientSession.createQueue(atestq, atestq, null, true);

    ClientMessage m1 = createTextMessage(clientSession, "");
    ClientMessage m2 = createTextMessage(clientSession, "");
    ClientMessage m3 = createTextMessage(clientSession, "");
    ClientMessage m4 = createTextMessage(clientSession, "");
    m1.putStringProperty("m1", "m1");
    m2.putStringProperty("m2", "m2");
    m3.putStringProperty("m3", "m3");
    m4.putStringProperty("m4", "m4");
    ClientProducer clientProducer = clientSession.createProducer(atestq);
    clientSession.start(xid, XAResource.TMNOFLAGS);
    clientProducer.send(m1);
    clientProducer.send(m2);
    clientProducer.send(m3);
    clientProducer.send(m4);
    clientSession.end(xid, XAResource.TMSUCCESS);
    clientSession.prepare(xid);

    HornetQServerControl serverControl = createManagementControl();

    JSONArray jsonArray = new JSONArray(serverControl.listProducersInfoAsJSON());

    assertEquals(1, jsonArray.length());
    assertEquals(4, ((JSONObject) jsonArray.get(0)).getInt("msgSent"));

    clientSession.close();
    locator.close();

    String txDetails = serverControl.listPreparedTransactionDetailsAsJSON();

    Assert.assertTrue(txDetails.matches(".*m1.*"));
    Assert.assertTrue(txDetails.matches(".*m2.*"));
    Assert.assertTrue(txDetails.matches(".*m3.*"));
    Assert.assertTrue(txDetails.matches(".*m4.*"));
  }
Пример #14
0
 public void start() throws Exception {
   serverLocator =
       HornetQClient.createServerLocatorWithoutHA(
           new TransportConfiguration(NettyConnectorFactory.class.getName()));
   sf = serverLocator.createSessionFactory();
   clientSession =
       sf.createSession(
           HornetQDefaultConfiguration.DEFAULT_CLUSTER_USER,
           HornetQDefaultConfiguration.DEFAULT_CLUSTER_PASSWORD,
           false,
           true,
           true,
           false,
           1);
   requestor =
       new ClientRequestor(clientSession, HornetQDefaultConfiguration.DEFAULT_MANAGEMENT_ADDRESS);
   clientSession.start();
 }
Пример #15
0
  private boolean isLiveDown() {
    Collection<TopologyMemberImpl> nodes = topology.getMembers();
    Collection<ServerLocator> locatorsList = new LinkedList<ServerLocator>();
    AtomicInteger pingCount = new AtomicInteger(0);
    int total = 0;
    for (TopologyMemberImpl tm : nodes) if (useIt(tm)) total++;

    if (total < 1) return true;

    final CountDownLatch voteLatch = new CountDownLatch(total);
    try {
      for (TopologyMemberImpl tm : nodes) {
        Pair<TransportConfiguration, TransportConfiguration> pair = tm.getConnector();

        TransportConfiguration serverTC = pair.getA();
        if (useIt(tm)) {
          ServerLocatorImpl locator =
              (ServerLocatorImpl) HornetQClient.createServerLocatorWithoutHA(serverTC);
          locatorsList.add(locator);
          executor.submit(
              new QuorumVoteServerConnect(voteLatch, total, pingCount, locator, serverTC));
        }
      }

      try {
        voteLatch.await(LATCH_TIMEOUT, TimeUnit.SECONDS);
      } catch (InterruptedException interruption) {
        // No-op. The best the quorum can do now is to return the latest number it has
      }
      // -1: because the live server is not being filtered out.
      boolean vote = nodeIsDown(total, pingCount.get());
      HornetQServerLogger.LOGGER.trace(
          "quorum vote is liveIsDown=" + vote + ", count=" + pingCount);
      return vote;
    } finally {
      for (ServerLocator locator : locatorsList) {
        try {
          locator.close();
        } catch (Exception e) {
          // no-op
        }
      }
    }
  }
Пример #16
0
  private void restartServer() throws Exception {
    server.stop();
    server = null;
    server = createServer(true, configuration);
    server.getAddressSettingsRepository().addMatch(address.toString(), qs);
    // start the server
    server.start();

    AddressSettings qs1 = new AddressSettings();
    qs1.setLastValueQueue(true);
    server.getAddressSettingsRepository().addMatch(address.toString(), qs1);
    // then we create a client as normal
    locator.close();
    locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));

    locator.setBlockOnAcknowledge(true);
    locator.setAckBatchSize(0);
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    clientSession = sessionFactory.createSession(false, true, true);
    clientSessionXa = sessionFactory.createSession(true, false, false);
  }
Пример #17
0
  private void init(final boolean transacted, final String queueName) throws Exception {
    Map<String, Object> params = new HashMap<String, Object>();

    params.put(TransportConstants.TCP_NODELAY_PROPNAME, perfParams.isTcpNoDelay());
    params.put(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, perfParams.getTcpBufferSize());
    params.put(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, perfParams.getTcpBufferSize());

    params.put(TransportConstants.HOST_PROP_NAME, perfParams.getHost());
    params.put(TransportConstants.PORT_PROP_NAME, perfParams.getPort());

    ServerLocator serverLocator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(NettyConnectorFactory.class.getName(), params));
    serverLocator.setPreAcknowledge(perfParams.isPreAck());
    serverLocator.setConfirmationWindowSize(perfParams.getConfirmationWindow());
    serverLocator.setProducerWindowSize(perfParams.getProducerWindow());
    serverLocator.setConsumerWindowSize(perfParams.getConsumerWindow());
    serverLocator.setAckBatchSize(perfParams.getBatchSize());

    serverLocator.setBlockOnAcknowledge(perfParams.isBlockOnACK());
    serverLocator.setBlockOnDurableSend(perfParams.isBlockOnPersistent());
    factory = serverLocator.createSessionFactory();
  }
Пример #18
0
  @Test
  public void testGetNumberOfPages() throws Exception {
    session.close();
    server.stop();
    server.getConfiguration().setPersistenceEnabled(true);

    SimpleString address = RandomUtil.randomSimpleString();

    AddressSettings addressSettings = new AddressSettings();
    addressSettings.setPageSizeBytes(1024);
    addressSettings.setMaxSizeBytes(10 * 1024);
    final int NUMBER_MESSAGES_BEFORE_PAGING = 5;

    server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings);
    server.start();
    ServerLocator locator2 =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    addServerLocator(locator2);
    ClientSessionFactory sf2 = createSessionFactory(locator2);

    session = sf2.createSession(false, true, false);
    session.start();
    session.createQueue(address, address, true);

    QueueImpl serverQueue = (QueueImpl) server.locateQueue(address);

    ClientProducer producer = session.createProducer(address);

    for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) {
      ClientMessage msg = session.createMessage(true);
      msg.getBodyBuffer().writeBytes(new byte[512]);
      producer.send(msg);
    }
    session.commit();

    AddressControl addressControl = createManagementControl(address);
    Assert.assertEquals(0, addressControl.getNumberOfPages());

    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();
    Assert.assertEquals(1, addressControl.getNumberOfPages());

    msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();
    Assert.assertEquals(1, addressControl.getNumberOfPages());

    msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();

    Assert.assertEquals("# of pages is 2", 2, addressControl.getNumberOfPages());

    System.out.println("Address size=" + addressControl.getAddressSize());

    Assert.assertEquals(
        serverQueue.getPageSubscription().getPagingStore().getAddressSize(),
        addressControl.getAddressSize());
  }
Пример #19
0
  public synchronized void deployBridge(final BridgeConfiguration config) throws Exception {
    if (config.getName() == null) {
      HornetQServerLogger.LOGGER.bridgeNotUnique();

      return;
    }

    if (config.getQueueName() == null) {
      HornetQServerLogger.LOGGER.bridgeNoQueue(config.getName());

      return;
    }

    if (config.getForwardingAddress() == null) {
      HornetQServerLogger.LOGGER.bridgeNoForwardAddress(config.getName());
    }

    if (bridges.containsKey(config.getName())) {
      HornetQServerLogger.LOGGER.bridgeAlreadyDeployed(config.getName());

      return;
    }

    Transformer transformer = instantiateTransformer(config.getTransformerClassName());

    Binding binding = postOffice.getBinding(new SimpleString(config.getQueueName()));

    if (binding == null) {
      HornetQServerLogger.LOGGER.bridgeQueueNotFound(config.getQueueName(), config.getName());

      return;
    }

    Queue queue = (Queue) binding.getBindable();

    ServerLocatorInternal serverLocator;

    if (config.getDiscoveryGroupName() != null) {
      DiscoveryGroupConfiguration discoveryGroupConfiguration =
          configuration.getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName());
      if (discoveryGroupConfiguration == null) {
        HornetQServerLogger.LOGGER.bridgeNoDiscoveryGroup(config.getDiscoveryGroupName());

        return;
      }

      if (config.isHA()) {
        serverLocator =
            (ServerLocatorInternal)
                HornetQClient.createServerLocatorWithHA(discoveryGroupConfiguration);
      } else {
        serverLocator =
            (ServerLocatorInternal)
                HornetQClient.createServerLocatorWithoutHA(discoveryGroupConfiguration);
      }

    } else {
      TransportConfiguration[] tcConfigs = connectorNameListToArray(config.getStaticConnectors());

      if (tcConfigs == null) {
        HornetQServerLogger.LOGGER.bridgeCantFindConnectors(config.getName());
        return;
      }

      if (config.isHA()) {
        serverLocator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(tcConfigs);
      } else {
        serverLocator =
            (ServerLocatorInternal) HornetQClient.createServerLocatorWithoutHA(tcConfigs);
      }
    }

    if (config.getForwardingAddress() != null) {
      AddressSettings addressConfig =
          configuration.getAddressesSettings().get(config.getForwardingAddress());

      // The address config could be null on certain test cases or some Embedded environment
      if (addressConfig == null) {
        // We will certainly have this warning on testcases which is ok
        HornetQServerLogger.LOGGER.bridgeCantFindAddressConfig(
            config.getName(), config.getForwardingAddress());
      } else {
        final int windowSize = config.getConfirmationWindowSize();
        final long maxBytes = addressConfig.getMaxSizeBytes();

        if (maxBytes != -1 && maxBytes < windowSize) {
          HornetQServerLogger.LOGGER.bridgeConfirmationWindowTooSmall(
              config.getName(), config.getForwardingAddress(), windowSize, maxBytes);
        }
      }
    }

    serverLocator.setIdentity("Bridge " + config.getName());
    serverLocator.setConfirmationWindowSize(config.getConfirmationWindowSize());

    // We are going to manually retry on the bridge in case of failure
    serverLocator.setReconnectAttempts(0);
    serverLocator.setInitialConnectAttempts(0);
    serverLocator.setRetryInterval(config.getRetryInterval());
    serverLocator.setMaxRetryInterval(config.getMaxRetryInterval());
    serverLocator.setRetryIntervalMultiplier(config.getRetryIntervalMultiplier());
    serverLocator.setClientFailureCheckPeriod(config.getClientFailureCheckPeriod());
    serverLocator.setConnectionTTL(config.getConnectionTTL());
    serverLocator.setBlockOnDurableSend(!config.isUseDuplicateDetection());
    serverLocator.setBlockOnNonDurableSend(!config.isUseDuplicateDetection());
    serverLocator.setMinLargeMessageSize(config.getMinLargeMessageSize());
    // disable flow control
    serverLocator.setProducerWindowSize(-1);

    // This will be set to 30s unless it's changed from embedded / testing
    // there is no reason to exception the config for this timeout
    // since the Bridge is supposed to be non-blocking and fast
    // We may expose this if we find a good use case
    serverLocator.setCallTimeout(config.getCallTimeout());
    if (!config.isUseDuplicateDetection()) {
      HornetQServerLogger.LOGGER.debug(
          "Bridge "
              + config.getName()
              + " is configured to not use duplicate detecion, it will send messages synchronously");
    }

    clusterLocators.add(serverLocator);

    Bridge bridge =
        new BridgeImpl(
            serverLocator,
            config.getReconnectAttempts(),
            config.getReconnectAttemptsOnSameNode(),
            config.getRetryInterval(),
            config.getRetryIntervalMultiplier(),
            config.getMaxRetryInterval(),
            nodeManager.getUUID(),
            new SimpleString(config.getName()),
            queue,
            executorFactory.getExecutor(),
            FilterImpl.createFilter(config.getFilterString()),
            SimpleString.toSimpleString(config.getForwardingAddress()),
            scheduledExecutor,
            transformer,
            config.isUseDuplicateDetection(),
            config.getUser(),
            config.getPassword(),
            !backup,
            server.getStorageManager());

    bridges.put(config.getName(), bridge);

    managementService.registerBridge(bridge, config);

    bridge.start();
  }
  @Test
  public void testSimpleDistributionBackupStrategyFull() throws Exception {
    HornetQServer server0 = createServer(0, 1, BackupStrategy.FULL);
    HornetQServer server1 = createServer(1, 0, BackupStrategy.FULL);
    TransportConfiguration liveConnector0 =
        getConnectorTransportConfiguration("liveConnector" + 0, 0);
    TransportConfiguration liveConnector1 =
        getConnectorTransportConfiguration("liveConnector" + 1, 1);

    try (ServerLocator serverLocator = HornetQClient.createServerLocatorWithoutHA(liveConnector0)) {
      server0.start();
      server1.start();
      ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0);
      waitForRemoteBackup(sessionFactory0, 10);
      ClientSessionFactory sessionFactory1 = serverLocator.createSessionFactory(liveConnector1);
      waitForRemoteBackup(sessionFactory1, 10);
      Topology topology = serverLocator.getTopology();
      Collection<TopologyMemberImpl> members = topology.getMembers();
      assertEquals(members.size(), 2);
      Map<String, HornetQServer> backupServers0 =
          server0.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers0.size(), 1);
      Map<String, HornetQServer> backupServers1 =
          server1.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers1.size(), 1);
      HornetQServer backupServer0 = backupServers0.values().iterator().next();
      HornetQServer backupServer1 = backupServers1.values().iterator().next();
      waitForRemoteBackupSynchronization(backupServer0);
      waitForRemoteBackupSynchronization(backupServer1);
      assertEquals(server0.getNodeID(), backupServer1.getNodeID());
      assertEquals(server1.getNodeID(), backupServer0.getNodeID());
      Set<TransportConfiguration> backupAcceptors0 =
          backupServer0.getConfiguration().getAcceptorConfigurations();
      assertEquals(1, backupAcceptors0.size());
      assertEquals("5545", backupAcceptors0.iterator().next().getParams().get("port"));
      Set<TransportConfiguration> backupAcceptors1 =
          backupServer1.getConfiguration().getAcceptorConfigurations();
      assertEquals(1, backupAcceptors1.size());
      assertEquals("5546", backupAcceptors1.iterator().next().getParams().get("port"));
      Map<String, TransportConfiguration> connectorConfigurations0 =
          backupServer0.getConfiguration().getConnectorConfigurations();
      assertEquals(2, connectorConfigurations0.size());
      assertEquals("5545", connectorConfigurations0.get("liveConnector0").getParams().get("port"));
      assertEquals(
          "5446", connectorConfigurations0.get("remoteConnector0").getParams().get("port"));
      Map<String, TransportConfiguration> connectorConfigurations1 =
          backupServer1.getConfiguration().getConnectorConfigurations();
      assertEquals(2, connectorConfigurations1.size());
      assertEquals("5546", connectorConfigurations1.get("liveConnector1").getParams().get("port"));
      assertEquals(
          "5445", connectorConfigurations1.get("remoteConnector1").getParams().get("port"));
      if (policyType == HAPolicy.POLICY_TYPE.COLOCATED_SHARED_STORE) {
        assertEquals(
            server0.getConfiguration().getJournalDirectory(),
            backupServer1.getConfiguration().getJournalDirectory());
        assertEquals(
            server0.getConfiguration().getBindingsDirectory(),
            backupServer1.getConfiguration().getBindingsDirectory());
        assertEquals(
            server0.getConfiguration().getLargeMessagesDirectory(),
            backupServer1.getConfiguration().getLargeMessagesDirectory());
        assertEquals(
            server0.getConfiguration().getPagingDirectory(),
            backupServer1.getConfiguration().getPagingDirectory());
        assertEquals(
            server1.getConfiguration().getJournalDirectory(),
            backupServer0.getConfiguration().getJournalDirectory());
        assertEquals(
            server1.getConfiguration().getBindingsDirectory(),
            backupServer0.getConfiguration().getBindingsDirectory());
        assertEquals(
            server1.getConfiguration().getLargeMessagesDirectory(),
            backupServer0.getConfiguration().getLargeMessagesDirectory());
        assertEquals(
            server1.getConfiguration().getPagingDirectory(),
            backupServer0.getConfiguration().getPagingDirectory());
      } else {
        assertNotEquals(
            server0.getConfiguration().getJournalDirectory(),
            backupServer1.getConfiguration().getJournalDirectory());
        assertNotEquals(
            server0.getConfiguration().getBindingsDirectory(),
            backupServer1.getConfiguration().getBindingsDirectory());
        assertNotEquals(
            server0.getConfiguration().getLargeMessagesDirectory(),
            backupServer1.getConfiguration().getLargeMessagesDirectory());
        assertNotEquals(
            server0.getConfiguration().getPagingDirectory(),
            backupServer1.getConfiguration().getPagingDirectory());
        assertNotEquals(
            server1.getConfiguration().getJournalDirectory(),
            backupServer0.getConfiguration().getJournalDirectory());
        assertNotEquals(
            server1.getConfiguration().getBindingsDirectory(),
            backupServer0.getConfiguration().getBindingsDirectory());
        assertNotEquals(
            server1.getConfiguration().getLargeMessagesDirectory(),
            backupServer0.getConfiguration().getLargeMessagesDirectory());
        assertNotEquals(
            server1.getConfiguration().getPagingDirectory(),
            backupServer0.getConfiguration().getPagingDirectory());
      }
    } finally {
      server0.stop();
      server1.stop();
    }
  }
  @Test
  public void testSimpleDistributionOfBackupsMaxBackupsExceeded() throws Exception {
    HornetQServer server0 = createServer(0, 1, BackupStrategy.FULL);
    HornetQServer server1 = createServer(1, 0, BackupStrategy.FULL);
    HornetQServer server2 = createServer(2, 0, BackupStrategy.FULL);
    HornetQServer server3 = createServer(3, 0, BackupStrategy.FULL);
    TransportConfiguration liveConnector0 =
        getConnectorTransportConfiguration("liveConnector" + 0, 0);
    TransportConfiguration liveConnector1 =
        getConnectorTransportConfiguration("liveConnector" + 1, 1);
    TransportConfiguration liveConnector2 =
        getConnectorTransportConfiguration("liveConnector" + 2, 2);
    TransportConfiguration liveConnector3 =
        getConnectorTransportConfiguration("liveConnector" + 3, 3);

    try (ServerLocator serverLocator = HornetQClient.createServerLocatorWithoutHA(liveConnector0)) {
      server0.start();
      server1.start();
      ClientSessionFactory sessionFactory0 = serverLocator.createSessionFactory(liveConnector0);
      waitForRemoteBackup(sessionFactory0, 10);
      ClientSessionFactory sessionFactory1 = serverLocator.createSessionFactory(liveConnector1);
      waitForRemoteBackup(sessionFactory1, 10);
      Topology topology = serverLocator.getTopology();
      Collection<TopologyMemberImpl> members = topology.getMembers();
      assertEquals(members.size(), 2);
      Map<String, HornetQServer> backupServers0 =
          server0.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers0.size(), 1);
      Map<String, HornetQServer> backupServers1 =
          server1.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers1.size(), 1);
      HornetQServer backupServer0 = backupServers0.values().iterator().next();
      HornetQServer backupServer1 = backupServers1.values().iterator().next();
      waitForRemoteBackupSynchronization(backupServer0);
      waitForRemoteBackupSynchronization(backupServer1);
      assertEquals(server0.getNodeID(), backupServer1.getNodeID());
      assertEquals(server1.getNodeID(), backupServer0.getNodeID());
      server2.start();
      // just give server2 time to try both server 0 and 1
      ClientSessionFactory sessionFactory2 = serverLocator.createSessionFactory(liveConnector2);
      server3.start();
      ClientSessionFactory sessionFactory3 = serverLocator.createSessionFactory(liveConnector3);
      waitForRemoteBackup(sessionFactory2, 10);
      waitForRemoteBackup(sessionFactory3, 10);
      assertEquals(members.size(), 2);
      Map<String, HornetQServer> backupServers2 =
          server2.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers2.size(), 1);
      Map<String, HornetQServer> backupServers3 =
          server3.getClusterManager().getHAManager().getBackupServers();
      assertEquals(backupServers3.size(), 1);
      HornetQServer backupServer2 = backupServers2.values().iterator().next();
      HornetQServer backupServer3 = backupServers3.values().iterator().next();
      waitForRemoteBackupSynchronization(backupServer2);
      waitForRemoteBackupSynchronization(backupServer3);
      assertEquals(server0.getNodeID(), backupServer1.getNodeID());
      assertEquals(server1.getNodeID(), backupServer0.getNodeID());
      assertEquals(server2.getNodeID(), backupServer3.getNodeID());
      assertEquals(server3.getNodeID(), backupServer2.getNodeID());
    } finally {
      server0.stop();
      server1.stop();
      server2.stop();
      server3.stop();
    }
  }
Пример #22
0
  @Test
  public void testTargetServerUpAndDown() throws Exception {
    // This test needs to use real files, since it requires duplicate detection, since when the
    // target server is
    // shutdown, messages will get resent when it is started, so the dup id cache needs
    // to be persisted

    Map<String, Object> server0Params = new HashMap<String, Object>();
    HornetQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params);

    Map<String, Object> server1Params = new HashMap<String, Object>();
    if (isNetty()) {
      server1Params.put(
          "port", org.hornetq.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1);
    } else {
      server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
    }
    HornetQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params);

    final String testAddress = "testAddress";
    final String queueName0 = "queue0";
    final String forwardAddress = "forwardAddress";
    final String queueName1 = "queue1";

    Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>();
    TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params);
    TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params);
    connectors.put(server1tc.getName(), server1tc);

    server0.getConfiguration().setConnectorConfigurations(connectors);

    ArrayList<String> staticConnectors = new ArrayList<String>();
    staticConnectors.add(server1tc.getName());

    final String bridgeName = "bridge1";

    BridgeConfiguration bridgeConfiguration =
        new BridgeConfiguration()
            .setName(bridgeName)
            .setQueueName(queueName0)
            .setForwardingAddress(forwardAddress)
            .setRetryInterval(500)
            .setReconnectAttempts(-1)
            .setReconnectAttemptsOnSameNode(0)
            .setConfirmationWindowSize(1024)
            .setStaticConnectors(staticConnectors);

    List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
    bridgeConfigs.add(bridgeConfiguration);
    server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);

    CoreQueueConfiguration queueConfig0 =
        new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0);
    List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
    queueConfigs0.add(queueConfig0);
    server0.getConfiguration().setQueueConfigurations(queueConfigs0);

    CoreQueueConfiguration queueConfig1 =
        new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1);
    List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
    queueConfigs1.add(queueConfig1);
    server1.getConfiguration().setQueueConfigurations(queueConfigs1);
    ServerLocator locator = null;
    try {
      // Don't start server 1 yet

      server0.start();
      waitForServer(server0);

      locator = HornetQClient.createServerLocatorWithoutHA(server0tc, server1tc);
      ClientSessionFactory sf0 = locator.createSessionFactory(server0tc);

      ClientSession session0 = sf0.createSession(false, true, true);

      ClientProducer producer0 = session0.createProducer(new SimpleString(testAddress));

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session0.createMessage(false);

        message.putIntProperty(propKey, i);

        producer0.send(message);
      }

      // Wait a bit
      Thread.sleep(1000);

      server1.start();
      waitForServer(server1);

      ClientSessionFactory sf1 = locator.createSessionFactory(server1tc);

      ClientSession session1 = sf1.createSession(false, true, true);

      ClientConsumer consumer1 = session1.createConsumer(queueName1);

      session1.start();

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(1000);

        Assert.assertNotNull(message);

        Assert.assertEquals(i, message.getObjectProperty(propKey));

        message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session0.createMessage(false);

        message.putIntProperty(propKey, i);

        producer0.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(1000);

        Assert.assertNotNull(message);

        Assert.assertEquals(i, message.getObjectProperty(propKey));

        message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      session1.close();

      sf1.close();

      BridgeStartTest.log.info("stopping server 1");

      server1.stop();

      BridgeStartTest.log.info("stopped server 1");

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session0.createMessage(false);

        message.putIntProperty(propKey, i);

        producer0.send(message);
      }

      BridgeStartTest.log.info("sent some more messages");

      server1.start();
      waitForServer(server1);

      BridgeStartTest.log.info("started server1");

      sf1 = locator.createSessionFactory(server1tc);

      session1 = sf1.createSession(false, true, true);

      consumer1 = session1.createConsumer(queueName1);

      session1.start();

      BridgeStartTest.log.info("started session");

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(1000);

        Assert.assertNotNull(message);

        Assert.assertEquals(i, message.getObjectProperty(propKey));

        message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      session1.close();

      sf1.close();

      session0.close();

      sf0.close();

      locator.close();
    } finally {
      if (locator != null) {
        locator.close();
      }

      server0.stop();

      server1.stop();
    }
  }
  public void testCreateAndDestroyBridge() throws Exception {
    String name = RandomUtil.randomString();
    String sourceAddress = RandomUtil.randomString();
    String sourceQueue = RandomUtil.randomString();
    String targetAddress = RandomUtil.randomString();
    String targetQueue = RandomUtil.randomString();

    HornetQServerControl serverControl = createManagementControl();

    checkNoResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    assertEquals(0, serverControl.getBridgeNames().length);

    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession session = csf.createSession();

    session.createQueue(sourceAddress, sourceQueue);
    session.createQueue(targetAddress, targetQueue);

    serverControl.createBridge(
        name,
        sourceQueue,
        targetAddress,
        null, // forwardingAddress
        null, // filterString
        HornetQClient.DEFAULT_RETRY_INTERVAL,
        HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER,
        HornetQClient.DEFAULT_RECONNECT_ATTEMPTS,
        false, // duplicateDetection
        1, // confirmationWindowSize
        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
        connectorConfig.getName(), // liveConnector
        false,
        false,
        null,
        null);

    checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    String[] bridgeNames = serverControl.getBridgeNames();
    assertEquals(1, bridgeNames.length);
    assertEquals(name, bridgeNames[0]);

    BridgeControl bridgeControl = ManagementControlHelper.createBridgeControl(name, mbeanServer);
    assertEquals(name, bridgeControl.getName());
    assertTrue(bridgeControl.isStarted());

    // check that a message sent to the sourceAddress is put in the tagetQueue
    ClientProducer producer = session.createProducer(sourceAddress);
    ClientMessage message = session.createMessage(false);
    String text = RandomUtil.randomString();
    message.putStringProperty("prop", text);
    producer.send(message);

    session.start();

    ClientConsumer targetConsumer = session.createConsumer(targetQueue);
    message = targetConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text, message.getStringProperty("prop"));

    ClientConsumer sourceConsumer = session.createConsumer(sourceQueue);
    assertNull(sourceConsumer.receiveImmediate());

    serverControl.destroyBridge(name);

    checkNoResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    assertEquals(0, serverControl.getBridgeNames().length);

    // check that a message is no longer diverted
    message = session.createMessage(false);
    String text2 = RandomUtil.randomString();
    message.putStringProperty("prop", text2);
    producer.send(message);

    assertNull(targetConsumer.receiveImmediate());
    message = sourceConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text2, message.getStringProperty("prop"));

    sourceConsumer.close();
    targetConsumer.close();

    session.deleteQueue(sourceQueue);
    session.deleteQueue(targetQueue);

    session.close();

    locator.close();
  }
Пример #24
0
  @Test
  public void testStartStop() throws Exception {
    Map<String, Object> server0Params = new HashMap<String, Object>();
    HornetQServer server0 = createClusteredServerWithParams(isNetty(), 0, true, server0Params);

    Map<String, Object> server1Params = new HashMap<String, Object>();
    if (isNetty()) {
      server1Params.put(
          "port", org.hornetq.core.remoting.impl.netty.TransportConstants.DEFAULT_PORT + 1);
    } else {
      server1Params.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
    }
    HornetQServer server1 = createClusteredServerWithParams(isNetty(), 1, true, server1Params);
    ServerLocator locator = null;
    try {
      final String testAddress = "testAddress";
      final String queueName0 = "queue0";
      final String forwardAddress = "forwardAddress";
      final String queueName1 = "queue1";

      Map<String, TransportConfiguration> connectors =
          new HashMap<String, TransportConfiguration>();
      TransportConfiguration server0tc = new TransportConfiguration(getConnector(), server0Params);
      TransportConfiguration server1tc = new TransportConfiguration(getConnector(), server1Params);
      connectors.put(server1tc.getName(), server1tc);

      server0.getConfiguration().setConnectorConfigurations(connectors);

      ArrayList<String> staticConnectors = new ArrayList<String>();
      staticConnectors.add(server1tc.getName());

      final String bridgeName = "bridge1";

      BridgeConfiguration bridgeConfiguration =
          new BridgeConfiguration()
              .setName(bridgeName)
              .setQueueName(queueName0)
              .setForwardingAddress(forwardAddress)
              .setRetryInterval(1000)
              .setReconnectAttempts(0)
              .setReconnectAttemptsOnSameNode(0)
              .setConfirmationWindowSize(1024)
              .setStaticConnectors(staticConnectors);

      List<BridgeConfiguration> bridgeConfigs = new ArrayList<BridgeConfiguration>();
      bridgeConfigs.add(bridgeConfiguration);
      server0.getConfiguration().setBridgeConfigurations(bridgeConfigs);

      CoreQueueConfiguration queueConfig0 =
          new CoreQueueConfiguration().setAddress(testAddress).setName(queueName0);
      List<CoreQueueConfiguration> queueConfigs0 = new ArrayList<CoreQueueConfiguration>();
      queueConfigs0.add(queueConfig0);
      server0.getConfiguration().setQueueConfigurations(queueConfigs0);

      CoreQueueConfiguration queueConfig1 =
          new CoreQueueConfiguration().setAddress(forwardAddress).setName(queueName1);
      List<CoreQueueConfiguration> queueConfigs1 = new ArrayList<CoreQueueConfiguration>();
      queueConfigs1.add(queueConfig1);
      server1.getConfiguration().setQueueConfigurations(queueConfigs1);

      server1.start();
      waitForServer(server1);

      server0.start();
      waitForServer(server0);

      locator = HornetQClient.createServerLocatorWithoutHA(server0tc, server1tc);
      ClientSessionFactory sf0 = locator.createSessionFactory(server0tc);

      ClientSessionFactory sf1 = locator.createSessionFactory(server1tc);

      ClientSession session0 = sf0.createSession(false, true, true);

      ClientSession session1 = sf1.createSession(false, true, true);

      ClientProducer producer0 = session0.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session1.createConsumer(queueName1);

      session1.start();

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session0.createMessage(false);

        message.putIntProperty(propKey, i);

        producer0.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(200);

        Assert.assertNotNull(message);

        Assert.assertEquals(i, message.getObjectProperty(propKey));

        message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Bridge bridge = server0.getClusterManager().getBridges().get(bridgeName);

      bridge.stop();

      bridge.flushExecutor();

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = session0.createMessage(false);

        message.putIntProperty(propKey, i);

        producer0.send(message);
      }

      Assert.assertNull(consumer1.receiveImmediate());

      bridge.start();

      for (int i = 0; i < numMessages; i++) {
        ClientMessage message = consumer1.receive(1000);

        Assert.assertNotNull(message);

        Assert.assertEquals(i, message.getObjectProperty(propKey));

        message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      session0.close();

      session1.close();

      sf0.close();

      sf1.close();
    } finally {
      if (locator != null) {
        locator.close();
      }

      server0.stop();

      server1.stop();
    }
  }
Пример #25
0
  public synchronized void deployBridge(final BridgeConfiguration config, final boolean start)
      throws Exception {
    if (config.getName() == null) {
      ClusterManagerImpl.log.warn(
          "Must specify a unique name for each bridge. This one will not be deployed.");

      return;
    }

    if (config.getQueueName() == null) {
      ClusterManagerImpl.log.warn(
          "Must specify a queue name for each bridge. This one will not be deployed.");

      return;
    }

    if (config.getForwardingAddress() == null) {
      ClusterManagerImpl.log.debug(
          "Forward address is not specified. Will use original message address instead");
    }

    if (bridges.containsKey(config.getName())) {
      ClusterManagerImpl.log.warn(
          "There is already a bridge with name "
              + config.getName()
              + " deployed. This one will not be deployed.");

      return;
    }

    Transformer transformer = instantiateTransformer(config.getTransformerClassName());

    Binding binding = postOffice.getBinding(new SimpleString(config.getQueueName()));

    if (binding == null) {
      ClusterManagerImpl.log.warn(
          "No queue found with name " + config.getQueueName() + " bridge will not be deployed.");

      return;
    }

    Queue queue = (Queue) binding.getBindable();

    ServerLocatorInternal serverLocator;

    if (config.getDiscoveryGroupName() != null) {
      DiscoveryGroupConfiguration discoveryGroupConfiguration =
          configuration.getDiscoveryGroupConfigurations().get(config.getDiscoveryGroupName());
      if (discoveryGroupConfiguration == null) {
        ClusterManagerImpl.log.warn(
            "No discovery group configured with name '"
                + config.getDiscoveryGroupName()
                + "'. The bridge will not be deployed.");

        return;
      }

      if (config.isHA()) {
        serverLocator =
            (ServerLocatorInternal)
                HornetQClient.createServerLocatorWithHA(discoveryGroupConfiguration);
      } else {
        serverLocator =
            (ServerLocatorInternal)
                HornetQClient.createServerLocatorWithoutHA(discoveryGroupConfiguration);
      }

    } else {
      TransportConfiguration[] tcConfigs = connectorNameListToArray(config.getStaticConnectors());

      if (tcConfigs == null) {
        return;
      }

      if (config.isHA()) {
        serverLocator = (ServerLocatorInternal) HornetQClient.createServerLocatorWithHA(tcConfigs);
      } else {
        serverLocator =
            (ServerLocatorInternal) HornetQClient.createServerLocatorWithoutHA(tcConfigs);
      }
    }

    serverLocator.setConfirmationWindowSize(config.getConfirmationWindowSize());

    // We are going to manually retry on the bridge in case of failure
    serverLocator.setReconnectAttempts(0);
    serverLocator.setInitialConnectAttempts(-1);
    serverLocator.setRetryInterval(config.getRetryInterval());
    serverLocator.setMaxRetryInterval(config.getMaxRetryInterval());
    serverLocator.setRetryIntervalMultiplier(config.getRetryIntervalMultiplier());
    serverLocator.setClientFailureCheckPeriod(config.getClientFailureCheckPeriod());
    serverLocator.setBlockOnDurableSend(!config.isUseDuplicateDetection());
    serverLocator.setBlockOnNonDurableSend(!config.isUseDuplicateDetection());
    serverLocator.setMinLargeMessageSize(config.getMinLargeMessageSize());
    // disable flow control
    serverLocator.setProducerWindowSize(-1);

    // This will be set to 30s unless it's changed from embedded / testing
    // there is no reason to exception the config for this timeout
    // since the Bridge is supposed to be non-blocking and fast
    // We may expose this if we find a good use case
    serverLocator.setCallTimeout(config.getCallTimeout());
    if (!config.isUseDuplicateDetection()) {
      log.debug(
          "Bridge "
              + config.getName()
              + " is configured to not use duplicate detecion, it will send messages synchronously");
    }

    clusterLocators.add(serverLocator);

    Bridge bridge =
        new BridgeImpl(
            serverLocator,
            config.getReconnectAttempts(),
            config.getRetryInterval(),
            config.getRetryIntervalMultiplier(),
            config.getMaxRetryInterval(),
            nodeUUID,
            new SimpleString(config.getName()),
            queue,
            executorFactory.getExecutor(),
            SimpleString.toSimpleString(config.getFilterString()),
            SimpleString.toSimpleString(config.getForwardingAddress()),
            scheduledExecutor,
            transformer,
            config.isUseDuplicateDetection(),
            config.getUser(),
            config.getPassword(),
            !backup,
            server.getStorageManager());

    bridges.put(config.getName(), bridge);

    managementService.registerBridge(bridge, config);

    if (start) {
      bridge.start();
    }
  }
  public void testCreateAndDestroyDivert() throws Exception {
    String address = RandomUtil.randomString();
    String name = RandomUtil.randomString();
    String routingName = RandomUtil.randomString();
    String forwardingAddress = RandomUtil.randomString();

    HornetQServerControl serverControl = createManagementControl();

    checkNoResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    assertEquals(0, serverControl.getDivertNames().length);

    serverControl.createDivert(
        name.toString(), routingName, address, forwardingAddress, true, null, null);

    checkResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    DivertControl divertControl =
        ManagementControlHelper.createDivertControl(name.toString(), mbeanServer);
    assertEquals(name.toString(), divertControl.getUniqueName());
    assertEquals(address, divertControl.getAddress());
    assertEquals(forwardingAddress, divertControl.getForwardingAddress());
    assertEquals(routingName, divertControl.getRoutingName());
    assertTrue(divertControl.isExclusive());
    assertNull(divertControl.getFilter());
    assertNull(divertControl.getTransformerClassName());
    String[] divertNames = serverControl.getDivertNames();
    assertEquals(1, divertNames.length);
    assertEquals(name, divertNames[0]);

    // check that a message sent to the address is diverted exclusively
    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));

    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession session = csf.createSession();

    String divertQueue = RandomUtil.randomString();
    String queue = RandomUtil.randomString();
    session.createQueue(forwardingAddress, divertQueue);
    session.createQueue(address, queue);

    ClientProducer producer = session.createProducer(address);
    ClientMessage message = session.createMessage(false);
    String text = RandomUtil.randomString();
    message.putStringProperty("prop", text);
    producer.send(message);

    ClientConsumer consumer = session.createConsumer(queue);
    ClientConsumer divertedConsumer = session.createConsumer(divertQueue);

    session.start();

    assertNull(consumer.receiveImmediate());
    message = divertedConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text, message.getStringProperty("prop"));

    serverControl.destroyDivert(name.toString());

    checkNoResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    assertEquals(0, serverControl.getDivertNames().length);

    // check that a message is no longer diverted
    message = session.createMessage(false);
    String text2 = RandomUtil.randomString();
    message.putStringProperty("prop", text2);
    producer.send(message);

    assertNull(divertedConsumer.receiveImmediate());
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(text2, message.getStringProperty("prop"));

    consumer.close();
    divertedConsumer.close();
    session.deleteQueue(queue);
    session.deleteQueue(divertQueue);
    session.close();

    locator.close();
  }