List of usage examples for javax.jms TextMessage setText
void setText(String string) throws JMSException;
From source file:org.exist.messaging.JmsMessageSender.java
private Message createMessage(Session session, Item item, MessagingMetadata mdd, XQueryContext xqcontext) throws JMSException, XPathException { Message message = null;//from www . j a va 2s . c om mdd.add("exist.datatype", Type.getTypeName(item.getType())); if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) { LOG.debug("Streaming element or document node"); if (item instanceof NodeProxy) { NodeProxy np = (NodeProxy) item; String uri = np.getDocument().getBaseURI(); LOG.debug("Document detected, adding URL " + uri); mdd.add("exist.document-uri", uri); } // Node provided Serializer serializer = xqcontext.getBroker().newSerializer(); NodeValue node = (NodeValue) item; InputStream is = new NodeInputStream(serializer, node); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException ex) { LOG.error(ex); throw new XPathException(ex); } IOUtils.closeQuietly(is); IOUtils.closeQuietly(baos); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(baos.toByteArray()); message = bytesMessage; } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) { LOG.debug("Streaming base64 binary"); if (item instanceof Base64BinaryDocument) { Base64BinaryDocument b64doc = (Base64BinaryDocument) item; String uri = b64doc.getUrl(); LOG.debug("Base64BinaryDocument detected, adding URL " + uri); mdd.add("exist.document-uri", uri); } BinaryValue binary = (BinaryValue) item; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = binary.getInputStream(); //TODO consider using BinaryValue.getInputStream() //byte[] data = (byte[]) binary.toJavaObject(byte[].class); try { IOUtils.copy(is, baos); } catch (IOException ex) { LOG.error(ex); throw new XPathException(ex); } IOUtils.closeQuietly(is); IOUtils.closeQuietly(baos); BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(baos.toByteArray()); message = bytesMessage; } else if (item.getType() == Type.STRING) { TextMessage textMessage = session.createTextMessage(); textMessage.setText(item.getStringValue()); message = textMessage; } else { ObjectMessage objectMessage = session.createObjectMessage(); //objectMessage.setObject(item.toJavaObject(Object.class)); TODO hmmmm message = objectMessage; } return message; }
From source file:Talk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue) { // Create a connection. try {/*from w w w . ja v a 2 s . c o m*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = 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 Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue); qReceiver.setMessageListener(this); // Now that 'receive' setup is complete, start the Connection connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) System.out.println("\nTalk application:\n" + "=================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will send messages to the " + sQueue + " queue.\n" + "The application creates a receiver on the " + rQueue + " queue to consume any messages allocated to it.\n\n" + "Type some text, and then press Enter to send it as a TextMesssage from " + username + ".\n"); else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // Queues usually are used for PERSISTENT messages. // Hold messages for 30 minutes (1,800,000 millisecs). sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java
@Test public void messageCorrelationBasedOnRequestCorrelationIdTimedOutFirstReply() throws Exception { ActiveMqTestUtils.prepare();/*from w ww . j a v a 2s. co m*/ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "producer-temp-reply-consumers.xml", this.getClass()); RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class); ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); final Destination requestDestination = context.getBean("siOutQueue", Destination.class); DefaultMessageListenerContainer dmlc = new DefaultMessageListenerContainer(); dmlc.setConnectionFactory(connectionFactory); dmlc.setDestination(requestDestination); dmlc.setMessageListener((SessionAwareMessageListener<Message>) (message, session) -> { Destination replyTo = null; try { replyTo = message.getJMSReplyTo(); } catch (Exception e1) { fail(); } String requestPayload = (String) extractPayload(message); if (requestPayload.equals("foo")) { try { Thread.sleep(6000); } catch (Exception e2) { /*ignore*/ } } try { TextMessage replyMessage = session.createTextMessage(); replyMessage.setText(requestPayload); replyMessage.setJMSCorrelationID(message.getJMSMessageID()); MessageProducer producer = session.createProducer(replyTo); producer.send(replyMessage); } catch (Exception e3) { // ignore. the test will fail } }); dmlc.afterPropertiesSet(); dmlc.start(); try { gateway.exchange(new GenericMessage<String>("foo")); } catch (Exception e) { // ignore } Thread.sleep(1000); try { assertEquals("bar", gateway.exchange(new GenericMessage<String>("bar")).getPayload()); } catch (Exception e) { e.printStackTrace(); fail(); } context.close(); }
From source file:org.mule.transport.jms.JmsMessageUtilsTestCase.java
@Test public void testConvertingStringToTextMessage() throws JMSException { String text = "Hello world"; Session session = mock(Session.class); TextMessage textMessage = new ActiveMQTextMessage(); textMessage.setText(text); when(session.createTextMessage(text)).thenReturn(textMessage); TextMessage message = (TextMessage) JmsMessageUtils.toMessage(text, session); assertEquals(textMessage, message);/*from w ww. j av a 2 s . c o m*/ verify(session, times(1)).createTextMessage(text); }
From source file:Replier.java
/** * Handle the message./*from w w w. ja v a 2 s. com*/ * (as specified in the javax.jms.MessageListener interface). * * IMPORTANT NOTES: * (1)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 queue specified there. * Failing to follow these steps might leave the originator * of the request waiting forever. * (2)Unlike the 'Talk' sample and others using an asynchronous * message listener, it is possible here to use ONLY * ONE SESSION because the messages being sent are sent from * the same thread of control handling message delivery. For * more information see the JMS spec v1.0.2 section 4.4.6. * * 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 Queue javax.jms.Queue replyQueue = (javax.jms.Queue) aMessage.getJMSReplyTo(); if (replyQueue != null) { // Send the modified message back. javax.jms.TextMessage reply = session.createTextMessage(); if (imode == UPPERCASE) reply.setText("Uppercasing-" + string.toUpperCase()); else reply.setText("Lowercasing-" + string.toLowerCase()); reply.setJMSCorrelationID(aMessage.getJMSMessageID()); replier.send(replyQueue, reply); session.commit(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } catch (java.lang.RuntimeException rte) { rte.printStackTrace(); } }
From source file:SelectorTalk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue, String selection) {/*from www. j a va 2 s . com*/ // Create a connection. try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = 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 Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { //NOTE: the Queue Receiver is set up with the Message Selector: javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue, PROPERTY_NAME + " = \'" + selection + "\'"); qReceiver.setMessageListener(this); connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) System.out.println("SelectorTalk application:\n" + "=========================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will send messages with " + PROPERTY_NAME + " set to " + selection + " to the " + sQueue + " queue.\n" + "The application creates a receiver on the " + rQueue + " queue selecting only messages where " + PROPERTY_NAME + " is " + selection + ".\n\n" + "Type some text, and then press Enter to publish it as a TextMesssage from " + username + ".\n"); else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // NOTE: here we set the property for each sent message. msg.setStringProperty(PROPERTY_NAME, selection); sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSReplySender.java
/** * Create a JMS Message from the given MessageContext and using the given * session/*from w w w . j a v a 2 s . co m*/ * * @param msgContext * the MessageContext * @param session * the JMS session * @param contentTypeProperty * the message property to be used to store the content type * @return a JMS message from the context and session * @throws JMSException * on exception * @throws AxisFault * on exception */ private Message createJMSMessage(MessageContext synCtx, Session session, String contentTypeProperty) throws JMSException { Message message = null; org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) synCtx) .getAxis2MessageContext(); String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE); String jmsPayloadType = guessMessageType(msgContext); if (jmsPayloadType == null) { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new JMSException("Unable to get the message formatter to use"); } String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); boolean useBytesMessage = msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1; OutputStream out; StringWriter sw; if (useBytesMessage) { BytesMessage bytesMsg = session.createBytesMessage(); sw = null; out = new BytesMessageOutputStream(bytesMsg); message = bytesMsg; } else { sw = new StringWriter(); try { out = new WriterOutputStream(sw, format.getCharSetEncoding()); } catch (UnsupportedCharsetException ex) { log.error("Unsupported encoding " + format.getCharSetEncoding(), ex); throw new JMSException("Unsupported encoding " + format.getCharSetEncoding()); } } try { messageFormatter.writeTo(msgContext, format, out, true); out.close(); } catch (IOException e) { log.error("IO Error while creating BytesMessage", e); throw new JMSException("IO Error while creating BytesMessage"); } if (!useBytesMessage) { TextMessage txtMsg = session.createTextMessage(); txtMsg.setText(sw.toString()); message = txtMsg; } if (contentTypeProperty != null) { message.setStringProperty(contentTypeProperty, contentType); } } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) { message = session.createBytesMessage(); BytesMessage bytesMsg = (BytesMessage) message; OMElement wrapper = msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER); OMNode omNode = wrapper.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { try { ((DataHandler) dh).writeTo(new BytesMessageOutputStream(bytesMsg)); } catch (IOException e) { log.error("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER, e); throw new JMSException("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER); } } } } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) { message = session.createTextMessage(); TextMessage txtMsg = (TextMessage) message; txtMsg.setText(msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText()); } else if (JMSConstants.JMS_MAP_MESSAGE.equalsIgnoreCase(jmsPayloadType)) { message = session.createMapMessage(); JMSUtils.convertXMLtoJMSMap( msgContext.getEnvelope().getBody().getFirstChildWithName(JMSConstants.JMS_MAP_QNAME), (MapMessage) message); } // set the JMS correlation ID if specified String correlationId = (String) synCtx.getProperty(JMSConstants.JMS_COORELATION_ID); if (correlationId != null) { message.setJMSCorrelationID(correlationId); } if (msgContext.isServerSide()) { // set SOAP Action as a property on the JMS message setProperty(message, msgContext, BaseConstants.SOAPACTION); } else { String action = msgContext.getOptions().getAction(); if (action != null) { message.setStringProperty(BaseConstants.SOAPACTION, action); } } JMSUtils.setTransportHeaders(msgContext, message); return message; }
From source file:de.taimos.dvalin.interconnect.core.spring.DaemonMessageSender.java
private void sendIVO(final String correlationID, final Destination replyTo, final InterconnectObject ico, final boolean secure) throws Exception { final String json = InterconnectMapper.toJson(ico); this.logger.debug("TextMessage send: " + json); this.template.send(replyTo, new MessageCreator() { @Override//w ww . ja va2s .c om public Message createMessage(final Session session) throws JMSException { final TextMessage textMessage = session.createTextMessage(); textMessage.setStringProperty(InterconnectConnector.HEADER_ICO_CLASS, ico.getClass().getName()); textMessage.setJMSCorrelationID(correlationID); textMessage.setText(json); if (secure) { try { MessageConnector.secureMessage(textMessage); } catch (CryptoException e) { throw new JMSException(e.getMessage()); } } return textMessage; } }); }
From source file:TransactedTalk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue) { // Create a connection. try {//w w w . ja v a2s . co 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 sent, // but not affect messages received. Therefore, we need two sessions. sendSession = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = 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 Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue); qReceiver.setMessageListener(this); // Now that 'receive' setup is complete, start the Connection connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) { System.out.println("TransactedTalk 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 " + sQueue + " until you either commit them or roll them back."); System.out.println("The application receives messages on " + rQueue + " to consume any committed messages sent there.\n"); System.out.println("1. Enter text to send 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 send all the staged messages."); System.out.println( " o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent."); } else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { 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.print("Cancelling messages..."); sendSession.rollback(); System.out.println("Staged messages have been cleared."); } else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // Queues usually are used for PERSISTENT messages. // Hold messages for 30 minutes (1,800,000 millisecs). sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); // 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.print("Committing messages..."); sendSession.commit(); System.out.println("Staged messages have all been sent."); } } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
From source file:com.amalto.core.storage.task.staging.ClusteredStagingTaskManager.java
protected void sendCancellationMessage(final String dataContainer, final String taskId) { jmsTemplate.send(new MessageCreator() { @Override//from w ww .ja v a 2 s .co m public Message createMessage(Session session) throws JMSException { TextMessage message = session.createTextMessage(); try { String msg = StagingJobCancellationMessage .toString(new StagingJobCancellationMessage(dataContainer, taskId)); message.setText(msg); return message; } catch (JAXBException e) { LOGGER.error("Cannot unmarshall message", e); throw new JMSException("Cannot unmarshall message"); } } }); }