Example usage for javax.jms Connection createSession

List of usage examples for javax.jms Connection createSession

Introduction

In this page you can find the example usage for javax.jms Connection createSession.

Prototype


Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a Session object, specifying transacted and acknowledgeMode .

Usage

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void tryConsumeExpectNone(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();// w  w  w  .j a va  2  s .co m
    if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) {
        fail("Should be no messages for this durable.");
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void consumeDurableMessages(Topic topic, int count) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();//from www. j  a  v a  2 s . co  m
    for (int i = 0; i < count; ++i) {
        if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) {
            fail("should have received a message");
        }
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

public void testCreateSSLConnectionUsingSystemProperties() throws Exception {
    if (shouldPerformTest()) {
        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s?ssl='true''";

        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }/*from ww  w. j  a  v a  2 s  .co m*/
}

From source file:org.chtijbug.drools.platform.runtime.servlet.historylistener.ServletJmsStorageHistoryListener.java

public void initJmsConnection() throws DroolsChtijbugException {

    int numberRetries = new Integer(this.numberRetriesString);
    int timeToWaitBetweenTwoRetries = new Integer(this.timeToWaitBetweenTwoRetriesString);
    String url = "tcp://" + this.platformServer + ":" + this.platformPort;
    ConnectionFactory factory = new ActiveMQConnectionFactory(url);
    Connection connection = null;
    JMSConnectionListener jmsConnectionListener = new JMSConnectionListener() {
        @Override/* w ww . ja  v a2s  .  co m*/
        public void connected(Connection connection) throws JMSException, InterruptedException {
            try {
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue queue = session.createQueue(platformQueueName);
                producer = session.createProducer(queue);
                jmsConnectedSemaphore.acquire();
                for (HistoryEvent cachedhistoryEvent : cachedHistoryEvents) {
                    ObjectMessage cachedmsg = session.createObjectMessage(cachedhistoryEvent);
                    producer.send(cachedmsg);
                }
                cachedHistoryEvents.clear();
                jmsConnected = true;
                jmsConnectedSemaphore.release();
            } catch (JMSException e) {
                LOG.error("ServletJmsStorageHistoryListener.initJmsConnection.JMSException", e);
                throw e;
            } catch (InterruptedException e) {
                LOG.error("ServletJmsStorageHistoryListener.initJmsConnection.InterruptedException", e);
                throw e;
            }

        }
    };
    CreateJMSConnectionThread createJMSConnectionThread = new CreateJMSConnectionThread(jmsConnectionListener,
            numberRetries, factory, timeToWaitBetweenTwoRetries);
    createJMSConnectionThread.start();
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

/**
 * Create an SSL connection using the SSL system properties for the trust and key store, but using
 * the {@link ConnectionURL} ssl='true' option to indicate use of SSL at a Connection level,
 * without specifying anything at the {@link ConnectionURL#OPTIONS_BROKERLIST} level.
 *///from www .  ja v  a  2 s  . co  m
public void testSslConnectionOption() throws Exception {
    if (shouldPerformTest()) {
        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        //Create URL enabling SSL at the connection rather than brokerlist level
        String url = "amqp://guest:guest@test/?ssl='true'&brokerlist='tcp://localhost:%s'";
        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

/**
 * Create an SSL connection using the SSL system properties for the trust and key store, but using
 * the {@link ConnectionURL} ssl='true' option to indicate use of SSL at a Connection level,
 * overriding the false setting at the {@link ConnectionURL#OPTIONS_BROKERLIST} level.
 *///  ww  w . j  a v  a  2  s.  com
public void testSslConnectionOptionOverridesBrokerlistOption() throws Exception {
    if (shouldPerformTest()) {
        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        //Create URL enabling SSL at the connection, overriding the false at the brokerlist level
        String url = "amqp://guest:guest@test/?ssl='true'&brokerlist='tcp://localhost:%s?ssl='false''";
        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

public void testCreateSSLConnectionUsingConnectionURLParamsTrustStoreOnly() throws Exception {
    if (shouldPerformTest()) {
        clearSslStoreSystemProperties();

        //Start the broker (WANTing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, false, true);
        super.setUp();

        String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s"
                + "?ssl='true'&ssl_verify_hostname='true'" + "&trust_store='%s'&trust_store_password='%s'"
                + "'";

        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT, TRUSTSTORE, TRUSTSTORE_PASSWORD);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }//from w ww.  j  a v a 2 s  . co m
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

public void testCreateSSLConnectionUsingConnectionURLParams() throws Exception {
    if (shouldPerformTest()) {
        clearSslStoreSystemProperties();

        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        String url = "amqp://guest:guest@test/?brokerlist='tcp://localhost:%s"
                + "?ssl='true'&ssl_verify_hostname='true'" + "&key_store='%s'&key_store_password='%s'"
                + "&trust_store='%s'&trust_store_password='%s'" + "'";

        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT, KEYSTORE, KEYSTORE_PASSWORD, TRUSTSTORE,
                TRUSTSTORE_PASSWORD);//from   w w w .  j a  va 2  s .c  o m

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }
}

From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * WARNING - starts infinite loop - you have to kill 
 * @param uri//from   ww  w .  jav  a2  s  .c o m
 * @param submitQName
 * @param statusTName
 * @param statusQName
 * @throws Exception
 */
private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName)
        throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(submitQName);

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    System.out.println("Starting consumer for submissions to queue " + submitQName);
    while (isActive()) { // You have to kill it or call stop() to stop it!

        try {

            // Consumes messages from the queue.
            Message m = consumer.receive(1000);
            if (m != null) {

                // TODO FIXME Check if we have the max number of processes
                // exceeded and wait until we dont...

                TextMessage t = (TextMessage) m;
                ObjectMapper mapper = new ObjectMapper();

                final StatusBean bean = mapper.readValue(t.getText(), getBeanClass());

                if (bean != null) { // We add this to the status list so that it can be rendered in the UI

                    if (!isHandled(bean))
                        continue; // Consume it and move on

                    // Now we put the bean in the status queue and we 
                    // start the process
                    RemoteSubmission factory = new RemoteSubmission(uri);
                    factory.setLifeTime(t.getJMSExpiration());
                    factory.setPriority(t.getJMSPriority());
                    factory.setTimestamp(t.getJMSTimestamp());
                    factory.setQueueName(statusQName); // Move the message over to a status queue.

                    factory.submit(bean, false);

                    final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean);
                    if (process != null) {
                        if (process.isBlocking()) {
                            System.out.println("About to run job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                        processCount++;
                        process.start();
                        if (process.isBlocking()) {
                            System.out.println(
                                    "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")");
                        } else {
                            System.out.println("Started job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                    }

                }
            }

        } catch (Throwable ne) {
            // Really basic error reporting, they have to pipe to file.
            ne.printStackTrace();
            setActive(false);
        }
    }

}

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

public void x_testSendWithInactiveAndActiveConsumers() throws Exception {
    Destination destination = createDestination();
    ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final int toSend = 100;
    final int numIterations = 5;

    double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    startConsumers(factory, destination);
    LOG.info("Activated consumer");

    double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1]
            + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]));
    final int reasonableMultiplier = 15; // not so reasonable but improving
    assertTrue(/* w  ww  . j a  v a  2  s  .  c o m*/
            "max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: "
                    + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]),
            withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier);

    final int toReceive = toSend * numIterations * consumerCount * 2;
    Wait.waitFor(new Wait.Condition() {
        public boolean isSatisified() throws Exception {
            LOG.info("count: " + allMessagesList.getMessageCount());
            return toReceive == allMessagesList.getMessageCount();
        }
    }, 60 * 1000);

    assertEquals("got all messages", toReceive, allMessagesList.getMessageCount());
}