List of usage examples for javax.jms ConnectionFactory createConnection
Connection createConnection(String userName, String password) throws JMSException;
From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java
private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf, String name) throws NamingException, JMSException, InterruptedException { AtomicInteger totalReceived = new AtomicInteger(0); System.out.printf("Subscription %s: \n", name); Destination subscription = (Destination) context.lookup(name); // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start();/*from ww w . ja v a 2 s .c om*/ // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer MessageConsumer consumer = session.createConsumer(subscription); // Set callback listener. Gets called for each received message. consumer.setMessageListener(message -> { try { System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter message.getJMSMessageID()); message.acknowledge(); } catch (Exception e) { System.out.printf("%s", e.toString()); } }); // 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(); }
From source file:TransactedTalk.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 {/* ww w . j ava 2 s .c om*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); // We want to be able up commit/rollback messages sent, // but not affect messages received. Therefore, we need two sessions. sendSession = connect.createSession(true, 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("TransactedTalk 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 " + sQueue + " until you either commit them or roll them back."); System.out.println("The application receives messages on " + rQueue + " to consume any committed messages sent there.\n"); System.out.println("1. Enter text to send 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 send all the staged messages."); System.out.println( " o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent."); } else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { 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.print("Cancelling messages..."); sendSession.rollback(); System.out.println("Staged messages have been cleared."); } 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); // 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.print("Committing messages..."); sendSession.commit(); System.out.println("Staged messages have all been sent."); } } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
From source file:org.apache.jmeter.protocol.jms.sampler.Receiver.java
/** * Constructor//from www.j a v a 2s . c o m * @param factory * @param receiveQueue Receive Queue * @param principal Username * @param credentials Password * @param useResMsgIdAsCorrelId * @param jmsSelector JMS Selector * @throws JMSException */ private Receiver(ConnectionFactory factory, Destination receiveQueue, String principal, String credentials, boolean useResMsgIdAsCorrelId, String jmsSelector) throws JMSException { if (null != principal && null != credentials) { log.info("creating receiver WITH authorisation credentials. UseResMsgId=" + useResMsgIdAsCorrelId); conn = factory.createConnection(principal, credentials); } else { log.info("creating receiver without authorisation credentials. UseResMsgId=" + useResMsgIdAsCorrelId); conn = factory.createConnection(); } session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (log.isDebugEnabled()) { log.debug("Receiver - ctor. Creating consumer with JMS Selector:" + jmsSelector); } if (StringUtils.isEmpty(jmsSelector)) { consumer = session.createConsumer(receiveQueue); } else { consumer = session.createConsumer(receiveQueue, jmsSelector); } this.useResMsgIdAsCorrelId = useResMsgIdAsCorrelId; log.debug("Receiver - ctor. Starting connection now"); conn.start(); log.info("Receiver - ctor. Connection to messaging system established"); }
From source file:com.zotoh.maedr.device.JmsIO.java
private void inizFac(Context ctx, Object obj) throws Exception { ConnectionFactory f = (ConnectionFactory) obj; final JmsIO me = this; Connection conn;/* ww w.j a v a 2 s.c o m*/ Object c = ctx.lookup(_dest); if (!isEmpty(_jmsUser)) { conn = f.createConnection(_jmsUser, _jmsPwd); } else { conn = f.createConnection(); } _conn = conn; if (c instanceof Destination) { //TODO ? ack always ? Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer u = s.createConsumer((Destination) c); u.setMessageListener(new MessageListener() { public void onMessage(Message msg) { me.onMessage(msg); } }); } else { throw new Exception("JmsIO: Object not of Destination type"); } }
From source file:com.adaptris.core.jms.JmsPollingConsumerImpl.java
protected Connection createConnection(ConnectionFactory factory, String user, String password) throws JMSException { return factory.createConnection(user, password); }
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 {/*from w w w. j av a 2s.co m*/ // 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: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 www.j av a 2 s .com*/ // 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:nl.nn.adapterframework.extensions.tibco.SendTibcoMessage.java
public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException { Connection connection = null; Session jSession = null;/*from ww w . j av a 2s.co m*/ MessageProducer msgProducer = null; Destination destination = null; String url_work; String authAlias_work; String userName_work; String password_work; String queueName_work; String messageProtocol_work; int replyTimeout_work; String soapAction_work; String result = null; ParameterValueList pvl = null; if (getParameterList() != null) { ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session); try { pvl = prc.getValues(getParameterList()); } catch (ParameterException e) { throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e); } } url_work = getParameterValue(pvl, "url"); if (url_work == null) { url_work = getUrl(); } authAlias_work = getParameterValue(pvl, "authAlias"); if (authAlias_work == null) { authAlias_work = getAuthAlias(); } userName_work = getParameterValue(pvl, "userName"); if (userName_work == null) { userName_work = getUserName(); } password_work = getParameterValue(pvl, "password"); if (password_work == null) { password_work = getPassword(); } queueName_work = getParameterValue(pvl, "queueName"); if (queueName_work == null) { queueName_work = getQueueName(); } messageProtocol_work = getParameterValue(pvl, "messageProtocol"); if (messageProtocol_work == null) { messageProtocol_work = getMessageProtocol(); } String replyTimeout_work_str = getParameterValue(pvl, "replyTimeout"); if (replyTimeout_work_str == null) { replyTimeout_work = getReplyTimeout(); } else { replyTimeout_work = Integer.parseInt(replyTimeout_work_str); } soapAction_work = getParameterValue(pvl, "soapAction"); if (soapAction_work == null) soapAction_work = getSoapAction(); if (StringUtils.isEmpty(soapAction_work) && !StringUtils.isEmpty(queueName_work)) { String[] q = queueName_work.split("\\."); if (q.length > 0) { if (q[0].equalsIgnoreCase("P2P") && q.length >= 4) { soapAction_work = q[3]; } else if (q[0].equalsIgnoreCase("ESB") && q.length == 8) { soapAction_work = q[5] + "_" + q[6]; } else if (q[0].equalsIgnoreCase("ESB") && q.length > 8) { soapAction_work = q[6] + "_" + q[7]; } } } if (StringUtils.isEmpty(soapAction_work)) { log.debug(getLogPrefix(session) + "deriving default soapAction"); try { URL resource = ClassUtils.getResourceURL(this, "/xml/xsl/esb/soapAction.xsl"); TransformerPool tp = new TransformerPool(resource, true); soapAction_work = tp.transform(input.toString(), null); } catch (Exception e) { log.error(getLogPrefix(session) + "failed to execute soapAction.xsl"); } } if (messageProtocol_work == null) { throw new PipeRunException(this, getLogPrefix(session) + "messageProtocol must be set"); } if (!messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY) && !messageProtocol_work.equalsIgnoreCase(FIRE_AND_FORGET)) { throw new PipeRunException(this, getLogPrefix(session) + "illegal value for messageProtocol [" + messageProtocol_work + "], must be '" + REQUEST_REPLY + "' or '" + FIRE_AND_FORGET + "'"); } CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work); try { TibjmsAdmin admin; try { admin = TibcoUtils.getActiveServerAdmin(url_work, cf); } catch (TibjmsAdminException e) { log.debug(getLogPrefix(session) + "caught exception", e); admin = null; } if (admin != null) { QueueInfo queueInfo; try { queueInfo = admin.getQueue(queueName_work); } catch (Exception e) { throw new PipeRunException(this, getLogPrefix(session) + " exception on getting queue info", e); } if (queueInfo == null) { throw new PipeRunException(this, getLogPrefix(session) + " queue [" + queueName_work + "] does not exist"); } try { admin.close(); } catch (TibjmsAdminException e) { log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e); } } ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work); connection = factory.createConnection(cf.getUsername(), cf.getPassword()); jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); destination = jSession.createQueue(queueName_work); msgProducer = jSession.createProducer(destination); TextMessage msg = jSession.createTextMessage(); msg.setText(input.toString()); Destination replyQueue = null; if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) { replyQueue = jSession.createTemporaryQueue(); msg.setJMSReplyTo(replyQueue); msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); msgProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); msgProducer.setTimeToLive(replyTimeout_work); } else { msg.setJMSDeliveryMode(DeliveryMode.PERSISTENT); msgProducer.setDeliveryMode(DeliveryMode.PERSISTENT); } if (StringUtils.isNotEmpty(soapAction_work)) { log.debug( getLogPrefix(session) + "setting [SoapAction] property to value [" + soapAction_work + "]"); msg.setStringProperty("SoapAction", soapAction_work); } msgProducer.send(msg); if (log.isDebugEnabled()) { log.debug(getLogPrefix(session) + "sent message [" + msg.getText() + "] " + "to [" + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]"); } else { if (log.isInfoEnabled()) { log.info(getLogPrefix(session) + "sent message to [" + msgProducer.getDestination() + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] " + "replyTo [" + msg.getJMSReplyTo() + "]"); } } if (messageProtocol_work.equalsIgnoreCase(REQUEST_REPLY)) { String replyCorrelationId = msg.getJMSMessageID(); MessageConsumer msgConsumer = jSession.createConsumer(replyQueue, "JMSCorrelationID='" + replyCorrelationId + "'"); log.debug(getLogPrefix(session) + "] start waiting for reply on [" + replyQueue + "] selector [" + replyCorrelationId + "] for [" + replyTimeout_work + "] ms"); try { connection.start(); Message rawReplyMsg = msgConsumer.receive(replyTimeout_work); if (rawReplyMsg == null) { throw new PipeRunException(this, getLogPrefix(session) + "did not receive reply on [" + replyQueue + "] replyCorrelationId [" + replyCorrelationId + "] within [" + replyTimeout_work + "] ms"); } TextMessage replyMsg = (TextMessage) rawReplyMsg; result = replyMsg.getText(); } finally { } } else { result = msg.getJMSMessageID(); } } catch (JMSException e) { throw new PipeRunException(this, getLogPrefix(session) + " exception on sending message to Tibco queue", e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { log.warn(getLogPrefix(session) + "exception on closing connection", e); } } } return result; }
From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java
public String doPipeWithTimeoutGuarded(Object input, IPipeLineSession session) throws PipeRunException { String result;/* w w w . j av a 2s. com*/ String url_work; String authAlias_work; String userName_work; String password_work; String queueName_work = null; ParameterValueList pvl = null; if (getParameterList() != null) { ParameterResolutionContext prc = new ParameterResolutionContext((String) input, session); try { pvl = prc.getValues(getParameterList()); } catch (ParameterException e) { throw new PipeRunException(this, getLogPrefix(session) + "exception on extracting parameters", e); } } url_work = getParameterValue(pvl, "url"); if (url_work == null) { url_work = getUrl(); } authAlias_work = getParameterValue(pvl, "authAlias"); if (authAlias_work == null) { authAlias_work = getAuthAlias(); } userName_work = getParameterValue(pvl, "userName"); if (userName_work == null) { userName_work = getUserName(); } password_work = getParameterValue(pvl, "password"); if (password_work == null) { password_work = getPassword(); } CredentialFactory cf = new CredentialFactory(authAlias_work, userName_work, password_work); Connection connection = null; Session jSession = null; TibjmsAdmin admin = null; try { admin = TibcoUtils.getActiveServerAdmin(url_work, cf); if (admin == null) { throw new PipeRunException(this, "could not find an active server"); } String ldapUrl = getParameterValue(pvl, "ldapUrl"); LdapSender ldapSender = null; if (StringUtils.isNotEmpty(ldapUrl)) { ldapSender = retrieveLdapSender(ldapUrl, cf); } queueName_work = getParameterValue(pvl, "queueName"); if (StringUtils.isNotEmpty(queueName_work)) { String countOnly_work = getParameterValue(pvl, "countOnly"); boolean countOnly = ("true".equalsIgnoreCase(countOnly_work) ? true : false); if (countOnly) { return getQueueMessageCountOnly(admin, queueName_work); } } ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url_work); connection = factory.createConnection(cf.getUsername(), cf.getPassword()); jSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); if (StringUtils.isNotEmpty(queueName_work)) { String queueItem_work = getParameterValue(pvl, "queueItem"); int qi; if (StringUtils.isNumeric(queueItem_work)) { qi = Integer.parseInt(queueItem_work); } else { qi = 1; } result = getQueueMessage(jSession, admin, queueName_work, qi, ldapSender); } else { String showAge_work = getParameterValue(pvl, "showAge"); boolean showAge = ("true".equalsIgnoreCase(showAge_work) ? true : false); result = getQueuesInfo(jSession, admin, showAge, ldapSender); } } catch (Exception e) { String msg = getLogPrefix(session) + "exception on showing Tibco queues, url [" + url_work + "]" + (StringUtils.isNotEmpty(queueName_work) ? " queue [" + queueName_work + "]" : ""); throw new PipeRunException(this, msg, e); } finally { if (admin != null) { try { admin.close(); } catch (TibjmsAdminException e) { log.warn(getLogPrefix(session) + "exception on closing Tibjms Admin", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { log.warn(getLogPrefix(session) + "exception on closing connection", e); } } } return result; }
From source file:org.openadaptor.auxil.connector.jms.JMSConnection.java
protected Connection createConnection(ConnectionFactory factory) throws JMSException { Connection newConnection;// w w w. j a va 2s . c om boolean useUsername = true; if (username == null || username.compareTo("") == 0) { useUsername = false; } if (isUseXa() && factory instanceof XAConnectionFactory) { if (useUsername) { newConnection = ((XAConnectionFactory) factory).createXAConnection(username, password); } else { newConnection = ((XAConnectionFactory) factory).createXAConnection(); } } else { if (useUsername) { newConnection = factory.createConnection(username, password); } else { newConnection = factory.createConnection(); } } return newConnection; }