List of usage examples for javax.jms TextMessage setText
void setText(String string) throws JMSException;
From source file:DurableChat.java
public void DurableChatter(String broker, String username, String password) { javax.jms.MessageProducer publisher = null; javax.jms.MessageConsumer subscriber = null; javax.jms.Topic topic = null;//from w w w . j a v a 2s . com //Create a connection: try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connection = factory.createConnection(username, password); //Durable Subscriptions are indexed by username, clientID and subscription name //It is a good practice to set the clientID: connection.setClientID(username); pubSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); subSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("Error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } //Create Publisher and Durable Subscriber: try { topic = pubSession.createTopic(APP_TOPIC); subscriber = subSession.createDurableSubscriber(topic, username); subscriber.setMessageListener(this); publisher = pubSession.createProducer(topic); connection.start(); } catch (javax.jms.JMSException jmse) { System.out.println("Error: connection not started."); jmse.printStackTrace(); System.exit(1); } //Wait for user input try { System.out.println("\nDurableChat application:\n" + "========================\n" + "The user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will publish messages to the " + APP_TOPIC + " topic.\n" + "The application also creates a durable subscription to that topic to consume any messages published there.\n\n" + "Type some text, and then press Enter to publish it as a TextMesssage from " + username + ".\n"); java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { String s = stdin.readLine(); if (s == null) { exit(); } else if (s.length() > 0) { try { javax.jms.TextMessage msg = pubSession.createTextMessage(); msg.setText(username + ": " + s); //Publish the message persistantly: publisher.send(msg, //message javax.jms.DeliveryMode.PERSISTENT, //publish persistently javax.jms.Message.DEFAULT_PRIORITY, //priority MESSAGE_LIFESPAN); //Time to Live } catch (javax.jms.JMSException jmse) { System.err.println("Error publishing message:" + jmse.getMessage()); } } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }
From source file:org.apache.qpid.multiconsumer.AMQTest.java
public void testCompression() throws Exception { setup();//from ww w . j a v a 2 s. c om String comp = this.compressString(HUGECONTENT); try { MsgHandler listener = new MsgHandler(); MessageConsumer subscriber = subSession.createConsumer(topic); subscriber.setMessageListener(listener); MessageProducer publisher = pubSession.createProducer(topic); // Send a single message TextMessage msg = pubSession.createTextMessage(); // Set the compressed text msg.setText(comp); msg.setBooleanProperty(COMPRESSION_PROPNAME, true); publisher.send(msg); Thread.sleep(1000); // Check listeners to ensure we got it if (listener.isGotIt()) { System.out.println("Got callback for listener"); } else { TestCase.fail("Listener did not get callback"); } } finally { close(); } }
From source file:HierarchicalChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password, String pubTopicname, String subTopicname) {/*from w w w . ja v a 2 s. c om*/ // Create a connection. try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics // Note that the publish and subscribe topics are different. try { javax.jms.Topic subscriberTopic = pubSession.createTopic(subTopicname); javax.jms.MessageConsumer subscriber = subSession.createConsumer(subscriberTopic, null, false); subscriber.setMessageListener(this); javax.jms.Topic publisherTopic = pubSession.createTopic(pubTopicname); publisher = pubSession.createProducer(publisherTopic); // Now that setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); System.out.println("\nHierarchicalChat application:\n" + "============================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will publish messages to the " + DEFAULT_PUBLISHER_TOPIC + " topic." + ".\n" + "The application also subscribes to topics using the wildcard syntax " + DEFAULT_SUBSCRIBER_TOPIC + " so that it can receive all messages to " + DEFAULT_SUBSCRIBER_ROOT + " and its subtopics.\n\n" + "Type some text, and then press Enter to publish a TextMesssage from " + username + ".\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0) { javax.jms.TextMessage msg = pubSession.createTextMessage(); msg.setText(username + ": " + s); publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:SelectorChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password, String selection) { // Create a connection. try {//from w ww . jav a2 s . c o m javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics try { javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC); // NOTE: The subscriber's message selector will now be set: javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic, PROPERTY_NAME + " = \'" + selection + "\'", false); subscriber.setMessageListener(this); publisher = pubSession.createProducer(topic); // Now that setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); System.exit(1); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); System.out.println("\nSelectorChat application:\n" + "===========================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will publish messages with " + PROPERTY_NAME + " set to " + selection + " to the " + APP_TOPIC + " topic .\n" + "The application also subscribes to that topic, selecting only messages where " + PROPERTY_NAME + " is " + selection + ".\n" + "Type some text, and then press Enter to publish it as a TextMesssage from " + username + ".\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0) { javax.jms.TextMessage msg = pubSession.createTextMessage(); msg.setText(username + ": " + s); // NOTE: here we set a property on messages to be published: msg.setStringProperty(PROPERTY_NAME, selection); publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java
@SuppressWarnings("resource") @Test//from w w w . j av a 2 s . c o m public void messageCorrelationBasedOnRequestMessageId() throws Exception { ActiveMqTestUtils.prepare(); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "producer-temp-reply-consumers.xml", this.getClass()); RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class); CachingConnectionFactory connectionFactory = context.getBean(CachingConnectionFactory.class); final JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory); final Destination requestDestination = context.getBean("siOutQueue", Destination.class); new Thread(() -> { final Message requestMessage = jmsTemplate.receive(requestDestination); Destination replyTo = null; try { replyTo = requestMessage.getJMSReplyTo(); } catch (Exception e) { fail(); } jmsTemplate.send(replyTo, (MessageCreator) session -> { try { TextMessage message = session.createTextMessage(); message.setText("bar"); message.setJMSCorrelationID(requestMessage.getJMSMessageID()); return message; } catch (Exception e) { // ignore } return null; }); }).start(); gateway.exchange(new GenericMessage<String>("foo")); context.close(); }
From source file:TransactedChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password) { // Create a connection. try {/* w ww. jav a2 s . c o m*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); // We want to be able up commit/rollback messages published, // but not affect messages consumed. Therefore, we need two sessions. publishSession = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); subscribeSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics try { javax.jms.Topic topic = subscribeSession.createTopic(APP_TOPIC); javax.jms.MessageConsumer subscriber = subscribeSession.createConsumer(topic); subscriber.setMessageListener(this); publisher = publishSession.createProducer(topic); // Now start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); boolean showMessage = true; while (true) { if (showMessage) { System.out.println("TransactedChat application:"); System.out.println("==========================="); System.out.println("The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + "."); System.out.println("The application will stage messages to the " + APP_TOPIC + " topic until you either commit them or roll them back."); System.out.println( "The application also subscribes to that topic to consume any committed messages published there.\n"); System.out.println("1. Enter text to publish and then press Enter to stage the message."); System.out.println("2. Add a few messages to the transaction batch."); System.out.println("3. Then, either:"); System.out.println( " o Enter the text 'COMMIT', and press Enter to publish all the staged messages."); System.out.println( " o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent."); showMessage = false; } String s = stdin.readLine(); if (s == null) exit(); else if (s.trim().equals("CANCEL")) { // Rollback the messages. A new transaction is implicitly // started for following messages. System.out.println("Cancelling messages..."); publishSession.rollback(); System.out.println("Staged messages have been cleared."); showMessage = false; // don't show the help message again. } else if (s.length() > 0) // See if we should send the messages if (s.trim().equals("COMMIT")) { // Commit (send) the messages. A new transaction is // implicitly started for following messages. System.out.println("Committing messages... "); publishSession.commit(); System.out.println("Staged messages have all been sent."); showMessage = false; // dont't show the help message again. } else { javax.jms.TextMessage msg = publishSession.createTextMessage(); msg.setText(username + ": " + s); // Publish the message persistently publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:com.att.ajsc.csilogging.common.QueueConnector.java
@Async public void sendPerformanceLog(String perfLog) { if (pefQueueSession != null && pefQueueSender != null) { TextMessage msg; try {/* ww w .j ava2s . c o m*/ msg = pefQueueSession.createTextMessage(); msg.setText(perfLog); logger.info("sending performance log to the CSI"); pefQueueSender.send(msg); perfSuccessiveFailureCount = 0; } catch (Exception e) { logger.error("Error while sending performance log to the Queue" + e); perfSuccessiveFailureCount++; if (perfSuccessiveFailureCount > PERF_SUCCESSIVE_FAILURE_LIMIT) { try { if (pefQueueSession != null) { pefQueueSession.close(); } if (pefQueueConnection != null) { pefQueueConnection.close(); } } catch (Exception exception) { logger.error("Error while closing performance log queue connections", exception); } pefQueueSender = null; pefQueueSender = null; pefQueueConnection = null; } } } else if (pefQueueSession == null && pefQueueSender == null && YES.equals(System.getenv(restartPerformanceQueue))) { logger.info("restarting the queues"); init(); sendPerformanceLog(perfLog); } }
From source file:com.att.ajsc.csilogging.common.QueueConnector.java
@Async public void sendAuditLog(String auditLog) { if (auditQueueSender != null && auditQueueSession != null) { TextMessage msg; try {/*from ww w . j a v a 2 s. com*/ msg = auditQueueSession.createTextMessage(); msg.setText(auditLog); logger.info("Sending audit log to the CSI"); auditQueueSender.send(msg); auditSuccessiveFailureCount = 0; } catch (Exception e) { logger.error("Error while sending audit log to the Queue" + e); auditSuccessiveFailureCount++; if (auditSuccessiveFailureCount > AUDIT_SUCCESSIVE_FAILURE_LIMIT) { try { if (auditQueueSession != null) { auditQueueSession.close(); } if (auditQueueConnection != null) { auditQueueConnection.close(); } } catch (Exception exception) { logger.error("Error while closing performance log queue connections", exception); } auditQueueSession = null; auditQueueSender = null; auditQueueConnection = null; } } } else if (auditQueueSession == null && auditQueueSender == null && YES.equals(restartAuditQueue)) { init(); sendPerformanceLog(auditLog); } }
From source file:TopicReplier.java
/** * Handle the message./*from ww w . j a v a 2 s .c om*/ * (as specified in the javax.jms.MessageListener interface). * * IMPORTANT NOTE: We must follow the design paradigm for JMS * synchronous requests. That is, we must: * - get the message * - look for the header specifying JMSReplyTo * - send a reply to the topic specified there. * Failing to follow these steps might leave the originator * of the request waiting forever. * * OPTIONAL BEHAVIOR: The following actions taken by the * message handler represent good programming style, but are * not required by the design paradigm for JMS requests. * - set the JMSCorrelationID (tying the response back to * the original request. * - use transacted session "commit" so receipt of request * won't happen without the reply being sent. * */ public void onMessage(javax.jms.Message aMessage) { try { // Cast the message as a text message. javax.jms.TextMessage textMessage = (javax.jms.TextMessage) aMessage; // This handler reads a single String from the // message and prints it to the standard output. try { String string = textMessage.getText(); System.out.println("[Request] " + string); // Check for a ReplyTo topic javax.jms.Topic replyTopic = (javax.jms.Topic) aMessage.getJMSReplyTo(); if (replyTopic != null) { // Send the modified message back. javax.jms.TextMessage reply = session.createTextMessage(); if (imode == UPPERCASE) reply.setText("Transformed " + string + " to all uppercase: " + string.toUpperCase()); else reply.setText("Transformed " + string + " to all lowercase " + string.toLowerCase()); reply.setJMSCorrelationID(aMessage.getJMSMessageID()); replier.send(replyTopic, reply); session.commit(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }
From source file:org.aludratest.service.jms.JmsActionImplTest.java
@Test public void testBasicJms() { String queueName = queues[0]; String textContent = UUID.randomUUID().toString(); try {/* w ww . ja v a 2 s. c o m*/ LOGGER.info("Begin testBasicJms"); LOGGER.info("Creating and sending TextMessage to queue " + queueName); TextMessage sentMessage = perform.createTextMessage(); sentMessage.setText(textContent); perform.sendMessage(sentMessage, queueName); LOGGER.info("Receiving TextMessage from queue " + queueName); Message receivedMessage = perform.receiveMessage(queues[0], 20); Assert.assertNotNull(receivedMessage); Assert.assertTrue(receivedMessage instanceof TextMessage); Assert.assertTrue( StringUtils.equalsIgnoreCase(sentMessage.getText(), ((TextMessage) receivedMessage).getText())); LOGGER.info("End testBasicJms"); } catch (Exception e) { Assert.fail("Failed on testBasicJms " + " : " + e.getMessage()); } }