Example usage for javax.jms Connection close

List of usage examples for javax.jms Connection close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the connection.

Usage

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testMessageSizeOneDurable() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from w  ww  .  j  av a2s  .  c o  m

    publishTestMessagesDurable(connection, new String[] { "sub1" }, 200, publishedMessageSize,
            DeliveryMode.PERSISTENT, false);

    // verify the count and size - durable is offline so all 200 should be
    // pending since none are in prefetch
    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume all messages
    consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.cli.test.ArtemisTest.java

public void testSimpleRun(String folderName) throws Exception {
    File instanceFolder = temporaryFolder.newFolder(folderName);

    setupAuth(instanceFolder);//from w  ww . j  a v a2 s .c  o m
    String queues = "q1,q2";
    String addresses = "a1,a2";

    // This is usually set when run from the command line via artemis.profile
    Run.setEmbedded(true);
    Artemis.main("create", instanceFolder.getAbsolutePath(), "--force", "--silent", "--no-web", "--queues",
            queues, "--addresses", addresses, "--no-autotune", "--require-login");
    System.setProperty("artemis.instance", instanceFolder.getAbsolutePath());

    // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol
    Artemis.internalExecute("run");

    try {
        try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616");
                ClientSessionFactory factory = locator.createSessionFactory();
                ClientSession coreSession = factory.createSession("admin", "admin", false, true, true, false,
                        0)) {
            for (String str : queues.split(",")) {
                ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find queue " + str, queryResult.isExists());
            }
            for (String str : addresses.split(",")) {
                ClientSession.AddressQuery queryResult = coreSession
                        .addressQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find address " + str, queryResult.isExists());
            }
        }

        try {
            Artemis.internalExecute("data", "print");
            Assert.fail("Exception expected");
        } catch (CLIException expected) {
        }
        Artemis.internalExecute("data", "print", "--f");

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("producer", "--message-count", "100",
                "--verbose", "--user", "admin", "--password", "admin"));
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--verbose", "--break-on-null",
                "--receive-timeout", "100", "--user", "admin", "--password", "admin"));

        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = cf.createConnection("admin", "admin");
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(
                ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE));

        TextMessage message = session.createTextMessage("Banana");
        message.setStringProperty("fruit", "banana");
        producer.send(message);

        for (int i = 0; i < 100; i++) {
            message = session.createTextMessage("orange");
            message.setStringProperty("fruit", "orange");
            producer.send(message);
        }
        session.commit();

        connection.close();
        cf.close();

        assertEquals(Integer.valueOf(1), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='banana'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='orange'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(101), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--user", "admin", "--password", "admin"));

        // should only receive 10 messages on browse as I'm setting messageCount=10
        assertEquals(Integer.valueOf(10), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--message-count", "10", "--user", "admin", "--password", "admin"));

        // Nothing was consumed until here as it was only browsing, check it's receiving again
        assertEquals(Integer.valueOf(1),
                Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null",
                        "--receive-timeout", "100", "--filter", "fruit='banana'", "--user", "admin",
                        "--password", "admin"));

        // Checking it was acked before
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose",
                "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin"));
    } finally {
        stopServer();
    }
}

From source file:org.wso2.carbon.apimgt.jms.listener.utils.JMSListener.java

private boolean checkJMSConnection(JMSTaskManager stm) {

    Connection connection = null;
    Hashtable<String, String> jmsProperties = stm.getJmsProperties();
    try {/*w  w w.  ja  v a  2s .c o m*/
        ConnectionFactory jmsConFactory = null;
        try {
            jmsConFactory = JMSUtils.lookup(new InitialContext(stm.getJmsProperties()), ConnectionFactory.class,
                    stm.getConnFactoryJNDIName());
        } catch (NamingException e) {
            log.error("Error looking up connection factory : " + stm.getConnFactoryJNDIName()
                    + "using JNDI properties : " + jmsProperties, e);
        }
        connection = JMSUtils.createConnection(jmsConFactory,
                jmsProperties.get(JMSConstants.PARAM_JMS_USERNAME),
                jmsProperties.get(JMSConstants.PARAM_JMS_PASSWORD), stm.isJmsSpec11(), stm.isQueue(),
                stm.isSubscriptionDurable(), stm.getDurableSubscriberClientId());
    } catch (JMSException ignore) {
    } // we silently ignore this as a JMSException can be expected when connection is not available
    finally {
        // Closing the connection, because if left open, when shutting down broker errors will be thrown
        // complaining about active subscriptions.
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                log.warn("Error while closing test connection.", e);
            }
        }
    }

    return (connection != null);
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testMessageSizeOneDurablePartialConsumption() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*from  w ww  . j  ava 2 s  .  c  o  m*/

    publishTestMessagesDurable(connection, new String[] { "sub1" }, 200, publishedMessageSize,
            DeliveryMode.PERSISTENT, false);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume partial messages
    consumeDurableTestMessages(connection, "sub1", 50, publishedMessageSize);

    // 150 should be left
    verifyPendingStats(defaultTopicName, 150, publishedMessageSize.get());
    // We don't really know the size here but it should be smaller than before
    // so take an average
    verifyPendingDurableStats(defaultTopicName, 150, (long) (.75 * publishedMessageSize.get()));

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicMessageSizeShared() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*  w w  w .  j  a  va  2 s .  co  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");
    MessageConsumer consumer2 = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 0, 0);
    consumer2.close();

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();//  www. ja  va  2 s.  co m

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

@SuppressWarnings({ "unchecked", "unused" })
private Object[] browseQueueWithJms(BrokerService broker) throws Exception {
    Object[] messages = null;/*  w w  w . j  av  a2 s  . c  o  m*/
    Connection connection = null;
    Session session = null;

    try {
        URI brokerUri = connector.getUri();
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString());
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(queueName);
        QueueBrowser browser = session.createBrowser(destination);
        List<Message> list = new ArrayList<Message>();
        for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) {
            list.add(enumn.nextElement());
        }
        messages = list.toArray();
    } finally {
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    LOG.info("+Browsed with JMS: " + messages.length);

    return messages;
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {//from  w w w .  jav a  2s.co m
        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:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testMessageSizeTwoDurables() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*  www  . ja  v a2  s  .c  o  m*/

    publishTestMessagesDurable(connection, new String[] { "sub1", "sub2" }, 200, publishedMessageSize,
            DeliveryMode.PERSISTENT, false);

    // verify the count and size - double because two durables so two queue
    // bindings
    verifyPendingStats(defaultTopicName, 400, 2 * publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 400, 2 * publishedMessageSize.get());

    // consume messages just for sub1
    consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize);

    // There is still a durable that hasn't consumed so the messages should
    // exist
    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());

    connection.close();

    // restart and verify load
    this.killServer();
    this.restartServer();
    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/*  w w w. ja va  2 s  .  c o  m*/
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyDeliveringStats(defaultQueueName, 0, 0);

    MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
    Message msg = consumer.receive();
    verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
    msg.acknowledge();

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyDeliveringStats(defaultQueueName, 0, 0);

    connection.close();
}