Example usage for javax.jms Message getJMSMessageID

List of usage examples for javax.jms Message getJMSMessageID

Introduction

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

Prototype


String getJMSMessageID() throws JMSException;

Source Link

Document

Gets the message ID.

Usage

From source file:dk.netarkivet.common.distribute.JMSConnection.java

/**
 * Unwraps a NetarkivetMessage from an ObjectMessage.
 *
 * @param msg a javax.jms.ObjectMessage//from  w w w  .  j a  va 2  s.  com
 *
 * @return a NetarkivetMessage
 *
 * @throws ArgumentNotValid when msg in valid or format of JMS Object
 *                          message is invalid
 */
public static NetarkivetMessage unpack(Message msg) throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(msg, "msg");

    ObjectMessage objMsg;
    try {
        objMsg = (ObjectMessage) msg;
    } catch (ClassCastException e) {
        log.warn("Invalid message type: " + msg.getClass());
        throw new ArgumentNotValid("Invalid message type: " + msg.getClass());
    }

    NetarkivetMessage netMsg;
    String classname = "Unknown class"; // for error reporting purposes
    try {
        classname = objMsg.getObject().getClass().getName();
        netMsg = (NetarkivetMessage) objMsg.getObject();
        // Note: Id is only updated if the message does not already have an
        // id. On unpack, this means the first time the message is received.

        // FIXME Fix for NAS-2043 doesn't seem to work
        //String randomID = UUID.randomUUID().toString();
        //netMsg.updateId(randomID);

        netMsg.updateId(msg.getJMSMessageID());
    } catch (ClassCastException e) {
        log.warn("Invalid message type: " + classname, e);
        throw new ArgumentNotValid("Invalid message type: " + classname, e);
    } catch (Exception e) {
        String message = "Message invalid. Unable to unpack " + "message: " + classname;
        log.warn(message, e);
        throw new ArgumentNotValid(message, e);
    }
    log.trace("Unpacked message '" + netMsg + "'");
    return netMsg;
}

From source file:com.datatorrent.lib.io.jms.AbstractJMSInputOperator.java

/**
 * If getJMSReplyTo is set then send message back to reply producer.
 *
 * @param message// w  w  w .  j a va2 s .  c om
 */
protected void sendReply(Message message) {
    try {
        if (message.getJMSReplyTo() != null) { // Send reply only if the replyTo destination is set
            replyProducer.send(message.getJMSReplyTo(),
                    getSession().createTextMessage("Reply: " + message.getJMSMessageID()));
        }
    } catch (JMSException ex) {
        LOG.error(ex.getLocalizedMessage());
        throwable.set(ex);
        throw new RuntimeException(ex);
    }
}

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

public void testMoveJmsHeadersAdaptrisMessageToJmsMessage() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    try {/*from  w ww.  j a v  a2  s  . c  om*/
        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.legstar.mq.client.AbstractCicsMQ.java

/**
 * Creates and send a JMS message to the mainframe.
 * <p/>//from   ww w  .  ja  va  2 s  . co m
 * Reply to queue name is where we expect the reply. We expect it to be
 * managed by the same mq manager as the request queue.
 * <p/>
 * Save the unique message ID that was generated by JMS. It will be needed
 * to retrieve the correlated reply.
 * 
 * @param request the request to be sent
 * @throws RequestException if send fails
 */
public void sendRequest(final LegStarRequest request) throws RequestException {

    MessageProducer producer = null;
    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Sending Request:" + request.getID() + " on Connection:" + _connectionID + " "
                    + request.getRequestMessage().getHeaderPart().getJsonString() + '.');
        }

        Message jmsMessage = createRequestMessage(request);
        jmsMessage.setJMSReplyTo(getJmsReplyQueue());
        producer = getJmsQueueSession().createProducer(getJmsRequestQueue());
        producer.send(jmsMessage);

        request.setAttachment(jmsMessage.getJMSMessageID().getBytes());

        _lastUsedTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Sent Request:" + request.getID() + " on Connection:" + _connectionID + ". Message ID:"
                    + jmsMessage.getJMSMessageID());
        }
    } catch (HeaderPartException e) {
        throw new RequestException(e);
    } catch (JMSException e) {
        throw new RequestException(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                _log.error(e);
            }
        }
    }
}

From source file:org.apache.servicemix.jms.endpoints.AbstractConsumerEndpoint.java

protected void setCorrelationId(Message query, Message reply) throws Exception {
    if (useMessageIdInResponse == null) {
        if (query.getJMSCorrelationID() != null) {
            reply.setJMSCorrelationID(query.getJMSCorrelationID());
        } else if (query.getJMSMessageID() != null) {
            reply.setJMSCorrelationID(query.getJMSMessageID());
        } else {/*  www  . j a  va 2  s .  c  om*/
            throw new IllegalStateException("No JMSCorrelationID or JMSMessageID set on query message");
        }
    } else if (useMessageIdInResponse.booleanValue()) {
        if (query.getJMSMessageID() != null) {
            reply.setJMSCorrelationID(query.getJMSMessageID());
        } else {
            throw new IllegalStateException("No JMSMessageID set on query message");
        }
    } else {
        if (query.getJMSCorrelationID() != null) {
            reply.setJMSCorrelationID(query.getJMSCorrelationID());
        } else {
            throw new IllegalStateException("No JMSCorrelationID set on query message");
        }
    }
}

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

@Override
public void onMessage(Message message) {
    if (message instanceof ObjectMessage) {
        timeoutWatch.update();/* www .  j a  v  a2s  .  co  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.servicemix.jms.JmsProviderEndpointTest.java

public void testSoapProviderInOut() throws Exception {
    JmsComponent component = new JmsComponent();

    JmsSoapProviderEndpoint endpoint = new JmsSoapProviderEndpoint();
    endpoint.setService(new QName("uri:HelloWorld", "HelloService"));
    endpoint.setEndpoint("HelloPort");
    endpoint.setConnectionFactory(connectionFactory);
    endpoint.setDestinationName("destination");
    endpoint.setReplyDestinationName("reply");
    endpoint.setWsdl(new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC.wsdl"));
    component.setEndpoints(new JmsProviderEndpoint[] { endpoint });
    container.activateComponent(component, "servicemix-jms");

    Thread th = new Thread() {
        public void run() {
            try {
                final Message msg = jmsTemplate.receive("destination");
                assertNotNull(msg);/*from w ww.ja  va 2s.  com*/
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                FileUtil.copyInputStream(
                        new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC-Output.xml")
                                .getInputStream(),
                        baos);
                jmsTemplate.send("reply", new MessageCreator() {
                    public Message createMessage(Session session) throws JMSException {
                        TextMessage rep = session.createTextMessage(baos.toString());
                        rep.setJMSCorrelationID(msg.getJMSCorrelationID() != null ? msg.getJMSCorrelationID()
                                : msg.getJMSMessageID());
                        return rep;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    th.start();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileUtil.copyInputStream(
            new ClassPathResource("org/apache/servicemix/jms/HelloWorld-RPC-Input-Hello.xml").getInputStream(),
            baos);
    InOut me = client.createInOutExchange();
    me.getInMessage().setContent(new StringSource(baos.toString()));
    me.setOperation(new QName("uri:HelloWorld", "Hello"));
    me.setService(new QName("uri:HelloWorld", "HelloService"));
    client.sendSync(me);
    assertEquals(ExchangeStatus.ACTIVE, me.getStatus());
    assertNotNull(me.getOutMessage());
    assertNotNull(me.getOutMessage().getContent());
    System.err.println(new SourceTransformer().contentToString(me.getOutMessage()));
    client.done(me);

}

From source file:com.amalto.core.server.routing.DefaultRoutingEngine.java

@Override
public void consume(final Message message) {
    try {//from w w  w.ja  va 2  s  . c o  m
        @SuppressWarnings("unchecked")
        String[] rules = getRulesList(message);
        final String pk = message.getStringProperty(JMS_PK_PROPERTY);
        final String type = message.getStringProperty(JMS_TYPE_PROPERTY);
        final String container = message.getStringProperty(JMS_CONTAINER_PROPERTY);
        final long timeScheduled = message.getLongProperty(JMS_SCHEDULED);
        final String routingOrderId = message.getJMSMessageID();
        for (int ruleIndex = 0; ruleIndex < rules.length; ruleIndex++) {
            String rule = rules[ruleIndex];
            final RoutingRulePOJO routingRule = routingRules.getRoutingRule(new RoutingRulePOJOPK(rule));
            // Apparently rule is not (yet) deployed onto this system's DB instance, but... that 's
            // rather unexpected since all nodes in cluster are supposed to share same system DB.
            if (routingRule == null) {
                throw new RuntimeException(
                        "Cannot execute rule(s) " + rules + ": routing rule '" + rule + "' can not be found.");
            }
            SecurityConfig.invokeSynchronousPrivateInternal(new Runnable() {
                @Override
                public void run() {
                    // execute all rules synchronously
                    final ItemPOJOPK itemPOJOPK = new ItemPOJOPK(new DataClusterPOJOPK(container), type,
                            pk.split("\\."));
                    applyRule(itemPOJOPK, routingRule, routingOrderId, timeScheduled);
                }
            });
        }
        // acknowledge message once all rules are executed
        message.acknowledge();
    } catch (Exception e) {
        throw new RuntimeException("Unable to process message.", e);
    }
}

From source file:org.apache.servicemix.jms.endpoints.JmsProviderEndpoint.java

/**
 * Process an InOnly or RobustInOnly exchange inside a JMS session.
 * This method delegates the JMS message creation to the marshaler and uses
 * the JMS template to send it.  If the JMS destination that was used to send
 * the message is not the default one, it synchronously wait for the message
 * to come back using a JMS selector.  Else, it just returns and the response
 * message will come back from the listener container.
 *
 * @param exchange//from   w w w . j a v a 2s .  co m
 * @param in
 * @param session
 * @throws Exception
 */
protected void processInOutInSession(final MessageExchange exchange, final NormalizedMessage in,
        final Session session) throws Exception {
    // Create destinations
    final Destination dest = getDestination(exchange, in, session);
    final Destination replyDest = getReplyDestination(exchange, in, session);
    // Create message and send it
    final Message sendJmsMsg = marshaler.createMessage(exchange, in, session);
    sendJmsMsg.setJMSReplyTo(replyDest);
    // handle correlation ID
    String correlationId = sendJmsMsg.getJMSMessageID() != null ? sendJmsMsg.getJMSMessageID()
            : exchange.getExchangeId();
    sendJmsMsg.setJMSCorrelationID(correlationId);

    boolean asynchronous = replyDest.equals(replyDestination);

    if (asynchronous) {
        store.store(correlationId, exchange);
    }

    try {
        template.send(dest, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return sendJmsMsg;
            }
        });
    } catch (Exception e) {
        if (asynchronous) {
            store.load(exchange.getExchangeId());
        }
        throw e;
    }

    if (!asynchronous) {
        // Create selector
        String jmsId = sendJmsMsg.getJMSMessageID();
        String selector = MSG_SELECTOR_START + jmsId + MSG_SELECTOR_END;
        // Receiving JMS Message, Creating and Returning NormalizedMessage out
        Message receiveJmsMsg = template.receiveSelected(replyDest, selector);
        if (receiveJmsMsg == null) {
            throw new IllegalStateException("Unable to receive response");
        }

        NormalizedMessage out = exchange.getMessage("out");
        if (out == null) {
            out = exchange.createMessage();
            exchange.setMessage(out, "out");
        }
        marshaler.populateMessage(receiveJmsMsg, exchange, out);
        boolean txSync = exchange.isTransacted()
                && Boolean.TRUE.equals(exchange.getProperty(JbiConstants.SEND_SYNC));
        if (txSync) {
            sendSync(exchange);
        } else {
            send(exchange);
        }
    }
}