List of usage examples for javax.jms Connection start
void start() throws JMSException;
From source file:com.ccc.ccm.client.JMSTemplateAutowired.java
/** * Execute the action specified by the given action object within a * JMS Session. Generalized version of <code>execute(SessionCallback)</code>, * allowing the JMS Connection to be started on the fly. * <p>Use <code>execute(SessionCallback)</code> for the general case. * Starting the JMS Connection is just necessary for receiving messages, * which is preferably achieved through the <code>receive</code> methods. * @param action callback object that exposes the Session * @param startConnection whether to start the Connection * @return the result object from working with the Session * @throws JmsException if there is any problem * @see #execute(SessionCallback)/*from w ww .ja va 2 s .com*/ * @see #receive */ public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException { Assert.notNull(action, "Callback object must not be null"); Connection conToClose = null; Session sessionToClose = null; try { Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(getConnectionFactory(), this.transactionalResourceFactory, startConnection); if (sessionToUse == null) { conToClose = createConnection(); sessionToClose = createSession(conToClose); if (startConnection) { conToClose.start(); } sessionToUse = sessionToClose; } if (logger.isDebugEnabled()) { logger.debug("Executing callback on JMS Session: " + sessionToUse); } return action.doInJms(sessionToUse); } catch (JMSException ex) { throw convertJmsAccessException(ex); } finally { JmsUtils.closeSession(sessionToClose); ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection); } }
From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java
/** * Consume all the messages in the specified queue. Helper to ensure * persistent tests don't leave data behind. * * @param queue the queue to purge/*w ww. j ava 2 s .c o m*/ * * @return the count of messages drained * * @throws Exception if a problem occurs */ protected int drainQueue(Queue queue) throws Exception { Connection connection = getConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); connection.start(); int count = 0; while (consumer.receive(1000) != null) { count++; } connection.close(); return count; }
From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java
/** * Creates a new JMS Connection./*from w w w .j a v a 2 s .c o m*/ * * @return A connection to the JMS Queue used as the store of this message store. * @throws JMSException */ public Connection newConnection() throws JMSException { Connection connection; if (connectionFactory == null) { logger.error(nameString() + ". Could not create a new connection to the broker." + " Initial Context Factory:[" + parameters.get(NAMING_FACTORY_INITIAL) + "]; Provider URL:[" + parameters.get(PROVIDER_URL) + "]; Connection Factory:[null]."); return null; } if (isVersion11) { if (userName != null && password != null) { connection = connectionFactory.createConnection(userName, password); } else { connection = connectionFactory.createConnection(); } } else { QueueConnectionFactory connectionFactory; connectionFactory = (QueueConnectionFactory) this.connectionFactory; if (userName != null && password != null) { connection = connectionFactory.createQueueConnection(userName, password); } else { connection = connectionFactory.createQueueConnection(); } } connection.start(); if (logger.isDebugEnabled()) { logger.debug(nameString() + ". Created JMS Connection."); } return connection; }
From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java
public void registerListener(List<String> eventTypeNames, MessageHandler handler) { if (brokerService == null || !brokerInitialized) { log.debug("The broker service is not running in registerListener."); return;//from w ww . j ava 2 s. c om } if (!isValidHandler(handler)) { return; } ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory(); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.setClientID(handler.getClientId()); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage()); } for (String eventTypeName : eventTypeNames) { log.info("Registering handler for event " + eventTypeName); Topic topic = topicMap.get(eventTypeName); if (topic == null) { log.error("Caller attempted to register interest to events of unknown type " + eventTypeName); throw new RuntimeException("Unknown event type specified in registration request."); } if (isListenerRegistered(handler, eventTypeName)) { log.warn("Caller attempted to register interest for the same event again."); return; } try { Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName()); MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber, handler); saveListenerRegistration(listener, eventTypeName); subscriber.setMessageListener(listener); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException( "Unable to setup registration for event notification: " + e.getMessage()); } } try { connection.start(); } catch (JMSException e) { log.error("Failed while setting up a registrant for notification events. Error: " + e, e); throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage()); } }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private Object sendAndReceiveWithContainer(Message<?> requestMessage) throws JMSException { Connection connection = this.createConnection(); // NOSONAR - closed in ConnectionFactoryUtils. Session session = null;//w w w . j a v a 2s .c om Destination replyTo = this.replyContainer.getReplyDestination(); try { session = this.createSession(connection); // convert to JMS Message Object objectToSend = requestMessage; if (this.extractRequestPayload) { objectToSend = requestMessage.getPayload(); } javax.jms.Message jmsRequest = this.messageConverter.toMessage(objectToSend, session); // map headers this.headerMapper.fromHeaders(requestMessage.getHeaders(), jmsRequest); jmsRequest.setJMSReplyTo(replyTo); connection.start(); if (logger.isDebugEnabled()) { logger.debug("ReplyTo: " + replyTo); } Integer priority = new IntegrationMessageHeaderAccessor(requestMessage).getPriority(); if (priority == null) { priority = this.priority; } Destination requestDestination = this.determineRequestDestination(requestMessage, session); Object reply = null; if (this.correlationKey == null) { /* * Remove any existing correlation id that was mapped from the inbound message * (it will be restored in the reply by normal ARPMH header processing). */ jmsRequest.setJMSCorrelationID(null); reply = doSendAndReceiveAsyncDefaultCorrelation(requestDestination, jmsRequest, session, priority); } else { reply = doSendAndReceiveAsync(requestDestination, jmsRequest, session, priority); } /* * Remove the gateway's internal correlation Id to avoid conflicts with an upstream * gateway. */ if (reply instanceof javax.jms.Message) { ((javax.jms.Message) reply).setJMSCorrelationID(null); } return reply; } finally { JmsUtils.closeSession(session); ConnectionFactoryUtils.releaseConnection(connection, this.connectionFactory, true); } }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private javax.jms.Message sendAndReceiveWithoutContainer(Message<?> requestMessage) throws JMSException { Connection connection = this.createConnection(); // NOSONAR - closed in ConnectionFactoryUtils. Session session = null;/*from www.ja v a 2 s . com*/ Destination replyTo = null; try { session = this.createSession(connection); // convert to JMS Message Object objectToSend = requestMessage; if (this.extractRequestPayload) { objectToSend = requestMessage.getPayload(); } javax.jms.Message jmsRequest = this.messageConverter.toMessage(objectToSend, session); // map headers this.headerMapper.fromHeaders(requestMessage.getHeaders(), jmsRequest); replyTo = this.determineReplyDestination(requestMessage, session); jmsRequest.setJMSReplyTo(replyTo); connection.start(); if (logger.isDebugEnabled()) { logger.debug("ReplyTo: " + replyTo); } Integer priority = new IntegrationMessageHeaderAccessor(requestMessage).getPriority(); if (priority == null) { priority = this.priority; } javax.jms.Message replyMessage = null; Destination requestDestination = this.determineRequestDestination(requestMessage, session); if (this.correlationKey != null) { replyMessage = doSendAndReceiveWithGeneratedCorrelationId(requestDestination, jmsRequest, replyTo, session, priority); } else if (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic) { replyMessage = doSendAndReceiveWithTemporaryReplyToDestination(requestDestination, jmsRequest, replyTo, session, priority); } else { replyMessage = doSendAndReceiveWithMessageIdCorrelation(requestDestination, jmsRequest, replyTo, session, priority); } return replyMessage; } finally { JmsUtils.closeSession(session); this.deleteDestinationIfTemporary(replyTo); ConnectionFactoryUtils.releaseConnection(connection, this.connectionFactory, true); } }
From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java
/** * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This * method is synchronized otherwise multiple threads may try to create the same connection * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent * threads will then retrieve the connection that was already created. *//*from w w w. j a va 2 s . c o m*/ private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties, String connectionKey, Long dispatcherId, boolean replace) throws Exception { // If the connection needs to be replaced, clean up the old connection and remove it from the cache. if (replace) { closeJmsConnectionQuietly(connectionKey); } JmsConnection jmsConnection = jmsConnections.get(connectionKey); if (jmsConnection == null) { if (jmsConnections.size() >= maxConnections) { throw new Exception("Cannot create new connection. Maximum number (" + maxConnections + ") of cached connections reached."); } Context initialContext = null; ConnectionFactory connectionFactory = null; Connection connection = null; Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties(); if (jmsDispatcherProperties.isUseJndi()) { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { MirthContextFactory contextFactory = contextFactoryController .getContextFactory(getResourceIds()); Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader()); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl()); env.put(Context.INITIAL_CONTEXT_FACTORY, jmsDispatcherProperties.getJndiInitialContextFactory()); env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername()); env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword()); initialContext = new InitialContext(env); String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName(); connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } else { String className = jmsDispatcherProperties.getConnectionFactoryClass(); MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds()); connectionFactory = (ConnectionFactory) Class .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance(); } BeanUtil.setProperties(connectionFactory, connectionProperties); try { logger.debug("Creating JMS connection and session"); connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(), jmsDispatcherProperties.getPassword()); String clientId = jmsDispatcherProperties.getClientId(); if (!clientId.isEmpty()) { connection.setClientID(clientId); } logger.debug("Starting JMS connection"); connection.start(); } catch (JMSException e) { try { if (connection != null) { connection.close(); } } catch (Exception e1) { logger.debug("Failed to close JMS connection.", e); } try { if (initialContext != null) { initialContext.close(); } } catch (Exception e1) { logger.debug("Failed to close initial context.", e); } throw e; } // Create the new JmsConnection and add it to the cache. jmsConnection = new JmsConnection(connection, initialContext); jmsConnections.put(connectionKey, jmsConnection); } return jmsConnection; }
From source file:org.apache.synapse.transport.jms.JMSSender.java
/** * Performs the actual sending of the JMS message *//*from w w w. j a v a2s . c o m*/ public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo) throws AxisFault { JMSConnectionFactory jmsConnectionFactory = null; Connection connection = null; // holds a one time connection if used JMSOutTransportInfo jmsOut = null; Session session = null; Destination destination = null; Destination replyDestination = null; try { if (targetAddress != null) { jmsOut = new JMSOutTransportInfo(targetAddress); // do we have a definition for a connection factory to use for this address? jmsConnectionFactory = getJMSConnectionFactory(jmsOut); if (jmsConnectionFactory != null) { // create new or get existing session to send to the destination from the CF session = jmsConnectionFactory.getSessionForDestination(JMSUtils.getDestination(targetAddress)); } else { // digest the targetAddress and locate CF from the EPR jmsOut.loadConnectionFactoryFromProperies(); try { // create a one time connection and session to be used Hashtable jndiProps = jmsOut.getProperties(); String user = (String) jndiProps.get(Context.SECURITY_PRINCIPAL); String pass = (String) jndiProps.get(Context.SECURITY_CREDENTIALS); QueueConnectionFactory qConFac = null; TopicConnectionFactory tConFac = null; ConnectionFactory conFac = null; if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) { qConFac = (QueueConnectionFactory) jmsOut.getConnectionFactory(); } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) { tConFac = (TopicConnectionFactory) jmsOut.getConnectionFactory(); } else { handleException( "Unable to determine type of JMS " + "Connection Factory - i.e Queue/Topic"); } if (user != null && pass != null) { if (qConFac != null) { connection = qConFac.createQueueConnection(user, pass); } else if (tConFac != null) { connection = tConFac.createTopicConnection(user, pass); } } else { if (qConFac != null) { connection = qConFac.createQueueConnection(); } else if (tConFac != null) { connection = tConFac.createTopicConnection(); } } if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) { session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) { session = ((TopicConnection) connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE); } } catch (JMSException e) { handleException("Error creating a connection/session for : " + targetAddress); } } destination = jmsOut.getDestination(); } else if (outTransportInfo != null && outTransportInfo instanceof JMSOutTransportInfo) { jmsOut = (JMSOutTransportInfo) outTransportInfo; jmsConnectionFactory = jmsOut.getJmsConnectionFactory(); session = jmsConnectionFactory.getSessionForDestination(jmsOut.getDestination().toString()); destination = jmsOut.getDestination(); } String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO); if (replyDestName != null) { if (jmsConnectionFactory != null) { replyDestination = jmsConnectionFactory.getDestination(replyDestName); } else { replyDestination = jmsOut.getReplyDestination(replyDestName); } } // now we are going to use the JMS session, but if this was a session from a // defined JMS connection factory, we need to synchronize as sessions are not // thread safe synchronized (session) { // convert the axis message context into a JMS Message that we can send over JMS Message message = null; String correlationId = null; try { message = createJMSMessage(msgCtx, session); } catch (JMSException e) { handleException("Error creating a JMS message from the axis message context", e); } String destinationType = jmsOut.getDestinationType(); // if the destination does not exist, see if we can create it destination = JMSUtils.createDestinationIfRequired(destination, destinationType, targetAddress, session); // should we wait for a synchronous response on this same thread? boolean waitForResponse = waitForSynchronousResponse(msgCtx); // if this is a synchronous out-in, prepare to listen on the response destination if (waitForResponse) { replyDestination = JMSUtils.setReplyDestination(replyDestination, session, message); } // send the outgoing message over JMS to the destination selected JMSUtils.sendMessageToJMSDestination(session, destination, message); // if we are expecting a synchronous response back for the message sent out if (waitForResponse) { try { connection.start(); } catch (JMSException ignore) { } try { correlationId = message.getJMSMessageID(); } catch (JMSException ignore) { } waitForResponseAndProcess(session, replyDestination, msgCtx, correlationId); } } } finally { if (connection != null) { try { connection.close(); } catch (JMSException ignore) { } } } }
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. ja va 2 s .c o 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; }