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:org.apache.falcon.regression.core.supportClasses.JmsMessageConsumer.java

@Override
public void run() {
    try {/*from   w  w  w.j av a2s . com*/
        // Getting JMS connection from the server
        Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection();
        connection.start();

        // Creating session for sending messages
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);

        try {
            LOGGER.info("Starting to receive messages.");
            int count = 0;
            for (; count < MAX_MESSAGE_COUNT; ++count) {
                Message message = consumer.receive(); //blocking call
                if (message == null) {
                    LOGGER.info("Received empty message, count = " + count);
                } else {
                    LOGGER.info("Received message, id = " + message.getJMSMessageID());
                    receivedMessages.add((MapMessage) message);
                }
            }
            if (count >= MAX_MESSAGE_COUNT) {
                LOGGER.warn("Not reading more messages, already read " + count + " messages.");
            }
        } finally {
            LOGGER.info("Stopping to receive messages.");
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.info("caught exception: " + ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.apache.jmeter.protocol.jms.sampler.Receiver.java

@Override
public void run() {
    active = true;/*from  w  w  w. ja v  a2  s. co m*/
    Message reply;

    while (active) {
        reply = null;
        try {
            reply = consumer.receive(5000);
            if (reply != null) {
                String messageKey;
                final MessageAdmin admin = MessageAdmin.getAdmin();
                if (useResMsgIdAsCorrelId) {
                    messageKey = reply.getJMSMessageID();
                    synchronized (admin) {// synchronize with FixedQueueExecutor
                        admin.putReply(messageKey, reply);
                    }
                } else {
                    messageKey = reply.getJMSCorrelationID();
                    if (messageKey == null) {// JMSMessageID cannot be null
                        log.warn("Received message with correlation id null. Discarding message ...");
                    } else {
                        admin.putReply(messageKey, reply);
                    }
                }
            }

        } catch (JMSException e1) {
            log.error("Error handling receive", e1);
        }
    }
    Utils.close(consumer, log);
    Utils.close(session, log);
    Utils.close(conn, log);
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

private void sendCommand(final Command command) {
    try {//from w ww .java  2s .  c  om
        final Message message = JmsMessageAdaptor.commandToMessage(_controllerSession, command);
        _controlQueueProducer.send(message);
        LOGGER.debug("Sent message for " + command.getType() + ". message id: " + message.getJMSMessageID());
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to send command: " + command, jmse);
    }
}

From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java

/**
 * Tests {@link ManagedQueue#viewMessages(long, long)} interface.
 *///from   ww  w  .jav a 2  s .  co m
public void testViewSingleMessage() throws Exception {
    final List<Message> sentMessages = sendMessage(_session, _sourceQueue, 1);
    syncSession(_session);
    final Message sentMessage = sentMessages.get(0);

    assertEquals("Unexpected queue depth", 1, _managedSourceQueue.getMessageCount().intValue());

    // Check the contents of the message
    final TabularData tab = _managedSourceQueue.viewMessages(1l, 1l);
    assertEquals("Unexpected number of rows in table", 1, tab.size());
    final Iterator<CompositeData> rowItr = (Iterator<CompositeData>) tab.values().iterator();

    final CompositeData row1 = rowItr.next();
    assertNotNull("Message should have AMQ message id", row1.get(ManagedQueue.MSG_AMQ_ID));
    assertEquals("Unexpected queue position", 1l, row1.get(ManagedQueue.MSG_QUEUE_POS));
    assertEquals("Unexpected redelivered flag", Boolean.FALSE, row1.get(ManagedQueue.MSG_REDELIVERED));

    // Check the contents of header (encoded in a string array)
    final String[] headerArray = (String[]) row1.get(ManagedQueue.MSG_HEADER);
    assertNotNull("Expected message header array", headerArray);
    final Map<String, String> headers = headerArrayToMap(headerArray);

    final String expectedJMSMessageID = isBroker010() ? sentMessage.getJMSMessageID().replace("ID:", "")
            : sentMessage.getJMSMessageID();
    final String expectedFormattedJMSTimestamp = FastDateFormat
            .getInstance(ManagedQueue.JMSTIMESTAMP_DATETIME_FORMAT).format(sentMessage.getJMSTimestamp());
    assertEquals("Unexpected JMSMessageID within header", expectedJMSMessageID, headers.get("JMSMessageID"));
    assertEquals("Unexpected JMSPriority within header", String.valueOf(sentMessage.getJMSPriority()),
            headers.get("JMSPriority"));
    assertEquals("Unexpected JMSTimestamp within header", expectedFormattedJMSTimestamp,
            headers.get("JMSTimestamp"));
}

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 w  w  w  .  j a v  a  2 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.apache.storm.jms.spout.JmsSpoutTest.java

@Test
public void testFailure() throws JMSException, Exception {
    JmsSpout spout = new JmsSpout();
    JmsProvider mockProvider = new MockJmsProvider();
    MockSpoutOutputCollector mockCollector = new MockSpoutOutputCollector();
    SpoutOutputCollector collector = new SpoutOutputCollector(mockCollector);
    spout.setJmsProvider(new MockJmsProvider());
    spout.setJmsTupleProducer(new MockTupleProducer());
    spout.setJmsAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    spout.setRecoveryPeriod(10); // Rapid recovery for testing.
    spout.open(new HashMap<String, String>(), null, collector);
    Message msg = this.sendMessage(mockProvider.connectionFactory(), mockProvider.destination());
    Thread.sleep(100);//from   www.  j a va  2 s .co m
    spout.nextTuple(); // Pretend to be storm.
    Assert.assertTrue(mockCollector.emitted);

    mockCollector.reset();
    spout.fail(msg.getJMSMessageID()); // Mock failure
    Thread.sleep(5000);
    spout.nextTuple(); // Pretend to be storm.
    Thread.sleep(5000);
    Assert.assertTrue(mockCollector.emitted); // Should have been re-emitted
}

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
 *//*from w  ww.j  a va2  s  . c om*/
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));
}

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

/**
 * Performs the actual sending of the JMS message
 *///  ww  w.  ja  va  2  s.  c  o m
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    JMSConnectionFactory jmsConnectionFactory = null;
    Connection connection = null; // holds a one time connection if used
    JMSOutTransportInfo jmsOut = null;
    Session session = null;
    Destination destination = null;
    Destination replyDestination = null;

    try {
        if (targetAddress != null) {

            jmsOut = new JMSOutTransportInfo(targetAddress);
            // do we have a definition for a connection factory to use for this address?
            jmsConnectionFactory = getJMSConnectionFactory(jmsOut);

            if (jmsConnectionFactory != null) {
                // create new or get existing session to send to the destination from the CF
                session = jmsConnectionFactory.getSessionForDestination(JMSUtils.getDestination(targetAddress));

            } else {
                // digest the targetAddress and locate CF from the EPR
                jmsOut.loadConnectionFactoryFromProperies();
                try {
                    // create a one time connection and session to be used
                    Hashtable jndiProps = jmsOut.getProperties();
                    String user = (String) jndiProps.get(Context.SECURITY_PRINCIPAL);
                    String pass = (String) jndiProps.get(Context.SECURITY_CREDENTIALS);

                    QueueConnectionFactory qConFac = null;
                    TopicConnectionFactory tConFac = null;
                    ConnectionFactory conFac = null;

                    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        qConFac = (QueueConnectionFactory) jmsOut.getConnectionFactory();
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        tConFac = (TopicConnectionFactory) jmsOut.getConnectionFactory();
                    } else {
                        handleException(
                                "Unable to determine type of JMS " + "Connection Factory - i.e Queue/Topic");
                    }

                    if (user != null && pass != null) {
                        if (qConFac != null) {
                            connection = qConFac.createQueueConnection(user, pass);
                        } else if (tConFac != null) {
                            connection = tConFac.createTopicConnection(user, pass);
                        }
                    } else {
                        if (qConFac != null) {
                            connection = qConFac.createQueueConnection();
                        } else if (tConFac != null) {
                            connection = tConFac.createTopicConnection();
                        }
                    }

                    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        session = ((QueueConnection) connection).createQueueSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        session = ((TopicConnection) connection).createTopicSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    }

                } catch (JMSException e) {
                    handleException("Error creating a connection/session for : " + targetAddress);
                }
            }
            destination = jmsOut.getDestination();

        } else if (outTransportInfo != null && outTransportInfo instanceof JMSOutTransportInfo) {

            jmsOut = (JMSOutTransportInfo) outTransportInfo;
            jmsConnectionFactory = jmsOut.getJmsConnectionFactory();

            session = jmsConnectionFactory.getSessionForDestination(jmsOut.getDestination().toString());
            destination = jmsOut.getDestination();
        }

        String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO);
        if (replyDestName != null) {
            if (jmsConnectionFactory != null) {
                replyDestination = jmsConnectionFactory.getDestination(replyDestName);
            } else {
                replyDestination = jmsOut.getReplyDestination(replyDestName);
            }
        }

        // now we are going to use the JMS session, but if this was a session from a
        // defined JMS connection factory, we need to synchronize as sessions are not
        // thread safe
        synchronized (session) {

            // convert the axis message context into a JMS Message that we can send over JMS
            Message message = null;
            String correlationId = null;
            try {
                message = createJMSMessage(msgCtx, session);
            } catch (JMSException e) {
                handleException("Error creating a JMS message from the axis message context", e);
            }

            String destinationType = jmsOut.getDestinationType();

            // if the destination does not exist, see if we can create it
            destination = JMSUtils.createDestinationIfRequired(destination, destinationType, targetAddress,
                    session);

            // should we wait for a synchronous response on this same thread?
            boolean waitForResponse = waitForSynchronousResponse(msgCtx);

            // if this is a synchronous out-in, prepare to listen on the response destination
            if (waitForResponse) {
                replyDestination = JMSUtils.setReplyDestination(replyDestination, session, message);
            }

            // send the outgoing message over JMS to the destination selected
            JMSUtils.sendMessageToJMSDestination(session, destination, message);

            // if we are expecting a synchronous response back for the message sent out
            if (waitForResponse) {
                try {
                    connection.start();
                } catch (JMSException ignore) {
                }
                try {
                    correlationId = message.getJMSMessageID();
                } catch (JMSException ignore) {
                }
                waitForResponseAndProcess(session, replyDestination, msgCtx, correlationId);
            }
        }

    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException ignore) {
            }
        }
    }
}

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   w w  w  .j a v a2 s .  c  o 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.JMSUtils.java

/**
 * Extract transport level headers for JMS from the given message into a Map
 *
 * @param message the JMS message//from w  ww .j a v  a 2s.c o m
 * @return a Map of the transport headers
 */
public static Map getTransportHeaders(Message message) {
    // create a Map to hold transport headers
    Map map = new HashMap();

    // correlation ID
    try {
        if (message.getJMSCorrelationID() != null) {
            map.put(JMSConstants.JMS_COORELATION_ID, message.getJMSCorrelationID());
        }
    } catch (JMSException ignore) {
    }

    // set the delivery mode as persistent or not
    try {
        map.put(JMSConstants.JMS_DELIVERY_MODE, Integer.toString(message.getJMSDeliveryMode()));
    } catch (JMSException ignore) {
    }

    // destination name
    try {
        if (message.getJMSDestination() != null) {
            Destination dest = message.getJMSDestination();
            map.put(JMSConstants.JMS_DESTINATION,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // expiration
    try {
        map.put(JMSConstants.JMS_EXPIRATION, Long.toString(message.getJMSExpiration()));
    } catch (JMSException ignore) {
    }

    // if a JMS message ID is found
    try {
        if (message.getJMSMessageID() != null) {
            map.put(JMSConstants.JMS_MESSAGE_ID, message.getJMSMessageID());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_PRIORITY, Long.toString(message.getJMSPriority()));
    } catch (JMSException ignore) {
    }

    // redelivered
    try {
        map.put(JMSConstants.JMS_REDELIVERED, Boolean.toString(message.getJMSRedelivered()));
    } catch (JMSException ignore) {
    }

    // replyto destination name
    try {
        if (message.getJMSReplyTo() != null) {
            Destination dest = message.getJMSReplyTo();
            map.put(JMSConstants.JMS_REPLY_TO,
                    dest instanceof Queue ? ((Queue) dest).getQueueName() : ((Topic) dest).getTopicName());
        }
    } catch (JMSException ignore) {
    }

    // priority
    try {
        map.put(JMSConstants.JMS_TIMESTAMP, Long.toString(message.getJMSTimestamp()));
    } catch (JMSException ignore) {
    }

    // message type
    try {
        if (message.getJMSType() != null) {
            map.put(JMSConstants.JMS_TYPE, message.getJMSType());
        }
    } catch (JMSException ignore) {
    }

    // any other transport properties / headers
    Enumeration e = null;
    try {
        e = message.getPropertyNames();
    } catch (JMSException ignore) {
    }

    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = (String) e.nextElement();
            try {
                map.put(headerName, message.getStringProperty(headerName));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, Boolean.valueOf(message.getBooleanProperty(headerName)));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, new Integer(message.getIntProperty(headerName)));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, new Long(message.getLongProperty(headerName)));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, new Double(message.getDoubleProperty(headerName)));
                continue;
            } catch (JMSException ignore) {
            }
            try {
                map.put(headerName, new Float(message.getFloatProperty(headerName)));
                continue;
            } catch (JMSException ignore) {
            }
        }
    }

    return map;
}