@Override
    public void onMessage(Message message) {
      try {
        if (message instanceof TextMessage) {
          TextMessage textMessage = (TextMessage) message;
          String text = textMessage.getText();

          if ("SHUTDOWN".equals(text)) {
            LOG.info("Got the SHUTDOWN command -> exit");
            producer.send(session.createTextMessage("SHUTDOWN is being performed"));
          } else if ("REPORT".equals(text)) {
            long time = System.currentTimeMillis() - start;
            producer.send(session.createTextMessage("Received " + count + " in " + time + "ms"));
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
              LOG.info("Wait for the report message to be sent was interrupted");
            }
            count = 0;
          } else {
            if (count == 0) {
              start = System.currentTimeMillis();
            }

            count++;
            LOG.info("Received " + count + " messages.");
          }
        }

      } catch (JMSException e) {
        LOG.error("Got an JMS Exception handling message: " + message, e);
      }
    }
  @Test
  public void testJmsDestination() throws Exception {
    ClientSession session = basicSetUp();

    jmsServer.createQueue(
        true, "myQueue", null, true, "myQueueJndiBinding1", "myQueueJndiBinding2");
    jmsServer.createTopic(true, "myTopic", "myTopicJndiBinding1", "myTopicJndiBinding2");

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

    ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream();
    XmlDataExporter xmlDataExporter = new XmlDataExporter();
    xmlDataExporter.process(
        xmlOutputStream,
        server.getConfiguration().getBindingsDirectory(),
        server.getConfiguration().getJournalDirectory(),
        server.getConfiguration().getPagingDirectory(),
        server.getConfiguration().getLargeMessagesDirectory());
    System.out.print(new String(xmlOutputStream.toByteArray()));

    clearDataRecreateServerDirs();
    server.start();
    locator = createInVMNonHALocator();
    factory = createSessionFactory(locator);
    session = factory.createSession(false, true, true);

    ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray());
    XmlDataImporter xmlDataImporter = new XmlDataImporter();
    xmlDataImporter.process(xmlInputStream, session);

    assertNotNull(namingContext.lookup("myQueueJndiBinding1"));
    assertNotNull(namingContext.lookup("myQueueJndiBinding2"));
    assertNotNull(namingContext.lookup("myTopicJndiBinding1"));
    assertNotNull(namingContext.lookup("myTopicJndiBinding2"));

    jmsServer.createConnectionFactory(
        "test-cf", false, JMSFactoryType.CF, Arrays.asList("in-vm1"), "test-cf");

    ConnectionFactory cf = (ConnectionFactory) namingContext.lookup("test-cf");
    Connection connection = cf.createConnection();
    Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer =
        jmsSession.createProducer((Destination) namingContext.lookup("myQueueJndiBinding1"));
    producer.send(jmsSession.createTextMessage());
    MessageConsumer consumer =
        jmsSession.createConsumer((Destination) namingContext.lookup("myQueueJndiBinding2"));
    connection.start();
    assertNotNull(consumer.receive(3000));

    consumer = jmsSession.createConsumer((Destination) namingContext.lookup("myTopicJndiBinding1"));
    producer = jmsSession.createProducer((Destination) namingContext.lookup("myTopicJndiBinding2"));
    producer.send(jmsSession.createTextMessage());
    assertNotNull(consumer.receive(3000));

    connection.close();
  }
Example #3
0
 @Override
 public Message createMessage(Session paramSession) throws JMSException {
   System.out.println("MyMessageCreator  n=" + n);
   if (n == 9) {
     // 在这个例子中表示第9次调用时,发送结束消息
     return paramSession.createTextMessage("end");
   }
   str = str1 + n + str2;
   return paramSession.createTextMessage(str);
 }
  /**
   * test messages are acknowledged and recovered properly
   *
   * @throws Exception
   */
  public void testClientAcknowledge() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);

    // send some messages

    TextMessage sent1 = producerSession.createTextMessage();
    sent1.setText("msg1");
    sent1.setStringProperty("str", "1");
    producer.send(sent1);

    TextMessage sent2 = producerSession.createTextMessage();
    sent2.setText("msg2");
    sent2.setStringProperty("str", "2");
    producer.send(sent2);

    TextMessage sent3 = producerSession.createTextMessage();
    sent2.setText("msg3");
    sent2.setStringProperty("str", "3");
    producer.send(sent3);

    TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + msgTest + " // " + msgTest.getText());
    TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    System.out.println("msgTest::" + rec2 + " // " + rec2.getText());
    assertNull(consumer.receiveNoWait());

    // ack rec2
    rec2.acknowledge();

    TextMessage sent4 = producerSession.createTextMessage();
    sent4.setText("msg4");
    producer.send(sent4);

    TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    consumerSession.recover();
    rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(rec4.equals(sent4));
    assertTrue(rec4.getJMSRedelivered());
    rec4.acknowledge();
    connection.close();
  }
  // https://issues.apache.org/jira/browse/ARTEMIS-214
  @Test
  public void testSendingBigMessage() throws Exception {
    Connection connection = null;
    ConnectionFactory connectionFactory = new JmsConnectionFactory("amqp://localhost:61616");

    try {
      connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue("jms.queue.exampleQueue");
      MessageProducer sender = session.createProducer(queue);

      String body = createMessage(10240);
      sender.send(session.createTextMessage(body));
      connection.start();

      MessageConsumer consumer = session.createConsumer(queue);
      TextMessage m = (TextMessage) consumer.receive(5000);

      Assert.assertEquals(body, m.getText());
    } finally {
      if (connection != null) {
        connection.close();
      }
    }
  }
Example #6
0
  public void produceMsg(String text) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Create a Session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    TextMessage message = session.createTextMessage(text);
    producer.send(message);

    // Clean up
    session.close();
    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);
  }
 @Override
 public Message toMessage(Object object, Session session)
     throws JMSException, MessageConversionException {
   TextMessage textMessage = session.createTextMessage();
   textMessage.setText(object.toString());
   return textMessage;
 }
  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);
  }
  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);
  }
  /** 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();
      }
    }
  }
 /**
  * Failure test for the method <code>handleMessage</code>.<br>
  * when ExpirationTime not valid date time value
  *
  * @throws Exception to JUnit.
  */
 @Test(expected = IllegalArgumentException.class)
 public void test_handleMessageFail2() throws Exception {
   clearDB();
   loadData();
   User user = getTestUser();
   user.setRole(entityManager.find(Role.class, "1"));
   user = userService.create(user);
   entityManager.flush();
   User user1 = getTestUser();
   user1.setRole(entityManager.find(Role.class, "1"));
   user1 = userService.create(user1);
   entityManager.flush();
   Connection connection = jmsTemplate.getConnectionFactory().createConnection();
   try {
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     TextMessage message = session.createTextMessage("");
     Document doc = getDataRequestDocument(request);
     doc.getElementsByTagName("ExpirationTime").item(0).setTextContent("invalida date");
     XPathFactory xpathFactory = XPathFactory.newInstance();
     XPath xpath = xpathFactory.newXPath();
     VelocityContext templateContext = new VelocityContext();
     instance.handleMessage(message, user1, doc, xpath, templateContext);
   } finally {
     connection.close();
   }
 }
 /**
  * Failure test for the method <code>handleMessage</code>.<br>
  * when request partner id not exist
  *
  * @throws Exception to JUnit.
  */
 @Test(expected = EntityNotFoundException.class)
 public void test_handleMessageFail1() throws Exception {
   clearDB();
   loadData();
   User user = getTestUser();
   user.setRole(entityManager.find(Role.class, "1"));
   user = userService.create(user);
   entityManager.flush();
   User user1 = getTestUser();
   user1.setRole(entityManager.find(Role.class, "1"));
   user1 = userService.create(user1);
   entityManager.flush();
   Connection connection = jmsTemplate.getConnectionFactory().createConnection();
   try {
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     TextMessage message = session.createTextMessage("");
     request.setRequestedPartners(Arrays.asList("not exist Id"));
     Document doc = getDataRequestDocument(request);
     XPathFactory xpathFactory = XPathFactory.newInstance();
     XPath xpath = xpathFactory.newXPath();
     VelocityContext templateContext = new VelocityContext();
     instance.handleMessage(message, user1, doc, xpath, templateContext);
   } finally {
     connection.close();
   }
 }
 protected void putMessageOnQueue(String queueName) throws Exception {
   JmsVendorConfiguration jmsConfig = new ActiveMQJmsConfiguration();
   Connection connection = null;
   try {
     connection = jmsConfig.getConnection(false, false);
     connection.start();
     Session session = null;
     try {
       session = connection.createSession(false, acknowledgeMode);
       Destination destination = session.createQueue(queueName);
       MessageProducer producer = null;
       try {
         producer = session.createProducer(destination);
         producer.setDeliveryMode(deliveryMode);
         Message msg =
             session.createTextMessage(AbstractJmsFunctionalTestCase.DEFAULT_INPUT_MESSAGE);
         msg.setJMSExpiration(0);
         producer.send(msg);
       } finally {
         if (producer != null) {
           producer.close();
         }
       }
     } finally {
       if (session != null) {
         session.close();
       }
     }
   } finally {
     if (connection != null) {
       connection.close();
     }
   }
 }
  /**
   * Map the given object to a {@link TextMessage}.
   *
   * @param object the object to be mapped
   * @param session current JMS session
   * @param objectMapper the mapper to use
   * @return the resulting message
   * @throws JMSException if thrown by JMS methods
   * @throws IOException in case of I/O errors
   * @see Session#createBytesMessage
   */
  protected TextMessage mapToTextMessage(Object object, Session session, ObjectMapper objectMapper)
      throws JMSException, IOException {

    StringWriter writer = new StringWriter();
    objectMapper.writeValue(writer, object);
    return session.createTextMessage(writer.toString());
  }
Example #16
0
 private Message createJMSMessageForrSSQueue(Session session, Object messageData)
     throws JMSException {
   // TODO create and populate message to send
   TextMessage tm = session.createTextMessage();
   tm.setText(messageData.toString());
   return tm;
 }
  @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();
  }
Example #18
0
  protected void setUp() throws Exception {
    super.setUp();

    // Create Client
    _clientConnection = getConnection("guest", "guest");

    _clientConnection.start();

    Session clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Queue queue = clientSession.createQueue("message-listener-test-queue");

    _consumer = clientSession.createConsumer(queue);

    // Create Producer

    Connection producerConnection = getConnection("guest", "guest");

    producerConnection.start();

    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = producerSession.createProducer(queue);

    for (int msg = 0; msg < MSG_COUNT; msg++) {
      producer.send(producerSession.createTextMessage("Message " + msg));
    }

    producerConnection.close();
  }
 /** Send a test message now. */
 protected void sendMessage() throws JMSException {
   Session sess = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer prod = sess.createProducer(queue);
   prod.send(sess.createTextMessage("X-TEST-MSG-X"));
   prod.close();
   sess.close();
 }
Example #20
0
  public void produceMessage(int x) {
    try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      // Create the destination
      //            Destination destination = session.createQueue("Testqueue");
      Destination destination = session.createTopic("Testtopic");

      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

      // Create a messages
      String text =
          "Hello world "
              + x
              + "! From: "
              + Thread.currentThread().getName()
              + " : "
              + this.hashCode();
      TextMessage message = session.createTextMessage(text);

      // Tell the producer to send the message
      System.out.println(
          "Sent message: " + message.hashCode() + " : " + Thread.currentThread().getName());

      producer.send(message);
      session.close();
    } catch (Exception e) {
      System.out.println("Caught: " + e);
      e.printStackTrace();
    }
  }
  /**
   * 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();
  }
  @Override
  public void blogracyContentReceived(BlogracyContent message) {
    if (message == null) return;

    TextMessage response;
    try {
      response = session.createTextMessage();

      JSONObject record = new JSONObject();
      record.put("request", "contentReceived");
      record.put("senderUserId", message.getSenderUserId());
      record.put("contentRecipientUserId", message.getContentRecipientUserId());

      JSONObject content = new JSONObject(message.getContent());
      record.put("contentData", content);
      record.put("contentId", content.getJSONObject("object").getString("id"));

      response.setText(record.toString());

      producer.send(outgoingQueue, response);
    } catch (JMSException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Example #23
0
 public void run() throws JMSException {
   for (int i = 0; i < 100; i++) {
     System.out.println("Creating Message " + i);
     Message message = session.createTextMessage("Hello World! " + i);
     producer.send(message);
   }
 }
Example #24
0
  public void sendMessage(final String textMessage) throws Exception {
    // Connection connection = null;
    // Session session = null;

    try {

      // Create a message
      String text =
          "DID IT WORK?! From: " + Thread.currentThread().getName() + " : " + this.hashCode();

      TextMessage message = session.createTextMessage(text);
      String timestamp = DateFormater.format(message.getJMSExpiration());

      // Tell the producer to send the message

      System.out.printf(
          "Sent message: %s : %s [%s]%n",
          message.hashCode(), Thread.currentThread().getName(), timestamp);

      // producer.setTimeToLive(DateTimeConstants.MILLIS_PER_HOUR);

      send(message);

    } catch (Exception e) {
      System.out.println("Caught: " + e);
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.close();
        if (session != null) {
          session.close();
        }
      }
    }
  }
 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();
 }
Example #26
0
  public static void main(String[] args) {
    try {
      Parameters parameters = new Parameters(args);

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

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

      Topic destination = session.createTopic(parameters.topic);

      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      String messageBody = IOUtils.toString(new FileReader(parameters.message));

      TextMessage message = session.createTextMessage(messageBody);
      message.setStringProperty("Channel", parameters.channel);
      message.setJMSExpiration(parameters.expiration);

      LOG.info("Sent message: {}", message);
      producer.send(message);

      session.close();
      connection.close();
    } catch (Exception e) {
      LOG.error("Producing interrupted", e);
    }
  }
Example #27
0
  public void sendMessage(Order order) {
    ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616");
    Queue queue = new ActiveMQQueue("sequence");
    Connection conn = null;
    Session sen = null;
    MessageProducer producer = null;
    TextMessage msg = null;
    JSONMapper mapper = new JSONMapper();

    Destination des = null;
    try {
      conn = factory.createConnection();
      sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producer = sen.createProducer(queue);
      conn.start();
      String str = mapper.writeObjectAsString(order);
      System.out.println(str);
      msg = sen.createTextMessage(str);
      producer.send(msg);
      producer.close();
      sen.close();
      conn.close();
    } catch (JMSException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Send a command via JMS.
   *
   * <p>Note: Opens and closes the connection per invocation of this method which, when run outside
   * a JavaEE container, is not very efficient.
   *
   * @param command
   * @throws JMSException
   */
  public void sendCommandMessage(Command command) throws JMSException {
    Connection connection = null;
    Session session = null;
    try {
      connection = connectionFactory.createConnection();
      session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE);

      // Construct a JMS "TextMessage"
      final TextMessage newMessage = session.createTextMessage();
      newMessage.setStringProperty("issuer", command.getIssuer());
      newMessage.setStringProperty("type", command.getType());
      newMessage.setText(command.getPayload());

      // Send the message
      final MessageProducer producer = session.createProducer(this.commandQueue);
      producer.send(newMessage);

      if (TRANSACTIONAL) {
        // JavaEE containers would manage this
        session.commit();
      }
    } finally {
      if (connection != null) {
        try {
          if (session != null) {
            session.close();
          }
          connection.stop();
          connection.close();
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #29
0
 private Message createMessage(Session session, int messageType) throws JMSException {
   switch (messageType) {
     case MessageImpl.TEXT_MESSAGE:
       return session.createTextMessage();
     case MessageImpl.BYTES_MESSAGE:
       return session.createBytesMessage();
     case MessageImpl.MAP_MESSAGE:
       return session.createMapMessage();
     case MessageImpl.STREAM_MESSAGE:
       return session.createStreamMessage();
     case MessageImpl.OBJECT_MESSAGE:
       return session.createObjectMessage();
     default:
       return session.createTextMessage();
   }
 }
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory cf = null;
    Connection connection = null;
    Session session = null;

    try {
      cf = (ConnectionFactory) initialContext.lookup("jms/RemoteConnectionFactory");
      Queue queue = (Queue) initialContext.lookup(QUEUE_NAME);
      connection = cf.createConnection("guest", "guest");
      connection.start(); // for consumer we need to start connection
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      TemporaryQueue replyQueue = session.createTemporaryQueue();
      TextMessage message = session.createTextMessage("hello goodbye");
      message.setJMSReplyTo(replyQueue);
      sender.send(message);
      log.trace("testSendMessage(): Message sent!");

      MessageConsumer consumer = session.createConsumer(replyQueue);
      Message replyMsg = consumer.receive(5000);
      Assert.assertNotNull(replyMsg);
      Assert.assertTrue(replyMsg instanceof TextMessage);
      String actual = ((TextMessage) replyMsg).getText();
      Assert.assertEquals("Howdy Fred! GoodBye user1", actual);
    } finally {
      if (session != null) {
        session.close();
      }
      closeConnection(connection);
    }
  }