Example usage for javax.jms Session createTemporaryQueue

List of usage examples for javax.jms Session createTemporaryQueue

Introduction

In this page you can find the example usage for javax.jms Session createTemporaryQueue.

Prototype


TemporaryQueue createTemporaryQueue() throws JMSException;

Source Link

Document

Creates a TemporaryQueue object.

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();//  ww w  .  jav  a2 s .c o 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.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]
 *///from w  ww .  java  2s.  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:net.lr.jmsbridge.ConnectionPool.java

public Destination getReplyDestination(ConnectionFactory connectionFactory, UserNameAndPassword auth) {
    Destination replyDest = replyDestMap.get(auth);
    if (replyDest != null) {
        return replyDest;
    }// w ww .j  a  v  a2 s . c om

    JmsTemplate jmsTemplate = new JmsTemplate();
    jmsTemplate.setConnectionFactory(connectionFactory);
    replyDest = (Destination) jmsTemplate.execute(new SessionCallback() {

        @Override
        public Object doInJms(Session session) throws JMSException {
            return session.createTemporaryQueue();
        }

    });
    replyDestMap.put(auth, replyDest);
    return replyDest;
}

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  www.ja v  a  2 s  .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:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {//w w w .  j  ava2 s . com
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

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

From source file:biz.fstechnology.micro.common.jms.SyncSessionCallbackImpl.java

/**
 * @see org.springframework.jms.core.SessionCallback#doInJms(javax.jms.Session)
 *///from w  ww.j  a v a2s  .c  om
@Override
public T doInJms(Session session) throws JMSException {
    Topic destTopic = session.createTopic(topicName);
    TemporaryQueue responseQueue = session.createTemporaryQueue();

    // oh my god...
    // why MessageProducer & MessageConsumer not have AutoCloseable!!!
    try (AutoCloseableWrapper<MessageProducer> producerCont = new AutoCloseableWrapper<>(
            () -> createProducer(session, destTopic), JmsUtils::closeMessageProducer);
            AutoCloseableWrapper<MessageConsumer> consumerCont = new AutoCloseableWrapper<>(
                    () -> createConsumer(session, responseQueue), JmsUtils::closeMessageConsumer)) {

        MessageProducer producer = producerCont.unwrap();
        MessageConsumer consumer = consumerCont.unwrap();
        consumer.setMessageListener(this);

        if (getMessageCreator() == null) {
            RequestMessageCreator messageCreator = new RequestMessageCreator();
            messageCreator.setContents(getMessageObj());
            setMessageCreator(messageCreator);
        }
        if (getMessageCreator() instanceof RequestMessageCreator) {
            ((RequestMessageCreator) getMessageCreator()).setReplyTo(responseQueue);
        }
        Message requestMessage = getMessageCreator().createMessage(session);
        producer.send(destTopic, requestMessage);

        if (getMessageCreator() instanceof RequestMessageCreator) {
            return waitResponse(consumer, requestMessage);
        } else {
            return null;
        }
    }
}

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()}
 */// w w w . ja  v a  2  s .  c  o  m
@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:nl.nn.adapterframework.extensions.tibco.SendTibcoMessage.java

public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException {
    Connection connection = null;
    Session jSession = null;
    MessageProducer msgProducer = null;/*from  w w w .  j a v a2s  .c  o  m*/
    Destination destination = null;

    String url_work;
    String authAlias_work;
    String userName_work;
    String password_work;
    String queueName_work;
    String messageProtocol_work;
    int replyTimeout_work;
    String soapAction_work;

    String result = null;

    ParameterValueList pvl = null;
    if (getParameterList() != null) {
        ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session);
        try {
            pvl = prc.getValues(getParameterList());
        } catch (ParameterException e) {
            throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e);
        }
    }

    url_work = getParameterValue(pvl, "url");
    if (url_work == null) {
        url_work = getUrl();
    }
    authAlias_work = getParameterValue(pvl, "authAlias");
    if (authAlias_work == null) {
        authAlias_work = getAuthAlias();
    }
    userName_work = getParameterValue(pvl, "userName");
    if (userName_work == null) {
        userName_work = getUserName();
    }
    password_work = getParameterValue(pvl, "password");
    if (password_work == null) {
        password_work = getPassword();
    }
    queueName_work = getParameterValue(pvl, "queueName");
    if (queueName_work == null) {
        queueName_work = getQueueName();
    }
    messageProtocol_work = getParameterValue(pvl, "messageProtocol");
    if (messageProtocol_work == null) {
        messageProtocol_work = getMessageProtocol();
    }
    String replyTimeout_work_str = getParameterValue(pvl, "replyTimeout");
    if (replyTimeout_work_str == null) {
        replyTimeout_work = getReplyTimeout();
    } else {
        replyTimeout_work = Integer.parseInt(replyTimeout_work_str);
    }
    soapAction_work = getParameterValue(pvl, "soapAction");
    if (soapAction_work == null)
        soapAction_work = getSoapAction();

    if (StringUtils.isEmpty(soapAction_work) && !StringUtils.isEmpty(queueName_work)) {
        String[] q = queueName_work.split("\\.");
        if (q.length > 0) {
            if (q[0].equalsIgnoreCase("P2P") && q.length >= 4) {
                soapAction_work = q[3];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length == 8) {
                soapAction_work = q[5] + "_" + q[6];
            } else if (q[0].equalsIgnoreCase("ESB") && q.length > 8) {
                soapAction_work = q[6] + "_" + q[7];
            }
        }
    }

    if (StringUtils.isEmpty(soapAction_work)) {
        log.debug(getLogPrefix(session) + "deriving default soapAction");
        try {
            URL resource = ClassUtils.getResourceURL(this, "/xml/xsl/esb/soapAction.xsl");
            TransformerPool tp = new TransformerPool(resource, true);
            soapAction_work = tp.transform(input.toString(), null);
        } catch (Exception e) {
            log.error(getLogPrefix(session) + "failed to execute soapAction.xsl");
        }
    }

    if (messageProtocol_work == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "messageProtocol must be set");
    }
    if (!messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)
            && !messageProtocol_work.equalsIgnoreCase(FIRE_AND_FORGET)) {
        throw new PipeRunException(this, getLogPrefix(session) + "illegal value for messageProtocol ["
                + messageProtocol_work + "], must be '" + REQUEST_REPLY + "' or '" + FIRE_AND_FORGET + "'");
    }

    CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work);
    try {
        TibjmsAdmin admin;
        try {
            admin = TibcoUtils.getActiveServerAdmin(url_work, cf);
        } catch (TibjmsAdminException e) {
            log.debug(getLogPrefix(session) + "caught exception", e);
            admin = null;
        }
        if (admin != null) {
            QueueInfo queueInfo;
            try {
                queueInfo = admin.getQueue(queueName_work);
            } catch (Exception e) {
                throw new PipeRunException(this, getLogPrefix(session) + " exception on getting queue info", e);
            }
            if (queueInfo == null) {
                throw new PipeRunException(this,
                        getLogPrefix(session) + " queue [" + queueName_work + "] does not exist");
            }

            try {
                admin.close();
            } catch (TibjmsAdminException e) {
                log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e);
            }
        }

        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work);
        connection = factory.createConnection(cf.getUsername(), cf.getPassword());
        jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        destination = jSession.createQueue(queueName_work);

        msgProducer = jSession.createProducer(destination);
        TextMessage msg = jSession.createTextMessage();
        msg.setText(input.toString());
        Destination replyQueue = null;
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            replyQueue = jSession.createTemporaryQueue();
            msg.setJMSReplyTo(replyQueue);
            msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            msgProducer.setTimeToLive(replyTimeout_work);
        } else {
            msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
            msgProducer.setDeliveryMode(DeliveryMode.PERSISTENT);
        }
        if (StringUtils.isNotEmpty(soapAction_work)) {
            log.debug(
                    getLogPrefix(session) + "setting [SoapAction] property to value [" + soapAction_work + "]");
            msg.setStringProperty("SoapAction", soapAction_work);
        }
        msgProducer.send(msg);
        if (log.isDebugEnabled()) {
            log.debug(getLogPrefix(session) + "sent message [" + msg.getText() + "] " + "to ["
                    + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] "
                    + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo()
                    + "]");
        } else {
            if (log.isInfoEnabled()) {
                log.info(getLogPrefix(session) + "sent message to [" + msgProducer.getDestination() + "] "
                        + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                        + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]");
            }
        }
        if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) {
            String replyCorrelationId = msg.getJMSMessageID();
            MessageConsumer msgConsumer = jSession.createConsumer(replyQueue,
                    "JMSCorrelationID='" + replyCorrelationId + "'");
            log.debug(getLogPrefix(session) + "] start waiting for reply on [" + replyQueue + "] selector ["
                    + replyCorrelationId + "] for [" + replyTimeout_work + "] ms");
            try {
                connection.start();
                Message rawReplyMsg = msgConsumer.receive(replyTimeout_work);
                if (rawReplyMsg == null) {
                    throw new PipeRunException(this,
                            getLogPrefix(session) + "did not receive reply on [" + replyQueue
                                    + "] replyCorrelationId [" + replyCorrelationId + "] within ["
                                    + replyTimeout_work + "] ms");
                }
                TextMessage replyMsg = (TextMessage) rawReplyMsg;
                result = replyMsg.getText();
            } finally {
            }

        } else {
            result = msg.getJMSMessageID();
        }
    } catch (JMSException e) {
        throw new PipeRunException(this, getLogPrefix(session) + " exception on sending message to Tibco queue",
                e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix(session) + "exception on closing connection", e);
            }
        }
    }
    return result;
}

From source file:nl.nn.adapterframework.jms.MessagingSource.java

public Queue getDynamicReplyQueue(Session session) throws JMSException {
    Queue result;//from   w ww  .j  a  v  a2s . c om
    if (useSingleDynamicReplyQueue()) {
        synchronized (this) {
            if (globalDynamicReplyQueue == null) {
                globalDynamicReplyQueue = session.createTemporaryQueue();
                log.info(getLogPrefix() + "created dynamic replyQueue ["
                        + globalDynamicReplyQueue.getQueueName() + "]");
            }
        }
        result = globalDynamicReplyQueue;
    } else {
        result = session.createTemporaryQueue();
    }
    return result;
}

From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java

/**
 * TEST TEMPORARY QUEUES//from   w  w w  .j  a  v a 2 s .com
 */
public void testTempQueue(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;

    Destination cons_dest;

    num_msg = 5;

    LOG.info("TESTING TEMP QUEUES " + prod_broker_url + " -> " + cons_broker_url + " (" + num_msg
            + " messages)");

    //
    // Connect to the bus.
    //
    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    LOG.trace("Creating destination");
    cons_dest = sess.createTemporaryQueue();

    testOneDest(conn, sess, cons_dest, num_msg);

    //
    // Cleanup
    //
    sess.close();
    conn.close();
}