List of usage examples for javax.jms Connection close
void close() throws JMSException;
From source file:com.fusesource.examples.activemq.DurableSubscriber.java
public static void main(String args[]) { Connection connection = null; try {/*from w w w . j av a 2s.c o m*/ // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); connection = factory.createConnection(); connection.setClientID(System.getProperty("clientID")); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.CLIENT_ACKNOWLEDGE); String topicName = System.getProperty("topic"); Topic topic = session.createTopic(topicName); MessageConsumer consumer = session.createDurableSubscriber(topic, "Test_Durable_Subscriber"); LOG.info("Start consuming messages from " + topicName + " with " + MESSAGE_TIMEOUT_MILLISECONDS + "ms timeout"); // Synchronous message consumer int i = 1; while (true) { Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); LOG.info("Got " + (i++) + ". message: " + text); } } else { break; } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error(t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
From source file:org.apache.activemq.demo.SimpleConsumer.java
/** * @param args the queue used by the example *///from ww w . j a v a 2 s .com public static void main(String[] args) { String destinationName = null; Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageConsumer consumer = null; /* * Read destination name from command line and display it. */ if (args.length != 1) { LOG.info("Usage: java SimpleConsumer <destination-name>"); System.exit(1); } destinationName = args[0]; LOG.info("Destination name is " + destinationName); /* * Create a JNDI API InitialContext object */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API " + "context: " + e.toString()); System.exit(1); } /* * Look up connection factory and destination. */ try { connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); destination = (Destination) jndiContext.lookup(destinationName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e.toString()); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create receiver, then start message * delivery. Receive all text messages from destination until a non-text * message is received indicating end of message stream. Close * connection. */ try { connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(destination); connection.start(); while (true) { Message m = consumer.receive(1); if (m != null) { if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; LOG.info("Reading message: " + message.getText()); } else { break; } } } } catch (JMSException e) { LOG.info("Exception occurred: " + e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } }
From source file:io.datalayer.activemq.consumer.SimpleConsumer.java
/** * @param args the queue used by the example *///from w w w. j a v a2s . c o m public static void main(String... args) { String destinationName = null; Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageConsumer consumer = null; /* * Read destination name from command line and display it. */ if (args.length != 1) { LOG.info("Usage: java SimpleConsumer <destination-name>"); System.exit(1); } destinationName = args[0]; LOG.info("Destination name is " + destinationName); /* * Create a JNDI API InitialContext object */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API " + "context: " + e.toString()); System.exit(1); } /* * Look up connection factory and destination. */ try { connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); destination = (Destination) jndiContext.lookup(destinationName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e.toString()); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create receiver, then start message * delivery. Receive all text messages from destination until a non-text * message is received indicating end of message stream. Close * connection. */ try { connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(destination); connection.start(); while (true) { Message m = consumer.receive(1); if (m != null) { if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; LOG.info("Reading message: " + message.getText()); } else { break; } } } } catch (JMSException e) { LOG.info("Exception occurred: " + e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } }
From source file:io.datalayer.activemq.producer.SimpleProducer.java
/** * @param args the destination name to send to and optionally, the number of * messages to send/* w w w .ja v a 2 s. c o m*/ */ public static void main(String... args) { Context jndiContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; Destination destination = null; MessageProducer producer = null; String destinationName = null; final int numMsgs; if ((args.length < 1) || (args.length > 2)) { LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]"); System.exit(1); } destinationName = args[0]; LOG.info("Destination name is " + destinationName); if (args.length == 2) { numMsgs = (new Integer(args[1])).intValue(); } else { numMsgs = 1; } /* * Create a JNDI API InitialContext object */ try { jndiContext = new InitialContext(); } catch (NamingException e) { LOG.info("Could not create JNDI API context: " + e.toString()); System.exit(1); } /* * Look up connection factory and destination. */ try { connectionFactory = (ConnectionFactory) jndiContext.lookup("ConnectionFactory"); destination = (Destination) jndiContext.lookup(destinationName); } catch (NamingException e) { LOG.info("JNDI API lookup failed: " + e); System.exit(1); } /* * Create connection. Create session from connection; false means * session is not transacted. Create sender and text message. Send * messages, varying text slightly. Send end-of-messages message. * Finally, close connection. */ try { connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); TextMessage message = session.createTextMessage(); for (int i = 0; i < numMsgs; i++) { message.setText("This is message " + (i + 1)); LOG.info("Sending message: " + message.getText()); producer.send(message); } /* * Send a non-text control message indicating end of messages. */ producer.send(session.createMessage()); } catch (JMSException e) { LOG.info("Exception occurred: " + e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { } } } }
From source file:example.wildcard.Client.java
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim();/*from w w w. j a v a 2 s . com*/ } ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url); Connection connection = null; try { Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName")); connection = connectionFactory.createConnection("admin", "password"); Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer sender = senderSession.createProducer(senderTopic); Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); String policyType = System.getProperty("wildcard", ".*"); String receiverTopicName = senderTopic.getTopicName() + policyType; Topic receiverTopic = receiverSession.createTopic(receiverTopicName); MessageConsumer receiver = receiverSession.createConsumer(receiverTopic); receiver.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("We received a new message: " + text); } } catch (JMSException e) { System.out.println("Could not read the receiver's topic because of a JMSException"); } } }); connection.start(); System.out.println("Listening on '" + receiverTopicName + "'"); System.out.println("Enter a message to send: "); Scanner inputReader = new Scanner(System.in); while (true) { String line = inputReader.nextLine(); if (line == null) { System.out.println("Done!"); break; } else if (line.length() > 0) { try { TextMessage message = senderSession.createTextMessage(); message.setText(line); System.out.println("Sending a message: " + message.getText()); sender.send(message); } catch (JMSException e) { System.out.println("Exception during publishing a message: "); } } } receiver.close(); receiverSession.close(); sender.close(); senderSession.close(); } catch (Exception e) { System.out.println("Caught exception!"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { System.out.println("When trying to close connection: "); } } } }
From source file:example.composite.dest.Consumer.java
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim();//from w w w . ja v a 2 s .c o m } System.out.println("\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s"); 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"); Destination destinationFoo = session.createQueue("test-queue-foo"); Destination destinationBar = session.createQueue("test-queue-bar"); Destination destinationTopicFoo = session.createTopic("test-topic-foo"); MessageConsumer consumer = session.createConsumer(destination); MessageConsumer consumerFoo = session.createConsumer(destinationFoo); MessageConsumer consumerBar = session.createConsumer(destinationBar); MessageConsumer consumerTopicFoo = session.createConsumer(destinationTopicFoo); int i = 0; while (true) { Message message = consumer.receive(TIMEOUT); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("Got " + i++ + ". message on test-queue: " + text); } } else { break; } message = consumerFoo.receive(TIMEOUT); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("Got " + i++ + ". message on test-queue-foo: " + text); } } else { break; } message = consumerBar.receive(TIMEOUT); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("Got " + i++ + ". message on test-queue-bar: " + text); } } else { break; } message = consumerTopicFoo.receive(TIMEOUT); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("Got " + i++ + ". message on test-topic-bar: " + text); } } else { break; } } consumer.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.jboss.activemq.clients.JMSConsumer.java
public static void main(String args[]) { Connection connection = null; try {//w w w . j av a2 s .c o m Options options = new Options(); options.addOption("h", "help", false, "help:"); options.addOption("url", true, "url for the broker to connect to"); options.addOption("u", "username", true, "User name for connection"); options.addOption("p", "password", true, "password for connection"); options.addOption("d", "destination", true, "destination to send to"); options.addOption("n", "number", true, "number of messages to send"); options.addOption("delay", true, "delay between each send"); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("OptionsTip", options); System.exit(0); } String url = commandLine.hasOption("host") ? commandLine.getOptionValue("host") : URL; String userName = commandLine.hasOption("u") ? commandLine.getOptionValue("u") : "admin"; String password = commandLine.hasOption("p") ? commandLine.getOptionValue("p") : "admin"; String destinationName = commandLine.hasOption("d") ? commandLine.getOptionValue("d") : DESTINATION_NAME; int numberOfMessages = commandLine.hasOption("n") ? Integer.parseInt(commandLine.getOptionValue("n")) : NUM_MESSAGES_TO_RECEIVE; ; ConnectionFactory factory = new ActiveMQConnectionFactory(userName, password, url); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(destinationName); MessageConsumer consumer = session.createConsumer(topic); LOG.info("Start consuming " + numberOfMessages + " messages from " + topic.toString()); for (int i = 0; i < numberOfMessages; i++) { Message message = consumer.receive(); if (message != null) { if (message instanceof BytesMessage) { BytesMessage bytesMessage = (BytesMessage) message; int len = (int) bytesMessage.getBodyLength(); byte[] data = new byte[len]; bytesMessage.readBytes(data); String value = new String(data); LOG.info("Got " + value); } else { LOG.info("Got a message " + message); } } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error("Error receiving message", t); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error("Error closing connection", e); } } } }
From source file:org.dawnsci.commandserver.core.util.JSONUtils.java
public static final void sendTopic(Object message, String topicName, URI uri) throws Exception { Connection connection = null; try {/*w ww .j a v a2s . c o m*/ ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); connection = connectionFactory.createConnection(); connection.start(); sendTopic(connection, message, topicName, uri); } finally { if (connection != null) connection.close(); } }
From source file:org.springframework.jms.support.JmsUtils.java
/** * Close the given JMS Connection and ignore any thrown exception. * This is useful for typical {@code finally} blocks in manual JMS code. * @param con the JMS Connection to close (may be {@code null}) * @param stop whether to call {@code stop()} before closing *//*from w w w . j a v a2s . c o m*/ public static void closeConnection(@Nullable Connection con, boolean stop) { if (con != null) { try { if (stop) { try { con.stop(); } finally { con.close(); } } else { con.close(); } } catch (javax.jms.IllegalStateException ex) { logger.debug("Ignoring Connection state exception - assuming already closed: " + ex); } catch (JMSException ex) { logger.debug("Could not close JMS Connection", ex); } catch (Throwable ex) { // We don't trust the JMS provider: It might throw RuntimeException or Error. logger.debug("Unexpected exception on closing JMS Connection", ex); } } }
From source file:org.nebulaframework.grid.Grid.java
/** * Checks the given Service URL to see if the * Broker is running./*from ww w.j av a 2s .c om*/ * * @param url connection url */ private static void checkJMSBroker(String url) { try { log.debug("Attempting to establish connection with Cluster " + url); ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(url); Connection testConnection = cf.createConnection(); testConnection.start(); testConnection.close(); log.debug("Connection established"); } catch (Exception e) { log.warn("Unable to establish cluster connection"); throw new DiscoveryFailureException("Unable to connect to Cluster", e); } }