List of usage examples for javax.jms Message getJMSCorrelationID
String getJMSCorrelationID() throws JMSException;
From source file:org.logicblaze.lingo.jms.JmsServiceExporterMessageListener.java
/** * Creates the invocation result response message * /* w ww . j a va2 s .co m*/ * @param session * the JMS session to use * @param message * the original request message, in case we want to attach any * properties etc. * @param result * the invocation result * @return the message response to send * @throws javax.jms.JMSException * if creating the messsage failed */ protected Message createResponseMessage(Session session, Message message, RemoteInvocationResult result) throws JMSException { // an alternative strategy could be to use XStream and text messages // though some JMS providers, like ActiveMQ, might do this kind of thing // for us under the covers if (result == null) { throw new IllegalArgumentException("result cannot be null"); } Message answer = getMarshaller().createResponseMessage(session, result, message); // lets preserve the correlation ID answer.setJMSCorrelationID(message.getJMSCorrelationID()); return answer; }
From source file:org.exist.messaging.JmsMessageSender.java
/** * Create messaging results report//from ww w. j a v a 2s. c o m * * TODO shared code */ private NodeImpl createReport(Message message, XQueryContext xqcontext) { MemTreeBuilder builder = xqcontext.getDocumentBuilder(); // start root element int nodeNr = builder.startElement("", "JMS", "JMS", null); try { String txt = message.getJMSMessageID(); if (txt != null) { builder.startElement("", "MessageID", "MessageID", null); builder.characters(message.getJMSMessageID()); builder.endElement(); } } catch (JMSException ex) { LOG.error(ex); } try { String txt = message.getJMSCorrelationID(); if (txt != null) { builder.startElement("", "CorrelationID", "CorrelationID", null); builder.characters(message.getJMSCorrelationID()); builder.endElement(); } } catch (JMSException ex) { LOG.error(ex); } try { String txt = message.getJMSType(); if (txt != null) { builder.startElement("", "Type", "Type", null); builder.characters(message.getJMSType()); builder.endElement(); } } catch (JMSException ex) { LOG.error(ex); } // finish root element builder.endElement(); // return result return ((DocumentImpl) builder.getDocument()).getNode(nodeNr); }
From source file:org.apache.camel.component.jms.JmsBinding.java
public Map<String, Object> extractHeadersFromJms(Message jmsMessage, Exchange exchange) { Map<String, Object> map = new HashMap<String, Object>(); if (jmsMessage != null) { // lets populate the standard JMS message headers try {// ww w . j av a 2s .c o m map.put("JMSCorrelationID", jmsMessage.getJMSCorrelationID()); map.put("JMSDeliveryMode", jmsMessage.getJMSDeliveryMode()); map.put("JMSDestination", jmsMessage.getJMSDestination()); map.put("JMSExpiration", jmsMessage.getJMSExpiration()); map.put("JMSMessageID", jmsMessage.getJMSMessageID()); map.put("JMSPriority", jmsMessage.getJMSPriority()); map.put("JMSRedelivered", jmsMessage.getJMSRedelivered()); map.put("JMSTimestamp", jmsMessage.getJMSTimestamp()); // to work around OracleAQ not supporting the JMSReplyTo header (CAMEL-2909) try { map.put("JMSReplyTo", jmsMessage.getJMSReplyTo()); } catch (JMSException e) { LOG.trace("Cannot read JMSReplyTo header. Will ignore this exception.", e); } // to work around OracleAQ not supporting the JMSType header (CAMEL-2909) try { map.put("JMSType", jmsMessage.getJMSType()); } catch (JMSException e) { LOG.trace("Cannot read JMSType header. Will ignore this exception.", e); } // this works around a bug in the ActiveMQ property handling map.put("JMSXGroupID", jmsMessage.getStringProperty("JMSXGroupID")); } catch (JMSException e) { throw new RuntimeCamelException(e); } Enumeration names; try { names = jmsMessage.getPropertyNames(); } catch (JMSException e) { throw new RuntimeCamelException(e); } while (names.hasMoreElements()) { String name = names.nextElement().toString(); try { Object value = jmsMessage.getObjectProperty(name); if (headerFilterStrategy != null && headerFilterStrategy.applyFilterToExternalHeaders(name, value, exchange)) { continue; } // must decode back from safe JMS header name to original header name // when storing on this Camel JmsMessage object. String key = jmsKeyFormatStrategy.decodeKey(name); map.put(key, value); } catch (JMSException e) { throw new RuntimeCamelException(name, e); } } } return map; }
From source file:org.springframework.integration.jms.JmsOutboundGatewayTests.java
@Test public void testReplyContainerRecovery() throws Exception { JmsOutboundGateway gateway = new JmsOutboundGateway(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); gateway.setConnectionFactory(connectionFactory); gateway.setRequestDestinationName("foo"); gateway.setUseReplyContainer(true);/*from w ww .j a va 2 s. c o m*/ ReplyContainerProperties replyContainerProperties = new ReplyContainerProperties(); final List<Throwable> errors = new ArrayList<Throwable>(); ErrorHandlingTaskExecutor errorHandlingTaskExecutor = new ErrorHandlingTaskExecutor( Executors.newFixedThreadPool(10), new ErrorHandler() { @Override public void handleError(Throwable t) { logger.info("Error:", t); errors.add(t); throw new RuntimeException(t); } }); replyContainerProperties.setTaskExecutor(errorHandlingTaskExecutor); replyContainerProperties.setRecoveryInterval(100L); gateway.setReplyContainerProperties(replyContainerProperties); final Connection connection = mock(Connection.class); final AtomicInteger connectionAttempts = new AtomicInteger(); doAnswer(new Answer<Connection>() { @SuppressWarnings("serial") @Override public Connection answer(InvocationOnMock invocation) throws Throwable { int theCount = connectionAttempts.incrementAndGet(); if (theCount > 1 && theCount < 4) { throw new JmsException("bar") { }; } return connection; } }).when(connectionFactory).createConnection(); Session session = mock(Session.class); when(connection.createSession(false, 1)).thenReturn(session); MessageConsumer consumer = mock(MessageConsumer.class); when(session.createConsumer(any(Destination.class), anyString())).thenReturn(consumer); when(session.createTemporaryQueue()).thenReturn(mock(TemporaryQueue.class)); final Message message = mock(Message.class); final AtomicInteger count = new AtomicInteger(); doAnswer(new Answer<Message>() { @SuppressWarnings("serial") @Override public Message answer(InvocationOnMock invocation) throws Throwable { int theCount = count.incrementAndGet(); if (theCount > 1 && theCount < 4) { throw new JmsException("foo") { }; } if (theCount > 4) { Thread.sleep(100); return null; } return message; } }).when(consumer).receive(anyLong()); when(message.getJMSCorrelationID()).thenReturn("foo"); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize(); beanFactory.registerSingleton("taskScheduler", taskScheduler); gateway.setBeanFactory(beanFactory); gateway.afterPropertiesSet(); gateway.start(); Thread.sleep(1000); assertTrue(count.get() > 4); assertEquals(0, errors.size()); }
From source file:org.apache.servicemix.jms.JmsProviderEndpointTest.java
public void testSoapProviderInOut() throws Exception { JmsComponent component = new JmsComponent(); JmsSoapProviderEndpoint endpoint = new JmsSoapProviderEndpoint(); endpoint.setService(new QName("uri:HelloWorld", "HelloService")); endpoint.setEndpoint("HelloPort"); endpoint.setConnectionFactory(connectionFactory); endpoint.setDestinationName("destination"); endpoint.setReplyDestinationName("reply"); endpoint.setWsdl(new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC.wsdl")); component.setEndpoints(new JmsProviderEndpoint[] { endpoint }); container.activateComponent(component, "servicemix-jms"); Thread th = new Thread() { public void run() { try { final Message msg = jmsTemplate.receive("destination"); assertNotNull(msg);//ww w. j a v a 2 s .co m final ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copyInputStream( new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC-Output.xml") .getInputStream(), baos); jmsTemplate.send("reply", new MessageCreator() { public Message createMessage(Session session) throws JMSException { TextMessage rep = session.createTextMessage(baos.toString()); rep.setJMSCorrelationID(msg.getJMSCorrelationID() != null ? msg.getJMSCorrelationID() : msg.getJMSMessageID()); return rep; } }); } catch (Exception e) { e.printStackTrace(); } } }; th.start(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtil.copyInputStream( new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC-Input-Hello.xml").getInputStream(), baos); InOut me = client.createInOutExchange(); me.getInMessage().setContent(new StringSource(baos.toString())); me.setOperation(new QName("uri:HelloWorld", "Hello")); me.setService(new QName("uri:HelloWorld", "HelloService")); client.sendSync(me); assertEquals(ExchangeStatus.ACTIVE, me.getStatus()); assertNotNull(me.getOutMessage()); assertNotNull(me.getOutMessage().getContent()); System.err.println(new SourceTransformer().contentToString(me.getOutMessage())); client.done(me); }
From source file:org.mitre.mpf.markup.MarkupRequestConsumer.java
public void onMessage(Message message) { Stopwatch stopwatch = Stopwatch.createStarted(); if (message == null) { log.warn("Received a null JMS message. No action will be taken."); return;//from w w w . j a v a2s . c om } if (!(message instanceof BytesMessage)) { log.warn("Received a JMS message, but it was not of the correct type. No action will be taken."); return; } try { log.info("Received JMS message. Type = {}. JMS Message ID = {}. JMS Correlation ID = {}.", message.getClass().getName(), message.getJMSMessageID(), message.getJMSCorrelationID()); final Map<String, Object> requestHeaders = new HashMap<String, Object>(); Enumeration<String> properties = message.getPropertyNames(); String propertyName = null; while (properties.hasMoreElements()) { propertyName = properties.nextElement(); requestHeaders.put(propertyName, message.getObjectProperty(propertyName)); } byte[] messageBytes = new byte[(int) (((BytesMessage) message).getBodyLength())]; ((BytesMessage) message).readBytes(messageBytes); Markup.MarkupRequest markupRequest = Markup.MarkupRequest.parseFrom(messageBytes); Markup.MarkupResponse.Builder markupResponseBuilder = initializeResponse(markupRequest); markupResponseBuilder.setRequestTimestamp(message.getJMSTimestamp()); log.debug("Processing markup request. Media Index = {}. Media ID = {} (type = {}). Request ID = {}.", markupRequest.getMediaIndex(), markupRequest.getMediaId(), markupRequest.getMediaType(), markupRequest.getRequestId()); try { if (!new File(URI.create(markupRequest.getDestinationUri())).canWrite()) { throw new Exception(); } } catch (Exception exception) { markupResponseBuilder.setHasError(true); markupResponseBuilder.setErrorMessage( String.format("The target URI '%s' is not writable.", markupRequest.getDestinationUri())); } try { if (!new File(URI.create(markupRequest.getSourceUri())).canRead()) { throw new Exception(); } } catch (Exception exception) { markupResponseBuilder.setHasError(true); markupResponseBuilder.setErrorMessage( String.format("The source URI '%s' is not readable.", markupRequest.getSourceUri())); } if (!markupResponseBuilder.getHasError()) { if (markupRequest.getMapEntriesCount() == 0) { try { FileUtils.copyFile(new File(URI.create(markupRequest.getSourceUri())), new File(URI.create(markupRequest.getDestinationUri()))); markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri()); } catch (Exception exception) { log.error("Failed to mark up the file '{}' because of an exception.", markupRequest.getSourceUri(), exception); finishWithError(markupResponseBuilder, exception); } } else if (markupRequest.getMediaType() == Markup.MediaType.IMAGE) { try { if (markupImage(markupRequest)) { markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri()); } else { markupResponseBuilder.setOutputFileUri(markupRequest.getSourceUri()); } } catch (Exception exception) { log.error("Failed to mark up the image '{}' because of an exception.", markupRequest.getSourceUri(), exception); finishWithError(markupResponseBuilder, exception); } } else { try { if (markupVideo(markupRequest)) { markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri()); } else { markupResponseBuilder.setOutputFileUri(markupRequest.getDestinationUri()); } } catch (Exception exception) { log.error("Failed to mark up the video '{}' because of an exception.", markupRequest.getSourceUri(), exception); finishWithError(markupResponseBuilder, exception); } } } stopwatch.stop(); markupResponseBuilder.setTimeProcessing(stopwatch.elapsed(TimeUnit.MILLISECONDS)); final Markup.MarkupResponse markupResponse = markupResponseBuilder.build(); log.info("Returning response for Media {}. Error: {}.", markupResponse.getMediaId(), markupResponse.getHasError()); markupResponseTemplate.setSessionTransacted(true); markupResponseTemplate.setDefaultDestination(message.getJMSReplyTo()); markupResponseTemplate.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { BytesMessage bytesMessage = session.createBytesMessage(); bytesMessage.writeBytes(markupResponse.toByteArray()); for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) { bytesMessage.setObjectProperty(entry.getKey(), entry.getValue()); } return bytesMessage; } }); } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:org.grouter.common.jms.TopicListenerDestination.java
/** * <br>/*w w w. java 2 s .com*/ */ public void sendReplyToTemporaryDestination(Message request) { TemporaryTopic replyTopic = null; TopicPublisher tempsender = null; String temporaryDestinationName = null; try { if (request.getJMSReplyTo() == null) { throw new IllegalStateException("The sender of this message has not entered a JMSReplyTo field - " + "impossible to send reply on temporary destination!!"); } temporaryDestinationName = request.getJMSReplyTo().toString(); request.setJMSCorrelationID(request.getJMSMessageID()); logger.debug("JMSCorrelationID was set!!!" + request.getJMSCorrelationID()); replyTopic = (TemporaryTopic) request.getJMSReplyTo(); tempsender = topicSession.createPublisher(replyTopic); logger.debug("Created a tempsender and sending reply to " + replyTopic); tempsender.send(request); } catch (JMSException ex) { //ignore logger.warn("Failed sending reply on temporary destination : " + temporaryDestinationName); } finally { try { if (tempsender != null) { tempsender.close(); } if (replyTopic != null) { replyTopic.delete(); } } catch (JMSException ex1) { //ignore } } }
From source file:org.apache.servicemix.jms.endpoints.JmsProviderEndpoint.java
/** * Process a JMS response message./*from w ww. j a v a 2 s .c o m*/ * This method delegates to the marshaler for the JBI out message creation * and sends it in to the NMR. * * @param message */ protected void onMessage(Message message) { MessageExchange exchange = null; try { exchange = (InOut) store.load(message.getJMSCorrelationID()); if (exchange == null) { throw new IllegalStateException("Could not find exchange " + message.getJMSCorrelationID()); } } catch (Exception e) { logger.error("Unable to load exchange related to incoming JMS message " + message, e); } try { NormalizedMessage out = exchange.getMessage("out"); if (out == null) { out = exchange.createMessage(); exchange.setMessage(out, "out"); } marshaler.populateMessage(message, exchange, out); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error while populating JBI exchange " + exchange, e); } exchange.setError(e); } try { boolean txSync = exchange.isTransacted() && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC)); if (txSync) { sendSync(exchange); } else { send(exchange); } } catch (Exception e) { logger.error("Unable to send JBI exchange " + exchange, e); } }
From source file:org.jwebsocket.jms.endpoint.JMSEndPointSender.java
/** * * @param aEndPoint// w w w . ja v a2s.c o m */ public JMSEndPointSender(JMSEndPoint aEndPoint) { mEndPoint = aEndPoint; mSession = aEndPoint.getSession(); mProducer = aEndPoint.getProducer(); mEndPointId = aEndPoint.getEndPointId(); mEndPoint.addListener(new IJMSMessageListener() { @Override public JMSEndPointSender getSender() { return null; } @Override public void setSender(JMSEndPointSender aSender) { } @Override public void onMessage(Message aMessage) { // mLog.debug("onMessage: " + aMessage); } @Override public void onBytesMessage(BytesMessage aMessage) { // mLog.debug("onBytesMessage: " + aMessage); } @Override public void onTextMessage(final TextMessage aMessage) { // mLog.debug("### onTextMessage: " + aMessage); try { boolean lIsProgressEvent = false; // try to get the correlation id (utid) directly from the message String lKey = aMessage.getJMSCorrelationID(); // if no correllation id (utid) found try to get it from token if (null == lKey) { Token lToken = JSONProcessor.JSONStringToToken(aMessage.getText()); if (null != lToken) { lKey = String.valueOf(lToken.getInteger("utid")); lIsProgressEvent = "event".equals(lToken.getString("type")) && "progress".equals(lToken.getString("name")); } } if (null != lKey) { // trying to get available response listener final IJMSResponseListener lRespListener; if (lIsProgressEvent) { lRespListener = mResponseListeners.get(lKey); } else { lRespListener = mResponseListeners.remove(lKey); } // if listener exists if (null != lRespListener) { // getting the response text final String lResponse = aMessage.getText(); // invoke "onResponse" callback out of this thread Tools.getThreadPool().submit(new Runnable() { @Override public void run() { lRespListener.onResponse(lResponse, aMessage); } }); } } } catch (JMSException lEx) { } // try { // boolean lIsProgressEvent = false; // // getting the correlation ID // String lKey = aMessage.getJMSCorrelationID(); // // // TODO: fix this temporary patch in the future, using only the JMSCorrelationID // if (null == lKey) { // Token lToken = JSONProcessor.JSONStringToToken(aMessage.getText()); // if (null != lToken && lToken.getMap().containsKey("utid")) { // lKey = String.valueOf(lToken.getInteger("utid")); // } // } // // // in case of progress events the utid is negative // if (null != lKey && lKey.startsWith("-")) { // lIsProgressEvent = true; // // cut leading "-" // lKey = lKey.substring(1); // } // // if (null != lKey) { // // trying to get available response listener // final IJMSResponseListener lRespListener; // if (lIsProgressEvent) { // lRespListener = mResponseListeners.get(lKey); // } else { // lRespListener = mResponseListeners.remove(lKey); // } // mLog.warn("#### Message A: " + aMessage.getText()); // // // if listener exists // if (null != lRespListener) { // // getting the response text // final String lResponse = aMessage.getText(); // // invoke "onResponse" callback out of this thread // Tools.getThreadPool().submit(new Runnable() { // @Override // public void run() { // mLog.warn("#### Message B: " + lResponse); // lRespListener.onResponse(lResponse, aMessage); // } // }); // } // } // // } catch (JMSException lEx) { // } } @Override public void onMapMessage(MapMessage aMessage) { } @Override public void onObjectMessage(ObjectMessage aMessage) { } }); }
From source file:org.apache.camel.component.jms.EndpointMessageListener.java
public void onMessage(final Message message) { LOG.trace("onMessage START"); if (LOG.isDebugEnabled()) { LOG.debug(endpoint + " consumer received JMS message: " + message); }//from w ww. j a v a 2 s . c o m RuntimeCamelException rce = null; try { Object replyDestination = getReplyToDestination(message); final Exchange exchange = createExchange(message, replyDestination); if (eagerLoadingOfProperties) { exchange.getIn().getHeaders(); } // process the exchange if (LOG.isTraceEnabled()) { LOG.trace("onMessage.process START"); } String correlationId = message.getJMSCorrelationID(); if (correlationId != null) { LOG.debug("Received Message has JMSCorrelationID [" + correlationId + "]"); } try { processor.process(exchange); } catch (Throwable e) { exchange.setException(e); } if (LOG.isTraceEnabled()) { LOG.trace("onMessage.process END"); } // get the correct jms message to send as reply JmsMessage body = null; Exception cause = null; boolean sendReply = false; if (exchange.isFailed() || exchange.isRollbackOnly()) { if (exchange.getException() != null) { // an exception occurred while processing if (endpoint.isTransferException()) { // send the exception as reply body = null; cause = exchange.getException(); sendReply = true; } else { // only throw exception if endpoint is not configured to transfer exceptions back to caller // do not send a reply but wrap and rethrow the exception rce = wrapRuntimeCamelException(exchange.getException()); } } else if (exchange.isRollbackOnly()) { // rollback only so wrap an exception so we can rethrow the exception to cause rollback rce = wrapRuntimeCamelException(new RollbackExchangeException(exchange)); } else if (exchange.getOut().getBody() != null) { // a fault occurred while processing body = (JmsMessage) exchange.getOut(); sendReply = true; } } else if (exchange.hasOut()) { // process OK so get the reply body = (JmsMessage) exchange.getOut(); sendReply = true; } // send the reply if we got a response and the exchange is out capable if (rce == null && sendReply && !disableReplyTo && exchange.getPattern().isOutCapable()) { LOG.trace("onMessage.sendReply START"); if (replyDestination instanceof Destination) { sendReply((Destination) replyDestination, message, exchange, body, cause); } else { sendReply((String) replyDestination, message, exchange, body, cause); } LOG.trace("onMessage.sendReply END"); } } catch (Exception e) { rce = wrapRuntimeCamelException(e); } if (rce != null) { handleException(rce); if (LOG.isTraceEnabled()) { LOG.trace("onMessage END throwing exception: " + rce.getMessage()); } throw rce; } LOG.trace("onMessage END"); }