/** Make sure redelivered flag is set on redelivery via rollback */
  @Test
  public void testRedeliveredQueue() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session sess = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageProducer producer = sess.createProducer(queue1);

      MessageConsumer consumer = sess.createConsumer(queue1);
      conn.start();

      Message mSent = sess.createTextMessage("igloo");
      producer.send(mSent);

      sess.commit();

      TextMessage mRec = (TextMessage) consumer.receive(2000);
      ProxyAssertSupport.assertEquals("igloo", mRec.getText());
      ProxyAssertSupport.assertFalse(mRec.getJMSRedelivered());

      sess.rollback();
      mRec = (TextMessage) consumer.receive(2000);
      ProxyAssertSupport.assertEquals("igloo", mRec.getText());
      ProxyAssertSupport.assertTrue(mRec.getJMSRedelivered());

      sess.commit();
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
Example #2
0
  public void testSendMessageWithCustomHeadersAndSelector() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'");

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SEND\n"
            + "foo:abc\n"
            + "bar:123\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n\n"
            + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    Assert.assertEquals("foo", "abc", message.getStringProperty("foo"));
    Assert.assertEquals("bar", "123", message.getStringProperty("bar"));
  }
Example #3
0
  public void testSubscribeWithAutoAck() throws Exception {

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(100000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SUBSCRIBE\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n"
            + "ack:auto\n\nfff"
            + Stomp.NULL;
    sendFrame(frame);

    sendMessage(getName());

    frame = receiveFrame(10000);
    System.out.println("-------- frame received: " + frame);
    Assert.assertTrue(frame.startsWith("MESSAGE"));
    Assert.assertTrue(frame.indexOf("destination:") > 0);
    Assert.assertTrue(frame.indexOf(getName()) > 0);

    frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    // message should not be received as it was auto-acked
    MessageConsumer consumer = session.createConsumer(queue);
    Message message = consumer.receive(1000);
    Assert.assertNull(message);
  }
  public void testDestinationStats() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    MessageProducer producer = session.createProducer(null);
    Queue query =
        session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName());
    Message msg = session.createMessage();

    producer.send(testQueue, msg);

    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
    /*
    for (Enumeration e = reply.getMapNames();e.hasMoreElements();) {
        String name = e.nextElement().toString();
        System.err.println(name+"="+reply.getObject(name));
    }
    */
  }
Example #5
0
  public void testSendMessageWithReceipt() throws Exception {
    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SEND\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n"
            + "receipt: 1234\n\n"
            + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    String f = receiveFrame(10000);
    Assert.assertTrue(f.startsWith("RECEIPT"));
    Assert.assertTrue(f.indexOf("receipt-id:1234") >= 0);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());

    // Make sure that the timestamp is valid - should
    // be very close to the current time.
    long tnow = System.currentTimeMillis();
    long tmsg = message.getJMSTimestamp();
    Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);
  }
Example #6
0
  public static void main(String[] args) throws JMSException {
    // Getting JMS connection from the server
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Creating session for seding messages
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Getting the queue 'JMSBEGINQUEUE'
    Destination destination = session.createQueue(subject);

    // MessageConsumer is used for receiving (consuming) messages
    MessageConsumer consumer = session.createConsumer(destination);

    // Here we receive the message.
    // By default this call is blocking, which means it will wait
    // for a message to arrive on the queue.
    Message message = consumer.receive();

    // There are many types of Message and TextMessage
    // is just one of them. Producer sent us a TextMessage
    // so we must cast to it to get access to its .getText()
    // method.
    if (message instanceof TextMessage) {
      TextMessage textMessage = (TextMessage) message;
      System.out.println("Received message '" + textMessage.getText() + "'");
    }
    connection.close();
  }
  /**
   * Test to check if consumer thread wakes up inside a receive(timeout) after a message is
   * dispatched to the consumer
   *
   * @throws javax.jms.JMSException
   */
  @Test(timeout = 30000)
  public void testConsumerReceiveBeforeMessageDispatched() throws JMSException {

    connection.start();

    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue queue = session.createQueue("test");

    Thread t =
        new Thread() {
          @Override
          public void run() {
            try {
              // wait for 10 seconds to allow consumer.receive to be run
              // first
              Thread.sleep(10000);
              MessageProducer producer = session.createProducer(queue);
              producer.send(session.createTextMessage("Hello"));
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    t.start();

    // Consume the message...
    MessageConsumer consumer = session.createConsumer(queue);
    Message msg = consumer.receive(60000);
    assertNotNull(msg);
    session.close();
  }
Example #8
0
  public static void main(String[] args) throws JMSException {
    AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer();

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    Connection connection = connectionFactory.createConnection();
    connection.start();

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

    Destination destination = session.createQueue(subject);

    MessageConsumer consumer = session.createConsumer(destination);

    consumer.setMessageListener(asyncConsumer);
    connection.setExceptionListener(asyncConsumer);

    try {
      while (true) {
        if (AsyncSimpleConsumer.catchExit) {
          break;
        }
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Sleep interrupted");
    }
    connection.close();
  }
  public static void consumeTopic() throws Exception {

    ActiveMQConnectionFactory connectionFactory =
        new ActiveMQConnectionFactory(
            ActiveMQConnectionFactory.DEFAULT_USER,
            ActiveMQConnectionFactory.DEFAULT_PASSWORD,
            ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.setClientID(clientID);
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(topicName);
    MessageConsumer consumer = session.createDurableSubscriber(topic, topicName);
    consumer.setMessageListener(
        new MessageListener() {
          public void onMessage(Message message) {

            TextMessage m = (TextMessage) message;
            try {
              System.out.println(m.getText());
            } catch (JMSException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        });
    connection.start();
  }
Example #10
0
 public Message receive(Scenario scenario) throws Exception {
   Connection connection = null;
   try {
     ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl());
     connection = factory.createConnection();
     connection.start();
     Session session = null;
     try {
       session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
       ActiveMQQueue destination = new ActiveMQQueue(scenario.getOutputQueue());
       MessageConsumer consumer = null;
       try {
         consumer = session.createConsumer(destination);
         return scenario.receive(session, consumer);
       } finally {
         if (consumer != null) {
           consumer.close();
         }
       }
     } finally {
       if (session != null) {
         session.close();
       }
     }
   } finally {
     if (connection != null) {
       connection.close();
     }
   }
 }
  public void init(
      Connection connection,
      String queue,
      boolean isTopic,
      MessageListener mlisten,
      boolean isActive) {
    try {
      // Session: 一个发送或接收消息的线程
      session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
      if (isTopic) {
        destination = session.createTopic(queue);
      } else {
        destination = session.createQueue(queue);
      }

      consumer = session.createConsumer(destination);
      if (isActive) {
        System.out.println(queue);
        LogSys.nodeLogger.info("创建一个主动方式获取消息的Receiver:" + queue);
      } else {
        if (mlisten == null) consumer.setMessageListener(this);
        else consumer.setMessageListener(mlisten);
      }
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #12
0
  public void testReceiveThenUseMessageListener() throws Exception {
    _logger.error("Test disabled as initial receive is not called first");
    // Perform initial receive to start connection
    assertTrue(_consumer.receive(2000) != null);
    _receivedCount++;

    // Sleep to ensure remaining 4 msgs end up on _synchronousQueue
    Thread.sleep(1000);

    // Set the message listener and wait for the messages to come in.
    _consumer.setMessageListener(this);

    _logger.info("Waiting 3 seconds for messages");

    try {
      _awaitMessages.await(3000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // do nothing
    }
    // Should have received all async messages
    assertEquals(MSG_COUNT, _receivedCount);

    _clientConnection.close();

    Connection conn = getConnection("guest", "guest");
    Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = clientSession.createQueue("message-listener-test-queue");
    MessageConsumer cons = clientSession.createConsumer(queue);
    conn.start();

    // check that the messages were actually dequeued
    assertTrue(cons.receive(2000) == null);
  }
  public void testPrefetchValueOne() throws Exception {

    ActiveMQTopic consumerDestination = new ActiveMQTopic(TOPIC_NAME + "?consumer.prefetchSize=1");
    consumer = session.createConsumer(consumerDestination);

    // add a consumer to the slow consumer advisory topic.
    ActiveMQTopic slowConsumerAdvisoryTopic =
        AdvisorySupport.getSlowConsumerAdvisoryTopic(destination);
    MessageConsumer slowConsumerAdvisory = session.createConsumer(slowConsumerAdvisoryTopic);

    // publish 2 messages
    Message txtMessage = session.createTextMessage("Sample Text Message");
    for (int i = 0; i < 2; i++) {
      producer.send(txtMessage);
    }

    // consume 2 messages
    for (int i = 0; i < 2; i++) {
      Message receivedMsg = consumer.receive(100);
      Assert.assertNotNull("received msg " + i + " should not be null", receivedMsg);
    }

    // check for "slow consumer" advisory message
    Message slowAdvisoryMessage = slowConsumerAdvisory.receive(100);
    Assert.assertNull(
        "should not have received a slow consumer advisory message", slowAdvisoryMessage);
  }
  @Test
  public void testSendRollbackQueue() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = producerSess.createProducer(queue1);

      Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageConsumer consumer = consumerSess.createConsumer(queue1);
      conn.start();

      final int NUM_MESSAGES = 10;

      // Send some messages
      for (int i = 0; i < NUM_MESSAGES; i++) {
        Message m = producerSess.createMessage();
        producer.send(m);
      }

      producerSess.rollback();

      Message m = consumer.receive(500);

      ProxyAssertSupport.assertNull(m);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
Example #15
0
  /**
   * Receive a message from destination with timeout.
   *
   * @param destinationName destinationName
   * @param timeout timeout
   * @return message
   */
  public String receiveTextMessageFromDestinationWithTimeout(
      final String destinationName, final int timeout) {

    if (!this.isConnected()) {
      throw new JmsNotConnectedException("Not connected");
    }
    MessageConsumer consumer = getConsumer(destinationName);
    TextMessage message;
    try {
      if (timeout == 0) {
        message = (TextMessage) consumer.receiveNoWait();
      } else {
        message = (TextMessage) consumer.receive(timeout);
      }
      if (message != null) {

        if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
          message.acknowledge();
        }
        return message.getText();
      } else {
        return null;
      }
    } catch (JMSException e) {
      throw new IllegalStateException("Unable to receive message from " + destinationName, e);
    }
  }
  @Test
  public void testSendReceiveMessage() throws Exception {
    Connection conn = createConnection();

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

    MessageProducer prod = sess.createProducer(queue1);

    // Make persistent to make sure message gets serialized
    prod.setDeliveryMode(DeliveryMode.PERSISTENT);

    MessageConsumer cons = sess.createConsumer(queue1);

    TestMessage tm = new TestMessage(123, false);

    ObjectMessage om = sess.createObjectMessage();

    om.setObject(tm);

    conn.start();

    prod.send(om);

    ObjectMessage om2 = (ObjectMessage) cons.receive(1000);

    ProxyAssertSupport.assertNotNull(om2);

    TestMessage tm2 = (TestMessage) om2.getObject();

    ProxyAssertSupport.assertEquals(123, tm2.getID());

    conn.close();
  }
  /**
   * Check a session is rollbacked on a Session close();
   *
   * @throws Exception
   */
  public void xtestTransactionRollbackOnSessionClose() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = null;
    if (topic) {
      consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED");
    } else {
      consumer = consumerSession.createConsumer(destination);
    }
    Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);

    TextMessage sentMsg = producerSession.createTextMessage();
    sentMsg.setText("msg1");
    producer.send(sentMsg);

    producerSession.commit();

    Message recMsg = consumer.receive(RECEIVE_TIMEOUT);
    assertFalse(recMsg.getJMSRedelivered());
    consumerSession.close();
    consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    consumer = consumerSession.createConsumer(destination);

    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    consumerSession.commit();
    assertTrue(recMsg.equals(sentMsg));
    connection.close();
  }
Example #18
0
  @Test
  public void testCompositeDestConsumer() throws Exception {

    final int numDests = 20;
    final int numMessages = 200;
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < numDests; i++) {
      if (stringBuffer.length() != 0) {
        stringBuffer.append(',');
      }
      stringBuffer.append("ST." + i);
    }
    stringBuffer.append("?consumer.prefetchSize=100");
    ActiveMQQueue activeMQQueue = new ActiveMQQueue(stringBuffer.toString());
    ConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI());
    Connection connection = factory.createConnection();
    connection.start();
    MessageProducer producer =
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(activeMQQueue);
    for (int i = 0; i < numMessages; i++) {
      producer.send(new ActiveMQTextMessage());
    }

    MessageConsumer consumer =
        connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(activeMQQueue);
    try {
      for (int i = 0; i < numMessages * numDests; i++) {
        assertNotNull("recieved:" + i, consumer.receive(4000));
      }
    } finally {
      connection.close();
    }
  }
  /**
   * check if receive(timeout) does timeout when prefetch=0 and redeliveries=0
   *
   * <p>send a message. consume and rollback to ensure redeliverCount is incremented try to consume
   * message with a timeout.
   */
  @Test(timeout = 20000)
  public void testConsumerReceivePrefetchZeroRedeliveryZero() throws Exception {

    connection.start();

    // push message to queue
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("test.prefetch.zero");
    MessageProducer producer = session.createProducer(queue);
    TextMessage textMessage = session.createTextMessage("test Message");
    producer.send(textMessage);
    session.close();

    // consume and rollback - increase redelivery counter on message
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    MessageConsumer consumer = session.createConsumer(queue);
    Message message = consumer.receive(2000);
    assertNotNull(message);
    session.rollback();
    session.close();

    // Reconnect with zero prefetch and zero redeliveries allowed.
    connection.close();
    connection = createConnection();
    connection.getPrefetchPolicy().setQueuePrefetch(0);
    connection.getRedeliveryPolicy().setMaximumRedeliveries(0);
    connection.start();

    // try consume with timeout - expect it to timeout and return NULL message
    session = connection.createSession(true, Session.SESSION_TRANSACTED);
    consumer = session.createConsumer(queue);
    message = consumer.receive(3000);

    assertNull(message);
  }
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory connFactory = lookup("ConnectionFactory", ConnectionFactory.class);
    Connection conn = connFactory.createConnection();
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TemporaryQueue replyQueue = session.createTemporaryQueue();
    TextMessage msg = session.createTextMessage("Hello world");
    msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
    msg.setJMSReplyTo(replyQueue);
    Queue queue = lookup("java:jboss/" + queueName, Queue.class);
    MessageProducer producer = session.createProducer(queue);
    producer.send(msg);
    MessageConsumer consumer = session.createConsumer(replyQueue);
    Message replyMsg = consumer.receive(5000);
    Assert.assertNotNull(replyMsg);
    if (replyMsg instanceof ObjectMessage) {
      Exception e = (Exception) ((ObjectMessage) replyMsg).getObject();
      throw e;
    }
    Assert.assertTrue(replyMsg instanceof TextMessage);
    String actual = ((TextMessage) replyMsg).getText();
    Assert.assertEquals("SUCCESS", actual);

    consumer.close();
    producer.close();
    session.close();
    conn.stop();
  }
  public void testBrokerStatsReset() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue replyTo = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(replyTo);
    Queue testQueue = session.createQueue("Test.Queue");
    Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX);
    MessageProducer producer = session.createProducer(null);

    producer.send(testQueue, session.createMessage());

    Message msg = session.createMessage();
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    MapMessage reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertTrue(reply.getLong("enqueueCount") >= 1);

    msg = session.createMessage();
    msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true);
    msg.setJMSReplyTo(replyTo);
    producer.send(query, msg);
    reply = (MapMessage) consumer.receive(10 * 1000);
    assertNotNull(reply);
    assertTrue(reply.getMapNames().hasMoreElements());
    assertEquals(0, reply.getLong("enqueueCount"));
    assertTrue(reply.getJMSTimestamp() > 0);
    assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority());
  }
  private void doTestIdleConsumer(boolean transacted) throws Exception {
    Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage("Msg1"));
    producer.send(session.createTextMessage("Msg2"));
    if (transacted) {
      session.commit();
    }
    // now lets receive it
    MessageConsumer consumer = session.createConsumer(queue);

    session.createConsumer(queue);
    TextMessage answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg1");
    if (transacted) {
      session.commit();
    }
    // this call would return null if prefetchSize > 0
    answer = (TextMessage) consumer.receive(5000);
    assertEquals("Should have received a message!", answer.getText(), "Msg2");
    if (transacted) {
      session.commit();
    }
    answer = (TextMessage) consumer.receiveNoWait();
    assertNull("Should have not received a message!", answer);
  }
Example #23
0
  public void testSendMessage() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SEND\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n\n"
            + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    // Assert default priority 4 is used when priority header is not set
    Assert.assertEquals("getJMSPriority", 4, message.getJMSPriority());

    // Make sure that the timestamp is valid - should
    // be very close to the current time.
    long tnow = System.currentTimeMillis();
    long tmsg = message.getJMSTimestamp();
    Assert.assertTrue(Math.abs(tnow - tmsg) < 1000);
  }
  // JMSCommunicationThread
  @Override
  protected void createProducersAndConsumers() throws Exception {
    final String configuration = model.getConfigurationName();
    // Write (if allowed) and also read the client topic
    if (model.isWriteAllowed())
      client_producer = createProducer(Preferences.getJMS_AlarmClientTopic(configuration));
    else client_producer = null;
    client_consumer = createConsumer(Preferences.getJMS_AlarmClientTopic(configuration));
    // Read messages from server
    server_consumer = createConsumer(Preferences.getJMS_AlarmServerTopic(configuration));

    // Handle MapMessages
    final MessageListener message_listener =
        new MessageListener() {
          @Override
          public void onMessage(final Message message) {
            if (message instanceof MapMessage) handleMapMessage((MapMessage) message);
            else
              Activator.getLogger()
                  .log(Level.WARNING, "Message type {0} not handled", message.getClass().getName());
          }
        };
    client_consumer.setMessageListener(message_listener);
    server_consumer.setMessageListener(message_listener);
  }
Example #25
0
  public void testJMSXGroupIdCanBeSet() throws Exception {

    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SEND\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n"
            + "JMSXGroupID: TEST\n\n"
            + "Hello World"
            + Stomp.NULL;

    sendFrame(frame);

    TextMessage message = (TextMessage) consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertEquals("Hello World", message.getText());
    // differ from StompConnect
    Assert.assertEquals("TEST", message.getStringProperty("JMSXGroupID"));
  }
  public Mail receiveMail() {
    ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
    Destination destination = new ActiveMQQueue("mail.queue");
    Connection conn = null;
    try {
      conn = cf.createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);

      conn.start();
      MapMessage message = (MapMessage) consumer.receive();
      Mail mail = new Mail();
      mail.setFrom(message.getString("from"));
      mail.setTo(message.getString("to"));
      mail.setSubject(message.getString("subject"));
      mail.setContent(message.getString("content"));
      mail.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getString("date")));
      session.close();
      return mail;
    } catch (JMSException e) {
      throw new RuntimeException(e);
    } catch (ParseException e) {
      throw new RuntimeException(e);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (JMSException e) {

        }
      }
    }
  }
Example #27
0
  public void testSendManyMessages() throws Exception {
    MessageConsumer consumer = session.createConsumer(queue);

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);
    frame = receiveFrame(10000);

    Assert.assertTrue(frame.startsWith("CONNECTED"));
    int count = 1000;
    final CountDownLatch latch = new CountDownLatch(count);
    consumer.setMessageListener(
        new MessageListener() {

          public void onMessage(Message arg0) {
            latch.countDown();
          }
        });

    frame =
        "SEND\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n\n"
            + "Hello World"
            + Stomp.NULL;
    for (int i = 1; i <= count; i++) {
      // Thread.sleep(1);
      // System.out.println(">>> " + i);
      sendFrame(frame);
    }

    assertTrue(latch.await(60, TimeUnit.SECONDS));
  }
Example #28
0
  /**
   * Listen to a message from JMS from a given destination by name.
   *
   * @param destinationName destinationName
   * @param messageListener messageListener
   */
  public void listenTextMessagesWithDestination(
      final String destinationName, final Consumer<String> messageListener) {
    final MessageConsumer consumer = getConsumer(destinationName);
    try {
      consumer.setMessageListener(
          message -> {
            try {
              messageListener.accept(((TextMessage) message).getText());

              if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
                message.acknowledge();
              }

            } catch (JMSException e) {

              throw new IllegalStateException(
                  "Unable to register get text from message in listener " + destinationName, e);
            } catch (Exception ex) {

              throw new IllegalStateException("Unable handle JMS Consumer  " + destinationName, ex);
            }
          });
    } catch (JMSException e) {

      throw new IllegalStateException("Unable to register message listener " + destinationName, e);
    }
  }
Example #29
0
  public void testRedeliveryWithClientAck() throws Exception {

    String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL;
    sendFrame(frame);

    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("CONNECTED"));

    frame =
        "SUBSCRIBE\n"
            + "destination:"
            + getQueuePrefix()
            + getQueueName()
            + "\n"
            + "ack:client\n\n"
            + Stomp.NULL;

    sendFrame(frame);

    sendMessage(getName());
    frame = receiveFrame(10000);
    Assert.assertTrue(frame.startsWith("MESSAGE"));

    frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL;
    sendFrame(frame);

    // message should be received since message was not acknowledged
    MessageConsumer consumer = session.createConsumer(queue);
    Message message = consumer.receive(1000);
    Assert.assertNotNull(message);
    Assert.assertTrue(message.getJMSRedelivered());
  }
  /**
   * Send some messages in transacted session. Don't commit. Verify message are not received by
   * consumer.
   */
  @Test
  public void testSendNoCommitTopic() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

      Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED);
      MessageProducer producer = producerSess.createProducer(ActiveMQServerTestCase.topic1);

      Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
      MessageConsumer consumer = consumerSess.createConsumer(ActiveMQServerTestCase.topic1);
      conn.start();

      final int NUM_MESSAGES = 10;

      // Send some messages
      for (int i = 0; i < NUM_MESSAGES; i++) {
        Message m = producerSess.createMessage();
        producer.send(m);
      }

      Message m = consumer.receive(500);
      ProxyAssertSupport.assertNull(m);
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }