List of usage examples for javax.jms MessageConsumer receive
Message receive(long timeout) throws JMSException;
From source file:org.codehaus.stomp.StompTest.java
public void testSendMessageWithContentLength() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame);//w w w.j a va 2 s . c o m frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); byte[] data = new byte[] { 1, 0, 0, 4 }; frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "content-length:" + data.length + "\n\n"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(frame.getBytes("UTF-8")); baos.write(data); baos.write('\0'); baos.flush(); sendFrame(baos.toByteArray()); BytesMessage message = (BytesMessage) consumer.receive(10000); Assert.assertNotNull(message); assertEquals(data.length, message.getBodyLength()); assertEquals(data[0], message.readByte()); assertEquals(data[1], message.readByte()); assertEquals(data[2], message.readByte()); assertEquals(data[3], message.readByte()); }
From source file:org.codehaus.stomp.StompTest.java
public void testTransactionCommit() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame);/* w w w . j a va2 s.com*/ String f = receiveFrame(1000); Assert.assertTrue(f.startsWith("CONNECTED")); frame = "BEGIN\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "transaction: tx1\n" + "\n\n" + "Hello World" + Stomp.NULL; sendFrame(frame); frame = "COMMIT\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); waitForFrameToTakeEffect(); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull("Should have received a message", message); }
From source file:org.springframework.integration.jms.JmsOutboundGateway.java
private javax.jms.Message receiveReplyMessage(MessageConsumer messageConsumer) throws JMSException { return (this.receiveTimeout >= 0) ? messageConsumer.receive(this.receiveTimeout) : messageConsumer.receive(); }
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 ww w .j ava 2 s . c o 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.apache.synapse.transport.jms.JMSSender.java
/** * Create a Consumer for the reply destination and wait for the response JMS message * synchronously. If a message arrives within the specified time interval, process it * through Axis2//from w w w .j av a 2s . c o m * @param session the session to use to listen for the response * @param replyDestination the JMS reply Destination * @param msgCtx the outgoing message for which we are expecting the response * @throws AxisFault on error */ private void waitForResponseAndProcess(Session session, Destination replyDestination, MessageContext msgCtx, String correlationId) throws AxisFault { try { MessageConsumer consumer = null; if (replyDestination instanceof Queue) { if (correlationId != null) { consumer = ((QueueSession) session).createReceiver((Queue) replyDestination, "JMSCorrelationID = '" + correlationId + "'"); } else { consumer = ((QueueSession) session).createReceiver((Queue) replyDestination); } } else { if (correlationId != null) { consumer = ((TopicSession) session).createSubscriber((Topic) replyDestination, correlationId, false); } else { consumer = ((TopicSession) session).createSubscriber((Topic) replyDestination); } } // how long are we willing to wait for the sync response long timeout = JMSConstants.DEFAULT_JMS_TIMEOUT; String waitReply = (String) msgCtx.getProperty(JMSConstants.JMS_WAIT_REPLY); if (waitReply != null) { timeout = Long.valueOf(waitReply).longValue(); } if (log.isDebugEnabled()) { log.debug("Waiting for a maximum of " + timeout + "ms for a response message to destination : " + replyDestination + " with JMS correlation ID : " + correlationId); } Message reply = consumer.receive(timeout); if (reply != null) { processSyncResponse(msgCtx, reply); } else { log.warn("Did not receive a JMS response within " + timeout + " ms to destination : " + replyDestination + " with JMS correlation ID : " + correlationId); } } catch (JMSException e) { handleException("Error creating consumer or receiving reply to : " + replyDestination, e); } }
From source file:org.codehaus.stomp.StompTest.java
public void testTransactionRollback() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame);//from w w w.j ava 2s . c o m String f = receiveFrame(1000); Assert.assertTrue(f.startsWith("CONNECTED")); frame = "BEGIN\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "transaction: tx1\n" + "\n" + "first message" + Stomp.NULL; sendFrame(frame); //rollback first message frame = "ABORT\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); frame = "BEGIN\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); frame = "SEND\n" + "destination:/queue/" + getQueueName() + "\n" + "transaction: tx1\n" + "\n" + "second message" + Stomp.NULL; sendFrame(frame); frame = "COMMIT\n" + "transaction: tx1\n" + "\n\n" + Stomp.NULL; sendFrame(frame); // This test case is currently failing waitForFrameToTakeEffect(); //only second msg should be received since first msg was rolled back TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("second message", message.getText().trim()); }
From source file:tools.ConsumerTool.java
@Override public void run() { Connection connection = null; Session session = null;/*from w w w . j a v a 2 s . c om*/ try { 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); } } } }