List of usage examples for javax.jms Message getJMSCorrelationID
String getJMSCorrelationID() throws JMSException;
From source file:gov.nih.nci.cabig.caaers.esb.client.impl.CtmsCaaersMessageConsumer.java
/** * This is the Callback method which gets invoked whenever there is a message on the InputQueue. * Once it receives a message this method delegates the processing to different methods. *///from ww w. ja v a 2 s .c om public void onMessage(Message message) { String identity = SecurityManager.getManager().getCaller(); if (identity == null) { identity = "ctms-caaers.inputQueue"; } logger.debug("Auditing request from " + identity); String info = null; info = configuration.get(Configuration.ESB_URL); gov.nih.nci.cabig.ctms.audit.domain.DataAuditInfo .setLocal(new DataAuditInfo(identity, info, new Date(), info)); try { if (message instanceof TextMessage) { String messageType = message.getStringProperty("MESSAGE_TYPE"); String jmsCorelationID = message.getJMSCorrelationID(); String responseXml = ""; StringBuffer sb = new StringBuffer(); boolean messageValid = false; logger.debug("JMSCorelationID=" + jmsCorelationID); logger.debug("MESSAGE_TYPE=" + messageType); //Step 1 messageValid = validateMessage(message, messageType, sb); //Step 2 if (messageValid) { responseXml = processMessage(message, messageType); } else { CaaersServiceResponse caaersResponse = Helper.createResponse(); caaersResponse.getServiceResponse().setResponsecode("1"); Helper.populateError(caaersResponse, "WS_GEN_001", messageSource.getMessage("WS_GEN_001", new String[] {}, "", Locale.getDefault())); jaxbContext = JAXBContext.newInstance("gov.nih.nci.cabig.caaers.integration.schema.common"); marshaller = jaxbContext.createMarshaller(); responseXml = responseAsString(caaersResponse, marshaller); } //Step 3 sendResponse(responseXml, jmsCorelationID, messageType); } } catch (JMSException je) { logger.error("onMessage caught ", je); } catch (JAXBException e) { logger.error("onMessage caught ", e); } }
From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java
/** * @see javax.jms.MessageListener#onMessage(javax.jms.Message) *//*from w w w.j av a 2s . c o m*/ @Override public void onMessage(Message message) { try { ExecutorService executor = Executors.newSingleThreadExecutor(); if (((ObjectMessage) message).getObject() instanceof Result) { // no op return; } Request<?> request = (Request<?>) ((ObjectMessage) message).getObject(); // cast hell... Future<Request<?>> preProcessFuture = executor.submit(() -> onPreProcessRequest(request)); Future<Result<?>> resultFuture = executor.submit(() -> processRequest(preProcessFuture.get())); Future<Result<?>> postProcessFuture = executor .submit(() -> onPostProcessRequest(request, resultFuture.get())); executor.shutdown(); Result<?> result = postProcessFuture.get(); ResponseMessageCreator messageCreator = new ResponseMessageCreator(); messageCreator.setContents(result); messageCreator.setRequestId(message.getJMSCorrelationID()); replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session)); } catch (JMSException | InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); Result<Object> result = new Result<>(e); try { ResponseMessageCreator messageCreator = new ResponseMessageCreator(); messageCreator.setContents(result); messageCreator.setRequestId(message.getJMSCorrelationID()); replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session)); } catch (JmsException | JMSException e1) { e1.printStackTrace(); } } }
From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityJMSMessageParser.java
/** * Makes map object containing activity object data collected from JMS message payload data. * * @param data//from ww w.j a v a2 s . co m * activity object data object - JMS message * * @return activity object data map */ @Override protected Map<String, ?> getDataMap(Object data) { if (data == null) { return null; } Message message = (Message) data; Map<String, Object> dataMap = new HashMap<>(); try { if (message instanceof TextMessage) { parseTextMessage((TextMessage) message, dataMap); } else if (message instanceof BytesMessage) { parseBytesMessage((BytesMessage) message, dataMap); } else if (message instanceof MapMessage) { parseMapMessage((MapMessage) message, dataMap); } else if (message instanceof StreamMessage) { parseStreamMessage((StreamMessage) message, dataMap); } else if (message instanceof ObjectMessage) { parseObjectMessage((ObjectMessage) message, dataMap); } else { parseCustomMessage(message, dataMap); } dataMap.put(StreamFieldType.Correlator.name(), message.getJMSCorrelationID()); } catch (JMSException exc) { logger().log(OpLevel.ERROR, StreamsResources.getString(JMSStreamConstants.RESOURCE_BUNDLE_NAME, "ActivityJMSMessageParser.payload.data.error"), exc); } if (!dataMap.isEmpty()) { dataMap.put(StreamsConstants.TRANSPORT_KEY, JMSStreamConstants.TRANSPORT_JMS); } return dataMap; }
From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java
/** * Checks if this is a message that the BridgeConnectionManager expects to handle and, if so, handles the message. These are messages that typically are * responses to requests sent by the BridgeConnectionManager code for its own purposes rather than messages explicitly sent or intended for a client. * // w w w.j a v a2s .com * @param msg * the message the handle * @return true if the message was handled, false otherwise. * @throws JMSException */ public boolean handleInternalMessage(Message msg) throws JMSException { boolean handled = false; if (msg != null) { String correlationId = msg.getJMSCorrelationID(); if (correlationId != null) { ClientStateToClose topicToDelete = null; mapLock.lock(); try { topicToDelete = topicsToDelete.get(correlationId); if (topicToDelete != null) { topicsToDelete.remove(correlationId); handled = true; } } finally { mapLock.unlock(); } if (topicToDelete != null) { log.debug(LogUtils.COMBUS_MARKER, "Finished deleting client JMS state for {}/{}", topicToDelete.username, topicToDelete.clientId); topicToDelete.close(); topicToDelete = null; } } } return handled; }
From source file:org.openanzo.combus.endpoint.BaseServiceListener.java
private void processMessage(Message request) { try {//from w w w. j a v a 2s .c o m IOperationContext context = null; TextMessage response = null; String operation = request.getStringProperty(SerializationConstants.operation); try { Destination replyTo = null; try { if (mp == null) { mp = session.createProducer(null); mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } replyTo = request.getJMSReplyTo(); String resultFormat = request.getStringProperty(SerializationConstants.resultFormat); context = new BaseOperationContext(operation, request.getJMSCorrelationID(), null); if (request.propertyExists(SerializationConstants.userDescription)) { context.setAttribute(SerializationConstants.userDescription, request.getStringProperty(SerializationConstants.userDescription)); } if (request.propertyExists(OPTIONS.SKIPCACHE)) { context.setAttribute(OPTIONS.SKIPCACHE, request.getBooleanProperty(OPTIONS.SKIPCACHE)); } if (request.propertyExists(OPTIONS.INCLUDEMETADATAGRAPHS)) { context.setAttribute(OPTIONS.INCLUDEMETADATAGRAPHS, request.getBooleanProperty(OPTIONS.INCLUDEMETADATAGRAPHS)); } AnzoPrincipal callerPrincipal = getContextPrincipal(context, request); context.setOperationPrincipal(callerPrincipal); if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(request, "Message Recieved from [" + callerPrincipal.getName() + "]" + ((replyTo != null) ? (" with replyto [" + replyTo + "]") : ""))); } else if (log.isDebugEnabled()) { log.debug(LogUtils.COMBUS_MARKER, "Message Recieved from [" + callerPrincipal.getName() + "]" + ((replyTo != null) ? (" with replyto [" + replyTo + "]") : "")); } context.setMDC(); Boolean analyzeRequest = request .getBooleanProperty(RequestAnalysis.CONTEXT_PROP_REQUEST_ENABLED); if (analyzeRequest || recorder != null) { RequestAnalysis.setCurrentContext(context.getAttributes()); RequestAnalysis.setRequestAnalysisEnabled(true); } if (recorder != null) { recorder.recordRequest((TextMessage) request, request.getStringProperty("JMSXUserID"), request.getStringProperty(SerializationConstants.runAsUser)); } long start = 0, end = 0; if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) { start = System.currentTimeMillis(); } response = handleMessage(context, replyTo, resultFormat, operation, (TextMessage) request, mp); if (RequestAnalysis.isAnalysisEnabled(context.getAttributes())) { end = System.currentTimeMillis(); RequestAnalysis.addAnalysisProperty(RequestAnalysis.ANS_PROP_OPERATION_TIME, String.valueOf(end - start)); } if (response != null) { response.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION); if (operation != null) { response.setStringProperty(SerializationConstants.operation, operation); } Integer totalSolutions = context.getAttribute(SerializationConstants.totalSolutions, Integer.class); if (totalSolutions != null) { response.setIntProperty(SerializationConstants.totalSolutions, totalSolutions.intValue()); } if (analyzeRequest) { for (String name : RequestAnalysis.getAnalysisPropertyNames()) { response.setStringProperty(name, context.getAttribute(name).toString()); } } } if (response != null && replyTo != null) { response.setJMSCorrelationID(request.getJMSCorrelationID()); if (log.isTraceEnabled()) { log.trace(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(response, "Sending Response to [" + replyTo + "]")); } else if (log.isDebugEnabled()) { log.debug(LogUtils.COMBUS_MARKER, "Sending Response to [" + replyTo + "]"); } mp.send(replyTo, response); } } catch (JMSException jmex) { response = sendJMSErrorMessage(replyTo, request, jmex, ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString()); } catch (AnzoException jmex) { response = sendJMSErrorMessage(replyTo, request, jmex, jmex.getErrorCode(), jmex.getArgs()); } catch (AnzoRuntimeException jmex) { response = sendJMSErrorMessage(replyTo, request, jmex, jmex.getErrorCode(), jmex.getArgs()); } catch (RuntimeException jmex) { response = sendJMSErrorMessage(replyTo, request, jmex, ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString()); } catch (Throwable jmex) { response = sendJMSErrorMessage(replyTo, request, jmex, ExceptionConstants.COMBUS.JMS_SERVICE_EXCEPTION, jmex.toString()); } if (recorder != null) { if (response != null) { recorder.recordResponse(response); } else { recorder.recordResponse(request.getJMSCorrelationID(), operation); } } } finally { if (context != null) { context.clearMDC(); } } } catch (JMSException jmsex) { if (jmsex.getCause() instanceof InterruptedException) { log.debug(LogUtils.COMBUS_MARKER, "Thread interrupted in order to stop.", jmsex); } else { log.error(LogUtils.COMBUS_MARKER, "Error in BaseService Listener's process thread loop", jmsex); } } catch (Throwable jmex) { log.error(LogUtils.COMBUS_MARKER, "Error in BaseService Listener's process thread loop", jmex); } }
From source file:org.openengsb.ports.jms.JMSIncomingPort.java
public void start() { simpleMessageListenerContainer = createListenerContainer(receive, new MessageListener() { @Override//from www.ja va 2 s . c o m 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:edu.harvard.i2b2.crc.ejb.QueryExecutorMDB.java
/** * Take the XML based message and delegate to the system coordinator to * handle the actual processing/* w ww . j a va2s .co m*/ * * @param msg * th JMS TextMessage object containing XML data */ public void onMessage(Message msg) { MapMessage message = null; QueueConnection conn = null; QueueSession session = null; QueueSender sender = null; QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); Queue replyToQueue = null; UserTransaction transaction = sessionContext.getUserTransaction(); // default timeout three minutes int transactionTimeout = 0; try { transactionTimeout = this.readTimeoutPropertyValue(SMALL_QUEUE); if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.MEDIUM_QUEUE)) { // four hours // transactionTimeout = 14400; transactionTimeout = this.readTimeoutPropertyValue(MEDIUM_QUEUE); } else if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.LARGE_QUEUE)) { // twelve hours // transactionTimeout = 43200; transactionTimeout = this.readTimeoutPropertyValue(LARGE_QUEUE); } transaction.setTransactionTimeout(transactionTimeout); transaction.begin(); message = (MapMessage) msg; String sessionId = msg.getJMSCorrelationID(); replyToQueue = (Queue) msg.getJMSReplyTo(); log.debug("Extracting the message [" + msg.getJMSMessageID() + " ] on " + callingMDBName); transaction.commit(); ExecRunnable er = new ExecRunnable(transaction, transactionTimeout, callingMDBName, message, sessionId); er.execute(); } catch (Exception ex) { ex.printStackTrace(); try { if (transaction.getStatus() != 4) { transaction.rollback(); } } catch (Exception e) { e.printStackTrace(); } log.error("Error extracting message", ex); } finally { QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil(); qmBeanUtil.closeAll(sender, null, conn, session); } }
From source file:org.openanzo.combus.endpoint.BaseServiceListener.java
private TextMessage sendJMSErrorMessage(Destination replyTo, Message request, Throwable jmex, long errorCode, String... args) throws JMSException { try {/*from w w w . j a v a 2s .co m*/ if (replyTo != null) { if (log.isWarnEnabled()) { log.warn(LogUtils.COMBUS_MARKER, "Exception while ServiceListener [" + name + "] was precessing request.", jmex); } String message = null; if (jmex instanceof AnzoException) { message = ((AnzoException) jmex).getMessage(false); } else if (jmex instanceof AnzoRuntimeException) { message = ((AnzoRuntimeException) jmex).getMessage(false); } else { message = jmex.getMessage(); } TextMessage response = session.createTextMessage(message); response.setJMSCorrelationID(request.getJMSCorrelationID()); response.setBooleanProperty(SerializationConstants.operationFailed, true); response.setLongProperty(SerializationConstants.errorTags, 0); response.setLongProperty(SerializationConstants.errorCode, errorCode); response.setIntProperty(SerializationConstants.protocolVersion, Constants.VERSION); // send a single arg string for compat. with older readers response.setStringProperty(SerializationConstants.errorMessageArg, Arrays.toString(args)); // send the individual error args for readers that can make use of them for (int i = 0; i < args.length; i++) { response.setStringProperty(SerializationConstants.errorMessageArg + i, args[i]); } // we log all JMS messages, even errors. if (log.isDebugEnabled()) { log.debug(LogUtils.COMBUS_MARKER, MessageUtils.prettyPrint(response, "Sending Response to " + replyTo)); } mp.send(replyTo, response); return response; } } catch (JMSException jmsex) { log.debug(LogUtils.COMBUS_MARKER, "Error sending error message to client", jmsex); } return null; }
From source file:net.blogracy.services.SeedService.java
@Override public void onMessage(Message request) { try {//from w ww .j a v a 2s .c o m String text = ((TextMessage) request).getText(); Logger.info("seed service:" + text + ";"); JSONObject entry = new JSONObject(text); try { File file = new File(entry.getString("file")); Torrent torrent = plugin.getTorrentManager().createFromDataFile(file, new URL("udp://tracker.openbittorrent.com:80")); torrent.setComplete(file.getParentFile()); String name = Base32.encode(torrent.getHash()); int index = file.getName().lastIndexOf('.'); if (0 < index && index <= file.getName().length() - 2) { name = name + file.getName().substring(index); } Download download = plugin.getDownloadManager().addDownload(torrent, null, // torrentFile, file.getParentFile()); if (download != null) download.renameDownload(name); entry.put("uri", torrent.getMagnetURI().toExternalForm()); if (request.getJMSReplyTo() != null) { TextMessage response = session.createTextMessage(); response.setText(entry.toString()); response.setJMSCorrelationID(request.getJMSCorrelationID()); producer.send(request.getJMSReplyTo(), response); } } catch (MalformedURLException e) { Logger.error("Malformed URL error: seed service " + text); } catch (TorrentException e) { Logger.error("Torrent error: seed service: " + text); e.printStackTrace(); } catch (DownloadException e) { Logger.error("Download error: seed service: " + text); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (JMSException e) { Logger.error("JMS error: seed service"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:nl.nn.adapterframework.jms.JMSFacade.java
public String send(MessageProducer messageProducer, Message message, boolean ignoreInvalidDestinationException) throws NamingException, JMSException { if (log.isDebugEnabled()) { log.debug(getLogPrefix() + "sender on [" + getDestinationName() + "] will send message with JMSDeliveryMode=[" + message.getJMSDeliveryMode() + "] \n JMSMessageID=[" + message.getJMSMessageID() + "] \n JMSCorrelationID=[" + message.getJMSCorrelationID() + "] \n JMSTimestamp=[" + DateUtils.format(message.getJMSTimestamp()) + "] \n JMSExpiration=[" + message.getJMSExpiration() + "] \n JMSPriority=[" + message.getJMSPriority() + "] \n Message=[" + message.toString() + "]"); }/*from ww w . java2 s.c o m*/ try { if (useJms102()) { if (messageProducer instanceof TopicPublisher) { ((TopicPublisher) messageProducer).publish(message); } else { ((QueueSender) messageProducer).send(message); } return message.getJMSMessageID(); } else { messageProducer.send(message); return message.getJMSMessageID(); } } catch (InvalidDestinationException e) { if (ignoreInvalidDestinationException) { log.warn("queue [" + messageProducer.getDestination() + "] doesn't exist"); return null; } else { throw e; } } }