List of usage examples for javax.jms Connection close
void close() throws JMSException;
From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java
private void sendMessages(Destination destination, int count) throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); for (int i = 0; i < count; ++i) { TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination); producer.send(message);// www. jav a 2 s. c o m } connection.close(); }
From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java
/** Comsume messages. */ protected void consumeMessages(Connection connection, Session session, MessageConsumer consumer, long timeout) throws JMSException, IOException { Message message;/* w ww . j av a 2 s . com*/ while (!this.receiver.getNoMoreMessagesFlag()) { while ((message = consumer.receive(timeout)) != null) { onMessageOptimistic(message); } } consumer.close(); session.close(); connection.close(); }
From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java
private long getMessageCount() throws SQLException { long messageCount = -1; java.sql.Connection con = dataSource.getConnection(); try {/*ww w . ja va 2 s. c om*/ Statement stmt = con.createStatement(); try { ResultSet rs = stmt.executeQuery("select count(*) from activemq_msgs"); try { while (rs.next()) messageCount = rs.getLong(1); } finally { rs.close(); } } finally { stmt.close(); } } finally { con.close(); } return messageCount; }
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 w w w . j a v a2s . c o 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:ConsumerTool.java
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer, long timeout) throws JMSException, IOException { System.out.println(// ww w . ja v a 2s. c om "[" + this.getName() + "] We will consume messages while they continue to be delivered within: " + timeout + " ms, and then we will shutdown"); Message message; while ((message = consumer.receive(timeout)) != null) { onMessage(message); } System.out.println("[" + this.getName() + "] Closing connection"); consumer.close(); session.close(); connection.close(); if (pauseBeforeShutdown) { System.out.println("[" + this.getName() + "] Press return to shut down"); System.in.read(); } }
From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("queue.QUEUE", "BasicQueue"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up queue Destination queue = (Destination) context.lookup("QUEUE"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side separately with minimal clutter {//from ww w. j a va 2 s. co m // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(queue); // Send messages for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } { // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer MessageConsumer consumer = session.createConsumer(queue); // create a listener callback to receive the messages consumer.setMessageListener(message -> { try { // receives message is passed to callback System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter message.getJMSMessageID()); message.acknowledge(); } catch (Exception e) { logger.error(e); } }); // wait on the main thread until all sent messages have been received while (totalReceived.get() < totalSend) { Thread.sleep(1000); } consumer.close(); session.close(); connection.stop(); connection.close(); } System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:ConsumerTool.java
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer) throws JMSException, IOException { System.out.println("[" + this.getName() + "] We are about to wait until we consume: " + maxiumMessages + " message(s) then we will shutdown"); for (int i = 0; i < maxiumMessages && isRunning();) { Message message = consumer.receive(1000); if (message != null) { i++;/*from w w w . ja v a 2s . co m*/ onMessage(message); } } System.out.println("[" + this.getName() + "] Closing connection"); consumer.close(); session.close(); connection.close(); if (pauseBeforeShutdown) { System.out.println("[" + this.getName() + "] Press return to shut down"); System.in.read(); } }
From source file:org.dhatim.routing.jms.activemq.ActiveMQProvider.java
private final void close(Connection conn, Session session) { try {//from w w w . j a va 2 s. c o m if (conn != null) { conn.stop(); logger.debug("Stopping JMS Connection for connected session."); } } catch (Throwable e) { logger.debug("Failed to stop JMS connection.", e); conn = null; } try { if (session != null) { session.close(); logger.debug("Closing JMS Session."); } } catch (Throwable e) { logger.debug("Failed to close JMS session.", e); } finally { session = null; } try { if (conn != null) { conn.close(); logger.debug("Closing JMS Connection for connected session."); } } catch (Throwable e) { logger.debug("Failed to close JMS connection.", e); } finally { conn = null; } }
From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up the JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("topic.TOPIC", "BasicTopic"); hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1"); hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2"); hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up the topic Destination topic = (Destination) context.lookup("TOPIC"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side seperately with minimal clutter {// w w w . j a v a 2 s.com // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(topic); // Send messaGES for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } // Look up the subscription (pretending it's a queue) receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3"); System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:org.springframework.jms.connection.ConnectionFactoryUtils.java
/** * Obtain a JMS Session that is synchronized with the current transaction, if any. * @param connectionFactory the JMS ConnectionFactory to bind for * (used as TransactionSynchronizationManager key) * @param resourceFactory the ResourceFactory to use for extracting or creating * JMS resources/* w w w.j a va 2s . c o m*/ * @param startConnection whether the underlying JMS Connection approach should be * started in order to allow for receiving messages. Note that a reused Connection * may already have been started before, even if this flag is {@code false}. * @return the transactional Session, or {@code null} if none found * @throws JMSException in case of JMS failure */ @Nullable public static Session doGetTransactionalSession(ConnectionFactory connectionFactory, ResourceFactory resourceFactory, boolean startConnection) throws JMSException { Assert.notNull(connectionFactory, "ConnectionFactory must not be null"); Assert.notNull(resourceFactory, "ResourceFactory must not be null"); JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager .getResource(connectionFactory); if (resourceHolder != null) { Session session = resourceFactory.getSession(resourceHolder); if (session != null) { if (startConnection) { Connection con = resourceFactory.getConnection(resourceHolder); if (con != null) { con.start(); } } return session; } if (resourceHolder.isFrozen()) { return null; } } if (!TransactionSynchronizationManager.isSynchronizationActive()) { return null; } JmsResourceHolder resourceHolderToUse = resourceHolder; if (resourceHolderToUse == null) { resourceHolderToUse = new JmsResourceHolder(connectionFactory); } Connection con = resourceFactory.getConnection(resourceHolderToUse); Session session = null; try { boolean isExistingCon = (con != null); if (!isExistingCon) { con = resourceFactory.createConnection(); resourceHolderToUse.addConnection(con); } session = resourceFactory.createSession(con); resourceHolderToUse.addSession(session, con); if (startConnection) { con.start(); } } catch (JMSException ex) { if (session != null) { try { session.close(); } catch (Throwable ex2) { // ignore } } if (con != null) { try { con.close(); } catch (Throwable ex2) { // ignore } } throw ex; } if (resourceHolderToUse != resourceHolder) { TransactionSynchronizationManager.registerSynchronization(new JmsResourceSynchronization( resourceHolderToUse, connectionFactory, resourceFactory.isSynchedLocalTransactionAllowed())); resourceHolderToUse.setSynchronizedWithTransaction(true); TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolderToUse); } return session; }