public void initConnection() throws Exception {
   ConnectionFactory connectionFactory =
       new ActiveMQConnectionFactory("vm://localhost?create=false");
   connection = (ActiveMQConnection) connectionFactory.createConnection();
   connection.setWatchTopicAdvisories(false);
   connection.start();
 }
  public void testNoScheduledRedeliveryOfExpired() throws Exception {
    startBroker(true);
    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    sendMessage(1500);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);

    // ensure there is another consumer to redispatch to
    MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination);

    // allow consumed to expire so it gets redelivered
    TimeUnit.SECONDS.sleep(2);
    consumer.close();

    // should go to dlq as it has expired
    // validate DLQ
    MessageConsumer dlqConsumer =
        consumerSession.createConsumer(
            new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
    Message dlqMessage = dlqConsumer.receive(2000);
    assertNotNull("Got message from dql", dlqMessage);
    assertEquals(
        "message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
  }
  @Test
  public void testReconnectMultipleTimesWithSameClientID() throws Exception {
    try {
      sameIdConnection = (ActiveMQConnection) this.factory.createConnection();
      useConnection(sameIdConnection);

      // now lets create another which should fail
      for (int i = 1; i < 11; i++) {
        Connection connection2 = this.factory.createConnection();
        try {
          useConnection(connection2);
          fail("Should have thrown InvalidClientIDException on attempt" + i);
        } catch (InvalidClientIDException e) {
          System.err.println("Caught expected: " + e);
        } finally {
          connection2.close();
        }
      }

      // now lets try closing the original connection and creating a new
      // connection with the same ID
      sameIdConnection.close();
      sameIdConnection = (ActiveMQConnection) factory.createConnection();
      useConnection(connection);
    } finally {
      if (sameIdConnection != null) {
        sameIdConnection.close();
      }
    }
  }
 @Test(expected = NoSuchElementException.class)
 public void testBorrowObject() throws Exception {
   ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
   pool.fillPool();
   assertNotNull(pool);
   ActiveMQConnection connection = (ActiveMQConnection) pool.borrowConnection();
   assertNotNull(connection);
   assertTrue(connection.isStarted());
   pool.borrowConnection();
 }
Example #5
0
  public void disconnect() throws JMSException {

    if (connection != null) {

      messageProducer.close();
      connection.stop();
      connection.close();
      System.out.println("disconnect");
    }
  }
 @Test
 public void testCreateObject() throws Exception {
   ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
   pool.fillPool();
   assertNotNull(pool);
   ActiveMQConnection connection = (ActiveMQConnection) pool.makeObject();
   assertNotNull(connection);
   assertTrue(connection.isStarted());
   pool.drainPool();
 }
 @Test
 public void testReturnObject() throws Exception {
   ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
   pool.fillPool();
   assertNotNull(pool);
   ActiveMQConnection connection = (ActiveMQConnection) pool.borrowConnection();
   assertNotNull(connection);
   assertTrue(connection.isStarted());
   pool.returnConnection(connection);
   ActiveMQConnection connection2 = (ActiveMQConnection) pool.borrowConnection();
   assertNotNull(connection2);
   pool.drainPool();
 }
 private void sendMessage(int timeToLive) throws Exception {
   ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection();
   producerConnection.start();
   Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = producerSession.createProducer(destination);
   if (timeToLive > 0) {
     producer.setTimeToLive(timeToLive);
   }
   Message message = producerSession.createMessage();
   message.setStringProperty("data", data);
   producer.send(message);
   producerConnection.close();
 }
  private Session getSession() throws Exception {
    if (connection == null) {
      init();
    }

    return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  }
 private void createAndStartConnection(String userName, String password, String url)
     throws JMSException {
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);
   connection = (ActiveMQConnection) connectionFactory.createConnection();
   connection.start();
   LOG.info("Connected successfully to {}", url);
 }
 private String receiveOne() throws Exception {
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   String received = receive(session);
   session.commit();
   session.close();
   return received;
 }
 private void enqueueOneMessage() throws Exception {
   Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
   MessageProducer producer = session.createProducer(destination);
   producer.send(session.createTextMessage("middle"));
   session.commit();
   session.close();
 }
  private void initializeWriting() throws JMSException {
    checkReadOnlyBody();
    if (this.dataOut == null) {
      this.bytesOut = new ByteArrayOutputStream();
      OutputStream os = bytesOut;
      ActiveMQConnection connection = getConnection();
      if (connection != null && connection.isUseCompression()) {
        // keep track of the real length of the content if
        // we are compressed.
        try {
          os.write(new byte[4]);
        } catch (IOException e) {
          throw JMSExceptionSupport.create(e);
        }
        length = 0;
        compressed = true;
        final Deflater deflater = new Deflater(Deflater.BEST_SPEED);
        os =
            new FilterOutputStream(new DeflaterOutputStream(os, deflater)) {
              @Override
              public void write(byte[] arg0) throws IOException {
                length += arg0.length;
                out.write(arg0);
              }

              @Override
              public void write(byte[] arg0, int arg1, int arg2) throws IOException {
                length += arg2;
                out.write(arg0, arg1, arg2);
              }

              @Override
              public void write(int arg0) throws IOException {
                length++;
                out.write(arg0);
              }

              @Override
              public void close() throws IOException {
                super.close();
                deflater.end();
              }
            };
      }
      this.dataOut = new DataOutputStream(os);
    }
  }
 @After
 public void tearDown() throws Exception {
   if (sameIdConnection != null) {
     sameIdConnection.close();
     sameIdConnection = null;
   }
   super.tearDown();
 }
 @After
 public void stopBroker() throws Exception {
   if (connection != null) {
     connection.close();
   }
   if (broker != null) {
     broker.stop();
   }
 }
Example #16
0
  public ADQueueWriterImpl() {
    try {
      properties = new Properties();
      properties.load(getClass().getClassLoader().getResourceAsStream("bril.properties"));

      propertiesXML = new Properties();
      propertiesXML.load(getClass().getClassLoader().getResourceAsStream("messagexml.properties"));

      // messaging.url.server for bril-dev server , messaging.url for localhost
      String brokerURL =
          properties.getProperty("messaging.url") + ":" + properties.getProperty("messaging.port");
      System.out.println(brokerURL);
      // String blobUploadURL="?jms.blobTransferPolicy.uploadUrl=http//:localhost:8161/fileserver";
      factory = new ActiveMQConnectionFactory(brokerURL);

      // using the connection factory create JMS connection
      connection = (ActiveMQConnection) factory.createConnection();

      // connection.setBlobTransferPolicy(blobTransferPolicy);

      // start the connection to enable messages to start flowing
      connection.start();

      // JMS session: auto acknowledge
      session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // producer = session.createProducer(null);
      // must be a message queue

      // create JMS queue using the session
      autoDepositQueue = session.createQueue(properties.getProperty("queue.submit.name"));

      // create JMS consumer using the session and destination
      messageProducer = session.createProducer(autoDepositQueue);
      // OutputStream out = connection.createOutputStream(autoDepositQueue);

    } catch (IOException e) {
      System.out.println("IOException : properties file not found  " + e);
    } catch (JMSException e) {
      System.out.println("JMSException :   " + e);
    }
  }
 @Override
 public void init() {
   try {
     createAndStartConnection("", "", brokerUrl);
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     destination = session.createQueue(destinationName);
     producer = session.createProducer(destination);
     consumer = session.createConsumer(destination);
     LOG.info("Initialized Queue on ActiveMQ: {}", destinationName);
   } catch (Exception e) {
     LOG.error("Error starting ActiveMQ connection for delayed queue", e);
     throw new RuntimeException("Error starting ActiveMQ connection for delayed queue", e);
   }
 }
Example #18
0
  /**
   * Get the current connection or create one using the connectionSupplier.
   *
   * @return JMS Connection
   */
  private Connection getConnection() {

    if (!connectionOption.isPresent()) {
      Connection connection = connectionSupplier.get();

      if (connection instanceof ActiveMQConnection) {
        ((ActiveMQConnection) connection)
            .addTransportListener(
                new TransportListener() {
                  @Override
                  public void onCommand(Object command) {}

                  @Override
                  public void onException(IOException error) {}

                  @Override
                  public void transportInterupted() {
                    connected.set(false);
                  }

                  @Override
                  public void transportResumed() {
                    connected.set(true);
                  }
                });
      }

      connected.set(true);

      if (startConnection) {
        try {
          connection.start();
        } catch (JMSException e) {
          throw new IllegalStateException("Unable to start JMS connection", e);
        }
      }
      connectionOption = Optional.of(connection);
    }
    return connectionOption.get();
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testPrefetchZeroConsumerThroughRestart() throws Exception {
    broker = createBroker(true);

    final CountDownLatch pullDone = new CountDownLatch(1);
    broker.setPlugins(
        new BrokerPlugin[] {
          new BrokerPluginSupport() {
            @Override
            public Response messagePull(ConnectionContext context, final MessagePull pull)
                throws Exception {
              context.setDontSendReponse(true);
              pullDone.countDown();
              Executors.newSingleThreadExecutor()
                  .execute(
                      new Runnable() {
                        @Override
                        public void run() {
                          LOG.info("Stopping broker on pull: " + pull);
                          try {
                            broker.stop();
                          } catch (Exception e) {
                            e.printStackTrace();
                          }
                        }
                      });
              return null;
            }
          }
        });
    broker.start();

    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(false);

    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();

    final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination =
        consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);

    final MessageConsumer consumer = consumerSession.createConsumer(destination);
    produceMessage(consumerSession, destination, 1);

    final CountDownLatch receiveDone = new CountDownLatch(1);
    final Vector<Message> received = new Vector<>();
    Executors.newSingleThreadExecutor()
        .execute(
            new Runnable() {
              @Override
              public void run() {
                try {
                  LOG.info("receive one...");
                  Message msg = consumer.receive(30000);
                  if (msg != null) {
                    received.add(msg);
                  }
                  receiveDone.countDown();
                  LOG.info("done receive");
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });

    // will be stopped by the plugin
    assertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS));
    broker.waitUntilStopped();
    broker = createBroker(false, url);
    broker.start();

    assertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS));

    assertTrue("we got our message:", !received.isEmpty());

    connection.close();
  }
  @Test
  public void validateUnorderedTxCommit() throws Exception {

    Executor executor = Executors.newCachedThreadPool();
    CountDownLatch readyForCommit = new CountDownLatch(2);
    CountDownLatch firstDone = new CountDownLatch(1);

    TransactedSend first = new TransactedSend(readyForCommit, firstDone, true);
    TransactedSend second = new TransactedSend(readyForCommit, firstDone, false);
    executor.execute(first);
    executor.execute(second);

    assertTrue("both started", readyForCommit.await(20, TimeUnit.SECONDS));

    LOG.info("commit out of order");
    // send interleaved so sequence id at time of commit could be reversed
    second.commit();

    // force usage over the limit before second commit to flush cache
    enqueueOneMessage();

    // can get lost in the cursor as it is behind the last sequenceId that was cached
    first.commit();

    LOG.info("send/commit done..");

    dumpMessages();

    String received1, received2, received3 = null;
    if (true) {
      LOG.info("receive and rollback...");
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      received1 = receive(session);
      received2 = receive(session);
      received3 = receive(session);

      assertEquals("second", received1);
      assertEquals("middle", received2);
      assertEquals("first", received3);

      session.rollback();
      session.close();
    }

    LOG.info("restart broker");
    stopBroker();
    broker = createRestartedBroker();
    initConnection();

    if (true) {
      LOG.info("receive and rollback after restart...");
      Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
      received1 = receive(session);
      received2 = receive(session);
      received3 = receive(session);
      assertEquals("second", received1);
      assertEquals("middle", received2);
      assertEquals("first", received3);
      session.rollback();
      session.close();
    }

    LOG.info("receive and ack each message");
    received1 = receiveOne();
    received2 = receiveOne();
    received3 = receiveOne();

    assertEquals("second", received1);
    assertEquals("middle", received2);
    assertEquals("first", received3);
  }
  public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ)
      throws Exception {

    startBroker(true);
    sendMessage(0);

    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
    redeliveryPolicy.setInitialRedeliveryDelay(0);
    redeliveryPolicy.setMaximumRedeliveries(0);
    consumerConnection.setRedeliveryPolicy(redeliveryPolicy);
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);
    LOG.info("got: " + message);
    consumerSession.rollback();

    for (int i = 0; i < maxBrokerRedeliveriesToValidate; i++) {
      Message shouldBeNull = consumer.receive(500);
      assertNull(
          "did not get message after redelivery count exceeded: " + shouldBeNull, shouldBeNull);

      TimeUnit.SECONDS.sleep(4);

      Message brokerRedeliveryMessage = consumer.receive(1500);
      LOG.info("got: " + brokerRedeliveryMessage);
      assertNotNull("got message via broker redelivery after delay", brokerRedeliveryMessage);
      assertEquals(
          "message matches",
          message.getStringProperty("data"),
          brokerRedeliveryMessage.getStringProperty("data"));
      assertEquals(
          "has expiryDelay specified - iteration:" + i,
          i == 0 ? initialRedeliveryDelayMillis : redeliveryDelayMillis,
          brokerRedeliveryMessage.getLongProperty(RedeliveryPlugin.REDELIVERY_DELAY));

      consumerSession.rollback();
    }

    if (validateDLQ) {
      MessageConsumer dlqConsumer =
          consumerSession.createConsumer(
              new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
      Message dlqMessage = dlqConsumer.receive(2000);
      assertNotNull("Got message from dql", dlqMessage);
      assertEquals(
          "message matches",
          message.getStringProperty("data"),
          dlqMessage.getStringProperty("data"));
      consumerSession.commit();
    } else {
      // consume/commit ok
      message = consumer.receive(3000);
      assertNotNull("got message", message);
      assertEquals(
          "redeliveries accounted for",
          maxBrokerRedeliveriesToValidate + 2,
          message.getLongProperty("JMSXDeliveryCount"));
      consumerSession.commit();
    }

    consumerConnection.close();
  }
  @Test
  public void testOnMessage() {
    try {
      BrokerService broker = new BrokerService();
      try {
        broker.addConnector(Constants.ACTIVEMQ_URL);
        broker.setPersistent(false);
        broker.start();
      } catch (Exception e1) {
        System.out.println("BROKER ERROR");
      }
      // ** connection start **
      connection = ActiveMQConnection.makeConnection(Constants.ACTIVEMQ_URL);
      connection.start();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destQueue = session.createQueue(Constants.QUEUENAME);
      producer = session.createProducer(destQueue);

      ChatClient client = new ChatClient(producer, session);

      // this is used to capture output
      PrintStream commandLine = System.out;
      final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
      System.setOut(new PrintStream(myOut));

      client.onMessage(session.createTextMessage("" + Constants.LOGIN_FAIL));
      String output = myOut.toString();
      // correct new line for current platform
      String separator = System.getProperty("line.separator");
      assertTrue(output.equals("Login Failed" + separator + "Login: "******"user name");
      output = myOut.toString();
      assertTrue(output.equals("No spaces allowed in username" + separator + "Login: "******"bob");
      output = myOut.toString();
      assertTrue(output.equals("Password: "******"cheese");
      client.onMessage(session.createTextMessage("" + Constants.LOGIN_SUCCESS));
      output = myOut.toString();
      assertTrue(output.equals("Logged In!\n"));
      myOut.reset();

      // Give the client a server message
      client.onMessage(session.createTextMessage(Constants.SERVER_MESSAGE + "Print this"));
      output = myOut.toString();
      assertTrue(output.equals("Print this" + separator));
      myOut.reset();
      /*System.setOut(commandLine);
      System.out.println(output);*/
    } catch (Exception e) {
      // should not fail
      e.printStackTrace();
      fail();
    }
  }