List of usage examples for javax.jms ConnectionFactory createConnection
Connection createConnection(String userName, String password) throws JMSException;
From source file:MessageMonitor.java
/** Constructor for MessageMonitor window. */ public MessageMonitor() { loadProperties();/*ww w . j a v a2 s . com*/ setTitle(title); // Connect to Message Broker try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(user, password, url); connection = factory.createConnection(userID, password); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("Cannot connect to Broker"); jmse.printStackTrace(); System.exit(1); } // Subscribe to Topics StringTokenizer topics = new StringTokenizer(subscriptionTopics, ","); while (topics.hasMoreTokens()) { try { String topicName = topics.nextToken(); System.out.println("Subscribing to: " + topicName); new Subscription(session.createTopic(topicName)); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } // Set up the viewing area. textArea.setEditable(false); scrollPane.setBorder( new CompoundBorder(new EmptyBorder(6, 6, 6, 6), new SoftBevelBorder(BevelBorder.LOWERED))); getContentPane().add(scrollPane, BorderLayout.CENTER); getContentPane().add(clearButton, BorderLayout.SOUTH); clearButton.addActionListener(new OnClear()); // Start the connection so that we can now receive messages. try { connection.start(); } catch (javax.jms.JMSException jmse) { System.err.println("Cannot start connection"); jmse.printStackTrace(); System.exit(1); } }
From source file:TopicReplier.java
/** Create JMS client for publishing and subscribing to messages. */ private void start(String broker, String username, String password, String mode) { // Set the operation mode imode = (mode.equals("uppercase")) ? UPPERCASE : LOWERCASE; // Create a connection. try {//w w w . j av a2s .c om javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); session = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Subscriber to application topics as well as a Publisher // to use for JMS replies. try { javax.jms.Topic topic = session.createTopic(APP_TOPIC); javax.jms.MessageConsumer subscriber = session.createConsumer(topic); subscriber.setMessageListener(this); replier = session.createProducer(null); // Topic will be set for each reply // Now that all setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.println("\nReplier application:\n" + "============================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application gets requests with JMSReplyTo set on the " + APP_TOPIC + " topic." + "The message is transformed to all uppercase or all lowercase, and then returned to the requestor." + "The Requestor application displays the result.\n\n" + "Enter EXIT or press Ctrl+C to close the Replier.\n"); String s = stdin.readLine(); if (s == null || s.equalsIgnoreCase("EXIT")) { System.out.println("\nStopping Replier. Please wait..\n>"); exit(); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }
From source file:TransactedChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password) { // Create a connection. try {// w ww. ja v a2 s .co m javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); // We want to be able up commit/rollback messages published, // but not affect messages consumed. Therefore, we need two sessions. publishSession = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); subscribeSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics try { javax.jms.Topic topic = subscribeSession.createTopic(APP_TOPIC); javax.jms.MessageConsumer subscriber = subscribeSession.createConsumer(topic); subscriber.setMessageListener(this); publisher = publishSession.createProducer(topic); // Now start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); boolean showMessage = true; while (true) { if (showMessage) { System.out.println("TransactedChat application:"); System.out.println("==========================="); System.out.println("The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + "."); System.out.println("The application will stage messages to the " + APP_TOPIC + " topic until you either commit them or roll them back."); System.out.println( "The application also subscribes to that topic to consume any committed messages published there.\n"); System.out.println("1. Enter text to publish and then press Enter to stage the message."); System.out.println("2. Add a few messages to the transaction batch."); System.out.println("3. Then, either:"); System.out.println( " o Enter the text 'COMMIT', and press Enter to publish all the staged messages."); System.out.println( " o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent."); showMessage = false; } String s = stdin.readLine(); if (s == null) exit(); else if (s.trim().equals("CANCEL")) { // Rollback the messages. A new transaction is implicitly // started for following messages. System.out.println("Cancelling messages..."); publishSession.rollback(); System.out.println("Staged messages have been cleared."); showMessage = false; // don't show the help message again. } else if (s.length() > 0) // See if we should send the messages if (s.trim().equals("COMMIT")) { // Commit (send) the messages. A new transaction is // implicitly started for following messages. System.out.println("Committing messages... "); publishSession.commit(); System.out.println("Staged messages have all been sent."); showMessage = false; // dont't show the help message again. } else { javax.jms.TextMessage msg = publishSession.createTextMessage(); msg.setText(username + ": " + s); // Publish the message persistently publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:Replier.java
/** Create JMS client for sending and receiving messages. */ private void start(String broker, String username, String password, String rQueue, String mode) { // Set the operation mode imode = (mode.equals("uppercase")) ? UPPERCASE : LOWERCASE; // Create a connection. try {/*from w w w. j a v a 2 s. c o m*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); session = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Receivers to application queues as well as a Sender // to use for JMS replies. try { javax.jms.Queue queue = session.createQueue(rQueue); javax.jms.MessageConsumer receiver = session.createConsumer(queue); receiver.setMessageListener(this); replier = session.createProducer(null); // Queue will be set for each reply // Now that all setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { // Read standard input waiting for "EXIT" command. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.println("\nReplier application:\n" + "============================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application gets requests with JMSReplyTo set on the " + DEFAULT_QUEUE + " queue." + "The message is transformed to all uppercase or all lowercase, and then returned to the requestor." + "The Requestor application displays the result.\n\n" + "Enter EXIT or press Ctrl+C to close the Replier.\n"); String s = stdin.readLine(); if (s == null || s.equalsIgnoreCase("EXIT")) { System.out.println("\nStopping Replier. Please wait..\n>"); exit(); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }
From source file:QueueMonitor.java
/** Constructor for MessageMonitor window. */ public QueueMonitor() { loadProperties();/*from www . j av a2 s .co m*/ setTitle(title); // Connect to Message Broker try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); session = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("Cannot connect to Broker"); jmse.printStackTrace(); System.exit(1); } // Set up Queues: StringTokenizer queues = new StringTokenizer(browseQueues, ","); while (queues.hasMoreTokens()) { try { String queueName = queues.nextToken(); System.out.println("Monitoring " + queueName); theQueues.addElement(session.createQueue(queueName)); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } } // After init it is time to start the connection try { connect.start(); } catch (javax.jms.JMSException jmse) { System.err.println("Cannot start connection"); jmse.printStackTrace(); System.exit(1); } //Elements visible on the screen textArea.setEditable(false); scrollPane.setBorder( new CompoundBorder(new EmptyBorder(6, 6, 6, 6), new SoftBevelBorder(BevelBorder.LOWERED))); getContentPane().add(scrollPane, BorderLayout.CENTER); getContentPane().add(browseButton, BorderLayout.SOUTH); browseButton.addActionListener(new OnBrowse()); }
From source file:Talk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue) { // Create a connection. try {/*from ww w . ja v a2 s. c o m*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue); qReceiver.setMessageListener(this); // Now that 'receive' setup is complete, start the Connection connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) System.out.println("\nTalk application:\n" + "=================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will send messages to the " + sQueue + " queue.\n" + "The application creates a receiver on the " + rQueue + " queue to consume any messages allocated to it.\n\n" + "Type some text, and then press Enter to send it as a TextMesssage from " + username + ".\n"); else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // Queues usually are used for PERSISTENT messages. // Hold messages for 30 minutes (1,800,000 millisecs). sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
From source file:org.fusesource.mq.itests.MQDistroTest.java
@Test public void testWebConsoleAndClient() throws Exception { // send message via webconsole, consume from jms openwire HttpClient client = new HttpClient(); // set credentials client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD)); // need to first get the secret GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp"); get.setDoAuthentication(true);//from w w w . j av a 2 s.co m // Give console some time to start for (int i = 0; i < 20; i++) { Thread.currentThread().sleep(1000); try { i = client.executeMethod(get); } catch (java.net.ConnectException ignored) { } } assertEquals("get succeeded on " + get, 200, get.getStatusCode()); String response = get.getResponseBodyAsString(); final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\""; String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length()); secret = secret.substring(0, secret.indexOf("\"/>")); final String destination = "validate.console.send"; final String content = "Hi for the " + Math.random() + "' time"; PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action"); post.setDoAuthentication(true); post.addParameter("secret", secret); post.addParameter("JMSText", content); post.addParameter("JMSDestination", destination); post.addParameter("JMSDestinationType", "queue"); // execute the send assertEquals("post succeeded, " + post, 302, client.executeMethod(post)); // consume what we sent ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory() .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connection.start(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination)) .receive(10 * 1000); assertNotNull("got a message", textMessage); assertEquals("it is ours", content, textMessage.getText()); } finally { connection.close(); } // verify osgi registration of cf ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class); assertTrue(connectionFactory instanceof ActiveMQConnectionFactory); ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connectionFromOsgiFactory.start(); try { assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName()); } finally { connectionFromOsgiFactory.close(); } // verify mq-client Process process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("producer worked, exit(0)?", 0, process.exitValue()); process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("consumer worked, exit(0)?", 0, process.exitValue()); System.out.println(executeCommand("activemq:bstat")); }
From source file:org.mule.transport.jms.Jms11Support.java
public Connection createConnection(ConnectionFactory connectionFactory, String username, String password) throws JMSException { if (connectionFactory == null) { throw new IllegalArgumentException("connectionFactory cannot be null"); }//w w w.j av a 2s . c o m return connectionFactory.createConnection(username, password); }
From source file:org.fusesource.fabric.itests.paxexam.mq.MQDistroTest.java
@Test public void testMQ() throws Exception { // send message via webconsole, consume from jms openwire HttpClient client = new HttpClient(); // set credentials client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD)); // need to first get the secret GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp"); get.setDoAuthentication(true);//from w ww . j av a2 s . co m // Give console some time to start for (int i = 0; i < 20; i++) { Thread.currentThread().sleep(1000); try { i = client.executeMethod(get); } catch (java.net.ConnectException ignored) { } } assertEquals("get succeeded on " + get, 200, get.getStatusCode()); String response = get.getResponseBodyAsString(); final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\""; String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length()); secret = secret.substring(0, secret.indexOf("\"/>")); final String destination = "validate.console.send"; final String content = "Hi for the " + Math.random() + "' time"; PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action"); post.setDoAuthentication(true); post.addParameter("secret", secret); post.addParameter("JMSText", content); post.addParameter("JMSDestination", destination); post.addParameter("JMSDestinationType", "queue"); // execute the send assertEquals("post succeeded, " + post, 302, client.executeMethod(post)); // consume what we sent ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory() .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connection.start(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination)) .receive(10 * 1000); assertNotNull("got a message", textMessage); assertEquals("it is ours", content, textMessage.getText()); } finally { connection.close(); } // verify osgi registration of cf ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class); assertTrue(connectionFactory instanceof ActiveMQConnectionFactory); ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD); connectionFromOsgiFactory.start(); try { assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName()); } finally { connectionFromOsgiFactory.close(); } // verify mq-client Process process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("producer worked, exit(0)?", 0, process.exitValue()); process = Runtime.getRuntime() .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user " + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env new File(System.getProperty("user.dir"))); process.waitFor(); assertEquals("consumer worked, exit(0)?", 0, process.exitValue()); }
From source file:SelectorTalk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue, String selection) {// ww w . ja v a2s . co m // Create a connection. try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { //NOTE: the Queue Receiver is set up with the Message Selector: javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue, PROPERTY_NAME + " = \'" + selection + "\'"); qReceiver.setMessageListener(this); connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) System.out.println("SelectorTalk application:\n" + "=========================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will send messages with " + PROPERTY_NAME + " set to " + selection + " to the " + sQueue + " queue.\n" + "The application creates a receiver on the " + rQueue + " queue selecting only messages where " + PROPERTY_NAME + " is " + selection + ".\n\n" + "Type some text, and then press Enter to publish it as a TextMesssage from " + username + ".\n"); else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // NOTE: here we set the property for each sent message. msg.setStringProperty(PROPERTY_NAME, selection); sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }