@Override
  protected void setUp() throws Exception {
    super.setUp();

    setupServer2();
    setupServer1();

    jmsServer1.start();
    jmsServer1.activated();

    jmsServer2.start();
    jmsServer2.activated();

    cf1 =
        (ConnectionFactory)
            HornetQJMSClient.createConnectionFactoryWithoutHA(
                JMSFactoryType.CF,
                new TransportConfiguration(
                    InVMConnectorFactory.class.getName(), generateInVMParams(0)));
    cf2 =
        (ConnectionFactory)
            HornetQJMSClient.createConnectionFactoryWithoutHA(
                JMSFactoryType.CF,
                new TransportConfiguration(
                    InVMConnectorFactory.class.getName(), generateInVMParams(1)));
  }
  @Test
  public void sendToNonExistantDestination() throws Exception {
    Destination destination = HornetQJMSClient.createQueue("DoesNotExist");
    TransportConfiguration transportConfiguration =
        new TransportConfiguration(InVMConnectorFactory.class.getName());
    ConnectionFactory localConnectionFactory =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, transportConfiguration);
    // Using JMS 1 API
    Connection connection = localConnectionFactory.createConnection();
    Session session = connection.createSession();
    try {
      MessageProducer messageProducer = session.createProducer(null);
      messageProducer.send(destination, session.createMessage());
      Assert.fail("Succeeded in sending message to a non-existant destination using JMS 1 API!");
    } catch (JMSException e) { // Expected }

    }

    // Using JMS 2 API
    JMSContext context = localConnectionFactory.createContext();
    JMSProducer jmsProducer = context.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT);

    try {
      jmsProducer.send(destination, context.createMessage());
      Assert.fail("Succeeded in sending message to a non-existant destination using JMS 2 API!");
    } catch (JMSRuntimeException e) { // Expected }
    }
  }
Exemple #3
0
  @Test
  public void testStartWithFailureThenSuccess() throws Exception {
    HornetQJMSConnectionFactory failingSourceCF =
        new HornetQJMSConnectionFactory(
            false, new TransportConfiguration(InVMConnectorFactory.class.getName())) {
          private static final long serialVersionUID = 4657153922210359725L;
          boolean firstTime = true;

          @Override
          public Connection createConnection() throws JMSException {
            if (firstTime) {
              firstTime = false;
              throw new JMSException("unable to create a conn");
            } else {
              return super.createConnection();
            }
          }
        };
    // Note! We disable automatic reconnection on the session factory. The bridge needs to do the
    // reconnection
    failingSourceCF.setReconnectAttempts(0);
    failingSourceCF.setBlockOnNonDurableSend(true);
    failingSourceCF.setBlockOnDurableSend(true);

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(failingSourceCF);
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    // retry after 10 ms
    bridge.setFailureRetryInterval(10);
    // retry only once
    bridge.setMaxRetries(1);
    bridge.setMaxBatchSize(1);
    bridge.setMaxBatchTime(-1);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();

    Thread.sleep(500);
    Assert.assertTrue(bridge.isStarted());
    Assert.assertFalse(bridge.isFailed());

    bridge.stop();
  }
Exemple #4
0
  @Test
  public void testStartWithRepeatedFailure() throws Exception {
    HornetQJMSConnectionFactory failingSourceCF =
        new HornetQJMSConnectionFactory(
            false, new TransportConfiguration(InVMConnectorFactory.class.getName())) {
          private static final long serialVersionUID = 2834937512213001068L;

          @Override
          public Connection createConnection() throws JMSException {
            throw new JMSException("unable to create a conn");
          }
        };

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(failingSourceCF);
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    // retry after 10 ms
    bridge.setFailureRetryInterval(10);
    // retry only once
    bridge.setMaxRetries(1);
    bridge.setMaxBatchSize(1);
    bridge.setMaxBatchTime(-1);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();

    Thread.sleep(50);
    Assert.assertFalse(bridge.isStarted());
    Assert.assertTrue(bridge.isFailed());

    bridge.stop();
  }
  @Test
  public void testCreateDurableQueueUsingJMSAndRestartServer() throws Exception {
    String queueName = RandomUtil.randomString();
    String binding = RandomUtil.randomString();

    UnitTestCase.checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    TransportConfiguration config =
        new TransportConfiguration(InVMConnectorFactory.class.getName());
    Connection connection =
        HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, config)
            .createConnection();
    connection.start();
    Queue managementQueue = HornetQJMSClient.createQueue("hornetq.management");
    QueueSession session = (QueueSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    QueueRequestor requestor = new QueueRequestor(session, managementQueue);
    Message message = session.createMessage();
    JMSManagementHelper.putOperationInvocation(
        message, "jms.server", "createQueue", queueName, binding);
    Message reply = requestor.request(message);
    assertTrue(JMSManagementHelper.hasOperationSucceeded(reply));
    connection.close();

    Object o = UnitTestCase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    Queue queue = (Queue) o;
    assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager.stop();

    checkNoBinding(context, binding);
    checkNoResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));

    serverManager = createJMSServer();
    serverManager.start();

    o = UnitTestCase.checkBinding(context, binding);
    Assert.assertTrue(o instanceof Queue);
    queue = (Queue) o;
    assertEquals(queueName, queue.getQueueName());
    checkResource(ObjectNameBuilder.DEFAULT.getJMSQueueObjectName(queueName));
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    Configuration conf = createDefaultConfig();
    conf.setSecurityEnabled(false);
    conf.getAcceptorConfigurations().add(new TransportConfiguration(INVM_ACCEPTOR_FACTORY));
    server = createServer(false, conf);
    jmsServer = new JMSServerManagerImpl(server);
    jmsServer.setContext(new NullInitialContext());
    jmsServer.start();

    cf1 =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
    cf2 =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));
  }
  @Before
  public void addTopic() throws Exception {

    count++;
    adminSupport.createJmsQueue(getQueueName(), getQueueJndiName());
    adminSupport.createJmsQueue(getOtherQueueName(), getOtherQueueJndiName());
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("host", TestSuiteEnvironment.getServerAddress());
    TransportConfiguration transportConfiguration =
        new TransportConfiguration(NettyConnectorFactory.class.getName(), map);
    HornetQConnectionFactory cf =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, transportConfiguration);
    cf.setClientID("sender");
    conn = cf.createQueueConnection("guest", "guest");
    conn.start();
    queue = HornetQJMSClient.createQueue(getQueueName());
    otherQueue = HornetQJMSClient.createQueue(getOtherQueueName());
    session = conn.createQueueSession(false, TopicSession.AUTO_ACKNOWLEDGE);
  }
    ProducerThread(final ConnectionFactory cf, final int numMessages) throws Exception {
      connection = cf.createConnection();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      producer = session.createProducer(HornetQJMSClient.createTopic("my-topic"));

      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

      this.numMessages = numMessages;
    }
    ConsumerThread(final ConnectionFactory cf, final int numMessages) throws Exception {
      connection = cf.createConnection();

      connection.start();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      consumer = session.createConsumer(HornetQJMSClient.createTopic("my-topic"));

      this.numMessages = numMessages;
    }
Exemple #10
0
  private static ConnectionFactory createConnectionFactory() {

    HornetQJMSConnectionFactory cf =
        (HornetQJMSConnectionFactory)
            HornetQJMSClient.createConnectionFactoryWithoutHA(
                JMSFactoryType.CF,
                new TransportConfiguration(InVMConnectorFactory.class.getName()));
    // Note! We disable automatic reconnection on the session factory. The bridge needs to do the
    // reconnection
    cf.setReconnectAttempts(0);
    cf.setBlockOnNonDurableSend(true);
    cf.setBlockOnDurableSend(true);
    return cf;
  }
  @Test
  public void testListConsumers() throws Exception {

    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("host", TestSuiteEnvironment.getServerAddress());
    TransportConfiguration transportConfiguration =
        new TransportConfiguration(NettyConnectorFactory.class.getName(), map);
    HornetQConnectionFactory cf =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, transportConfiguration);
    cf.setClientID("consumer");
    consumerConn = cf.createQueueConnection("guest", "guest");
    consumerConn.start();
    consumerSession = consumerConn.createQueueSession(false, TopicSession.AUTO_ACKNOWLEDGE);

    ModelNode result = execute(getQueueOperation("list-consumers-as-json"), true);
    Assert.assertTrue(result.isDefined());
    Assert.assertEquals(ModelType.STRING, result.getType());
  }
  @Test
  public void testPagingOverCreatedDestinationTopics() throws Exception {

    Configuration config = createDefaultConfig();

    config.setJournalSyncNonTransactional(false);

    HornetQServer server =
        createServer(true, config, PAGE_SIZE, -1, new HashMap<String, AddressSettings>());

    JMSServerManagerImpl jmsServer = new JMSServerManagerImpl(server);
    InVMNamingContext context = new InVMNamingContext();
    jmsServer.setContext(context);
    jmsServer.start();

    jmsServer.createTopic(true, "tt", "/topic/TT");

    server
        .getHornetQServerControl()
        .addAddressSettings(
            "jms.topic.TT",
            "DLQ",
            "DLQ",
            -1,
            false,
            5,
            1024 * 1024,
            1024 * 10,
            5,
            5,
            1,
            1000,
            0,
            false,
            "PAGE",
            -1,
            10,
            "KILL");

    HornetQJMSConnectionFactory cf =
        (HornetQJMSConnectionFactory)
            HornetQJMSClient.createConnectionFactoryWithoutHA(
                JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));

    Connection conn = cf.createConnection();
    conn.setClientID("tst");
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = (Topic) context.lookup("/topic/TT");
    sess.createDurableSubscriber(topic, "t1");

    MessageProducer prod = sess.createProducer(topic);
    prod.setDeliveryMode(DeliveryMode.PERSISTENT);
    TextMessage txt = sess.createTextMessage("TST");
    prod.send(txt);

    PagingStore store = server.getPagingManager().getPageStore(new SimpleString("jms.topic.TT"));

    assertEquals(1024 * 1024, store.getMaxSize());
    assertEquals(10 * 1024, store.getPageSizeBytes());

    jmsServer.stop();

    server = createServer(true, config, PAGE_SIZE, -1, new HashMap<String, AddressSettings>());

    jmsServer = new JMSServerManagerImpl(server);
    context = new InVMNamingContext();
    jmsServer.setContext(context);
    jmsServer.start();

    AddressSettings settings = server.getAddressSettingsRepository().getMatch("jms.topic.TT");

    assertEquals(1024 * 1024, settings.getMaxSizeBytes());
    assertEquals(10 * 1024, settings.getPageSizeBytes());
    assertEquals(AddressFullMessagePolicy.PAGE, settings.getAddressFullMessagePolicy());

    store = server.getPagingManager().getPageStore(new SimpleString("TT"));

    conn.close();

    server.stop();
  }
Exemple #13
0
  protected void setupDestination() throws Exception {

    String destinationName = spec.getDestination();

    if (spec.isUseJNDI()) {
      Context ctx;
      if (spec.getParsedJndiParams() == null) {
        ctx = new InitialContext();
      } else {
        ctx = new InitialContext(spec.getParsedJndiParams());
      }
      HornetQRALogger.LOGGER.debug("Using context " + ctx.getEnvironment() + " for " + spec);
      if (HornetQActivation.trace) {
        HornetQRALogger.LOGGER.trace("setupDestination(" + ctx + ")");
      }

      String destinationTypeString = spec.getDestinationType();
      if (destinationTypeString != null && !destinationTypeString.trim().equals("")) {
        HornetQRALogger.LOGGER.debug("Destination type defined as " + destinationTypeString);

        Class<?> destinationType;
        if (Topic.class.getName().equals(destinationTypeString)) {
          destinationType = Topic.class;
          isTopic = true;
        } else {
          destinationType = Queue.class;
        }

        HornetQRALogger.LOGGER.debug(
            "Retrieving " + destinationType.getName() + " \"" + destinationName + "\" from JNDI");

        try {
          destination =
              (HornetQDestination) HornetQRaUtils.lookup(ctx, destinationName, destinationType);
        } catch (Exception e) {
          if (destinationName == null) {
            throw HornetQRABundle.BUNDLE.noDestinationName();
          }

          String calculatedDestinationName =
              destinationName.substring(destinationName.lastIndexOf('/') + 1);

          HornetQRALogger.LOGGER.debug(
              "Unable to retrieve "
                  + destinationName
                  + " from JNDI. Creating a new "
                  + destinationType.getName()
                  + " named "
                  + calculatedDestinationName
                  + " to be used by the MDB.");

          // If there is no binding on naming, we will just create a new instance
          if (isTopic) {
            destination =
                (HornetQDestination) HornetQJMSClient.createTopic(calculatedDestinationName);
          } else {
            destination =
                (HornetQDestination) HornetQJMSClient.createQueue(calculatedDestinationName);
          }
        }
      } else {
        HornetQRALogger.LOGGER.debug(
            "Destination type not defined in MDB activation configuration.");
        HornetQRALogger.LOGGER.debug(
            "Retrieving " + Destination.class.getName() + " \"" + destinationName + "\" from JNDI");

        destination =
            (HornetQDestination) HornetQRaUtils.lookup(ctx, destinationName, Destination.class);
        if (destination instanceof Topic) {
          isTopic = true;
        }
      }
    } else {
      HornetQRALogger.LOGGER.instantiatingDestination(
          spec.getDestinationType(), spec.getDestination());

      if (Topic.class.getName().equals(spec.getDestinationType())) {
        destination = (HornetQDestination) HornetQJMSClient.createTopic(spec.getDestination());
        isTopic = true;
      } else {
        destination = (HornetQDestination) HornetQJMSClient.createQueue(spec.getDestination());
      }
    }
  }
Exemple #14
0
  @Test
  public void testExceptionOnSourceAndRetryFails() throws Exception {
    final AtomicReference<Connection> sourceConn = new AtomicReference<Connection>();
    HornetQJMSConnectionFactory failingSourceCF =
        new HornetQJMSConnectionFactory(false, new TransportConfiguration(INVM_CONNECTOR_FACTORY)) {
          private static final long serialVersionUID = 8216804886099984645L;
          boolean firstTime = true;

          @Override
          public Connection createConnection() throws JMSException {
            if (firstTime) {
              firstTime = false;
              sourceConn.set(super.createConnection());
              return sourceConn.get();
            } else {
              throw new JMSException("exception while retrying to connect");
            }
          }
        };
    // Note! We disable automatic reconnection on the session factory. The bridge needs to do the
    // reconnection
    failingSourceCF.setReconnectAttempts(0);
    failingSourceCF.setBlockOnNonDurableSend(true);
    failingSourceCF.setBlockOnDurableSend(true);

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(failingSourceCF);
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();
    Assert.assertNotNull(bridge);

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    bridge.setFailureRetryInterval(100);
    bridge.setMaxRetries(1);
    bridge.setMaxBatchSize(1);
    bridge.setMaxBatchTime(-1);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();
    Assert.assertTrue(bridge.isStarted());

    sourceConn
        .get()
        .getExceptionListener()
        .onException(new JMSException("exception on the source"));
    Thread.sleep(4 * bridge.getFailureRetryInterval());
    // reconnection must have failed
    Assert.assertFalse(bridge.isStarted());
  }
Exemple #15
0
  @Test
  public void testExceptionOnSourceAndRetrySucceeds() throws Exception {
    final AtomicReference<Connection> sourceConn = new AtomicReference<Connection>();
    HornetQJMSConnectionFactory failingSourceCF =
        new HornetQJMSConnectionFactory(
            false, new TransportConfiguration(InVMConnectorFactory.class.getName())) {
          private static final long serialVersionUID = -8866390811966688830L;

          @Override
          public Connection createConnection() throws JMSException {
            sourceConn.set(super.createConnection());
            return sourceConn.get();
          }
        };
    // Note! We disable automatic reconnection on the session factory. The bridge needs to do the
    // reconnection
    failingSourceCF.setReconnectAttempts(0);
    failingSourceCF.setBlockOnNonDurableSend(true);
    failingSourceCF.setBlockOnDurableSend(true);

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(failingSourceCF);
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();
    Assert.assertNotNull(bridge);

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    bridge.setFailureRetryInterval(10);
    bridge.setMaxRetries(2);
    bridge.setMaxBatchSize(1);
    bridge.setMaxBatchTime(-1);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();
    Assert.assertTrue(bridge.isStarted());

    sourceConn
        .get()
        .getExceptionListener()
        .onException(new JMSException("exception on the source"));
    Thread.sleep(4 * bridge.getFailureRetryInterval());
    // reconnection must have succeeded
    Assert.assertTrue(bridge.isStarted());

    bridge.stop();
    Assert.assertFalse(bridge.isStarted());
  }
Exemple #16
0
  @Test
  public void testSendMessagesWithMaxBatchSize() throws Exception {
    final int numMessages = 10;

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();
    Assert.assertNotNull(bridge);

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    bridge.setFailureRetryInterval(10);
    bridge.setMaxRetries(-1);
    bridge.setMaxBatchSize(numMessages);
    bridge.setMaxBatchTime(-1);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();
    Assert.assertTrue(bridge.isStarted());

    Connection targetConn = JMSBridgeImplTest.createConnectionFactory().createConnection();
    Session targetSess = targetConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = targetSess.createConsumer(targetDF.createDestination());
    final List<Message> messages = new LinkedList<Message>();
    final CountDownLatch latch = new CountDownLatch(numMessages);
    MessageListener listener =
        new MessageListener() {
          public void onMessage(final Message message) {
            messages.add(message);
            latch.countDown();
          }
        };
    consumer.setMessageListener(listener);
    targetConn.start();

    Connection sourceConn = JMSBridgeImplTest.createConnectionFactory().createConnection();
    Session sourceSess = sourceConn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = sourceSess.createProducer(sourceDF.createDestination());

    for (int i = 0; i < numMessages - 1; i++) {
      TextMessage msg = sourceSess.createTextMessage();
      producer.send(msg);
      JMSBridgeImplTest.log.info("sent message " + i);
    }

    Thread.sleep(1000);

    Assert.assertEquals(0, messages.size());

    TextMessage msg = sourceSess.createTextMessage();

    producer.send(msg);

    Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    sourceConn.close();

    Assert.assertEquals(numMessages, messages.size());

    bridge.stop();
    Assert.assertFalse(bridge.isStarted());

    targetConn.close();
  }
Exemple #17
0
  /*
   * we receive only 1 message. The message is sent when the maxBatchTime
   * expires even if the maxBatchSize is not reached
   */
  @Test
  public void testSendMessagesWhenMaxBatchTimeExpires() throws Exception {
    int maxBatchSize = 2;
    long maxBatchTime = 500;

    ConnectionFactoryFactory sourceCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    ConnectionFactoryFactory targetCFF =
        JMSBridgeImplTest.newConnectionFactoryFactory(JMSBridgeImplTest.createConnectionFactory());
    DestinationFactory sourceDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.SOURCE));
    DestinationFactory targetDF =
        JMSBridgeImplTest.newDestinationFactory(
            HornetQJMSClient.createQueue(JMSBridgeImplTest.TARGET));
    TransactionManager tm = JMSBridgeImplTest.newTransactionManager();

    JMSBridgeImpl bridge = new JMSBridgeImpl();
    Assert.assertNotNull(bridge);

    bridge.setSourceConnectionFactoryFactory(sourceCFF);
    bridge.setSourceDestinationFactory(sourceDF);
    bridge.setTargetConnectionFactoryFactory(targetCFF);
    bridge.setTargetDestinationFactory(targetDF);
    bridge.setFailureRetryInterval(10);
    bridge.setMaxRetries(-1);
    bridge.setMaxBatchSize(maxBatchSize);
    bridge.setMaxBatchTime(maxBatchTime);
    bridge.setTransactionManager(tm);
    bridge.setQualityOfServiceMode(QualityOfServiceMode.AT_MOST_ONCE);

    Assert.assertFalse(bridge.isStarted());
    bridge.start();
    Assert.assertTrue(bridge.isStarted());

    Connection targetConn = JMSBridgeImplTest.createConnectionFactory().createConnection();
    Session targetSess = targetConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = targetSess.createConsumer(targetDF.createDestination());
    final List<Message> messages = new LinkedList<Message>();
    MessageListener listener =
        new MessageListener() {

          public void onMessage(final Message message) {
            messages.add(message);
          }
        };
    consumer.setMessageListener(listener);
    targetConn.start();

    Connection sourceConn = JMSBridgeImplTest.createConnectionFactory().createConnection();
    Session sourceSess = sourceConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = sourceSess.createProducer(sourceDF.createDestination());
    producer.send(sourceSess.createTextMessage());
    sourceConn.close();

    Assert.assertEquals(0, messages.size());
    Thread.sleep(3 * maxBatchTime);

    Assert.assertEquals(1, messages.size());

    bridge.stop();
    Assert.assertFalse(bridge.isStarted());

    targetConn.close();
  }
  @Test
  public void testPagingOverCreatedDestinationQueues() throws Exception {

    Configuration config = createDefaultConfig();

    config.setJournalSyncNonTransactional(false);

    HornetQServer server =
        createServer(
            true,
            config,
            -1,
            -1,
            AddressFullMessagePolicy.BLOCK,
            new HashMap<String, AddressSettings>());

    JMSServerManagerImpl jmsServer = new JMSServerManagerImpl(server);
    InVMNamingContext context = new InVMNamingContext();
    jmsServer.setContext(context);
    jmsServer.start();

    server
        .getHornetQServerControl()
        .addAddressSettings(
            "jms.queue.Q1",
            "DLQ",
            "DLQ",
            -1,
            false,
            5,
            100 * 1024,
            10 * 1024,
            5,
            5,
            1,
            1000,
            0,
            false,
            "PAGE",
            -1,
            10,
            "KILL");

    jmsServer.createQueue(true, "Q1", null, true, "/queue/Q1");

    HornetQJMSConnectionFactory cf =
        (HornetQJMSConnectionFactory)
            HornetQJMSClient.createConnectionFactoryWithoutHA(
                JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));

    conn = cf.createConnection();
    conn.setClientID("tst");
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    javax.jms.Queue queue = (javax.jms.Queue) context.lookup("/queue/Q1");

    MessageProducer prod = sess.createProducer(queue);
    prod.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage bmt = sess.createBytesMessage();

    bmt.writeBytes(new byte[1024]);

    for (int i = 0; i < 500; i++) {
      prod.send(bmt);
    }

    PagingStore store = server.getPagingManager().getPageStore(new SimpleString("jms.queue.Q1"));

    assertEquals(100 * 1024, store.getMaxSize());
    assertEquals(10 * 1024, store.getPageSizeBytes());
    assertEquals(AddressFullMessagePolicy.PAGE, store.getAddressFullMessagePolicy());

    jmsServer.stop();

    server =
        createServer(
            true,
            config,
            -1,
            -1,
            AddressFullMessagePolicy.BLOCK,
            new HashMap<String, AddressSettings>());

    jmsServer = new JMSServerManagerImpl(server);
    context = new InVMNamingContext();
    jmsServer.setContext(context);
    jmsServer.start();

    AddressSettings settings = server.getAddressSettingsRepository().getMatch("jms.queue.Q1");

    assertEquals(100 * 1024, settings.getMaxSizeBytes());
    assertEquals(10 * 1024, settings.getPageSizeBytes());
    assertEquals(AddressFullMessagePolicy.PAGE, settings.getAddressFullMessagePolicy());

    store = server.getPagingManager().getPageStore(new SimpleString("jms.queue.Q1"));
    assertEquals(100 * 1024, store.getMaxSize());
    assertEquals(10 * 1024, store.getPageSizeBytes());
    assertEquals(AddressFullMessagePolicy.PAGE, store.getAddressFullMessagePolicy());
  }
  @Test
  public void testAutomaticFailover() throws Exception {
    HornetQConnectionFactory jbcf =
        HornetQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc);
    jbcf.setReconnectAttempts(-1);
    jbcf.setBlockOnDurableSend(true);
    jbcf.setBlockOnNonDurableSend(true);

    // Note we set consumer window size to a value so we can verify that consumer credit re-sending
    // works properly on failover
    // The value is small enough that credits will have to be resent several time

    final int numMessages = 10;

    final int bodySize = 1000;

    jbcf.setConsumerWindowSize(numMessages * bodySize / 10);

    HornetQConnection conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5);

    MyFailoverListener listener = new MyFailoverListener();

    conn.setFailoverListener(listener);

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ClientSession coreSession = ((HornetQSession) sess).getCoreSession();

    SimpleString jmsQueueName =
        new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + "myqueue");

    coreSession.createQueue(jmsQueueName, jmsQueueName, null, true);

    Queue queue = sess.createQueue("myqueue");

    MessageProducer producer = sess.createProducer(queue);

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    MessageConsumer consumer = sess.createConsumer(queue);

    byte[] body = RandomUtil.randomBytes(bodySize);

    for (int i = 0; i < numMessages; i++) {
      BytesMessage bm = sess.createBytesMessage();

      bm.writeBytes(body);

      producer.send(bm);
    }

    conn.start();

    JMSFailoverListenerTest.log.info("sent messages and started connection");

    Thread.sleep(2000);

    JMSUtil.crash(liveService, ((HornetQSession) sess).getCoreSession());

    Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.getEventTypeList().get(0));
    for (int i = 0; i < numMessages; i++) {
      JMSFailoverListenerTest.log.info("got message " + i);

      BytesMessage bm = (BytesMessage) consumer.receive(1000);

      Assert.assertNotNull(bm);

      Assert.assertEquals(body.length, bm.getBodyLength());
    }

    TextMessage tm = (TextMessage) consumer.receiveNoWait();

    Assert.assertNull(tm);
    Assert.assertEquals(FailoverEventType.FAILOVER_COMPLETED, listener.getEventTypeList().get(1));

    conn.close();
    Assert.assertEquals(
        "Expected 2 FailoverEvents to be triggered", 2, listener.getEventTypeList().size());
  }
  public void doTestStressSend(final boolean netty) throws Exception {
    // first set up the server
    Map<String, Object> params = new HashMap<String, Object>();
    params.put(TransportConstants.PORT_PROP_NAME, 5445);
    params.put(TransportConstants.HOST_PROP_NAME, "localhost");
    params.put(TransportConstants.USE_NIO_PROP_NAME, true);
    // minimize threads to maximize possibility for deadlock
    params.put(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, 1);
    params.put(TransportConstants.BATCH_DELAY, 50);
    Configuration config = createDefaultConfig(params, ServiceTestBase.NETTY_ACCEPTOR_FACTORY);
    HornetQServer server = createServer(true, config);
    server.getConfiguration().setThreadPoolMaxSize(2);
    server.start();

    // now the client side
    Map<String, Object> connectionParams = new HashMap<String, Object>();
    connectionParams.put(TransportConstants.PORT_PROP_NAME, 5445);
    connectionParams.put(TransportConstants.HOST_PROP_NAME, "localhost");
    connectionParams.put(TransportConstants.USE_NIO_PROP_NAME, true);
    connectionParams.put(TransportConstants.BATCH_DELAY, 50);
    connectionParams.put(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, 6);
    final TransportConfiguration transpConf =
        new TransportConfiguration(NettyConnectorFactory.class.getName(), connectionParams);
    final ServerLocator locator = createNonHALocator(netty);

    // each thread will do this number of transactions
    final int numberOfMessages = 100;

    // these must all be the same
    final int numProducers = 30;
    final int numConsumerProducers = 30;
    final int numConsumers = 30;

    // each produce, consume+produce and consume increments this counter
    final AtomicInteger totalCount = new AtomicInteger(0);

    // the total we expect if all producers, consumer-producers and
    // consumers complete normally
    int totalExpectedCount =
        (numProducers + numConsumerProducers + numConsumerProducers) * numberOfMessages;

    // each group gets a separate connection
    final Connection connectionProducer;
    final Connection connectionConsumerProducer;
    final Connection connectionConsumer;

    // create the 2 queues used in the test
    ClientSessionFactory sf = locator.createSessionFactory(transpConf);
    ClientSession session = sf.createTransactedSession();
    session.createQueue("jms.queue.queue", "jms.queue.queue");
    session.createQueue("jms.queue.queue2", "jms.queue.queue2");
    session.commit();
    sf.close();
    session.close();
    locator.close();

    // create and start JMS connections
    HornetQConnectionFactory cf =
        HornetQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.CF, transpConf);
    connectionProducer = cf.createConnection();
    connectionProducer.start();

    connectionConsumerProducer = cf.createConnection();
    connectionConsumerProducer.start();

    connectionConsumer = cf.createConnection();
    connectionConsumer.start();

    // these threads produce messages on the the first queue
    for (int i = 0; i < numProducers; i++) {
      new Thread() {
        @Override
        public void run() {

          Session session = null;
          try {
            session = connectionProducer.createSession(true, Session.SESSION_TRANSACTED);
            MessageProducer messageProducer =
                session.createProducer(HornetQDestination.createQueue("queue"));
            messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

            for (int i = 0; i < numberOfMessages; i++) {
              BytesMessage message = session.createBytesMessage();
              message.writeBytes(new byte[3000]);
              message.setStringProperty("Service", "LoadShedService");
              message.setStringProperty("Action", "testAction");

              messageProducer.send(message);
              session.commit();

              totalCount.incrementAndGet();
            }
          } catch (Exception e) {
            throw new RuntimeException(e);
          } finally {
            if (session != null) {
              try {
                session.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        }
      }.start();
    }

    // these threads just consume from the one and produce on a second queue
    for (int i = 0; i < numConsumerProducers; i++) {
      new Thread() {
        @Override
        public void run() {
          Session session = null;
          try {
            session = connectionConsumerProducer.createSession(true, Session.SESSION_TRANSACTED);
            MessageConsumer consumer =
                session.createConsumer(HornetQDestination.createQueue("queue"));
            MessageProducer messageProducer =
                session.createProducer(HornetQDestination.createQueue("queue2"));
            messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
            for (int i = 0; i < numberOfMessages; i++) {
              BytesMessage message = (BytesMessage) consumer.receive(5000);
              if (message == null) {
                return;
              }
              message = session.createBytesMessage();
              message.writeBytes(new byte[3000]);
              message.setStringProperty("Service", "LoadShedService");
              message.setStringProperty("Action", "testAction");
              messageProducer.send(message);
              session.commit();

              totalCount.incrementAndGet();
            }
          } catch (Exception e) {
            throw new RuntimeException(e);
          } finally {
            if (session != null) {
              try {
                session.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        }
      }.start();
    }

    // these threads consume from the second queue
    for (int i = 0; i < numConsumers; i++) {
      new Thread() {
        @Override
        public void run() {
          Session session = null;
          try {
            session = connectionConsumer.createSession(true, Session.SESSION_TRANSACTED);
            MessageConsumer consumer =
                session.createConsumer(HornetQDestination.createQueue("queue2"));
            for (int i = 0; i < numberOfMessages; i++) {
              BytesMessage message = (BytesMessage) consumer.receive(5000);
              if (message == null) {
                return;
              }
              session.commit();

              totalCount.incrementAndGet();
            }
          } catch (Exception e) {
            throw new RuntimeException(e);
          } finally {
            if (session != null) {
              try {
                session.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        }
      }.start();
    }

    // check that the overall transaction count reaches the expected number,
    // which would indicate that the system didn't stall
    int timeoutCounter = 0;
    int maxSecondsToWait = 60;
    while (timeoutCounter < maxSecondsToWait && totalCount.get() < totalExpectedCount) {
      timeoutCounter++;
      Thread.sleep(1000);
      System.out.println(
          "Not done yet.. " + (maxSecondsToWait - timeoutCounter) + "; " + totalCount.get());
    }
    System.out.println("Done.." + totalCount.get() + ", expected " + totalExpectedCount);
    Assert.assertEquals("Possible deadlock", totalExpectedCount, totalCount.get());
    System.out.println("After assert");

    // attempt cleaning up (this is not in a finally, still needs some work)
    connectionProducer.close();
    connectionConsumerProducer.close();
    connectionConsumer.close();

    server.stop();
  }
  @Test
  public void testManualFailover() throws Exception {
    HornetQConnectionFactory jbcfLive =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY));

    jbcfLive.setBlockOnNonDurableSend(true);
    jbcfLive.setBlockOnDurableSend(true);

    HornetQConnectionFactory jbcfBackup =
        HornetQJMSClient.createConnectionFactoryWithoutHA(
            JMSFactoryType.CF, new TransportConfiguration(INVM_CONNECTOR_FACTORY, backupParams));
    jbcfBackup.setBlockOnNonDurableSend(true);
    jbcfBackup.setBlockOnDurableSend(true);
    jbcfBackup.setInitialConnectAttempts(-1);
    jbcfBackup.setReconnectAttempts(-1);

    HornetQConnection connLive = (HornetQConnection) jbcfLive.createConnection();

    MyFailoverListener listener = new MyFailoverListener();

    connLive.setFailoverListener(listener);

    Session sessLive = connLive.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ClientSession coreSessionLive = ((HornetQSession) sessLive).getCoreSession();

    SimpleString jmsQueueName =
        new SimpleString(HornetQDestination.JMS_QUEUE_ADDRESS_PREFIX + "myqueue");

    coreSessionLive.createQueue(jmsQueueName, jmsQueueName, null, true);

    Queue queue = sessLive.createQueue("myqueue");

    final int numMessages = 1000;

    MessageProducer producerLive = sessLive.createProducer(queue);

    for (int i = 0; i < numMessages; i++) {
      TextMessage tm = sessLive.createTextMessage("message" + i);

      producerLive.send(tm);
    }

    // Note we block on P send to make sure all messages get to server before failover

    JMSUtil.crash(liveService, coreSessionLive);
    Assert.assertEquals(FailoverEventType.FAILURE_DETECTED, listener.getEventTypeList().get(0));
    connLive.close();

    // Now recreate on backup

    Connection connBackup = jbcfBackup.createConnection();

    Session sessBackup = connBackup.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageConsumer consumerBackup = sessBackup.createConsumer(queue);

    connBackup.start();

    for (int i = 0; i < numMessages; i++) {
      TextMessage tm = (TextMessage) consumerBackup.receive(1000);

      Assert.assertNotNull(tm);

      Assert.assertEquals("message" + i, tm.getText());
    }

    TextMessage tm = (TextMessage) consumerBackup.receiveNoWait();
    Assert.assertEquals(FailoverEventType.FAILOVER_FAILED, listener.getEventTypeList().get(1));
    Assert.assertEquals(
        "Expected 2 FailoverEvents to be triggered", 2, listener.getEventTypeList().size());
    Assert.assertNull(tm);

    connBackup.close();
  }