List of usage examples for javax.jms Message getJMSMessageID
String getJMSMessageID() throws JMSException;
From source file:org.jbpm.ejb.impl.CommandListenerBean.java
public void onMessage(Message message) { try {/*from w ww.j a va2 s .c o m*/ // extract command from message Command command = extractCommand(message); if (command == null) { discard(message); return; } // execute command via local command executor bean Object result = commandService.execute(command); // send a response back if a "reply to" destination is set Destination replyTo = message.getJMSReplyTo(); if (replyTo != null && (result instanceof Serializable || result == null)) { sendResult((Serializable) result, replyTo, message.getJMSMessageID()); } } catch (JMSException e) { messageDrivenContext.setRollbackOnly(); log.error("could not process message " + message, e); } }
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 a2 s .c o m } 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.mule.transport.jms.JmsMessageUtils.java
public static Message copyJMSProperties(Message from, Message to, JmsConnector connector) throws JMSException { if (connector.supportsProperty(JmsConstants.JMS_CORRELATION_ID)) { to.setJMSCorrelationID(from.getJMSCorrelationID()); }/* w w w . j av a 2 s . c om*/ if (connector.supportsProperty(JmsConstants.JMS_DELIVERY_MODE)) { to.setJMSDeliveryMode(from.getJMSDeliveryMode()); } if (connector.supportsProperty(JmsConstants.JMS_DESTINATION)) { to.setJMSDestination(from.getJMSDestination()); } if (connector.supportsProperty(JmsConstants.JMS_EXPIRATION)) { to.setJMSExpiration(from.getJMSExpiration()); } if (connector.supportsProperty(JmsConstants.JMS_MESSAGE_ID)) { to.setJMSMessageID(from.getJMSMessageID()); } if (connector.supportsProperty(JmsConstants.JMS_PRIORITY)) { to.setJMSPriority(from.getJMSPriority()); } if (connector.supportsProperty(JmsConstants.JMS_REDELIVERED)) { to.setJMSRedelivered(from.getJMSRedelivered()); } if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) { to.setJMSReplyTo(from.getJMSReplyTo()); } if (connector.supportsProperty(JmsConstants.JMS_TIMESTAMP)) { to.setJMSTimestamp(from.getJMSTimestamp()); } if (connector.supportsProperty(JmsConstants.JMS_TYPE)) { to.setJMSType(from.getJMSType()); } return to; }
From source file:org.mule.transport.jms.redelivery.CountingRedeliveryHandler.java
/** * process the redelivered message. If the Jms receiver should process the * message, it should be returned. Otherwise the connector should throw a * <code>MessageRedeliveredException</code> to indicate that the message should * be handled by the connector Exception Handler. * /* ww w. j ava 2 s .c om*/ */ @Override public void handleRedelivery(Message message, InboundEndpoint endpoint, FlowConstruct flow) throws JMSException, MuleException { final int connectorRedelivery = connector.getMaxRedelivery(); if (connectorRedelivery == JmsConnector.REDELIVERY_IGNORE || connectorRedelivery < 0) // just in case, for manual setting) { if (logger.isDebugEnabled()) { logger.debug("We were asked to ignore the redelivery count, nothing to do here."); } return; } String id = message.getJMSMessageID(); if (id == null) { if (logger.isDebugEnabled()) { logger.debug( "Message doesn't have a JMSMessageID set, Mule can't handle redelivery for it. " + message); } return; } Integer redeliveryCount = messages.remove(id); if (redeliveryCount != null) { redeliveryCount += 1; // inc the count } if (redeliveryCount == null) { if (logger.isDebugEnabled()) { logger.debug("Message with id: " + id + " has been redelivered for the first time"); } messages.put(id, 1); } else if (redeliveryCount == 1) { if (logger.isDebugEnabled()) { logger.debug("Message with id: " + id + " has been redelivered for the first time"); } if (connectorRedelivery == JmsConnector.REDELIVERY_FAIL_ON_FIRST) { MuleMessage msg = createMuleMessage(message); throw new MessageRedeliveredException(id, redeliveryCount, connectorRedelivery, endpoint, flow, msg); } } else if (redeliveryCount > connectorRedelivery) { MuleMessage msg = createMuleMessage(message); throw new MessageRedeliveredException(id, redeliveryCount, connectorRedelivery, endpoint, flow, msg); } else { messages.put(id, redeliveryCount); if (logger.isDebugEnabled()) { logger.debug("Message with id: " + id + " has been redelivered " + redeliveryCount + " times"); } } }
From source file:org.mule.transport.jms.redelivery.JmsXRedeliveryHandler.java
/** * process the redelivered message. If the Jms receiver should process the * message, it should be returned. Otherwise the connector should throw a * <code>MessageRedeliveredException</code> to indicate that the message should * be handled by the connector Exception Handler. * //from ww w . j av a2 s . co m */ @Override public void handleRedelivery(Message message, InboundEndpoint endpoint, FlowConstruct flow) throws JMSException, MuleException { final int connectorRedelivery = connector.getMaxRedelivery(); if (connectorRedelivery == JmsConnector.REDELIVERY_IGNORE || connectorRedelivery < 0) // just in case, for manual setting) { if (logger.isDebugEnabled()) { logger.debug("We were asked to ignore the redelivery count, nothing to do here."); } return; } String messageId = message.getJMSMessageID(); int deliveryCount = -1; try { deliveryCount = message.getIntProperty(JmsConstants.JMS_X_DELIVERY_COUNT); } catch (NumberFormatException nex) { throw new MuleRuntimeException(MessageFactory.createStaticMessage(String.format( "Invalid use of %s. Message is flagged with JMSRedelivered, but JMSXDeliveryCount is not set", getClass().getName()))); } int redeliveryCount = deliveryCount - 1; if (redeliveryCount == 1) { if (logger.isDebugEnabled()) { logger.debug("Message with id: " + messageId + " has been redelivered for the first time"); } if (connectorRedelivery == JmsConnector.REDELIVERY_FAIL_ON_FIRST) { MuleMessage msg = createMuleMessage(message); throw new MessageRedeliveredException(messageId, redeliveryCount, connectorRedelivery, endpoint, flow, msg); } } else if (redeliveryCount > connectorRedelivery) { MuleMessage msg = createMuleMessage(message); throw new MessageRedeliveredException(messageId, redeliveryCount, connectorRedelivery, endpoint, flow, msg); } else { if (logger.isDebugEnabled()) { // re-delivery count is actually less by 1 than an actual delivery count logger.debug( "Message with id: " + messageId + " has been redelivered " + redeliveryCount + " times"); } } }
From source file:org.openadaptor.auxil.connector.jms.JMSReadConnector.java
/** * Receive a message from the configured destination. This is a blocking receive which will time out based * on the value of the <b>timeout</b> property. * * @return Object The contents of the received message. *///from www . ja va 2 s. c o m protected Object receive(long timeoutMs) { Message msg; try { if (timeoutMs < 0) { msg = messageConsumer.receive(); } else { msg = messageConsumer.receive(timeoutMs); //Populate Metadata if this is configured if (msg != null && isPopulateMetadataFromProperties()) { readMetadataFromMessageProperties(msg); } } if ((msg != null) && (logMessageId)) { log.info("[" + getId() + "=" + getDestinationName() + "] received message [JMSMessageID=" + msg.getJMSMessageID() + "]"); } // If we have been sent a JMSException via the ExceptionListener registration mechanism. // We treat the exception as if it had been thrown by the receive method by throwing it now. if (listenerException != null) { ConnectionException ce = new ConnectionException("onException called during receive.", listenerException, this); listenerException = null; throw ce; } } catch (JMSException jmse) { log.error("Exception during receive message [JMSException: " + jmse + "]"); throw new ConnectionException("Exception during receive message.", jmse, this); } // Unpack the message contents return unpackJMSMessage(msg); }
From source file:org.openadaptor.auxil.connector.jms.JMSWriteConnector.java
/** * Deliver the parameter to the confgured destination. * * @param message/*from w w w . ja va 2 s. c o m*/ * @return String The JMS Message ID. */ protected String deliverRecord(Object message) { String msgId; if ((messageGenerator instanceof IMetadataAware) && (getPropagateMetadata())) { ((IMetadataAware) messageGenerator).setMetadata(metadata); } try { // Delegate message creation to an instance of IMessageGenerator. Message msg = messageGenerator.createMessage(message, session); // At this point if a MessageProducer exists it should have a Destination set based // on the configured destination, the override destination set in the metadata // or the configured destination name. So we update the JMS Message to match. //if (messageProducer != null) { // msg.setJMSDestination(messageProducer.getDestination()); //} // send the record if (log.isDebugEnabled()) log.debug("JmsPublisher sending [" + message + "]"); // If the override is set then we need to close any existing producer if (isDestinationOverride() && (messageProducer != null)) { messageProducer.close(); messageProducer = null; // Force getting a new producer } // Go get a new producer. if (messageProducer == null) { messageProducer = createMessageProducer(); } messageProducer.send(msg, deliveryMode, priority, timeToLive); msgId = msg.getJMSMessageID(); if (logMessageId) { // Optionally log the message id of the published message. log.info("[" + getId() + "=" + getActualDestinationName() + "] sent message [ JMSMessageID=" + msgId + "] to data connection/service"); } } catch (RecordFormatException e) { throw new ProcessingException("RecordFormatException during publish.", e, this); } catch (InvalidDestinationException e) { throw new ConnectionException("InvalidDestinationException during publish.", e, this); } catch (JMSException jmse) { throw new ConnectionException("JMSException during publish.", jmse, this); } return msgId; }
From source file:org.openengsb.ports.jms.JMSIncomingPort.java
public void start() { simpleMessageListenerContainer = createListenerContainer(receive, new MessageListener() { @Override/*from w w w . j av a2s . c om*/ public void onMessage(Message message) { LOGGER.trace("JMS-message recieved. Checking if the type is supported"); if (!(message instanceof TextMessage)) { LOGGER.debug("Received JMS-message is not type of text message."); return; } LOGGER.trace("Received a text message and start parsing"); TextMessage textMessage = (TextMessage) message; String textContent = extractTextFromMessage(textMessage); HashMap<String, Object> metadata = new HashMap<String, Object>(); String result = null; try { LOGGER.debug("starting filterchain for incoming message"); result = (String) getFilterChainToUse().filter(textContent, metadata); } catch (Exception e) { LOGGER.error("an error occured when processing the filterchain", e); result = ExceptionUtils.getStackTrace(e); } Destination replyQueue; final String correlationID; try { if (message.getJMSCorrelationID() == null) { correlationID = message.getJMSMessageID(); } else { correlationID = message.getJMSCorrelationID(); } replyQueue = message.getJMSReplyTo(); } catch (JMSException e) { LOGGER.warn("error when getting destination queue or correlationid from client message: {}", e); return; } if (replyQueue == null) { LOGGER.warn("no replyTo destination specifyed could not send response"); return; } new JmsTemplate(connectionFactory).convertAndSend(replyQueue, result, new MessagePostProcessor() { @Override public Message postProcessMessage(Message message) throws JMSException { message.setJMSCorrelationID(correlationID); return message; } }); } private String extractTextFromMessage(TextMessage textMessage) { try { return textMessage.getText(); } catch (JMSException e) { throw new IllegalStateException("Couldn't extract text from jms message", e); } } }); simpleMessageListenerContainer.start(); }
From source file:org.socraticgrid.taskmanager.TaskHandler.java
public void onMessage(Message message) { TaskMessage taskMessage = null;//w ww. ja v a 2s . co m try { log.debug("Received message id: " + message.getJMSMessageID()); if (message instanceof ObjectMessage) { ObjectMessage oMsg = (ObjectMessage) message; Object object = oMsg.getObject(); if (object instanceof TaskMessage) { taskMessage = (TaskMessage) object; } } } catch (JMSException e) { log.error("Error processing message for task bean.", e); //Don't rollback else message gets stuck in queue //mdc.setRollbackOnly(); } catch (Throwable te) { log.error("Error processing message for task handler.", te); } //Check if TaskMessage was found if (taskMessage == null) { log.error("Expected TaskMessage(ObjectMessage) not found, ignoring message."); return; } try { //Pull out task from database TaskService taskService = new TaskService(); TaskType task = taskService.getTask(new Long(taskMessage.getTaskID())); if (task == null) { throw new Exception("Task id(" + taskMessage.getTaskID() + ") was not found."); } if ((task.getSpecifications() == null) || (task.getSpecifications().isEmpty())) { throw new Exception("Task id(" + task.getTaskTypeId() + ") has no specifications."); } //Find tasking service String taskingServiceId = null; for (Specification spec : task.getSpecifications()) { if (SpecConstants.NAME_SERVICE_REF.equals(spec.getName())) { taskingServiceId = spec.getValue(); break; } } if (taskingServiceId == null) { throw new Exception("Task id(" + task.getTaskTypeId() + ") had no specification(" + SpecConstants.NAME_SERVICE_REF + ")."); } TaskServiceRef serviceRef = taskService.getServiceRef(new Long(taskingServiceId)); if (serviceRef == null) { throw new Exception("Task id(" + task.getTaskTypeId() + ") tasking service id(" + taskingServiceId + ") did not exist."); } //Handle each method appropriately // if (ServiceConstants.TYPE_JMS_QUEUE.equals(serviceRef.getType())) { // notifyQueue(message.getJMSMessageID(), serviceRef.getLocation(), taskMessage, task); // } // else if (ServiceConstants.TYPE_SWIFT_SMS.equals(serviceRef.getType())) { new SwiftSMSHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_ZIMBRA_VTODO.equals(serviceRef.getType())) { new VTodoHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_ZIMBRA_VEVENT.equals(serviceRef.getType())) { new VEventHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_SMTP.equals(serviceRef.getType())) { new MailHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_DISEASE_REGISTRY.equals(serviceRef.getType())) { new DiseaseRegistryHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_LAB_ORDER.equals(serviceRef.getType())) { new LabOrderHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else if (ServiceConstants.TYPE_SLOT_REQUEST.equals(serviceRef.getType())) { new SlotRequestHandler().handleMessage(message.getJMSMessageID(), serviceRef, taskMessage, task); } else { throw new UnsupportedOperationException("Unsupported task service method: " + serviceRef.getType()); } } catch (Throwable t) { log.error("Error processing message for task handler.", t); } }
From source file:org.springframework.flex.messaging.jms.FlexMessageConverter.java
/** * //from ww w.ja v a2 s. c om * {@inheritDoc} */ public Object fromMessage(Message message) throws JMSException, MessageConversionException { Object messageBody = this.targetConverter.fromMessage(message); AsyncMessage flexMessage = new AsyncMessage(); flexMessage.setBody(messageBody); flexMessage.setMessageId(message.getJMSMessageID()); flexMessage.setClientId(message.getObjectProperty(FLEX_CLIENT_ID)); flexMessage.setTimestamp(message.getJMSTimestamp()); Object timeToLive = message.getObjectProperty(FLEX_TIME_TO_LIVE); if (timeToLive != null && long.class.isAssignableFrom(timeToLive.getClass())) { flexMessage.setTimeToLive(Long.parseLong(timeToLive.toString())); } Enumeration<?> propertyNames = message.getPropertyNames(); while (propertyNames.hasMoreElements()) { String name = (String) propertyNames.nextElement(); if (!name.startsWith(HEADER_PREFIX)) { flexMessage.setHeader(name, message.getObjectProperty(name)); } } return flexMessage; }