List of usage examples for javax.jms Connection createSession
Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:com.fusesource.examples.activemq.VirtualConsumer.java
public static void main(String args[]) { Connection connection = null; try {/*www . java 2 s . 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.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(System.getProperty("queue")); MessageConsumer consumer = session.createConsumer(queue); LOG.info("Start consuming messages from " + queue + " 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:com.fusesource.examples.activemq.SimpleProducer.java
public static void main(String args[]) { Connection connection = null; try {//w w w . ja va2 s. c o m // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); producer.setTimeToLive(MESSAGE_TIME_TO_LIVE_MILLISECONDS); for (int i = 1; i <= NUM_MESSAGES_TO_BE_SENT; i++) { TextMessage message = session.createTextMessage(i + ". message sent"); LOG.info("Sending to destination: " + destination.toString() + " this text: '" + message.getText()); producer.send(message); Thread.sleep(MESSAGE_DELAY_MILLISECONDS); } // Cleanup producer.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:com.fusesource.examples.activemq.SimpleConsumer.java
public static void main(String args[]) { Connection connection = null; try {/*from www . ja v a2 s. c o m*/ // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); LOG.info("Start consuming messages from " + destination.toString() + " 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 w w w.jav a2s .co 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.consumer.SimpleConsumer.java
/** * @param args the queue used by the example *//*from ww w .j a va2 s . co 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//ww w . j av a 2 s . com */ 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:org.jboss.activemq.clients.JMSConsumer.java
public static void main(String args[]) { Connection connection = null; try {//from w w w . j av a 2 s . co 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.apache.uima.examples.as.GetMetaRequest.java
/** * retrieve meta information for a UIMA-AS Service attached to a broker * It uses the port 1099 as the JMX port on the broker, unless overridden * by defining the system property activemq.broker.jmx.port with a value of another port number * It uses the default JMX ActiveMQ Domain "org.apache.activemq", unless overridden * by defining the system property activemq.broker.jmx.domain with a value of the domain to use * This normally never needs to be done unless multiple brokers are run on the same node * as is sometimes done for unit tests. * @param args - brokerUri serviceName [-verbose] *//* w ww .j a va2 s .c o m*/ public static void main(String[] args) { if (args.length < 2) { System.err.println("Need arguments: brokerURI serviceName [-verbose]"); System.exit(1); } String brokerURI = args[0]; String queueName = args[1]; boolean printReply = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("-verbose")) { printReply = true; } else { System.err.println("Unknown argument: " + args[2]); System.exit(1); } } final Connection connection; Session producerSession = null; Queue producerQueue = null; MessageProducer producer; MessageConsumer consumer; Session consumerSession = null; TemporaryQueue consumerDestination = null; long startTime = 0; // Check if JMX server port number was specified jmxPort = System.getProperty("activemq.broker.jmx.port"); if (jmxPort == null || jmxPort.trim().length() == 0) { jmxPort = "1099"; // default } try { // First create connection to a broker ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURI); connection = factory.createConnection(); connection.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { if (connection != null) { connection.close(); } if (jmxc != null) { jmxc.close(); } } catch (Exception ex) { } } })); URI target = new URI(brokerURI); String brokerHost = target.getHost(); attachToRemoteBrokerJMXServer(brokerURI); if (isQueueAvailable(queueName) == QueueState.exists) { System.out.println("Queue " + queueName + " found on " + brokerURI); System.out.println("Sending getMeta..."); } else if (isQueueAvailable(queueName) == QueueState.existsnot) { System.err.println("Queue " + queueName + " does not exist on " + brokerURI); System.exit(1); } else { System.out.println("Cannot see queues on JMX port " + brokerHost + ":" + jmxPort); System.out.println("Sending getMeta anyway..."); } producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producerQueue = producerSession.createQueue(queueName); producer = producerSession.createProducer(producerQueue); consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumerDestination = consumerSession.createTemporaryQueue(); // ----------------------------------------------------------------------------- // Create message consumer. The consumer uses a selector to filter out messages other // then GetMeta replies. Currently UIMA AS service returns two messages for each request: // ServiceInfo message and GetMeta message. The ServiceInfo message is returned by the // service immediately upon receiving a message from a client. This serves dual purpose, // 1) to make sure the client reply destination exists // 2) informs the client which service is processing its request // ----------------------------------------------------------------------------- consumer = consumerSession.createConsumer(consumerDestination, "Command=2001"); TextMessage msg = producerSession.createTextMessage(); msg.setStringProperty(AsynchAEMessage.MessageFrom, consumerDestination.getQueueName()); msg.setStringProperty(UIMAMessage.ServerURI, brokerURI); msg.setIntProperty(AsynchAEMessage.MessageType, AsynchAEMessage.Request); msg.setIntProperty(AsynchAEMessage.Command, AsynchAEMessage.GetMeta); msg.setJMSReplyTo(consumerDestination); msg.setText(""); producer.send(msg); startTime = System.nanoTime(); System.out.println("Sent getMeta request to " + queueName + " at " + brokerURI); System.out.println("Waiting for getMeta reply..."); ActiveMQTextMessage reply = (ActiveMQTextMessage) consumer.receive(); long waitTime = (System.nanoTime() - startTime) / 1000000; System.out.println( "Reply from " + reply.getStringProperty("ServerIP") + " received in " + waitTime + " ms"); if (printReply) { System.out.println("Reply MessageText: " + reply.getText()); } } catch (Exception e) { System.err.println(e.toString()); } System.exit(0); }
From source file:service.emailer.Emailer.java
/** * Send email with parameters to emailQueue * @param area//from w w w. j a v a2 s .c o m * @param email */ public static void sendEmail(String area, List<String> email) { try { //JMS QUEUE SEND final ConnectionFactory connectionFactory = lookup(ConnectionFactory.class, JNDI_CONNECTION_FACTORY); final Queue queue = lookup(Queue.class, JNDI_QUEUE); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); MapMessage message = session.createMapMessage(); message.setString("type", "warnFile"); message.setString("area", area); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(email); message.setString("emailReceivers", json); producer.send(message); } catch (JMSException ex) { Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex); } catch (JsonProcessingException ex) { Logger.getLogger(Emailer.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.logicblaze.lingo.jms.impl.DefaultJmsProducer.java
public static DefaultJmsProducer newInstance(Connection connection, JmsProducerConfig config, boolean ownsConnection) throws JMSException { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); return new DefaultJmsProducer(connection, session, config, ownsConnection); }