Example usage for javax.jms Message getJMSCorrelationID

List of usage examples for javax.jms Message getJMSCorrelationID

Introduction

In this page you can find the example usage for javax.jms Message getJMSCorrelationID.

Prototype


String getJMSCorrelationID() throws JMSException;

Source Link

Document

Gets the correlation ID for the message.

Usage

From source file:com.cognifide.aet.runner.distribution.RunnerMessageListener.java

private void sendFatalMessage(Message wrapperMessage, String message) {
    try {//w  w  w .j  a v  a  2  s.co  m
        final Destination jmsReplyTo = wrapperMessage.getJMSReplyTo();
        if (jmsReplyTo != null) {
            final MessageProducer producer = session.createProducer(jmsReplyTo);
            final FatalErrorMessage errorMessage = new FatalErrorMessage(
                    "Failed to process test suite: " + message, wrapperMessage.getJMSCorrelationID());
            producer.send(session.createObjectMessage(errorMessage));
            producer.close();
        }
    } catch (Exception e) {
        LOGGER.error("Fatal exception, can't deliver message {}!", message, e);
    }
}

From source file:org.logicblaze.lingo.jms.impl.MultiplexingRequestor.java

public Message request(Destination destination, Message message, long timeout) throws JMSException {
    // lets create a correlationID unless we are already given one -
    // we are already given a correaltionID if we are on the server side
    // responding to a remote object reference
    FutureTask future = null;//w w  w .  j a  v a  2  s . c  o  m
    String correlationID = message.getJMSCorrelationID();
    if (correlationID == null) {
        correlationID = createCorrelationID();
        message.setJMSCorrelationID(correlationID);
    } else {
        Object currentHandler = requestMap.get(correlationID);
        if (currentHandler instanceof AsyncReplyHandler) {
            AsyncReplyHandler handler = (AsyncReplyHandler) currentHandler;
            future = handler.newResultHandler();
        }
    }

    if (future == null) {
        FutureHandler futureHandler = new FutureHandler();
        future = futureHandler;
        requestMap.put(correlationID, futureHandler, timeout);
    }
    populateHeaders(message);
    send(destination, message);

    try {
        if (timeout < 0) {
            return (Message) future.get();
        } else {
            return (Message) future.get(timeout, TimeUnit.MILLISECONDS);
        }
    } catch (Exception e) {
        throw createJMSException(e);
    }
}

From source file:com.fusesource.forge.jmstest.tests.AsyncConsumer.java

public void onMessage(Message msg) {
    if (receiveCount != null) {
        receiveCount.incrementAndGet();//w  ww  .j  av  a2 s . com
    }
    MessageProducer producer = null;
    try {
        Destination replyDest = msg.getJMSReplyTo();
        if (replyDest != null) {
            Message response = getSession().createTextMessage("Response");
            response.setStringProperty("ServedBy", getName());
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            for (Enumeration<?> en = msg.getPropertyNames(); en.hasMoreElements();) {
                String key = (String) en.nextElement();
                Object value = msg.getObjectProperty(key);
                if (key.equals("BrokerStamp")) {
                    value = value.toString() + " --";
                }
                response.setObjectProperty(key, value);
            }
            producer = getSession().createProducer(replyDest);
            producer.send(response);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.classLoader.simple.RemoteClassProvider.java

@Override
public void onMessage(Message message) {
    String className = null;/*w  w  w . ja  v a 2 s.c  o  m*/

    try {
        className = ((ClassRequest) ((ObjectMessage) message).getObject()).className;

        log.fine("Message received:" + className);

        // we expect sender to specify the query he's waiting response into the JMSReplyTo
        Destination destination = message.getJMSReplyTo();
        UUID correlationId = UUID.fromString(message.getJMSCorrelationID());

        // preparing class bytecode.
        byte[] bytecode = null;

        try {
            String classPath = className.replace('.', '/') + ".class";//TODO: use utils.
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(classPath);

            // If the class cannot be found, attempt to find a resource with the requested name
            if (is == null) {
                try {
                    ClassPathResource resource = new ClassPathResource(className);
                    if (resource.exists()) {
                        is = resource.getInputStream();
                    }
                } catch (IOException e) {
                    // Ignore
                }
            }

            if (is == null)
                log.severe(String.format("Requested class %s was not found.", className));
            else
                bytecode = RemoteClassLoaderUtils.getByteArray(is);

        } catch (Exception ex) {
            log.severe("Failed to provide required class " + className + ": " + ex.toString());
            ex.printStackTrace();
        } finally {
            mq.respond(new ClassResponse(bytecode), destination, correlationId);
        }

    } catch (JMSException e) {
        log.severe("Failed to process message (" + className + "): " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.apache.axis2.transport.jms.JMSMessageReceiver.java

/**
 * Process the new message through Axis2
 *
 * @param message the JMS message//from w  ww  .j a v  a 2s .  c  o  m
 * @param ut      the UserTransaction used for receipt
 * @return true if the caller should commit
 * @throws JMSException, on JMS exceptions
 * @throws AxisFault     on Axis2 errors
 */
private boolean processThoughEngine(Message message, UserTransaction ut) throws JMSException, AxisFault {

    MessageContext msgContext = endpoint.createMessageContext();

    // set the JMS Message ID as the Message ID of the MessageContext
    try {
        msgContext.setMessageID(message.getJMSMessageID());
        String jmsCorrelationID = message.getJMSCorrelationID();
        if (jmsCorrelationID != null && jmsCorrelationID.length() > 0) {
            msgContext.setProperty(JMSConstants.JMS_COORELATION_ID, jmsCorrelationID);
        } else {
            msgContext.setProperty(JMSConstants.JMS_COORELATION_ID, message.getJMSMessageID());
        }
    } catch (JMSException ignore) {
    }

    String soapAction = JMSUtils.getProperty(message, BaseConstants.SOAPACTION);

    ContentTypeInfo contentTypeInfo = endpoint.getContentTypeRuleSet().getContentTypeInfo(message);
    if (contentTypeInfo == null) {
        throw new AxisFault("Unable to determine content type for message " + msgContext.getMessageID());
    }

    // set the message property OUT_TRANSPORT_INFO
    // the reply is assumed to be over the JMSReplyTo destination, using
    // the same incoming connection factory, if a JMSReplyTo is available
    Destination replyTo = message.getJMSReplyTo();
    if (replyTo == null) {
        // does the service specify a default reply destination ?
        String jndiReplyDestinationName = endpoint.getJndiReplyDestinationName();
        if (jndiReplyDestinationName != null) {
            replyTo = jmsConnectionFactory.getDestination(jndiReplyDestinationName,
                    endpoint.getReplyDestinationType());
        }

    }
    if (replyTo != null) {
        msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                new JMSOutTransportInfo(jmsConnectionFactory, replyTo, contentTypeInfo.getPropertyName()));
    }

    JMSUtils.setSOAPEnvelope(message, msgContext, contentTypeInfo.getContentType());
    if (ut != null) {
        msgContext.setProperty(BaseConstants.USER_TRANSACTION, ut);
    }

    jmsListener.handleIncomingMessage(msgContext, JMSUtils.getTransportHeaders(message), soapAction,
            contentTypeInfo.getContentType());

    Object o = msgContext.getProperty(BaseConstants.SET_ROLLBACK_ONLY);
    if (o != null) {
        if ((o instanceof Boolean && ((Boolean) o)) || (o instanceof String && Boolean.valueOf((String) o))) {
            return false;
        }
    }
    return true;
}

From source file:com.oneops.inductor.Listener.java

/**
 * MessageListener mapped in application-context.xml - will deserialize to a
 * WorkOrder (iaas/swdist) or ActionOrder (procedure)
 *
 * @param msg Message/*from  w ww . j a va 2 s.  c  om*/
 * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
 */
public void onMessage(Message msg) {
    try {
        checkFreeSpace();
        activeThreads.getAndIncrement();
        if (msg instanceof TextMessage) {
            String msgText = ((TextMessage) msg).getText();
            final String correlationID = msg.getJMSCorrelationID();
            Map<String, String> responseMsgMap;
            String type = msg.getStringProperty("type");
            CmsWorkOrderSimpleBase wo;

            // WorkOrder
            if (type.equals(WORK_ORDER_TYPE)) {
                long t = System.currentTimeMillis();
                wo = getWorkOrderOf(msgText, CmsWorkOrderSimple.class);
                wo.putSearchTag("iWoCrtTime", Long.toString(System.currentTimeMillis() - t));
                preProcess(wo);
                wo.putSearchTag("rfcAction", wo.getAction());
                responseMsgMap = workOrderExecutor.process(wo, correlationID);
                // ActionOrder
            } else if (type.equals(ACTION_ORDER_TYPE)) {
                long t = System.currentTimeMillis();
                wo = getWorkOrderOf(msgText, CmsActionOrderSimple.class);
                wo.putSearchTag("iAoCrtTime", Long.toString(System.currentTimeMillis() - t));
                preProcess(wo);
                responseMsgMap = actionOrderExecutor.process(wo, correlationID);
            } else {
                logger.error(new IllegalArgumentException("Unknown msg type - " + type));
                msg.acknowledge();
                return;
            }

            // Controller will process this message
            responseMsgMap.put("correlationID", correlationID);
            responseMsgMap.put("type", type);

            long startTime = System.currentTimeMillis();

            if (!correlationID.equals("test"))
                messagePublisher.publishMessage(responseMsgMap);
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            // ack message
            logger.debug("send message took:" + duration + "ms");
            msg.acknowledge();

        }
    } catch (JMSException | SecurityException | IOException | IllegalArgumentException e) {
        logger.error("Error occurred in processing message", e);
    } finally {
        /*
         * Decrement the total number of active threads consumed by 1
        */
        activeThreads.getAndDecrement();
        clearStateFile();
    }
}

From source file:com.adaptris.core.jms.MessageTypeTranslatorCase.java

public void testMoveJmsHeadersAdaptrisMessageToJmsMessage() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    try {//from ww w .  j a  v  a 2s.c o  m
        broker.start();
        Session session = broker.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);

        AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
        addMetadata(msg);
        addRedundantJmsHeaders(msg);

        trans.setMoveJmsHeaders(true);
        start(trans, session);

        Message jmsMsg = trans.translate(msg);
        assertEquals(msg.getMetadataValue(JMS_TYPE), jmsMsg.getJMSType());
        assertNotSame(msg.getMetadataValue(JMS_CORRELATION_ID), jmsMsg.getJMSCorrelationID());
        assertNotSame(msg.getMetadataValue(JMS_TIMESTAMP), jmsMsg.getJMSTimestamp());
        assertNotSame(msg.getMetadataValue(JMS_REDELIVERED), jmsMsg.getJMSPriority());
        assertNotSame(msg.getMetadataValue(JMS_MESSAGE_ID), jmsMsg.getJMSMessageID());
        assertNotSame(msg.getMetadataValue(JMS_EXPIRATION), jmsMsg.getJMSExpiration());
        assertNotSame(msg.getMetadataValue(JMS_DELIVERY_MODE), jmsMsg.getJMSDeliveryMode());
        assertJmsProperties(jmsMsg);
    } finally {
        stop(trans);
        broker.destroy();
    }

}

From source file:com.cognifide.aet.runner.distribution.dispatch.CollectionResultsRouter.java

@Override
public void onMessage(Message message) {
    if (message instanceof ObjectMessage) {
        timeoutWatch.update();/* ww  w  .  jav a  2 s .c  o  m*/
        try {
            CollectorResultData collectorResultData = (CollectorResultData) ((ObjectMessage) message)
                    .getObject();

            collectorJobScheduler.messageReceived(collectorResultData.getRequestMessageId(),
                    message.getJMSCorrelationID());
            String testName = collectorResultData.getTestName();

            updateCounters(collectorResultData.getStatus());

            LOGGER.info(
                    "Reseived message {} - url {} in test `{}` collected with status {}. Results received "
                            + "successful {} / failed {} of {} total. CorrelationId: {}.",
                    message.getJMSMessageID(), collectorResultData.getUrl(), testName,
                    collectorResultData.getStatus(), messagesReceivedSuccess.get(),
                    messagesReceivedFailed.get(), getTotalTasksCount(), correlationId);

            if (collectorResultData.getStatus() == JobStatus.SUCCESS) {
                onSuccess(collectorResultData, testName);
            } else {
                final Url failedUrl = collectorResultData.getUrl();
                failedUrl.setErrorMessage(collectorResultData.getProcessingError().getDescription());
                updateSuiteUrl(testName, failedUrl);
                onError(collectorResultData.getProcessingError());
            }

            if (isFinished()) {
                LOGGER.info("CollectionResultsRouter task finished.");
                finishTask();
            }
        } catch (JMSException e) {
            LOGGER.error("Error while collecting results in CollectionResultsRouter", e);
            onError(ProcessingError.collectingError(e.getMessage()));
        }
    }
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Send the given message to the Destination using the given session
 * @param session the session to use to send
 * @param destination the Destination//from  ww  w .j  av  a2s  .  co m
 * @param message the JMS Message
 * @throws AxisFault on error
 */
public static void sendMessageToJMSDestination(Session session, Destination destination, Message message)
        throws AxisFault {

    MessageProducer producer = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("Sending message to destination : " + destination);
        }

        if (destination instanceof Queue) {
            producer = ((QueueSession) session).createSender((Queue) destination);
            ((QueueSender) producer).send(message);
        } else {
            producer = ((TopicSession) session).createPublisher((Topic) destination);
            ((TopicPublisher) producer).publish(message);
        }

        if (log.isDebugEnabled()) {
            log.debug("Sent message to destination : " + destination + "\nMessage ID : "
                    + message.getJMSMessageID() + "\nCorrelation ID : " + message.getJMSCorrelationID()
                    + "\nReplyTo ID : " + message.getJMSReplyTo());
        }

    } catch (JMSException e) {
        handleException("Error creating a producer or sending to : " + destination, e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException ignore) {
            }
        }
    }
}

From source file:org.apache.synapse.transport.jms.JMSMessageReceiver.java

/**
 * The entry point on the recepit of each JMS message
 *
 * @param message the JMS message received
 *///  w ww  .  j  a  v a 2s  . c o  m
public void onMessage(Message message) {
    // directly create a new worker and delegate processing
    try {
        if (log.isDebugEnabled()) {
            StringBuffer sb = new StringBuffer();
            sb.append("Received JMS message to destination : " + message.getJMSDestination());
            sb.append("\nMessage ID : " + message.getJMSMessageID());
            sb.append("\nCorrelation ID : " + message.getJMSCorrelationID());
            sb.append("\nReplyTo ID : " + message.getJMSReplyTo());
            log.debug(sb.toString());
            if (log.isTraceEnabled() && message instanceof TextMessage) {
                log.trace("\nMessage : " + ((TextMessage) message).getText());
            }
        }
    } catch (JMSException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error reading JMS message headers for debug logging", e);
        }
    }

    // has this message already expired? expiration time == 0 means never expires
    try {
        long expiryTime = message.getJMSExpiration();
        if (expiryTime > 0 && System.currentTimeMillis() > expiryTime) {
            if (log.isDebugEnabled()) {
                log.debug("Discard expired message with ID : " + message.getJMSMessageID());
            }
            return;
        }
    } catch (JMSException ignore) {
    }

    workerPool.execute(new Worker(message));
}