List of usage examples for javax.jms Session createConsumer
MessageConsumer createConsumer(Destination destination, java.lang.String messageSelector) throws JMSException;
From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java
@Override public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) { String ip = null;//from w ww. j a v a2 s. co m try { ip = Inet4Address.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.severe("Unable to get localhost IP address."); } String ltopic = getTopic(); if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) { log.info("Waiting for message with selector: " + selector); Connection connection = null; MessageConsumer consumer = null; try { ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory(); connection = connectionFactory.createConnection(); connection.setClientID(ip + "_" + UUID.randomUUID().toString()); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic destination = session.createTopic(ltopic); consumer = session.createConsumer(destination, selector); Message message = consumer.receive(timeout * 60 * 1000); if (message != null) { String value = getMessageBody(message); if (build != null) { if (StringUtils.isNotEmpty(variable)) { EnvVars vars = new EnvVars(); vars.put(variable, value); build.addAction(new CIEnvironmentContributingAction(vars)); } } log.info("Received message with selector: " + selector + "\n" + formatMessage(message)); return value; } log.info("Timed out waiting for message!"); } catch (Exception e) { log.log(Level.SEVERE, "Unhandled exception waiting for message.", e); } finally { if (consumer != null) { try { consumer.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } } else { log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker."); } return null; }
From source file:org.apache.james.queue.jms.JMSMailQueue.java
/** * <p>//from w w w .j av a 2 s . co m * Dequeues a mail when it is ready to process. As JMS does not support delay scheduling out-of-the box, * we use a messageselector to check if a mail is ready. For this a * {@link MessageConsumer#receive(long)} is used with a timeout of 10 * seconds. * </p> * <p> * Many JMS implementations support better solutions for this, so this * should get overridden by these implementations * </p> */ @Override public MailQueueItem deQueue() throws MailQueueException { Session session = null; MessageConsumer consumer = null; while (true) { TimeMetric timeMetric = metricFactory.timer(DEQUEUED_TIMER_METRIC_NAME_PREFIX + queueName); try { session = connection.createSession(true, Session.SESSION_TRANSACTED); Queue queue = session.createQueue(queueName); consumer = session.createConsumer(queue, getMessageSelector()); Message message = consumer.receive(10000); if (message != null) { dequeuedMailsMetric.increment(); return createMailQueueItem(session, consumer, message); } else { session.commit(); closeConsumer(consumer); closeSession(session); } } catch (Exception e) { rollback(session); closeConsumer(consumer); closeSession(session); throw new MailQueueException("Unable to dequeue next message", e); } finally { timeMetric.stopAndPublish(); } } }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Gets an MQ message off a specified queue and returns it as an * <code>Object</code> to the requestor for further processing. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param responseQueue - The request queue name to put the message on * @param timeout - How long to wait for a connection or response * @param messageId - The JMS correlation ID of the message the response is associated with * @return <code>Object</code> - The serializable data returned by the MQ request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from w ww .ja v a2 s .co m*/ public static final synchronized Object getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException { final String methodName = MQUtils.CNAME + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", responseQueue); DEBUGGER.debug("Value: {}", timeout); DEBUGGER.debug("Value: {}", messageId); } Connection conn = null; Session session = null; Object response = null; Context envContext = null; MessageConsumer consumer = null; ConnectionFactory connFactory = null; try { try { InitialContext initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } if (envContext != null) { try { consumer = session.createConsumer((Destination) envContext.lookup(responseQueue), "JMSCorrelationID='" + messageId + "'"); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createQueue(responseQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'"); } if (DEBUG) { DEBUGGER.debug("MessageConsumer: {}", consumer); } ObjectMessage message = (ObjectMessage) consumer.receive(timeout); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } if (message == null) { throw new UtilityException("Failed to retrieve message within the timeout specified."); } response = message.getObject(); message.acknowledge(); if (DEBUG) { DEBUGGER.debug("Object: {}", response); } } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return response; }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java
public MessageConsumer createMessageConsumer(Session session, Destination destination) { try {/*from w w w . j a va 2 s . c o m*/ if (JMSConstants.JMS_SPEC_VERSION_2_0.equals(jmsSpec) && isSharedSubscription) { if (isDurable) { return session.createSharedDurableConsumer((Topic) destination, subscriptionName, messageSelector); } else { return session.createSharedConsumer((Topic) destination, subscriptionName, messageSelector); } } else if ((JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)) || (JMSConstants.JMS_SPEC_VERSION_2_0.equals(jmsSpec) && !isSharedSubscription)) { if (isDurable) { return session.createDurableSubscriber((Topic) destination, subscriptionName, messageSelector, noPubSubLocal); } else { return session.createConsumer(destination, messageSelector); } } else { if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) { return ((QueueSession) session).createReceiver((Queue) destination, messageSelector); } else { if (isDurable) { return ((TopicSession) session).createDurableSubscriber((Topic) destination, subscriptionName, messageSelector, noPubSubLocal); } else { return ((TopicSession) session).createSubscriber((Topic) destination, messageSelector, false); } } } } catch (JMSException e) { logger.error("JMS Exception while creating consumer. " + e.getMessage(), e); } return null; }
From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java
public void createConsumer(final CreateConsumerCommand command) { try {/*from ww w . j a v a 2 s . co m*/ final Session session = _testSessions.get(command.getSessionName()); if (session == null) { throw new DistributedTestException("No test session found called: " + command.getSessionName(), command); } synchronized (session) { Destination destination; MessageConsumer jmsConsumer; if (command.isTopic()) { Topic topic = session.createTopic(command.getDestinationName()); if (command.isDurableSubscription()) { String subscription = "subscription-" + command.getParticipantName() + System.currentTimeMillis(); jmsConsumer = session.createDurableSubscriber(topic, subscription); _testSubscriptions.put(subscription, session); LOGGER.debug("created durable suscription " + subscription + " to topic " + topic); } else { jmsConsumer = session.createConsumer(topic, command.getSelector()); } destination = topic; } else { destination = session.createQueue(command.getDestinationName()); jmsConsumer = session.createConsumer(destination, command.getSelector()); } _testConsumers.put(command.getParticipantName(), jmsConsumer); } } catch (final JMSException jmse) { throw new DistributedTestException("Unable to create new consumer: " + command, jmse); } }
From source file:nl.nn.adapterframework.jms.JMSFacade.java
/** * Create a MessageConsumer. In this overloaded function the selector is taken into account. * This ensures that listeners (or other extensions of this class) do not influence how the selector * is used: when a correlationID should be in the filter the <code>getMessageConsumerForCorrelationId</code> * should be used, other wise the <code>getMessageConsumer</code> function which has no attribute for * <code>selector</code>. Whe a MessageSelector is set, it will be used when no correlation id is required. * @param session the Session//from w w w. j a va 2 s .c o m * @param destination the Destination * @param selector the MessageSelector * @return MessageConsumer * @throws NamingException * @throws JMSException */ public MessageConsumer getMessageConsumer(Session session, Destination destination, String selector) throws NamingException, JMSException { if (useTopicFunctions) { if (useJms102()) { return getTopicSubscriber((TopicSession) session, (Topic) destination, selector); } else { return getTopicSubscriber(session, (Topic) destination, selector); } } else { if (useJms102()) { return getQueueReceiver((QueueSession) session, (Queue) destination, selector); } else { return session.createConsumer(destination, selector); } } }
From source file:tools.ConsumerTool.java
@Override public void run() { Connection connection = null; Session session = null; try {// ww w . j av a 2 s .c o m connection = connectionFactory.createConnection(); if (clientId != null) { connection.setClientID(clientId); } connection.start(); session = connection.createSession(transacted, acknowledgeMode); Destination destination = null; if (jndiLookupDestinations) { destination = (Destination) context.lookup(destinationName); } else { if (useQueueDestinations) { if (useTemporaryDestinations) { destination = session.createTemporaryQueue(); } else { destination = session.createQueue(destinationName); } } else { if (useTemporaryDestinations) { destination = session.createTemporaryTopic(); } else { destination = session.createTopic(destinationName); } } } if (useQueueBrowser) { runQueueBrowser(session, (Queue) destination); } else { MessageConsumer consumer = null; if (useQueueDestinations) { //Queues if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } else { //Queues if (durable) { //Durable Subscribers if (selector != null) { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName, selector, false); } else { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName); } } else { //Non-Durable Subscribers if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } } if (useAsyncListener) { final Session consumerSession = session; final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { perConsumerReceivedMessages.incrementAndGet(); handleMessage(consumerSession, message, perConsumerReceivedMessages.get()); } }); while (perConsumerReceivedMessages.get() < numMessages) { Thread.sleep(100); } } else { int perConsumerReceivedMessages = 0; while (perConsumerReceivedMessages < numMessages) { Message message = null; if (receiveTimeoutMS > -1) { message = consumer.receive(receiveTimeoutMS); } else { message = consumer.receive(); } if (message != null) { perConsumerReceivedMessages++; handleMessage(session, message, perConsumerReceivedMessages); } } } consumer.close(); } } catch (Exception ex) { LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { LOGGER.error("JMSException closing session", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { LOGGER.error("JMSException closing connection", e); } } } }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private javax.jms.Message retryableReceiveReply(Session session, Destination replyTo, String messageSelector) throws JMSException { Connection consumerConnection = null; //NOSONAR Session consumerSession = session; MessageConsumer messageConsumer = null; JMSException exception = null;//ww w . j a va 2s .c o m boolean isTemporaryReplyTo = replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic; long replyTimeout = isTemporaryReplyTo ? Long.MIN_VALUE : this.receiveTimeout < 0 ? Long.MAX_VALUE : System.currentTimeMillis() + this.receiveTimeout; try { do { try { messageConsumer = consumerSession.createConsumer(replyTo, messageSelector); javax.jms.Message reply = receiveReplyMessage(messageConsumer); if (reply == null) { if (replyTimeout > System.currentTimeMillis()) { throw new JMSException("Consumer closed before timeout"); } } return reply; } catch (JMSException e) { exception = e; if (logger.isDebugEnabled()) { logger.debug("Connection lost waiting for reply, retrying: " + e.getMessage()); } do { try { consumerConnection = createConnection(); consumerSession = createSession(consumerConnection); break; } catch (JMSException ee) { exception = ee; if (logger.isDebugEnabled()) { logger.debug("Could not reconnect, retrying: " + ee.getMessage()); } try { Thread.sleep(1000); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); return null; } } } while (replyTimeout > System.currentTimeMillis()); } } while (replyTimeout > System.currentTimeMillis()); if (isTemporaryReplyTo) { return null; } else { throw exception; } } finally { if (consumerSession != session) { JmsUtils.closeSession(consumerSession); JmsUtils.closeConnection(consumerConnection); } JmsUtils.closeMessageConsumer(messageConsumer); } }
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; MessageProducer msgProducer = null;/*w w w . j av a2 s .com*/ 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; }