예제 #1
0
 @Override
 public void run() {
   try {
     // Create a ConncetionFactory
     ActiveMQConnectionFactory connectionFactory =
         new ActiveMQConnectionFactory("tcp://MSPL-08-09-D158:61616");
     // Create a Connection
     Connection connection = connectionFactory.createConnection();
     connection.start();
     // Create a session
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     // Create the destination (Topic or Queue)
     Destination destination = session.createQueue("HELLOWORLD.TESTQ");
     // Create a MessageProducer from the Session to the Topic or Queue
     MessageConsumer consumer = session.createConsumer(destination);
     Message message = consumer.receive(1000);
     if (message instanceof TextMessage) {
       TextMessage textMessage = (TextMessage) message;
       String text = textMessage.getText();
       System.out.println("Received : " + text);
     } else {
       System.out.println("Received : " + message);
     }
     consumer.close();
     session.close();
     connection.close();
   } catch (Exception e) {
     System.out.println("Error Occure : " + e);
     e.printStackTrace();
   }
 }
예제 #2
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);
  }
예제 #3
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"));
  }
예제 #4
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);
    }
  }
예제 #5
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();
  }
예제 #6
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;
 }
  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 onMessage(final Message message) {
    try {
      // Step 9. We know the client is sending a text message so we cast
      TextMessage textMessage = (TextMessage) message;

      // Step 10. get the text from the message.
      String text = textMessage.getText();

      System.out.println("message " + text + " received");

      if (!textMessage.getJMSRedelivered()) {
        // Step 11. On first delivery get the transaction, take a look, and throw an exception
        Transaction tx = tm.getTransaction();

        if (tx != null) {
          System.out.println("something is wrong, there should be no global transaction: " + tx);
        } else {
          System.out.println(
              "there is no global transaction, although the message delivery is using a local transaction");
          System.out.println("let's throw an exception and see what happens");
          throw new RuntimeException("DOH!");
        }
      } else {
        // Step 12. Print the message
        System.out.println(
            "The message was redelivered since the message delivery used a local transaction");
      }

    } catch (JMSException e) {
      e.printStackTrace();
    } catch (SystemException e) {
      e.printStackTrace();
    }
  }
예제 #9
0
  public static void main(String[] args) {
    try { // Create and start connection
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory f = (QueueConnectionFactory) ctx.lookup("myQueueConnectionFactory");
      QueueConnection con = f.createQueueConnection();
      con.start();
      // 2) create queue session
      QueueSession ses = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      // 3) get the Queue object
      Queue t = (Queue) ctx.lookup("myQueue");
      // 4)create QueueSender object
      QueueSender sender = ses.createSender(t);
      // 5) create TextMessage object
      TextMessage msg = ses.createTextMessage();

      // 6) write message
      BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
        System.out.println("Enter Msg, end to terminate:");
        String s = b.readLine();
        if (s.equals("end")) break;
        msg.setText(s);
        // 7) send message
        sender.send(msg);
        System.out.println("Message successfully sent.");
      }
      // 8) connection close
      con.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
    @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);
      }
    }
예제 #11
0
  @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();
    }
  }
예제 #12
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();
    }
  }
예제 #13
0
  @Override
  public void run() {

    this.threadName = Thread.currentThread().getName();
    int numMessages =
        Integer.parseInt(
            appProperties.getProperty(
                Constants.PROP_NUM_MESSAGES, Constants.PROP_NUM_MESSAGES_DEFAULT));
    boolean printMessages =
        Boolean.parseBoolean(
            appProperties.getProperty(
                Constants.PROP_CONSUMER_PRINT_MESSAGES,
                Constants.PROP_CONSUMER_PRINT_MESSAGES_DEFAULT));

    try {
      while (true) {
        TextMessage message = (TextMessage) consumer.receive();
        int messageNumber = messageCounter.increment();
        // Message can be null if another thread is making application exit
        if ((message != null) && printMessages) {
          String prefix = threadName + ": " + "message " + messageNumber;
          logger.info("{} - {}", prefix, message.getText());
        }
        if (messageNumber == numMessages) break;
      }
    } catch (JMSException e) {
      logger.error("{} halted: {}", threadName, StackTraceUtil.getStackTrace(e));
    } finally {
      if (privateConnection != null)
        try {
          privateConnection.close();
        } catch (Exception e) {
        }
    }
  }
  /** 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();
      }
    }
  }
예제 #15
0
 @Override
 public void onMessageDo(Message msg) throws Exception {
   String type = msg.getStringProperty("type");
   if (ResmMessageListener.TYPE_OBJECT_SYNC.equals(type)) {
     TextMessage text = (TextMessage) msg;
     int id = StringUtil.parseInt(text.getText(), -1);
     logger.debug("接收到同步消息:资源ID=" + text.getText());
     if (id > 0) ServiceManager.getResourceUpdateService().syncResource(id);
   } else if (ResmMessageListener.TYPE_CACHE_ADD.equals(type)) {
     ObjectMessage object = (ObjectMessage) msg;
     String cacheName = msg.getStringProperty("cache");
     CacheableObject obj = (CacheableObject) object.getObject();
     logger.debug("接收到缓存增加消息:" + cacheName + " " + obj.getClass().getName());
     obj.onDeserialize();
     obj.dump();
     CacheManager.addCache(cacheName, obj);
   } else if (ResmMessageListener.TYPE_CACHE_REMOVE.equals(type)) {
     ObjectMessage object = (ObjectMessage) msg;
     String cacheName = msg.getStringProperty("cache");
     CacheableObject obj = (CacheableObject) object.getObject();
     logger.debug("接收到缓存删除消息:" + cacheName + " " + obj.getClass().getName());
     obj.onDeserialize();
     obj.dump();
     CacheManager.removeCache(cacheName, obj);
   } else {
     System.out.println(msg.toString());
   }
 }
예제 #16
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();
        }
      }
    }
  }
예제 #17
0
파일: JmsHelper.java 프로젝트: araqne/logdb
  public static Map<String, Object> parse(Message message) throws JMSException {
    if (message instanceof TextMessage) {
      TextMessage msg = (TextMessage) message;
      String text = msg.getText();
      Date date = msg.getJMSTimestamp() == 0 ? new Date() : new Date(msg.getJMSTimestamp());

      Map<String, Object> m = new HashMap<String, Object>();
      m.put("_time", date);
      m.put("_msg_id", msg.getJMSMessageID());
      m.put("line", text);

      return m;
    } else if (message instanceof MapMessage) {
      MapMessage msg = (MapMessage) message;
      Date date = msg.getJMSTimestamp() == 0 ? new Date() : new Date(msg.getJMSTimestamp());

      Map<String, Object> m = new HashMap<String, Object>();
      m.put("_time", date);
      m.put("_msg_id", msg.getJMSMessageID());

      @SuppressWarnings("unchecked")
      Enumeration<String> e = msg.getPropertyNames();
      while (e.hasMoreElements()) {
        String key = e.nextElement();
        Object val = msg.getObjectProperty(key);
        m.put(key, val);
      }

      return m;
    }

    return null;
  }
  public void doSend() {

    QueueSession queueSession = null;
    QueueSender queueSender = null;
    TextMessage message = null;

    if (doSetup()) {

      try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        message = queueSession.createTextMessage();
        for (int i = 0; i < NUM_MSGS; i++) {
          message.setText("This is message " + (i + 1));
          System.out.println("Sending message: " + message.getText());
          queueSender.send(message);
        }

        /*
         * Send a non-text control message indicating end of messages.
         */
        queueSender.send(queueSession.createMessage());
      } catch (JMSException e) {
        log.error("JMS Send Exception occurred: " + e.toString());
      } finally {
        doCleanup();
      }
    }
  }
예제 #19
0
  @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();
  }
  /** use auto acknowledge which automatically has the client say OK */
  public void doReceiveAuto() {

    if (doSetup()) {
      try {
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession =
            queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueReceiver queueReceiver = queueSession.createReceiver(queue);
        queueConnection.start();
        while (true) {
          Message m = queueReceiver.receive(1);
          if (m != null) {
            if (m instanceof TextMessage) {
              TextMessage message = (TextMessage) m;
              log.debug("Reading message:==> " + message.getText());
            } else {
              break;
            }
          }
        }
      } catch (JMSException e) {
        log.error("Listen Exception occurred: " + e.toString());
      } finally {
        doCleanup();
      }
    }
  }
예제 #21
0
 @Override
 public Message toMessage(Object object, Session session)
     throws JMSException, MessageConversionException {
   TextMessage textMessage = session.createTextMessage();
   textMessage.setText(object.toString());
   return textMessage;
 }
예제 #22
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);
    }
  }
  /**
   * 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();
  }
예제 #24
0
  @Test
  public void testDelay() throws Exception {
    JMSProducer producer = context.createProducer();

    JMSConsumer consumer = context.createConsumer(queue1);

    producer.setDeliveryDelay(500);

    long timeStart = System.currentTimeMillis();

    String strRandom = newXID().toString();

    producer.send(queue1, context.createTextMessage(strRandom));

    TextMessage msg = (TextMessage) consumer.receive(2500);

    assertNotNull(msg);

    long actualDelay = System.currentTimeMillis() - timeStart;
    assertTrue(
        "delay is not working, actualDelay=" + actualDelay,
        actualDelay >= 500 && actualDelay < 2000);

    assertEquals(strRandom, msg.getText());
  }
예제 #25
0
  @JmsListener(destination = "raulQueue", containerFactory = "jmsConFactory")
  public void processMessages(Message msg) {
    try {
      if (msg instanceof TextMessage) {
        TextMessage txtMsg = (TextMessage) msg;
        System.out.println("Receiving message " + txtMsg.getText());
      }
      /*ConnectionFactory connFactory=new ActiveMQConnectionFactory("tcp://localhost:61616");
      Connection connection=connFactory.createConnection();
      Session session=connection.createSession(true, 0);
      Destination dest=new ActiveMQQueue("raulQueue");
      MessageConsumer consumer=session.createConsumer(dest);
      TextMessage msg1=(TextMessage)consumer.receive();
      System.out.println("Msg1 " +msg1.getText());
      Thread.sleep(5000);
      TextMessage msg2=(TextMessage)consumer.receive();
      System.out.println("Msg2 " +msg2.getText());
      Thread.sleep(5000);
      TextMessage msg3=(TextMessage)consumer.receive();
      System.out.println("Msg3 " +msg3.getText());
      session.commit();
      session.close();*/

    } catch (JMSException e) {
      // TODO: handle exception
    }
  }
  /**
   * 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();
        }
      }
    }
  }
예제 #27
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);
  }
예제 #28
0
 protected void writeMessageResponse(
     PrintWriter writer, Message message, String id, String destinationName)
     throws JMSException, IOException {
   writer.print("<response id='");
   writer.print(id);
   writer.print("'");
   if (destinationName != null) {
     writer.print(" destination='" + destinationName + "' ");
   }
   writer.print(">");
   if (message instanceof TextMessage) {
     TextMessage textMsg = (TextMessage) message;
     String txt = textMsg.getText();
     if (txt != null) {
       if (txt.startsWith("<?")) {
         txt = txt.substring(txt.indexOf("?>") + 2);
       }
       writer.print(txt);
     }
   } else if (message instanceof ObjectMessage) {
     ObjectMessage objectMsg = (ObjectMessage) message;
     Object object = objectMsg.getObject();
     if (object != null) {
       writer.print(object.toString());
     }
   }
   writer.println("</response>");
 }
예제 #29
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"));
  }
예제 #30
0
  /** @see MessageListener#onMessage(Message) */
  public void onMessage(Message message) {

    TextMessage tmsg = null;
    tmsg = (TextMessage) message;
    String parameter0 = null;
    String parameter1 = null;
    System.out.println("<sms module>");

    // parsing message into opcode, and parameters
    String preParse;
    try {
      preParse = tmsg.getText();
      String[] postParse = preParse.split("[|]+");
      parameter0 = postParse[0];
      parameter1 = postParse[1];

    } catch (JMSException e1) {
      e1.printStackTrace();
    }

    try {
      // TODO
      sendSMS(parameter0, parameter1);
    } catch (Exception e) {

      e.printStackTrace();
    }
  }