List of usage examples for javax.jms Session createObjectMessage
ObjectMessage createObjectMessage(Serializable object) throws JMSException;
From source file:com.cws.esolutions.agent.mq.MQMessageHandler.java
public void onMessage(final Message message) { final String methodName = MQMessageHandler.CNAME + "#onMessage(final Message message)"; if (DEBUG) {/* ww w . j a v a 2 s .com*/ DEBUGGER.debug(methodName); DEBUGGER.debug("Message: {}", message); } final Session session = agentBean.getSession(); final MessageProducer producer = agentBean.getProducer(); final Destination destination = MQMessageHandler.agentBean.getResponseQueue(); if (DEBUG) { DEBUGGER.debug("Session: {}", session); DEBUGGER.debug("MessageProducer: {}", producer); DEBUGGER.debug("Destination: {}", destination); } try { ObjectMessage mqMessage = (ObjectMessage) message; if (DEBUG) { DEBUGGER.debug("mqMessage: {}", mqMessage); } if ((StringUtils.equals(MQMessageHandler.serverConfig.getRequestQueue(), MQMessageHandler.serverConfig.getResponseQueue())) && (mqMessage.getObject() instanceof AgentResponse)) { return; } AgentRequest agentRequest = (AgentRequest) mqMessage.getObject(); if (DEBUG) { DEBUGGER.debug("agentRequest: {}", agentRequest); } mqMessage.acknowledge(); AgentResponse agentResponse = MQMessageHandler.processor.processRequest(agentRequest); if (DEBUG) { DEBUGGER.debug("AgentResponse: {}", agentResponse); } ObjectMessage oMessage = session.createObjectMessage(true); oMessage.setObject(agentResponse); oMessage.setJMSCorrelationID(message.getJMSCorrelationID()); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", oMessage); } producer.send(destination, oMessage); } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } catch (AgentException ax) { ERROR_RECORDER.error(ax.getMessage(), ax); } }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from w w w . j a v a 2 s. c o m*/ public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return correlationId; }
From source file:nl.nn.adapterframework.jms.JmsTransactionalStorage.java
public String storeMessage(String messageId, String correlationId, Date receivedDate, String comments, String label, Serializable message) throws SenderException { Session session = null; try {//from w w w .j a v a 2s.c o m session = createSession(); ObjectMessage msg = session.createObjectMessage(message); msg.setStringProperty(FIELD_TYPE, getType()); msg.setStringProperty(FIELD_ORIGINAL_ID, messageId); msg.setJMSCorrelationID(correlationId); msg.setLongProperty(FIELD_RECEIVED_DATE, receivedDate.getTime()); msg.setStringProperty(FIELD_COMMENTS, comments); if (StringUtils.isNotEmpty(getSlotId())) { msg.setStringProperty(FIELD_SLOTID, getSlotId()); } msg.setStringProperty(FIELD_LABEL, label); return send(session, getDestination(), msg); } catch (Exception e) { throw new SenderException(e); } finally { closeSession(session); } }
From source file:org.apache.camel.component.jms.JmsBinding.java
protected Message createJmsMessage(Exception cause, Session session) throws JMSException { if (LOG.isTraceEnabled()) { LOG.trace("Using JmsMessageType: " + Object); }/* w w w . j av a 2s . c o m*/ return session.createObjectMessage(cause); }
From source file:org.apache.camel.component.jms.JmsBinding.java
protected Message createJmsMessage(Exchange exchange, Object body, Map<String, Object> headers, Session session, CamelContext context) throws JMSException { JmsMessageType type = null;// w w w .ja v a2 s . c o m // special for transferExchange if (endpoint != null && endpoint.isTransferExchange()) { if (LOG.isTraceEnabled()) { LOG.trace("Option transferExchange=true so we use JmsMessageType: Object"); } Serializable holder = DefaultExchangeHolder.marshal(exchange); return session.createObjectMessage(holder); } // use a custom message converter if (endpoint != null && endpoint.getMessageConverter() != null) { if (LOG.isTraceEnabled()) { LOG.trace("Creating JmsMessage using a custom MessageConverter: " + endpoint.getMessageConverter() + " with body: " + body); } return endpoint.getMessageConverter().toMessage(body, session); } // check if header have a type set, if so we force to use it if (headers.containsKey(JmsConstants.JMS_MESSAGE_TYPE)) { type = context.getTypeConverter().convertTo(JmsMessageType.class, headers.get(JmsConstants.JMS_MESSAGE_TYPE)); } else if (endpoint != null && endpoint.getConfiguration().getJmsMessageType() != null) { // force a specific type from the endpoint configuration type = endpoint.getConfiguration().getJmsMessageType(); } else { type = getJMSMessageTypeForBody(exchange, body, headers, session, context); } // create the JmsMessage based on the type if (type != null) { if (LOG.isTraceEnabled()) { LOG.trace("Using JmsMessageType: " + type); } return createJmsMessageForType(exchange, body, headers, session, context, type); } // warn if the body could not be mapped if (body != null && LOG.isWarnEnabled()) { LOG.warn("Cannot determine specific JmsMessage type to use from body class." + " Will use generic JmsMessage." + " Body class: " + ObjectHelper.classCanonicalName(body) + ". If you want to send a POJO then your class might need to implement java.io.Serializable" + ", or you can force a specific type by setting the jmsMessageType option on the JMS endpoint."); } // return a default message return session.createMessage(); }
From source file:org.apache.camel.component.jms.JmsBinding.java
/** * // ww w . j av a 2s .c o m * Create the {@link Message} * * @return jmsMessage or null if the mapping was not successfully */ protected Message createJmsMessageForType(Exchange exchange, Object body, Map<String, Object> headers, Session session, CamelContext context, JmsMessageType type) throws JMSException { switch (type) { case Text: { TextMessage message = session.createTextMessage(); String payload = context.getTypeConverter().convertTo(String.class, exchange, body); message.setText(payload); return message; } case Bytes: { BytesMessage message = session.createBytesMessage(); byte[] payload = context.getTypeConverter().convertTo(byte[].class, exchange, body); message.writeBytes(payload); return message; } case Map: { MapMessage message = session.createMapMessage(); Map payload = context.getTypeConverter().convertTo(Map.class, exchange, body); populateMapMessage(message, payload, context); return message; } case Object: Serializable payload; try { payload = context.getTypeConverter().mandatoryConvertTo(Serializable.class, exchange, body); } catch (NoTypeConversionAvailableException e) { // cannot convert to serializable then thrown an exception to avoid sending a null message JMSException cause = new MessageFormatException(e.getMessage()); cause.initCause(e); throw cause; } return session.createObjectMessage(payload); default: break; } return null; }
From source file:org.apache.james.queue.jms.JMSMailQueue.java
/** * Create a copy of the given {@link Message}. This includes the properties * and the payload/*from ww w. j a va2s .com*/ * * @param session * @param m * @return copy * @throws JMSException */ @SuppressWarnings("unchecked") protected Message copy(Session session, Message m) throws JMSException { ObjectMessage message = (ObjectMessage) m; ObjectMessage copy = session.createObjectMessage(message.getObject()); Enumeration<String> properties = message.getPropertyNames(); while (properties.hasMoreElements()) { String name = properties.nextElement(); copy.setObjectProperty(name, message.getObjectProperty(name)); } return copy; }
From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java
public void process(MessageExchange exchange) throws Exception { Context context = (Context) pendingMessages.remove(exchange.getExchangeId()); Message message = (Message) context.getProperty(Message.class.getName()); Message response = null;//from ww w . j av a2 s . co m Connection connection = null; try { if (exchange.getStatus() == ExchangeStatus.DONE) { return; } else if (exchange.getStatus() == ExchangeStatus.ERROR) { if (endpoint.isRollbackOnError()) { TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent() .getComponentContext().getTransactionManager(); tm.setRollbackOnly(); return; } else if (exchange instanceof InOnly) { LOG.info("Exchange in error: " + exchange, exchange.getError()); return; } else { connection = connectionFactory.createConnection(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Exception error = exchange.getError(); if (error == null) { error = new Exception("Exchange in error"); } response = session.createObjectMessage(error); MessageProducer producer = session.createProducer(message.getJMSReplyTo()); if (endpoint.isUseMsgIdInResponse()) { response.setJMSCorrelationID(message.getJMSMessageID()); } else { response.setJMSCorrelationID(message.getJMSCorrelationID()); } producer.send(response); } } else { connection = connectionFactory.createConnection(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); response = fromNMSResponse(exchange, context, session); if (response != null) { MessageProducer producer = session.createProducer(message.getJMSReplyTo()); if (endpoint.isUseMsgIdInResponse()) { response.setJMSCorrelationID(message.getJMSMessageID()); } else { response.setJMSCorrelationID(message.getJMSCorrelationID()); } producer.send(response); } } } finally { if (connection != null) { connection.close(); } if (exchange.getStatus() == ExchangeStatus.ACTIVE) { exchange.setStatus(ExchangeStatus.DONE); channel.send(exchange); } } }
From source file:org.jbpm.bpel.integration.jms.OutstandingRequest.java
public void sendReply(Map parts, QName faultName, Session jmsSession) throws JMSException { MessageProducer producer = null;//from ww w. j a va 2 s.c o m try { producer = jmsSession.createProducer(replyDestination); /* * the given parts likely are an instance of PersistentMap which does not serialize nicely; * copy the parts to a transient Map implementation */ switch (parts.size()) { case 0: parts = Collections.EMPTY_MAP; break; case 1: { Map.Entry single = (Entry) parts.entrySet().iterator().next(); parts = Collections.singletonMap(single.getKey(), single.getValue()); break; } default: parts = new HashMap(parts); break; } Message responseMsg = jmsSession.createObjectMessage((Serializable) parts); responseMsg.setJMSCorrelationID(correlationID); // set the fault name, if any if (faultName != null) { responseMsg.setStringProperty(IntegrationConstants.FAULT_NAME_PROP, faultName.getLocalPart()); } // send the response producer.send(responseMsg); log.debug("sent response: " + RequestListener.messageToString(responseMsg)); } finally { if (producer != null) { try { producer.close(); } catch (JMSException e) { log.warn("could not close jms producer", e); } } } }
From source file:org.jbpm.ejb.CommandListenerBean.java
private void sendResult(Serializable result, Destination destination, String correlationId) throws JMSException { if (log.isDebugEnabled()) log.debug("sending " + result + " to " + destination); Connection jmsConnection = jmsConnectionFactory.createConnection(); try {//from ww w . java 2s . co m /* * if the connection supports xa, the session will be transacted, else the session will * auto acknowledge; in either case no explicit transaction control must be performed - * see ejb 2.1 - 17.3.5 */ Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Message resultMessage = jmsSession.createObjectMessage(result); resultMessage.setJMSCorrelationID(correlationId); MessageProducer producer = jmsSession.createProducer(destination); producer.send(resultMessage); } finally { // there is no need to close the sessions and producers of a closed connection // http://download.oracle.com/javaee/1.4/api/javax/jms/Connection.html#close() try { jmsConnection.close(); } catch (JMSException e) { log.warn("failed to close jms connection", e); } } }