Example usage for javax.jms Session createQueue

List of usage examples for javax.jms Session createQueue

Introduction

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

Prototype

Queue createQueue(String queueName) throws JMSException;

Source Link

Document

Creates a Queue object which encapsulates a specified provider-specific queue name.

Usage

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;/*ww w .  java  2 s .c o  m*/
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

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

/**
 * Test one destination between the given "producer broker" and "consumer broker" specified.
 *//*from w ww  . ja v a  2  s.co  m*/
public void testOneDest(Connection conn, Session sess, Destination cons_dest, int num_msg) throws Exception {
    Destination prod_dest;
    MessageProducer msg_prod;

    //
    // Create the Producer to the echo request Queue
    //
    LOG.trace("Creating echo queue and producer");
    prod_dest = sess.createQueue("echo");
    msg_prod = sess.createProducer(prod_dest);

    //
    // Pass messages around.
    //
    testMessages(sess, msg_prod, cons_dest, num_msg);

    msg_prod.close();
}

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

/**
 * TEST QUEUES/*from www  .  jav a2 s  . c  om*/
 */
public void testQueue(String prod_broker_url, String cons_broker_url) throws Exception {
    int num_msg;

    Connection conn;
    Session sess;
    String queue_name;

    Destination cons_dest;

    num_msg = 5;

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

    conn = createConnection(cons_broker_url);
    conn.start();
    sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    //
    // Create the destination on which messages are being tested.
    //
    queue_name = "topotest2.perm.queue";
    LOG.trace("Removing existing Queue");
    removeQueue(conn, queue_name);
    LOG.trace("Creating Queue, " + queue_name);
    cons_dest = sess.createQueue(queue_name);

    testOneDest(conn, sess, cons_dest, num_msg);

    removeQueue(conn, queue_name);
    sess.close();
    conn.close();
}

From source file:org.apache.axis2.transport.jms.ServiceTaskManager.java

/**
 * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
 * @param session which is used to create the destinations if not present and if possible 
 * @return the JMS Destination to which this STM listens for messages
 *//*from   w w w . j  av  a 2s. co m*/
private Destination getDestination(Session session) {
    if (destination == null) {
        try {
            context = getInitialContext();
            destination = JMSUtils.lookupDestination(context, getDestinationJNDIName(),
                    JMSUtils.getDestinationTypeAsString(destinationType));
            if (log.isDebugEnabled()) {
                log.debug("JMS Destination with JNDI name : " + getDestinationJNDIName() + " found for service "
                        + serviceName);
            }
        } catch (NamingException e) {
            try {
                switch (destinationType) {
                case JMSConstants.QUEUE: {
                    destination = session.createQueue(getDestinationJNDIName());
                    break;
                }
                case JMSConstants.TOPIC: {
                    destination = session.createTopic(getDestinationJNDIName());
                    break;
                }
                default: {
                    handleException("Error looking up JMS destination : " + getDestinationJNDIName()
                            + " using JNDI properties : " + jmsProperties, e);
                }
                }
            } catch (JMSException j) {
                handleException("Error looking up JMS destination and auto " + "creating JMS destination : "
                        + getDestinationJNDIName() + " using JNDI properties : " + jmsProperties, e);
            }
        }
    }
    return destination;
}

From source file:org.apache.camel.component.jms.JmsProducer.java

protected boolean processInOnly(final Exchange exchange, final AsyncCallback callback) {
    final org.apache.camel.Message in = exchange.getIn();

    String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class);
    if (destinationName != null) {
        // remove the header so it wont be propagated
        in.removeHeader(JmsConstants.JMS_DESTINATION_NAME);
    }/*w  ww  .j  av  a2  s. c o m*/
    if (destinationName == null) {
        destinationName = endpoint.getDestinationName();
    }

    Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class);
    if (destination != null) {
        // remove the header so it wont be propagated
        in.removeHeader(JmsConstants.JMS_DESTINATION);
    }
    if (destination == null) {
        destination = endpoint.getDestination();
    }
    if (destination != null) {
        // prefer to use destination over destination name
        destinationName = null;
    }
    final String to = destinationName != null ? destinationName : "" + destination;

    MessageCreator messageCreator = new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null);

            // when in InOnly mode the JMSReplyTo is a bit complicated
            // we only want to set the JMSReplyTo on the answer if
            // there is a JMSReplyTo from the header/endpoint and
            // we have been told to preserveMessageQos

            Object jmsReplyTo = answer.getJMSReplyTo();
            if (endpoint.isDisableReplyTo()) {
                // honor disable reply to configuration
                if (LOG.isDebugEnabled()) {
                    LOG.debug("ReplyTo is disabled on endpoint: " + endpoint);
                }
                answer.setJMSReplyTo(null);
            } else {
                // if the binding did not create the reply to then we have to try to create it here
                if (jmsReplyTo == null) {
                    // prefer reply to from header over endpoint configured
                    jmsReplyTo = exchange.getIn().getHeader("JMSReplyTo", String.class);
                    if (jmsReplyTo == null) {
                        jmsReplyTo = endpoint.getReplyTo();
                    }
                }
            }

            // we must honor these special flags to preserve QoS
            // as we are not OUT capable and thus do not expect a reply, and therefore
            // the consumer of this message should not return a reply so we remove it
            // unless we use preserveMessageQos=true to tell that we still want to use JMSReplyTo
            if (jmsReplyTo != null && !(endpoint.isPreserveMessageQos() || endpoint.isExplicitQosEnabled())) {
                // log at debug what we are doing, as higher level may cause noise in production logs
                // this behavior is also documented at the camel website
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Disabling JMSReplyTo: " + jmsReplyTo + " for destination: " + to
                            + ". Use preserveMessageQos=true to force Camel to keep the JMSReplyTo on endpoint: "
                            + endpoint);
                }
                jmsReplyTo = null;
            }

            // the reply to is a String, so we need to look up its Destination instance
            // and if needed create the destination using the session if needed to
            if (jmsReplyTo != null && jmsReplyTo instanceof String) {
                // must normalize the destination name
                String replyTo = normalizeDestinationName((String) jmsReplyTo);
                // we need to null it as we use the String to resolve it as a Destination instance
                jmsReplyTo = null;

                // try using destination resolver to lookup the destination
                if (endpoint.getDestinationResolver() != null) {
                    jmsReplyTo = endpoint.getDestinationResolver().resolveDestinationName(session, replyTo,
                            endpoint.isPubSubDomain());
                }
                if (jmsReplyTo == null) {
                    // okay then fallback and create the queue
                    if (endpoint.isPubSubDomain()) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Creating JMSReplyTo topic: " + replyTo);
                        }
                        jmsReplyTo = session.createTopic(replyTo);
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Creating JMSReplyTo queue: " + replyTo);
                        }
                        jmsReplyTo = session.createQueue(replyTo);
                    }
                }
            }

            // set the JMSReplyTo on the answer if we are to use it
            Destination replyTo = null;
            if (jmsReplyTo instanceof Destination) {
                replyTo = (Destination) jmsReplyTo;
            }
            if (replyTo != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using JMSReplyTo destination: " + replyTo);
                }
                answer.setJMSReplyTo(replyTo);
            } else {
                // do not use JMSReplyTo
                answer.setJMSReplyTo(null);
            }

            return answer;
        }
    };

    doSend(false, destinationName, destination, messageCreator, null);

    // after sending then set the OUT message id to the JMSMessageID so its identical
    setMessageId(exchange);

    // we are synchronous so return true
    callback.done(true);
    return true;
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from w  w  w.jav a  2  s. c  o m

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * <p>//from   w  ww.  j a  v a 2s  .  co m
 * Dequeues a mail when it is ready to process. As JMS does not support delay scheduling out-of-the box,
 * we use a messageselector to check if a mail is ready. For this a
 * {@link MessageConsumer#receive(long)} is used with a timeout of 10
 * seconds.
 * </p>
 * <p>
 * Many JMS implementations support better solutions for this, so this
 * should get overridden by these implementations
 * </p>
 */
@Override
public MailQueueItem deQueue() throws MailQueueException {
    Session session = null;
    MessageConsumer consumer = null;

    while (true) {
        TimeMetric timeMetric = metricFactory.timer(DEQUEUED_TIMER_METRIC_NAME_PREFIX + queueName);
        try {
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue queue = session.createQueue(queueName);
            consumer = session.createConsumer(queue, getMessageSelector());

            Message message = consumer.receive(10000);

            if (message != null) {
                dequeuedMailsMetric.increment();
                return createMailQueueItem(session, consumer, message);
            } else {
                session.commit();
                closeConsumer(consumer);
                closeSession(session);
            }

        } catch (Exception e) {
            rollback(session);
            closeConsumer(consumer);
            closeSession(session);
            throw new MailQueueException("Unable to dequeue next message", e);
        } finally {
            timeMetric.stopAndPublish();
        }
    }
}

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

public void createProducer(final CreateProducerCommand command) {
    try {//from  www .  java 2  s .com
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            final Destination destination;
            if (command.isTopic()) {
                destination = session.createTopic(command.getDestinationName());
            } else {
                destination = session.createQueue(command.getDestinationName());
            }

            final MessageProducer jmsProducer = session.createProducer(destination);

            if (command.getPriority() != -1) {
                jmsProducer.setPriority(command.getPriority());
            }
            if (command.getTimeToLive() > 0) {
                jmsProducer.setTimeToLive(command.getTimeToLive());
            }

            if (command.getDeliveryMode() == DeliveryMode.NON_PERSISTENT
                    || command.getDeliveryMode() == DeliveryMode.PERSISTENT) {
                jmsProducer.setDeliveryMode(command.getDeliveryMode());
            }

            addProducer(command.getParticipantName(), jmsProducer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new producer: " + command, jmse);
    }
}

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

public void createConsumer(final CreateConsumerCommand command) {
    try {/*from w w  w. j  a v a 2  s.  c  o  m*/
        final Session session = _testSessions.get(command.getSessionName());
        if (session == null) {
            throw new DistributedTestException("No test session found called: " + command.getSessionName(),
                    command);
        }

        synchronized (session) {
            Destination destination;
            MessageConsumer jmsConsumer;
            if (command.isTopic()) {
                Topic topic = session.createTopic(command.getDestinationName());
                if (command.isDurableSubscription()) {
                    String subscription = "subscription-" + command.getParticipantName()
                            + System.currentTimeMillis();
                    jmsConsumer = session.createDurableSubscriber(topic, subscription);

                    _testSubscriptions.put(subscription, session);
                    LOGGER.debug("created durable suscription " + subscription + " to topic " + topic);
                } else {
                    jmsConsumer = session.createConsumer(topic, command.getSelector());
                }

                destination = topic;
            } else {
                destination = session.createQueue(command.getDestinationName());
                jmsConsumer = session.createConsumer(destination, command.getSelector());
            }

            _testConsumers.put(command.getParticipantName(), jmsConsumer);
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to create new consumer: " + command, jmse);
    }
}

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

public void testTransactedSessionWithUnackMessages() throws Exception {
    _connection = getConnection();/*from  ww w.  ja va2 s  . co m*/
    _connection.start();

    boolean transactional = true;
    int numberOfMessages = 2;
    final Session session = _connection.createSession(transactional, Session.SESSION_TRANSACTED);
    final Destination destination = session.createQueue(getTestQueueName());
    final MessageConsumer consumer = session.createConsumer(destination);

    sendMessage(session, destination, numberOfMessages);
    receiveMessagesWithoutCommit(consumer, numberOfMessages);

    final ManagedConnection mBean = getConnectionMBean();
    final CompositeDataSupport row = getTheOneChannelRow(mBean);
    boolean flowBlocked = false;
    assertChannelRowData(row, numberOfMessages, transactional, flowBlocked);

    // check that commit advances the lastIoTime
    final Date initialLastIOTime = mBean.getLastIoTime();
    session.commit();
    assertTrue("commit should have caused last IO time to advance",
            mBean.getLastIoTime().after(initialLastIOTime));

    // check that channels() now returns one session with no unacknowledged messages
    final CompositeDataSupport rowAfterCommit = getTheOneChannelRow(mBean);
    final Number unackCountAfterCommit = (Number) rowAfterCommit.get(ManagedConnection.UNACKED_COUNT);
    assertEquals("Unexpected number of unacknowledged messages", 0, unackCountAfterCommit);
}