List of usage examples for javax.jms Message getJMSMessageID
String getJMSMessageID() throws JMSException;
From source file:org.springframework.integration.jms.DefaultJmsHeaderMapper.java
public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) { Map<String, Object> headers = new HashMap<String, Object>(); try {//from w w w. jav a2 s .c om try { String messageId = jmsMessage.getJMSMessageID(); if (messageId != null) { headers.put(JmsHeaders.MESSAGE_ID, messageId); } } catch (Exception e) { logger.info("failed to read JMSMessageID property, skipping", e); } try { String correlationId = jmsMessage.getJMSCorrelationID(); if (correlationId != null) { headers.put(JmsHeaders.CORRELATION_ID, correlationId); } } catch (Exception e) { logger.info("failed to read JMSCorrelationID property, skipping", e); } try { Destination replyTo = jmsMessage.getJMSReplyTo(); if (replyTo != null) { headers.put(JmsHeaders.REPLY_TO, replyTo); } } catch (Exception e) { logger.info("failed to read JMSReplyTo property, skipping", e); } try { headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered()); } catch (Exception e) { logger.info("failed to read JMSRedelivered property, skipping", e); } try { String type = jmsMessage.getJMSType(); if (type != null) { headers.put(JmsHeaders.TYPE, type); } } catch (Exception e) { logger.info("failed to read JMSType property, skipping", e); } try { headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp()); } catch (Exception e) { logger.info("failed to read JMSTimestamp property, skipping", e); } Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames(); if (jmsPropertyNames != null) { while (jmsPropertyNames.hasMoreElements()) { String propertyName = jmsPropertyNames.nextElement().toString(); try { String headerName = this.toHeaderName(propertyName); headers.put(headerName, jmsMessage.getObjectProperty(propertyName)); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("error occurred while mapping JMS property '" + propertyName + "' to Message header", e); } } } } } catch (JMSException e) { if (logger.isWarnEnabled()) { logger.warn("error occurred while mapping from JMS properties to MessageHeaders", e); } } return headers; }
From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java
@SuppressWarnings("resource") @Test/*ww w . j a v a2 s.com*/ 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:org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener.java
/** * Post-process the given response message before it will be sent. * <p>The default implementation sets the response's correlation id * to the request message's correlation id, if any; otherwise to the * request message id.//w ww . ja v a 2 s . co m * @param request the original incoming JMS message * @param response the outgoing JMS message about to be sent * @throws JMSException if thrown by JMS API methods * @see javax.jms.Message#setJMSCorrelationID */ protected void postProcessResponse(Message request, Message response) throws JMSException { String correlation = request.getJMSCorrelationID(); if (correlation == null) { correlation = request.getJMSMessageID(); } response.setJMSCorrelationID(correlation); }
From source file:org.springframework.jms.support.converter.SimpleJmsHeaderMapper.java
@Override public Map<String, Object> toHeaders(javax.jms.Message jmsMessage) { Map<String, Object> headers = new HashMap<String, Object>(); try {//from ww w. ja v a2s.c o m try { String correlationId = jmsMessage.getJMSCorrelationID(); if (correlationId != null) { headers.put(JmsHeaders.CORRELATION_ID, correlationId); } } catch (Exception e) { logger.info("failed to read JMSCorrelationID property, skipping", e); } try { Destination destination = jmsMessage.getJMSDestination(); if (destination != null) { headers.put(JmsHeaders.DESTINATION, destination); } } catch (Exception e) { logger.info("failed to read JMSDestination property, skipping", e); } try { int deliveryMode = jmsMessage.getJMSDeliveryMode(); headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode); } catch (Exception e) { logger.info("failed to read JMSDeliveryMode property, skipping", e); } try { long expiration = jmsMessage.getJMSExpiration(); headers.put(JmsHeaders.EXPIRATION, expiration); } catch (Exception e) { logger.info("failed to read JMSExpiration property, skipping", e); } try { String messageId = jmsMessage.getJMSMessageID(); if (messageId != null) { headers.put(JmsHeaders.MESSAGE_ID, messageId); } } catch (Exception e) { logger.info("failed to read JMSMessageID property, skipping", e); } try { headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority()); } catch (Exception e) { logger.info("failed to read JMSPriority property, skipping", e); } try { Destination replyTo = jmsMessage.getJMSReplyTo(); if (replyTo != null) { headers.put(JmsHeaders.REPLY_TO, replyTo); } } catch (Exception e) { logger.info("failed to read JMSReplyTo property, skipping", e); } try { headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered()); } catch (Exception e) { logger.info("failed to read JMSRedelivered property, skipping", e); } try { String type = jmsMessage.getJMSType(); if (type != null) { headers.put(JmsHeaders.TYPE, type); } } catch (Exception e) { logger.info("failed to read JMSType property, skipping", e); } try { headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp()); } catch (Exception e) { logger.info("failed to read JMSTimestamp property, skipping", e); } Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames(); if (jmsPropertyNames != null) { while (jmsPropertyNames.hasMoreElements()) { String propertyName = jmsPropertyNames.nextElement().toString(); try { String headerName = this.toHeaderName(propertyName); headers.put(headerName, jmsMessage.getObjectProperty(propertyName)); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("error occurred while mapping JMS property '" + propertyName + "' to Message header", e); } } } } } catch (JMSException e) { if (logger.isWarnEnabled()) { logger.warn("error occurred while mapping from JMS properties to MessageHeaders", e); } } return headers; }
From source file:org.springframework.jms.support.SimpleJmsHeaderMapper.java
@Override public MessageHeaders toHeaders(javax.jms.Message jmsMessage) { Map<String, Object> headers = new HashMap<String, Object>(); try {//from w w w . ja v a2s . c om try { String correlationId = jmsMessage.getJMSCorrelationID(); if (correlationId != null) { headers.put(JmsHeaders.CORRELATION_ID, correlationId); } } catch (Exception ex) { logger.info("failed to read JMSCorrelationID property, skipping", ex); } try { Destination destination = jmsMessage.getJMSDestination(); if (destination != null) { headers.put(JmsHeaders.DESTINATION, destination); } } catch (Exception ex) { logger.info("failed to read JMSDestination property, skipping", ex); } try { int deliveryMode = jmsMessage.getJMSDeliveryMode(); headers.put(JmsHeaders.DELIVERY_MODE, deliveryMode); } catch (Exception ex) { logger.info("failed to read JMSDeliveryMode property, skipping", ex); } try { long expiration = jmsMessage.getJMSExpiration(); headers.put(JmsHeaders.EXPIRATION, expiration); } catch (Exception ex) { logger.info("failed to read JMSExpiration property, skipping", ex); } try { String messageId = jmsMessage.getJMSMessageID(); if (messageId != null) { headers.put(JmsHeaders.MESSAGE_ID, messageId); } } catch (Exception ex) { logger.info("failed to read JMSMessageID property, skipping", ex); } try { headers.put(JmsHeaders.PRIORITY, jmsMessage.getJMSPriority()); } catch (Exception ex) { logger.info("failed to read JMSPriority property, skipping", ex); } try { Destination replyTo = jmsMessage.getJMSReplyTo(); if (replyTo != null) { headers.put(JmsHeaders.REPLY_TO, replyTo); } } catch (Exception ex) { logger.info("failed to read JMSReplyTo property, skipping", ex); } try { headers.put(JmsHeaders.REDELIVERED, jmsMessage.getJMSRedelivered()); } catch (Exception ex) { logger.info("failed to read JMSRedelivered property, skipping", ex); } try { String type = jmsMessage.getJMSType(); if (type != null) { headers.put(JmsHeaders.TYPE, type); } } catch (Exception ex) { logger.info("failed to read JMSType property, skipping", ex); } try { headers.put(JmsHeaders.TIMESTAMP, jmsMessage.getJMSTimestamp()); } catch (Exception ex) { logger.info("failed to read JMSTimestamp property, skipping", ex); } Enumeration<?> jmsPropertyNames = jmsMessage.getPropertyNames(); if (jmsPropertyNames != null) { while (jmsPropertyNames.hasMoreElements()) { String propertyName = jmsPropertyNames.nextElement().toString(); try { String headerName = this.toHeaderName(propertyName); headers.put(headerName, jmsMessage.getObjectProperty(propertyName)); } catch (Exception ex) { if (logger.isWarnEnabled()) { logger.warn("Error occurred while mapping JMS property '" + propertyName + "' to Message header", ex); } } } } } catch (JMSException ex) { if (logger.isWarnEnabled()) { logger.warn("Error occurred while mapping from JMS properties to MessageHeaders", ex); } } return new MessageHeaders(headers); }
From source file:org.wso2.carbon.event.output.adapter.jms.internal.util.JMSMessageSender.java
/** * Perform actual send of JMS message to the Destination selected *//*from w w w. ja v a 2 s. c o m*/ public void send(Object message, JMSEventAdapter.PublisherDetails publisherDetails, String jmsHeaders) { Map<String, String> messageProperties = publisherDetails.getMessageConfig(); Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND); Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY); Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE); Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY); Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE); MessageProducer producer = null; Destination destination = null; Session session = null; boolean sendingSuccessful = false; JMSConnectionFactory.JMSPooledConnectionHolder pooledConnection = null; try { pooledConnection = jmsConnectionFactory.getConnectionFromPool(); producer = pooledConnection.getProducer(); session = pooledConnection.getSession(); Message jmsMessage = convertToJMSMessage(message, publisherDetails.getMessageConfig(), session); setJMSTransportHeaders(jmsMessage, jmsHeaders); // Do not commit, if message is marked for rollback if (rollbackOnly != null && rollbackOnly) { jtaCommit = Boolean.FALSE; } if (persistent != null) { try { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer for PERSISTENT delivery", e); } } if (priority != null) { try { producer.setPriority(priority); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer priority to : " + priority, e); } } if (timeToLive != null) { try { producer.setTimeToLive(timeToLive); } catch (JMSException e) { handleConnectionException("Error setting JMS Producer TTL to : " + timeToLive, e); } } // perform actual message sending // try { if (jmsSpec11 || isQueue == null) { producer.send(jmsMessage); } else { if (isQueue) { ((QueueSender) producer).send(jmsMessage); } else { ((TopicPublisher) producer).publish(jmsMessage); } } sendingSuccessful = true; if (log.isDebugEnabled()) { // // set the actual MessageID to the message context for use by any others down the line String msgId = null; try { msgId = jmsMessage.getJMSMessageID(); } catch (JMSException jmse) { log.error(jmse.getMessage(), jmse); } log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination()); } } catch (JMSException e) { handleConnectionException("Error sending message to destination : " + destination, e); } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (jtaCommit != null) { try { if (session.getTransacted()) { if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) { session.commit(); } else { session.rollback(); } } if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " local (JMS Session) Transaction"); } } catch (Exception e) { handleConnectionException("Error committing/rolling back local (i.e. session) " + "transaction after sending of message "//with MessageContext ID : " + + " to destination : " + destination, e); } } if (pooledConnection != null) { jmsConnectionFactory.returnPooledConnection(pooledConnection); } } }
From source file:org.wso2.carbon.event.output.adaptor.jms.internal.util.JMSMessageSender.java
/** * Perform actual send of JMS message to the Destination selected * * @param messageProperties the Axis2 MessageContext *//*from w w w. j a v a2s .co m*/ public void send(Message jmsMessage, Map<String, String> messageProperties) { Boolean jtaCommit = getBooleanProperty(messageProperties, BaseConstants.JTA_COMMIT_AFTER_SEND); Boolean rollbackOnly = getBooleanProperty(messageProperties, BaseConstants.SET_ROLLBACK_ONLY); Boolean persistent = getBooleanProperty(messageProperties, JMSConstants.JMS_DELIVERY_MODE); Integer priority = getIntegerProperty(messageProperties, JMSConstants.JMS_PRIORITY); Integer timeToLive = getIntegerProperty(messageProperties, JMSConstants.JMS_TIME_TO_LIVE); // Do not commit, if message is marked for rollback if (rollbackOnly != null && rollbackOnly) { jtaCommit = Boolean.FALSE; } if (persistent != null) { try { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } catch (JMSException e) { handleException("Error setting JMS Producer for PERSISTENT delivery", e); } } if (priority != null) { try { producer.setPriority(priority); } catch (JMSException e) { handleException("Error setting JMS Producer priority to : " + priority, e); } } if (timeToLive != null) { try { producer.setTimeToLive(timeToLive); } catch (JMSException e) { handleException("Error setting JMS Producer TTL to : " + timeToLive, e); } } boolean sendingSuccessful = false; // perform actual message sending try { if (jmsSpec11 || isQueue == null) { producer.send(jmsMessage); } else { if (isQueue) { ((QueueSender) producer).send(jmsMessage); } else { ((TopicPublisher) producer).publish(jmsMessage); } } // // set the actual MessageID to the message context for use by any others down the line String msgId = null; try { msgId = jmsMessage.getJMSMessageID(); // if (msgId != null) { // msgCtx.setProperty(JMSConstants.JMS_MESSAGE_ID, msgId); // } } catch (JMSException ignore) { } sendingSuccessful = true; if (log.isDebugEnabled()) { log.debug(" with JMS Message ID : " + msgId + " to destination : " + producer.getDestination()); } } catch (JMSException e) { handleException("Error sending message to destination : " + destination, e); } finally { if (jtaCommit != null) { // UserTransaction ut = (UserTransaction) msgCtx.getProperty(BaseConstants.USER_TRANSACTION); // if (ut != null) { // // try { // if (sendingSuccessful && jtaCommit) { // ut.commit(); // } else { // ut.rollback(); // } // msgCtx.removeProperty(BaseConstants.USER_TRANSACTION); // // if (log.isDebugEnabled()) { // log.debug((sendingSuccessful ? "Committed" : "Rolled back") + // " JTA Transaction"); // } // // } catch (Exception e) { // handleException("Error committing/rolling back JTA transaction after " + // "sending of message "+//with MessageContext ID : " + msgCtx.getMessageID() + // " to destination : " + destination, e); // } // } // // } else { try { if (session.getTransacted()) { if (sendingSuccessful && (rollbackOnly == null || !rollbackOnly)) { session.commit(); } else { session.rollback(); } } if (log.isDebugEnabled()) { log.debug((sendingSuccessful ? "Committed" : "Rolled back") + " local (JMS Session) Transaction"); } } catch (JMSException e) { handleException("Error committing/rolling back local (i.e. session) " + "transaction after sending of message "//with MessageContext ID : " + + " to destination : " + destination, e); } } } }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSInjectHandler.java
/** * Invoke the mediation logic for the passed message * *//* ww w. j ava2s.c o m*/ public boolean invoke(Object object, String name) throws SynapseException { Message msg = (Message) object; try { org.apache.synapse.MessageContext msgCtx = createMessageContext(); msgCtx.setProperty("inbound.endpoint.name", name); InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name); CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName()); String contentType = msg.getJMSType(); if (contentType == null || contentType.trim().equals("")) { String contentTypeProperty = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE_PROPERTY); if (contentTypeProperty != null) { contentType = msg.getStringProperty(contentTypeProperty); } } else { msgCtx.setProperty(JMSConstants.JMS_MESSAGE_TYPE, contentType); } if (contentType == null || contentType.trim().equals("")) { contentType = jmsProperties.getProperty(JMSConstants.CONTENT_TYPE); } if (log.isDebugEnabled()) { log.debug("Processed JMS Message of Content-type : " + contentType); } MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx) .getAxis2MessageContext(); //setting transport headers axis2MsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, JMSUtils.getTransportHeaders(msg, axis2MsgCtx)); // set the JMS Message ID as the Message ID of the MessageContext try { msgCtx.setMessageID(msg.getJMSMessageID()); String jmsCorrelationID = msg.getJMSCorrelationID(); if (jmsCorrelationID != null && !jmsCorrelationID.isEmpty()) { msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID); } else { msgCtx.setProperty(JMSConstants.JMS_COORELATION_ID, msg.getJMSMessageID()); } } catch (JMSException ignore) { log.warn("Error getting the COORELATION ID from the message."); } // Handle dual channel Destination replyTo = msg.getJMSReplyTo(); if (replyTo != null) { msgCtx.setProperty(SynapseConstants.IS_INBOUND, true); // Create the cachedJMSConnectionFactory with the existing // connection CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory( jmsProperties, connection); String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME); String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD); JMSReplySender jmsReplySender = new JMSReplySender(replyTo, cachedJMSConnectionFactory, strUserName, strPassword); msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender); } else if (replyDestination != null) { msgCtx.setProperty(SynapseConstants.IS_INBOUND, true); // Create the cachedJMSConnectionFactory with the existing // connection CachedJMSConnectionFactory cachedJMSConnectionFactory = new CachedJMSConnectionFactory( jmsProperties, connection); String strUserName = jmsProperties.getProperty(JMSConstants.PARAM_JMS_USERNAME); String strPassword = jmsProperties.getProperty(JMSConstants.PARAM_JMS_PASSWORD); JMSReplySender jmsReplySender = new JMSReplySender(replyDestination, cachedJMSConnectionFactory, strUserName, strPassword); msgCtx.setProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER, jmsReplySender); } // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } OMElement documentElement = null; // set the message payload to the message context try { if (msg instanceof TextMessage) { String message = ((TextMessage) msg).getText(); InputStream in = new AutoCloseInputStream(new ByteArrayInputStream(message.getBytes())); documentElement = builder.processDocument(in, contentType, axis2MsgCtx); } else if (msg instanceof BytesMessage) { if (builder instanceof DataSourceMessageBuilder) { documentElement = ((DataSourceMessageBuilder) builder).processDocument( new BytesMessageDataSource((BytesMessage) msg), contentType, axis2MsgCtx); } else { documentElement = builder.processDocument(new BytesMessageInputStream((BytesMessage) msg), contentType, axis2MsgCtx); } } else if (msg instanceof MapMessage) { documentElement = convertJMSMapToXML((MapMessage) msg); } } catch (Exception ex) { // Handle message building error log.error("Error while building the message", ex); msgCtx.setProperty(SynapseConstants.ERROR_CODE, GenericConstants.INBOUND_BUILD_ERROR); msgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, ex.getMessage()); SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint); faultSequence.mediate(msgCtx); if (isRollback(msgCtx)) { return false; } return true; } // Setting JMSXDeliveryCount header on the message context try { int deliveryCount = msg.getIntProperty("JMSXDeliveryCount"); msgCtx.setProperty(JMSConstants.DELIVERY_COUNT, deliveryCount); } catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug("JMSXDeliveryCount is not set in the received message"); } } // Inject the message to the sequence. msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); if (injectingSeq == null || injectingSeq.equals("")) { log.error("Sequence name not specified. Sequence : " + injectingSeq); return false; } SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration() .getSequence(injectingSeq); if (seq != null) { if (log.isDebugEnabled()) { log.debug("injecting message to sequence : " + injectingSeq); } if (!seq.isInitialized()) { seq.init(synapseEnvironment); } SequenceMediator faultSequence = getFaultSequence(msgCtx, inboundEndpoint); MediatorFaultHandler mediatorFaultHandler = new MediatorFaultHandler(faultSequence); msgCtx.pushFaultHandler(mediatorFaultHandler); if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) { return false; } } else { log.error("Sequence: " + injectingSeq + " not found"); } if (isRollback(msgCtx)) { return false; } } catch (SynapseException se) { throw se; } catch (Exception e) { log.error("Error while processing the JMS Message", e); throw new SynapseException("Error while processing the JMS Message", e); } return true; }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSPollingConsumer.java
/** * Create connection with broker and retrieve the messages. Then inject * according to the registered handler/* ww w.java 2 s.c o m*/ */ public Message poll() { logger.debug("Polling JMS messages."); try { connection = jmsConnectionFactory.getConnection(strUserName, strPassword); if (connection == null) { logger.warn("Inbound JMS endpoint unable to get a connection."); isConnected = false; return null; } if (retryIteration != 0) { logger.info("Reconnection attempt: " + retryIteration + " for the JMS Inbound: " + name + " was successful!"); this.retryIteration = 0; this.retryDuration = 1; } isConnected = true; session = jmsConnectionFactory.getSession(connection); //Fixing ESBJAVA-4446 //Closing the connection if we cannot get a session. //Then in the next poll iteration it will create a new connection //instead of using cached connection if (session == null) { logger.warn("Inbound JMS endpoint unable to get a session."); jmsConnectionFactory.closeConnection(); return null; } destination = jmsConnectionFactory.getDestination(session); if (replyDestinationName != null && !replyDestinationName.trim().equals("")) { if (logger.isDebugEnabled()) { logger.debug( "Using the reply destination as " + replyDestinationName + " in inbound endpoint."); } replyDestination = jmsConnectionFactory.createDestination(session, replyDestinationName); } messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination); Message msg = receiveMessage(messageConsumer); if (msg == null) { logger.debug("Inbound JMS Endpoint. No JMS message received."); return null; } while (msg != null) { if (!JMSUtils.inferJMSMessageType(msg).equals(TextMessage.class.getName())) { logger.error("JMS " + "Inbound transport support JMS TextMessage type only. Found message type " + JMSUtils.inferJMSMessageType(msg)); return null; } if (injectHandler != null) { boolean commitOrAck = true; // Set the reply destination and connection if (replyDestination != null) { injectHandler.setReplyDestination(replyDestination); } injectHandler.setConnection(connection); commitOrAck = injectHandler.invoke(msg, name); // if client acknowledgement is selected, and processing // requested ACK if (jmsConnectionFactory.getSessionAckMode() == Session.CLIENT_ACKNOWLEDGE) { if (commitOrAck) { try { msg.acknowledge(); if (logger.isDebugEnabled()) { logger.debug("Message : " + msg.getJMSMessageID() + " acknowledged"); } } catch (JMSException e) { logger.error("Error acknowledging message : " + msg.getJMSMessageID(), e); } } else { // Need to create a new consumer and session since // we need to rollback the message if (messageConsumer != null) { jmsConnectionFactory.closeConsumer(messageConsumer); } if (session != null) { jmsConnectionFactory.closeSession(session); } session = jmsConnectionFactory.getSession(connection); messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination); } } // if session was transacted, commit it or rollback if (jmsConnectionFactory.isTransactedSession()) { try { if (session.getTransacted()) { if (commitOrAck) { session.commit(); if (logger.isDebugEnabled()) { logger.debug( "Session for message : " + msg.getJMSMessageID() + " committed"); } } else { session.rollback(); if (logger.isDebugEnabled()) { logger.debug( "Session for message : " + msg.getJMSMessageID() + " rolled back"); } } } } catch (JMSException e) { logger.error("Error " + (commitOrAck ? "committing" : "rolling back") + " local session txn for message : " + msg.getJMSMessageID(), e); } } } else { return msg; } msg = receiveMessage(messageConsumer); } } catch (JMSException e) { logger.error("Error while receiving JMS message. " + e.getMessage(), e); } catch (Exception e) { logger.error("Error while receiving JMS message. " + e.getMessage(), e); } finally { if (!isConnected) { if (reconnectDuration != null) { retryDuration = reconnectDuration; logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name + " failed. Next retry in " + (retryDuration / 1000) + " seconds. (Fixed Interval)"); } else { retryDuration = (long) (retryDuration * reconnectionProgressionFactor); if (retryDuration > maxReconnectDuration) { retryDuration = maxReconnectDuration; logger.info("InitialReconnectDuration reached to MaxReconnectDuration."); } logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name + " failed. Next retry in " + (retryDuration / 1000) + " seconds"); } try { Thread.sleep(retryDuration); } catch (InterruptedException ignore) { } } if (messageConsumer != null) { jmsConnectionFactory.closeConsumer(messageConsumer); } if (session != null) { jmsConnectionFactory.closeSession(session); } if (connection != null) { jmsConnectionFactory.closeConnection(connection); } } return null; }
From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageListener.java
public void onMessage(Message message) { messageCount.incrementAndGet();/*from w ww .j ava 2s.co m*/ localMessageCount++; Message receivedMessage = message; try { String redelivery = ""; if (message.getJMSRedelivered()) { redelivery = "REDELIVERED"; } else { redelivery = "ORIGINAL"; } if (messageCount.get() % printNumberOfMessagesPer == 0) { log.info("[QUEUE RECEIVE] ThreadID:" + Thread.currentThread().getId() + " queue:" + queueName + " " + "localMessageCount:" + localMessageCount + " totalMessageCount:" + messageCount.get() + " max" + " count:" + stopMessageCount); } if (receivedMessage instanceof TextMessage) { TextMessage textMessage = (TextMessage) receivedMessage; if (isToPrintEachMessage) { log.info("(count:" + messageCount.get() + "/threadID:" + Thread.currentThread().getId() + "/queue:" + queueName + ") " + redelivery + " >> " + textMessage.getText()); AndesClientUtils.writeToFile(textMessage.getText(), fileToWriteReceivedMessages); } } if (messageCount.get() % ackAfterEach == 0) { if (queueSession.getAcknowledgeMode() == QueueSession.CLIENT_ACKNOWLEDGE) { receivedMessage.acknowledge(); log.info("Acked message : " + receivedMessage.getJMSMessageID()); } } //commit get priority if (messageCount.get() % commitPerMessageCount == 0) { queueSession.commit(); log.info("Committed Queue Session"); } else if (messageCount.get() % rollbackPerMessagecount == 0) { queueSession.rollback(); log.info("Rollbacked Queue Session"); } if (messageCount.get() >= stopMessageCount) { stopMessageListener(); AndesClientUtils.sleepForInterval(200); } if (delayBetweenMessages != 0) { try { Thread.sleep(delayBetweenMessages); } catch (InterruptedException e) { //silently ignore } } } catch (NumberFormatException e) { log.error("Wrong inputs.", e); } catch (JMSException e) { log.error("JMS Exception", e); } }