List of usage examples for javax.jms MessageConsumer receive
Message receive(long timeout) throws JMSException;
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
private void assertMessageIndicesOn(Destination queue, int... expectedIndices) throws Exception { MessageConsumer consumer = _session.createConsumer(queue); for (int i : expectedIndices) { TextMessage message = (TextMessage) consumer.receive(1000); assertNotNull("Expected message with index " + i, message); assertEquals("Expected message with index " + i, i, message.getIntProperty(INDEX)); assertEquals("Expected message content", getContentForMessageNumber(i), message.getText()); }//from ww w.ja va2s . c o m assertNull("Unexpected message encountered", consumer.receive(1000)); }
From source file:org.codehaus.stomp.StompTest.java
public void testRedeliveryWithClientAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame);/* w w w .j a v a2 s.c o m*/ frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SUBSCRIBE\n" + "destination:/queue/" + getQueueName() + "\n" + "ack:client\n\n" + Stomp.NULL; sendFrame(frame); sendMessage(getName()); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("MESSAGE")); frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); // message should be received since message was not acknowledged MessageConsumer consumer = session.createConsumer(queue); Message message = consumer.receive(1000); Assert.assertNotNull(message); Assert.assertTrue(message.getJMSRedelivered()); }
From source file:org.jbpm.bpel.integration.server.SoapHandler.java
protected ObjectMessage receiveResponse(Session jmsSession, Destination replyTo, String requestId, JbpmContext jbpmContext) throws JMSException, SOAPFaultException { // set up consumer String selector = "JMSCorrelationID='" + requestId + '\''; MessageConsumer consumer = jmsSession.createConsumer(replyTo, selector); try {/* w w w .j av a2 s.c om*/ // receive response message log.debug("listening for response: destination=" + replyTo + ", requestId=" + requestId); Number responseTimeout = getResponseTimeout(jbpmContext); ObjectMessage jmsResponse = (ObjectMessage) (responseTimeout != null ? consumer.receive(responseTimeout.longValue()) : consumer.receive()); // did a message arrive in time? if (jmsResponse == null) { log.debug("response timeout expired: destination=" + replyTo + ", requestId" + requestId); throw new SOAPFaultException(SoapBindConstants.SERVER_FAULTCODE, SoapBindConstants.TIMEOUT_FAULTSTRING, null, null); } jmsResponse.acknowledge(); log.debug("received response: " + RequestListener.messageToString(jmsResponse)); return jmsResponse; } finally { // release consumer resources consumer.close(); } }
From source file:org.codehaus.stomp.StompTest.java
public void testSubscribeWithClientAck() throws Exception { String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame);/* www .j a va2s. c o m*/ frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SUBSCRIBE\n" + "destination:/queue/" + getQueueName() + "\n" + "ack:client\n\n" + Stomp.NULL; sendFrame(frame); sendMessage(getName()); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("MESSAGE")); frame = "DISCONNECT\n" + "\n\n" + Stomp.NULL; sendFrame(frame); // message should be received since message was not acknowledged MessageConsumer consumer = session.createConsumer(queue); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertTrue(message.getJMSRedelivered()); }
From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java
/** * Function to retrieve message from specified message queue * * @param queueName Name of the queue//w w w . j a va 2 s . co m * @param timeout Timeout value (in milliseconds) * @return Retrieved message from the queue * @throws JMSException if error occurred */ public Message consumeMessageFromQueue(String queueName, long timeout) throws JMSException { Connection connection = null; Session session = null; MessageConsumer consumer = null; try { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); // Create a Connection connection = connectionFactory.createConnection(); connection.start(); connection.setExceptionListener(this); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue(queueName); // Create a MessageConsumer from the Session to the Topic or Queue consumer = session.createConsumer(destination); // Wait for a message return consumer.receive(timeout); } finally { if (consumer != null) { consumer.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
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 w w w. java 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; }
From source file:com.legstar.mq.client.AbstractCicsMQ.java
/** * A response is serialized as a header message part followed by data * message parts. This method creates a response message for the request. * <p/>/*w ww.j a va2s . c om*/ * The reply is correlated to the request by means of the JMS message ID * that was generated when we sent the request. That ID was attached to the * request object. * * @param request the request being serviced * @throws RequestException if receive fails */ public void recvResponse(final LegStarRequest request) throws RequestException { MessageConsumer consumer = null; try { String selector = "JMSCorrelationID='" + new String(request.getAttachment()) + "'"; if (_log.isDebugEnabled()) { _log.debug("Receiving response for Request:" + request.getID() + " on Connection:" + _connectionID + ". Selector: " + selector); } consumer = getJmsQueueSession().createConsumer(getJmsReplyQueue(), selector); Message jmsMessage = consumer.receive(getCicsMQEndpoint().getReceiveTimeout()); if (!(jmsMessage instanceof BytesMessage)) { throw new RequestException("Message received does not contain bytes"); } BytesMessage message = (BytesMessage) jmsMessage; message.reset(); /* Check that data length makes sense */ long dataLength = message.getBodyLength(); if (dataLength > Integer.MAX_VALUE) { throw new RequestException("Size of BytesMessage exceeds Integer.MAX_VALUE"); } request.setResponseMessage(createReplyMessage(message, (int) dataLength)); _lastUsedTime = System.currentTimeMillis(); if (_log.isDebugEnabled()) { _log.debug("Received response for Request:" + request.getID() + " on Connection:" + _connectionID + ". Selector: " + selector); } } catch (JMSException e) { throw new RequestException(e); } catch (HostReceiveException e) { throw new RequestException(e); } finally { if (consumer != null) { try { consumer.close(); } catch (JMSException e) { _log.error(e); } } } }
From source file:org.apache.james.queue.jms.JMSMailQueue.java
/** * <p>/*w w w . j a va2 s.c om*/ * 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.ccc.ccm.client.JMSTemplateAutowired.java
/** * Actually receive a message from the given consumer. * @param consumer the JMS MessageConsumer to receive with * @param timeout the receive timeout//from w w w .j a v a2 s. c o m * @return the JMS Message received, or <code>null</code> if none * @throws JMSException if thrown by JMS API methods */ private Message doReceive(MessageConsumer consumer, long timeout) throws JMSException { if (timeout == RECEIVE_TIMEOUT_NO_WAIT) { return consumer.receiveNoWait(); } else if (timeout > 0) { return consumer.receive(timeout); } else { return consumer.receive(); } }
From source file:org.springframework.jms.core.JmsTemplate.java
protected Message doReceive(Session session, Destination destination) throws JMSException { MessageConsumer consumer = createConsumer(session, destination); try {/*from w w w. j a va2 s . c o m*/ // use transaction timeout if available long timeout = getReceiveTimeout(); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager .getResource(getConnectionFactory()); if (conHolder != null && conHolder.hasTimeout()) { timeout = conHolder.getTimeToLiveInMillis(); } Message message = (timeout >= 0) ? consumer.receive(timeout) : consumer.receive(); if (session.getTransacted()) { if (conHolder == null) { // transacted session created by this template -> commit session.commit(); } } else if (message != null && isClientAcknowledge(session)) { message.acknowledge(); } return message; } finally { JmsUtils.closeMessageConsumer(consumer); } }