Example usage for javax.jms TextMessage setJMSReplyTo

List of usage examples for javax.jms TextMessage setJMSReplyTo

Introduction

In this page you can find the example usage for javax.jms TextMessage 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:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * retrieve meta information for a UIMA-AS Service attached to a broker
 * It uses the port 1099 as the JMX port on the broker, unless overridden
 *   by defining the system property activemq.broker.jmx.port with a value of another port number
 * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden
 *   by defining the system property activemq.broker.jmx.domain with a value of the domain to use
 *   This normally never needs to be done unless multiple brokers are run on the same node 
 *   as is sometimes done for unit tests.
 * @param args - brokerUri serviceName [-verbose]
 *//*w  ww.  j a  v  a  2  s.c  o m*/
public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Need arguments: brokerURI serviceName [-verbose]");
        System.exit(1);
    }
    String brokerURI = args[0];
    String queueName = args[1];
    boolean printReply = false;
    if (args.length > 2) {
        if (args[2].equalsIgnoreCase("-verbose")) {
            printReply = true;
        } else {
            System.err.println("Unknown argument: " + args[2]);
            System.exit(1);
        }
    }
    final Connection connection;
    Session producerSession = null;
    Queue producerQueue = null;
    MessageProducer producer;
    MessageConsumer consumer;
    Session consumerSession = null;
    TemporaryQueue consumerDestination = null;
    long startTime = 0;

    //  Check if JMX server port number was specified
    jmxPort = System.getProperty("activemq.broker.jmx.port");
    if (jmxPort == null || jmxPort.trim().length() == 0) {
        jmxPort = "1099"; // default
    }

    try {
        //  First create connection to a broker
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI);
        connection = factory.createConnection();
        connection.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                try {
                    if (connection != null) {
                        connection.close();
                    }
                    if (jmxc != null) {
                        jmxc.close();
                    }
                } catch (Exception ex) {
                }
            }
        }));

        URI target = new URI(brokerURI);
        String brokerHost = target.getHost();

        attachToRemoteBrokerJMXServer(brokerURI);
        if (isQueueAvailable(queueName) == QueueState.exists) {
            System.out.println("Queue " + queueName + " found on " + brokerURI);
            System.out.println("Sending getMeta...");
        } else if (isQueueAvailable(queueName) == QueueState.existsnot) {
            System.err.println("Queue " + queueName + " does not exist on " + brokerURI);
            System.exit(1);
        } else {
            System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort);
            System.out.println("Sending getMeta anyway...");
        }

        producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producerQueue = producerSession.createQueue(queueName);
        producer = producerSession.createProducer(producerQueue);
        consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        consumerDestination = consumerSession.createTemporaryQueue();
        //  -----------------------------------------------------------------------------
        //  Create message consumer. The consumer uses a selector to filter out messages other
        //  then GetMeta replies. Currently UIMA AS service returns two messages for each request:
        //  ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the 
        //  service immediately upon receiving a message from a client. This serves dual purpose, 
        //  1) to make sure the client reply destination exists
        //  2) informs the client which service is processing its request
        //  -----------------------------------------------------------------------------
        consumer = consumerSession.createConsumer(consumerDestination, "Command=2001");
        TextMessage msg = producerSession.createTextMessage();
        msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName());
        msg.setStringProperty(UIMAMessage.ServerURI, brokerURI);
        msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request);
        msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta);
        msg.setJMSReplyTo(consumerDestination);
        msg.setText("");
        producer.send(msg);
        startTime = System.nanoTime();

        System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI);
        System.out.println("Waiting for getMeta reply...");
        ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive();
        long waitTime = (System.nanoTime() - startTime) / 1000000;

        System.out.println(
                "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms");
        if (printReply) {
            System.out.println("Reply MessageText: " + reply.getText());
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }
    System.exit(0);
}

From source file:test.SecureSampleApp.java

private static String sendMessage(final String encryptedMessage) {
    return template.execute(new SessionCallback<String>() {
        @Override/*w w w.  jav  a2 s  .  c  o  m*/
        public String doInJms(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(encryptedMessage);
            Queue outQueue = session.createQueue("receive");
            Destination inDest = session.createTemporaryQueue();
            String correlationID = UUID.randomUUID().toString();
            message.setJMSReplyTo(inDest);
            message.setJMSCorrelationID(correlationID);
            MessageProducer producer = session.createProducer(outQueue);
            producer.send(outQueue, message);
            return ((TextMessage) session.createConsumer(inDest).receive(10000)).getText();
        }
    }, true);
}

From source file:org.btc4j.jms.BtcDaemonCaller.java

public String sendReceive(final String destination, final String payload) {
    return jmsTemplate.execute(new SessionCallback<String>() {
        @Override/*from   w ww.  ja  v a2s .c o  m*/
        public String doInJms(Session session) throws JMSException {
            final TemporaryQueue replyQueue = session.createTemporaryQueue();
            jmsTemplate.send(destination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    TextMessage message = session.createTextMessage();
                    message.setJMSReplyTo(replyQueue);
                    message.setText(payload);
                    message.setStringProperty("btcapi:account", account);
                    message.setStringProperty("btcapi:password", password);
                    return message;
                }
            });
            return String.valueOf(jmsTemplate.receiveAndConvert(replyQueue));
        }
    });
}

From source file:net.lr.jmsbridge.BridgeServlet.java

/**
 * Forward HTTP request to a jms queue and listen on a temporary queue for the reply.
 * Connects to the jms server by using the username and password from the HTTP basic auth.
 *///from w w w. j av a2s . c om
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        resp.setHeader("WWW-Authenticate", "Basic realm=\"Bridge\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "auth");
        return;
    }
    UserNameAndPassword auth = extractUserNamePassword(authHeader);
    PrintStream out = new PrintStream(resp.getOutputStream());
    String contextPath = req.getContextPath();
    String uri = req.getRequestURI();
    String queueName = uri.substring(contextPath.length() + 1);
    final StringBuffer reqContent = retrieveRequestContent(req.getReader());

    ConnectionFactory cf = connectionPool.getConnectionFactory(auth);
    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(cf);
    jmsTemplate.setReceiveTimeout(10000);
    final Destination replyDest = connectionPool.getReplyDestination(cf, auth);
    jmsTemplate.send(queueName, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            TextMessage message = session.createTextMessage(reqContent.toString());
            message.setJMSReplyTo(replyDest);
            return message;
        }

    });
    Message replyMsg = jmsTemplate.receive(replyDest);
    if (replyMsg instanceof TextMessage) {
        TextMessage replyTMessage = (TextMessage) replyMsg;
        try {
            out.print(replyTMessage.getText());
        } catch (JMSException e) {
            JmsUtils.convertJmsAccessException(e);
        }
    }
}

From source file:de.adorsys.jmspojo.JMSMessageListenerServiceAdapterTest.java

@Test
public void testCreateAdapterWithException() throws JMSException {
    TextMessage textMessage = queueSession.createTextMessage(OBJECT_MAPPER.serialize(new PingMessage("ping")));
    textMessage.setJMSReplyTo(reqlayQ);

    SampleMessageServiceWithException service = new SampleMessageServiceWithException();
    JMSMessageListenerServiceAdapter<SampleMessageServiceWithException> adapter = JMSMessageListenerServiceAdapter
            .createAdapter(service, cf, OBJECT_MAPPER);
    adapter.onMessage(textMessage);/*from   ww  w .  ja  v a  2 s . c om*/

    TextMessage message = (TextMessage) queueSession.createReceiver(reqlayQ).receive(1000);
    assertNotNull(message);
    assertEquals("java.lang.RuntimeException: expected problem", message.getStringProperty("ERROR"));
}

From source file:de.adorsys.jmspojo.JMSMessageListenerServiceAdapterTest.java

@Test
public void testCreateAdapterWithReply() throws JMSException {
    TextMessage textMessage = queueSession.createTextMessage(OBJECT_MAPPER.serialize(new PingMessage("ping")));
    textMessage.setJMSReplyTo(reqlayQ);

    SampleMessageServiceWithReply service = new SampleMessageServiceWithReply();
    JMSMessageListenerServiceAdapter<SampleMessageServiceWithReply> adapter = JMSMessageListenerServiceAdapter
            .createAdapter(service, cf, OBJECT_MAPPER);
    adapter.onMessage(textMessage);//from   ww w .j ava 2 s.com

    TextMessage message = (TextMessage) queueSession.createReceiver(reqlayQ).receive(1000);
    assertNotNull(message);
    assertNull(message.getStringProperty("ERROR"));
    assertEquals("{\"ping\":\"ping\"}", message.getText());
}

From source file:de.adorsys.jmspojo.JMSMessageListenerServiceAdapterTest.java

@Test
public void testCreateAdapterVoid() throws JMSException {
    TextMessage textMessage = queueSession.createTextMessage(OBJECT_MAPPER.serialize(new PingMessage("ping")));
    textMessage.setJMSReplyTo(reqlayQ);

    SampleMessageServiceVoid service = new SampleMessageServiceVoid();
    JMSMessageListenerServiceAdapter<SampleMessageServiceVoid> adapter = JMSMessageListenerServiceAdapter
            .createAdapter(service, cf, OBJECT_MAPPER);
    adapter.onMessage(textMessage);/*  w  w  w.j  ava  2 s  . c  om*/

    TextMessage message = (TextMessage) queueSession.createReceiver(reqlayQ).receive(1000);
    assertNotNull(message);
    assertNull(message.getStringProperty("ERROR"));
    assertNull(message.getText());
}

From source file:de.adorsys.jmspojo.JMSMessageListenerServiceAdapterTest.java

@Test
public void testCreateAdapterWithHeaders() throws JMSException {
    TextMessage textMessage = queueSession.createTextMessage(OBJECT_MAPPER.serialize(new PingMessage("ping")));
    textMessage.setJMSReplyTo(reqlayQ);
    textMessage.setBooleanProperty("testHeader", true);

    SampleMessageServiceWithHeaders service = new SampleMessageServiceWithHeaders();
    JMSMessageListenerServiceAdapter<SampleMessageServiceWithHeaders> adapter = JMSMessageListenerServiceAdapter
            .createAdapter(service, cf, OBJECT_MAPPER);
    adapter.onMessage(textMessage);/*w  w  w.  j  ava  2s . co m*/

    TextMessage message = (TextMessage) queueSession.createReceiver(reqlayQ).receive(1000);
    assertNotNull(message);
    assertNull(message.getStringProperty("ERROR"));
    assertNull(message.getText());
}

From source file:RequesterTool.java

protected void requestLoop() throws Exception {

    for (int i = 0; i < messageCount || messageCount == 0; i++) {

        TextMessage message = session.createTextMessage(createMessageText(i));
        message.setJMSReplyTo(replyDest);

        if (verbose) {
            String msg = message.getText();
            if (msg.length() > 50) {
                msg = msg.substring(0, 50) + "...";
            }//from   ww w. j  a  v a  2 s  .c om
            System.out.println("Sending message: " + msg);
        }

        producer.send(message);
        if (transacted) {
            session.commit();
        }

        System.out.println("Waiting for reponse message...");
        Message message2 = consumer.receive();
        if (message2 instanceof TextMessage) {
            System.out.println("Reponse message: " + ((TextMessage) message2).getText());
        } else {
            System.out.println("Reponse message: " + message2);
        }
        if (transacted) {
            session.commit();
        }

        Thread.sleep(sleepTime);

    }
}

From source file:net.blogracy.controller.DistributedHashTable.java

public void lookup(final String id) {
    try {/*from   ww  w . j av  a2 s.c  om*/
        Destination tempDest = session.createTemporaryQueue();
        MessageConsumer responseConsumer = session.createConsumer(tempDest);
        responseConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message response) {
                try {
                    String msgText = ((TextMessage) response).getText();
                    JSONObject keyValue = new JSONObject(msgText);
                    String value = keyValue.getString("value");
                    PublicKey signerKey = JsonWebSignature.getSignerKey(value);
                    JSONObject record = new JSONObject(JsonWebSignature.verify(value, signerKey));
                    JSONObject currentRecord = getRecord(id);
                    if (currentRecord == null
                            || currentRecord.getString("version").compareTo(record.getString("version")) < 0) {
                        putRecord(record);
                        String uri = record.getString("uri");
                        FileSharing.getSingleton().download(uri);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        JSONObject record = new JSONObject();
        record.put("id", id);

        TextMessage message = session.createTextMessage();
        message.setText(record.toString());
        message.setJMSReplyTo(tempDest);
        producer.send(lookupQueue, message);

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