/**
   * 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();
  }
  public void onMessage(Message inMessage) {
    TextMessage msg = null;

    try {
      if (inMessage instanceof TextMessage) {
        msg = (TextMessage) inMessage;
        System.out.println("MESSAGE BEAN: Message received: " + msg.getText());
        long sleepTime = msg.getLongProperty("sleeptime");
        System.out.println("Sleeping for : " + sleepTime + " milli seconds ");
        Thread.sleep(sleepTime);
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        TextMessage message = queueSession.createTextMessage();

        message.setText("REPLIED:" + msg.getText());
        message.setIntProperty("replyid", msg.getIntProperty("id"));
        System.out.println("Sending message: " + message.getText());
        queueSender.send(message);
      } else {
        System.out.println("Message of wrong type: " + inMessage.getClass().getName());
      }
    } catch (JMSException e) {
      e.printStackTrace();
    } catch (Throwable te) {
      te.printStackTrace();
    } finally {
      try {
        queueSession.close();
        queueConnection.close();
      } catch (Exception e) {
      }
    }
  } // onMessage
 @Test
 public void testPublishTextMessage()
     throws FileNotFoundException, JMSException, OpenJMSAdapterException {
   YamlConfigurationHolder holder =
       new YamlConfigurationHolder("C:/NetBeansProjects/openjmsadapter/test/yaml_config.yml");
   ActiveMQConnectionFactoryBuilder builder = new ActiveMQConnectionFactoryBuilder();
   OpenJMSAdapterConnection connection =
       new OpenJMSAdapterConnection(builder.getConnectionFactory(holder.getConfig()));
   connection.connect();
   connection.createQueuePublishingSession("test.queue");
   QueuePublishSession session =
       (QueuePublishSession) connection.getQueuePublishSession("test.queue");
   TextMessage msg = session.createTextMessage();
   msg.setText("HELLO");
   session.publish(msg);
   connection.disconnect();
   Connection conn = builder.getConnectionFactory(holder.getConfig()).createConnection();
   conn.start();
   Session receive_session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer =
       receive_session.createConsumer(receive_session.createQueue("test.queue"));
   TextMessage rx_msg = (TextMessage) consumer.receive();
   assertNotNull(rx_msg);
   assertTrue(rx_msg.getText().equals("HELLO"));
   consumer.close();
   receive_session.close();
   conn.close();
 }
 public void onMessage(Message message) {
   try {
     MapMessage request = (MapMessage) message;
     String correlationID = request.getJMSCorrelationID();
     int itemId = request.getInt("itemId");
     // Retrieve the connection factory
     connectionFactory =
         (TopicConnectionFactory) initialContext.lookup(BeanConfig.TopicConnectionFactoryName);
     // get the bids history
     String html = getBidHistory(itemId);
     // send the reply
     TemporaryTopic temporaryTopic = (TemporaryTopic) request.getJMSReplyTo();
     if (temporaryTopic != null) {
       // create a connection
       connection = connectionFactory.createTopicConnection();
       // create a session: no transaction, auto ack
       session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
       TextMessage reply = session.createTextMessage();
       reply.setJMSCorrelationID(correlationID);
       reply.setText(html);
       replier = session.createPublisher(null); // unidentified publisher
       connection.start();
       replier.publish(temporaryTopic, reply);
       replier.close();
       session.close();
       connection.stop();
       connection.close();
     }
   } catch (Exception e) {
     throw new EJBException("Message traitment failed for MDB_ViewBidHistory: " + e);
   }
 }
 @Override
 public Message toMessage(Object object, Session session)
     throws JMSException, MessageConversionException {
   TextMessage textMessage = session.createTextMessage();
   textMessage.setText(object.toString());
   return textMessage;
 }
  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();
      }
    }
  }
  public String doSend() {

    log.warn("Hello");
    String retVal = "run method in Sender";

    if (connectionFactory != null && dest != null) {
      retVal = "connectionFactory and dest are there";
    } else {
      retVal = "CDI didn't work, getting from Context";
      retVal += " (" + getFromContext() + ") ";
    }

    try {
      retVal += "sending ... ";
      Connection connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(dest);
      TextMessage msg = session.createTextMessage();
      msg.setText("My JMS Client");
      producer.send(msg);
      producer.close();
      connection.close();
      retVal += "success";
    } catch (Exception e) {
      retVal += e.toString();
    }

    return retVal;
  }
  /**
   * 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();
        }
      }
    }
  }
  @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();
    }
  }
Exemple #10
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;
 }
Exemple #11
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);
    }
  }
  /**
   * 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();
  }
Exemple #13
0
  private void writeMessage(String s) throws JMSException {

    TextMessage message = session.createTextMessage();
    message.setStringProperty("language", "java");
    message.setText(s);
    System.out.println("sending text message " + message);
    pub.publish(message);
  }
 /**
  * Each message will be divided into groups and create the map message
  *
  * @param producer Used for sending messages to a destination
  * @param session Used to produce the messages to be sent
  * @param messagesList List of messages to be sent
  */
 public static void publishTextMessage(
     MessageProducer producer, Session session, List<String> messagesList) throws JMSException {
   for (String message : messagesList) {
     TextMessage jmsMessage = session.createTextMessage();
     jmsMessage.setText(message);
     producer.send(jmsMessage);
   }
 }
Exemple #15
0
 /**
  * Create the {@link Message}
  *
  * @return jmsMessage or null if the mapping was not successfully
  */
 protected Message createJmsMessageForType(
     Exchange exchange,
     Object body,
     Map<String, Object> headers,
     Session session,
     CamelContext context,
     JmsMessageType type)
     throws JMSException {
   switch (type) {
     case Text:
       {
         TextMessage message = session.createTextMessage();
         if (body != null) {
           String payload = context.getTypeConverter().convertTo(String.class, exchange, body);
           message.setText(payload);
         }
         return message;
       }
     case Bytes:
       {
         BytesMessage message = session.createBytesMessage();
         if (body != null) {
           byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body);
           message.writeBytes(payload);
         }
         return message;
       }
     case Map:
       {
         MapMessage message = session.createMapMessage();
         if (body != null) {
           Map<?, ?> payload = context.getTypeConverter().convertTo(Map.class, exchange, body);
           populateMapMessage(message, payload, context);
         }
         return message;
       }
     case Object:
       ObjectMessage message = session.createObjectMessage();
       if (body != null) {
         try {
           Serializable payload =
               context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body);
           message.setObject(payload);
         } catch (NoTypeConversionAvailableException e) {
           // cannot convert to serializable then thrown an exception to avoid sending a null
           // message
           JMSException cause = new MessageFormatException(e.getMessage());
           cause.initCause(e);
           throw cause;
         }
       }
       return message;
     default:
       break;
   }
   return null;
 }
 private TextMessage createMessage(String text) throws JMSException {
   TextMessage message = session.createTextMessage();
   String streamId = (String) MDC.get(Constants.STREAM_ID);
   if (streamId != null) {
     message.setJMSCorrelationID(streamId);
   }
   message.setText(text);
   return message;
 }
 public void txtSender(String content, String correlationid) throws JMSException {
   TextMessage txtMessage = session.createTextMessage();
   txtMessage.setText(content);
   txtMessage.setJMSReplyTo(consumerQueue);
   String correlationId = correlationid;
   txtMessage.setJMSCorrelationID(correlationId);
   System.out.println(correlationId);
   this.producer.send(txtMessage);
 }
 public void sendReply(Message request, int sum) {
   try {
     MessageProducer MP = session.createProducer(null);
     Destination reply = request.getJMSReplyTo();
     TextMessage TM = session.createTextMessage();
     TM.setText("" + sum);
     MP.send(reply, TM);
   } catch (JMSException JMSE) {
     System.out.println("JMS Exception: " + JMSE);
   }
 }
  public static void setTextData(Message message, String text) throws JMSException {
    if (text == null) {
      return;
    }

    if (message instanceof TextMessage) {
      ((TextMessage) message).setText(text);
    } else {
      message.setStringProperty(MessagePropertyNames.TEXT_DATA, text);
    }
  }
Exemple #20
0
  public boolean send(@NotNull Value value, @Optional JMSQueue replyTo) throws JMSException {
    Message message = null;

    if (value.isArray()) {
      message = _session.createMapMessage();

      ArrayValue array = (ArrayValue) value;

      Set<Map.Entry<Value, Value>> entrySet = array.entrySet();

      for (Map.Entry<Value, Value> entry : entrySet) {
        if (entry.getValue() instanceof BinaryValue) {
          byte[] bytes = ((BinaryValue) entry.getValue()).toBytes();

          ((MapMessage) message).setBytes(entry.getKey().toString(), bytes);
        } else {
          // every primitive except for bytes can be translated from a string
          ((MapMessage) message).setString(entry.getKey().toString(), entry.getValue().toString());
        }
      }
    } else if (value instanceof BinaryValue) {
      message = _session.createBytesMessage();

      byte[] bytes = ((BinaryValue) value).toBytes();

      ((BytesMessage) message).writeBytes(bytes);
    } else if (value.isLongConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeLong(value.toLong());
    } else if (value.isDoubleConvertible()) {
      message = _session.createStreamMessage();

      ((StreamMessage) message).writeDouble(value.toDouble());
    } else if (value.toJavaObject() instanceof String) {
      message = _session.createTextMessage();

      ((TextMessage) message).setText(value.toString());
    } else if (value.toJavaObject() instanceof Serializable) {
      message = _session.createObjectMessage();

      ((ObjectMessage) message).setObject((Serializable) value.toJavaObject());
    } else {
      return false;
    }

    if (replyTo != null) message.setJMSReplyTo(replyTo._destination);

    _producer.send(message);

    return true;
  }
 /**
  * Test that the <code>Message.clearProperties()</code> method does not clear the value of the
  * Message's body.
  */
 @Test
 public void testClearProperties_2() {
   try {
     TextMessage message = senderSession.createTextMessage();
     message.setText("foo");
     message.clearProperties();
     Assert.assertEquals(
         "sec. 3.5.7 Clearing a message's  property entries does not clear the value of its body.\n",
         "foo",
         message.getText());
   } catch (JMSException e) {
     fail(e);
   }
 }
  @Test
  public void testReceivedRollbackTopic() throws Exception {
    Connection conn = null;

    try {
      conn = createConnection();

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

      MessageConsumer consumer = sess.createConsumer(ActiveMQServerTestCase.topic1);
      conn.start();

      log.info("sending message first time");
      TextMessage mSent = sess.createTextMessage("igloo");
      producer.send(mSent);
      log.info("sent message first time");

      sess.commit();

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

      sess.commit();

      log.info("sending message again");
      mSent.setText("rollback");
      producer.send(mSent);
      log.info("sent message again");

      sess.commit();

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

      TextMessage mRec2 = (TextMessage) consumer.receive(2000);

      sess.commit();

      ProxyAssertSupport.assertNotNull(mRec2);

      ProxyAssertSupport.assertEquals(mRec.getText(), mRec2.getText());
    } finally {
      if (conn != null) {
        conn.close();
      }
    }
  }
  @Test
  public void testReceivedRollbackQueue() throws Exception {
    Connection conn = createConnection();

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

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

    TextMessage mSent = sess.createTextMessage("igloo");
    producer.send(mSent);
    log.trace("sent1");

    sess.commit();

    TextMessage mRec = (TextMessage) consumer.receive(1000);
    ProxyAssertSupport.assertNotNull(mRec);
    log.trace("Got 1");
    ProxyAssertSupport.assertNotNull(mRec);
    ProxyAssertSupport.assertEquals("igloo", mRec.getText());

    sess.commit();

    mSent.setText("rollback");
    producer.send(mSent);

    sess.commit();

    log.trace("Receiving 2");
    mRec = (TextMessage) consumer.receive(1000);
    ProxyAssertSupport.assertNotNull(mRec);

    log.trace("Received 2");
    ProxyAssertSupport.assertNotNull(mRec);
    ProxyAssertSupport.assertEquals("rollback", mRec.getText());

    sess.rollback();

    TextMessage mRec2 = (TextMessage) consumer.receive(1000);
    ProxyAssertSupport.assertNotNull(mRec2);
    ProxyAssertSupport.assertEquals("rollback", mRec2.getText());

    sess.commit();

    ProxyAssertSupport.assertEquals(mRec.getText(), mRec2.getText());

    conn.close();
  }
  /**
   * check messages are actuallly sent on a tx rollback
   *
   * @throws Exception
   */
  public void testTransactionRollbackOnSend() 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 = 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);
    consumerSession.commit();
    assertTrue(recMsg.equals(sentMsg));

    sentMsg = producerSession.createTextMessage();
    sentMsg.setText("msg2");
    producer.send(sentMsg);
    producerSession.rollback();

    sentMsg = producerSession.createTextMessage();
    sentMsg.setText("msg3");
    producer.send(sentMsg);
    producerSession.commit();

    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(recMsg.equals(sentMsg));
    consumerSession.commit();

    connection.close();
  }
  private void sendJmsMessage() {
    String message = "Salutation generated for MDB";
    try {
      Connection connection = queueConnectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer messageProducer = (MessageProducer) session.createProducer(queue);
      TextMessage textMessage = session.createTextMessage();
      textMessage.setText(message);
      messageProducer.send(textMessage);
      Logger.getLogger("SalutationLog")
          .log(Level.WARNING, "Message sent successfully", "Message sent successfully2");

    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
  public void testNoExceptionOnRedeliveryAckWithSimpleTopicConsumer() throws Exception {
    Destination destination = createDestination(getClass().getName());
    Connection connection = createConnection();
    final AtomicBoolean gotException = new AtomicBoolean();
    connection.setExceptionListener(
        new ExceptionListener() {
          @Override
          public void onException(JMSException exception) {
            LOG.error("unexpected ex:" + exception);
            gotException.set(true);
          }
        });
    connection.setClientID(idGen.generateId());
    connection.start();
    Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = null;
    if (topic) {
      consumer = consumerSession.createConsumer(destination);
    } 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());
    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    consumerSession.rollback();
    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(recMsg.getJMSRedelivered());
    consumerSession.rollback();
    recMsg = consumer.receive(RECEIVE_TIMEOUT);
    assertTrue(recMsg.getJMSRedelivered());
    consumerSession.commit();
    assertTrue(recMsg.equals(sentMsg));
    assertTrue(recMsg.getJMSRedelivered());
    connection.close();

    assertFalse("no exception", gotException.get());
  }
 @AroundInvoke
 public Object log(InvocationContext context) throws Exception {
   System.out.println("---" + context.getMethod());
   QueueConnection conn = qcf.createQueueConnection();
   conn.start();
   QueueSession session = conn.createQueueSession(true, Session.SESSION_TRANSACTED);
   TextMessage msg = session.createTextMessage();
   msg.setText(
       context.getMethod().getDeclaringClass().getSimpleName()
           + ";"
           + context.getMethod().getName()
           + ";"
           + sessionContext.getCallerPrincipal().getName());
   QueueSender queueSender = session.createSender(queue);
   queueSender.send(msg);
   return context.proceed();
 }
  public void sendMessage(String text) {

    try {

      Connection connection = getConnection();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = getQueue();
      MessageProducer producer = session.createProducer(destination);
      TextMessage msg = session.createTextMessage();
      msg.setText(text);

      producer.send(msg);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #29
0
  public void onMessage(Message message) {

    try {
      boolean accepted = false;

      // Get the data from the message
      MapMessage msg = (MapMessage) message;
      double salary = msg.getDouble("Salary");
      double loanAmt = msg.getDouble("LoanAmount");

      // Determine whether to accept or decline the loan
      if (loanAmt < 200000) {
        accepted = (salary / loanAmt) > .25;
      } else {
        accepted = (salary / loanAmt) > .33;
      }
      System.out.println(
          ""
              + "Percent = "
              + (salary / loanAmt)
              + ", loan is "
              + (accepted ? "Accepted!" : "Declined"));

      // Send the results back to the borrower
      TextMessage tmsg = qSession.createTextMessage();
      tmsg.setText(accepted ? "Accepted!" : "Declined");

      // correlation
      tmsg.setJMSCorrelationID(message.getJMSMessageID());

      // Create the sender and send the message
      qSender = qSession.createSender((Queue) message.getJMSReplyTo());
      qSender.send(tmsg);

      System.out.println("\nWaiting for loan requests...");

    } catch (JMSException jmse) {
      jmse.printStackTrace();
      System.exit(1);
    } catch (Exception jmse) {
      jmse.printStackTrace();
      System.exit(1);
    }
  }
  public void handleRequest(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    PrintWriter out = res.getWriter();

    ConnectionFactory cf;
    Destination dest;

    try {
      Context initCtx = new InitialContext();
      Context envCtx = (Context) initCtx.lookup("java:comp/env");
      cf = (ConnectionFactory) envCtx.lookup("jms/connectionFactory");
      dest = (Destination) envCtx.lookup(QUEUE_NAME);
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }

    Connection connection = null;
    try {
      connection = cf.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(dest);
      TextMessage message = session.createTextMessage();
      for (int i = 0; i < NUM_MSGS; i++) {
        message.setText("This is message " + (i + 1));
        log.info("Sending message: " + message.getText());
        producer.send(message);
      }
      producer.send(session.createTextMessage());

    } catch (JMSException e) {
      throw new RuntimeException(e);
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
        }
      }
    }

    out.write("<p>Wrote " + NUM_MSGS + " to queue " + QUEUE_NAME + " followed by a blank.</p>");
    out.close();
  }