Example usage for javax.jms Message setJMSReplyTo

List of usage examples for javax.jms Message setJMSReplyTo

Introduction

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

Prototype


void setJMSReplyTo(Destination replyTo) throws JMSException;

Source Link

Document

Sets the Destination object to which a reply to this message should be sent.

Usage

From source file:example.tempdest.ProducerRequestReply.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/* w ww .  java  2  s.co  m*/
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("test-queue");
        MessageProducer producer = session.createProducer(destination);
        Destination replyDest = session.createTemporaryQueue();

        // set up the consumer to handle the reply
        MessageConsumer replyConsumer = session.createConsumer(replyDest);
        replyConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                System.out.println("*** REPLY *** ");
                System.out.println(message.toString());
            }
        });

        TextMessage message = session.createTextMessage("I need a response for this, please");
        message.setJMSReplyTo(replyDest);

        producer.send(message);

        // wait for a response
        TimeUnit.SECONDS.sleep(2);
        producer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:org.calrissian.mango.jms.stream.utils.SendReceiveRequestor.java

@Override
public Message postProcessMessage(Message message) throws JMSException {
    Message msg = populateProperties(message);
    msg.setJMSReplyTo(topic);
    return msg;/* w ww .j  av  a2s  . c om*/
}

From source file:org.calrissian.mango.jms.stream.utils.SendReceiveRequestor.java

public void send(Message message) throws JMSException {
    message.setJMSReplyTo(topic);
    final Message msg = populateProperties(message);
    jmsTemplate.send(topic, new MessageCreator() {

        @Override//from  www  . j a v  a 2s  .c  o m
        public Message createMessage(Session session) throws JMSException {
            return msg;
        }
    });
}

From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * // w ww.ja  v  a 2  s  . c  o  m
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

From source file:org.calrissian.mango.jms.stream.JmsFileReceiverInputStream.java

protected void start() {
    support.getJmsTemplate().send(receiveAckDestination, new MessageCreator() {

        @Override/*from   w  ww.ja v a  2 s  . co m*/
        public Message createMessage(Session session) throws JMSException {
            final Message responseMessage = toResponseMessage(session, new Response(STARTSEND));
            responseMessage.setJMSReplyTo(support.factoryDestination(session, sendDataDestination));
            return responseMessage;
        }

    });
    started = true;
}

From source file:org.apache.servicemix.jms.JMSComponentTest.java

public void testConsumerInOut() throws Exception {
    // JMS Component
    JmsComponent component = new JmsComponent();
    container.activateComponent(component, "JMSComponent");

    // Add an echo component
    EchoComponent echo = new EchoComponent();
    ActivationSpec asEcho = new ActivationSpec("receiver", echo);
    asEcho.setService(new QName("http://jms.servicemix.org/Test", "Echo"));
    container.activateComponent(asEcho);

    // Deploy Consumer SU
    URL url = getClass().getClassLoader().getResource("consumer/jms.wsdl");
    File path = new File(new URI(url.toString()));
    path = path.getParentFile();//from  www .  ja v  a2 s .  co  m
    component.getServiceUnitManager().deploy("consumer", path.getAbsolutePath());
    component.getServiceUnitManager().init("consumer", path.getAbsolutePath());
    component.getServiceUnitManager().start("consumer");

    // Send test message
    jmsTemplate.setDefaultDestinationName("queue/A");
    jmsTemplate.afterPropertiesSet();
    jmsTemplate.send(new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            Message m = session.createTextMessage("<hello>world</hello>");
            m.setJMSReplyTo(session.createQueue("queue/B"));
            return m;
        }
    });

    // Receive echo message
    TextMessage reply = (TextMessage) jmsTemplate.receive("queue/B");
    assertNotNull(reply);
    logger.info(reply.getText());
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;// w  w  w.  j  a v  a2 s. com
    Destination orderQueue;
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Try to use ActiveMQ StatisticsPlugin to get size and if that fails
 * fallback to {@link JMSMailQueue#getSize()}
 *//*from  w w  w  . jav  a2s  .  com*/
@Override
public long getSize() throws MailQueueException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    TemporaryQueue replyTo = null;
    long size = -1;

    try {
        connection = connectionFactory.createConnection();
        connection.start();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        replyTo = session.createTemporaryQueue();
        consumer = session.createConsumer(replyTo);

        Queue myQueue = session.createQueue(queuename);
        producer = session.createProducer(null);

        String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName();
        Queue query = session.createQueue(queueName);

        Message msg = session.createMessage();
        msg.setJMSReplyTo(replyTo);
        producer.send(query, msg);
        MapMessage reply = (MapMessage) consumer.receive(2000);
        if (reply != null && reply.itemExists("size")) {
            try {
                size = reply.getLong("size");
                return size;
            } catch (NumberFormatException e) {
                // if we hit this we can't calculate the size so just catch
                // it
            }
        }

    } catch (Exception e) {
        throw new MailQueueException("Unable to remove mails", e);

    } finally {

        if (consumer != null) {

            try {
                consumer.close();
            } catch (JMSException e1) {
                e1.printStackTrace();
                // ignore on rollback
            }
        }

        if (producer != null) {

            try {
                producer.close();
            } catch (JMSException e1) {
                // ignore on rollback
            }
        }

        if (replyTo != null) {
            try {

                // we need to delete the temporary queue to be sure we will
                // free up memory if thats not done and a pool is used
                // its possible that we will register a new mbean in jmx for
                // every TemporaryQueue which will never get unregistered
                replyTo.delete();
            } catch (JMSException e) {
            }
        }
        try {
            if (session != null)
                session.close();
        } catch (JMSException e1) {
            // ignore here
        }

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

    // if we came to this point we should just fallback to super method
    return super.getSize();
}

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * Creates and send a JMS message to the mainframe.
 * <p/>//w w w  . ja  v  a 2 s  .c o 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:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

protected JMSHeader createJMSHeader(SubmitContext submitContext, Request request, Hermes hermes,
        Message message, Destination replyToDestination) {
    JMSHeader jmsHeader = new JMSHeader();
    jmsHeader.setMessageHeaders(message, request, hermes, submitContext);
    JMSHeader.setMessageProperties(message, request, hermes, submitContext);
    try {/* w w  w. j a va  2  s . c om*/
        if (message.getJMSReplyTo() == null) {
            message.setJMSReplyTo(replyToDestination);
        }

        if (addSoapAction) {

            message.setStringProperty(JMSHeader.SOAPJMS_SOAP_ACTION, request.getOperation().getName());
            if (request.getOperation() instanceof WsdlOperation) {
                message.setStringProperty(JMSHeader.SOAP_ACTION,
                        ((WsdlOperation) request.getOperation()).getAction());
            } else {
                message.setStringProperty(JMSHeader.SOAP_ACTION, request.getOperation().getName());
            }
        }
    } catch (JMSException e) {
        SoapUI.logError(e);
    }
    return jmsHeader;
}