protected String consume() throws Exception { Connection con = null; MessageConsumer c = consumer; if (connectionPerMessage) { con = factory.createConnection(); con.start(); Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); c = s.createConsumer(getConsumeDestination()); } TextMessage result = (TextMessage) c.receive(timeout); if (result != null) { if (audit.isDuplicate(result.getJMSMessageID())) { throw new JMSException("Received duplicate " + result.getText()); } if (!audit.isInOrder(result.getJMSMessageID())) { throw new JMSException("Out of order " + result.getText()); } if (connectionPerMessage) { Thread.sleep(SLEEP_TIME); // give the broker a chance con.close(); } } return result != null ? result.getText() : null; }
@Override public void onMessageDo(Message msg) throws Exception { String type = msg.getStringProperty("type"); if (ResmMessageListener.TYPE_OBJECT_SYNC.equals(type)) { TextMessage text = (TextMessage) msg; int id = StringUtil.parseInt(text.getText(), -1); logger.debug("接收到同步消息:资源ID=" + text.getText()); if (id > 0) ServiceManager.getResourceUpdateService().syncResource(id); } else if (ResmMessageListener.TYPE_CACHE_ADD.equals(type)) { ObjectMessage object = (ObjectMessage) msg; String cacheName = msg.getStringProperty("cache"); CacheableObject obj = (CacheableObject) object.getObject(); logger.debug("接收到缓存增加消息:" + cacheName + " " + obj.getClass().getName()); obj.onDeserialize(); obj.dump(); CacheManager.addCache(cacheName, obj); } else if (ResmMessageListener.TYPE_CACHE_REMOVE.equals(type)) { ObjectMessage object = (ObjectMessage) msg; String cacheName = msg.getStringProperty("cache"); CacheableObject obj = (CacheableObject) object.getObject(); logger.debug("接收到缓存删除消息:" + cacheName + " " + obj.getClass().getName()); obj.onDeserialize(); obj.dump(); CacheManager.removeCache(cacheName, obj); } else { System.out.println(msg.toString()); } }
private void doTestIdleConsumer(boolean transacted) throws Exception { Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Msg1")); producer.send(session.createTextMessage("Msg2")); if (transacted) { session.commit(); } // now lets receive it MessageConsumer consumer = session.createConsumer(queue); session.createConsumer(queue); TextMessage answer = (TextMessage) consumer.receive(5000); assertEquals("Should have received a message!", answer.getText(), "Msg1"); if (transacted) { session.commit(); } // this call would return null if prefetchSize > 0 answer = (TextMessage) consumer.receive(5000); assertEquals("Should have received a message!", answer.getText(), "Msg2"); if (transacted) { session.commit(); } answer = (TextMessage) consumer.receiveNoWait(); assertNull("Should have not received a message!", answer); }
public void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " + msg.getText()); long sleepTime = msg.getLongProperty("sleeptime"); System.out.println("Sleeping for : " + sleepTime + " milli seconds "); Thread.sleep(sleepTime); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); TextMessage message = queueSession.createTextMessage(); message.setText("REPLIED:" + msg.getText()); message.setIntProperty("replyid", msg.getIntProperty("id")); System.out.println("Sending message: " + message.getText()); queueSender.send(message); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); } catch (Throwable te) { te.printStackTrace(); } finally { try { queueSession.close(); queueConnection.close(); } catch (Exception e) { } } } // onMessage
/** Make sure redelivered flag is set on redelivery via rollback */ @Test public void testRedeliveredQueue() throws Exception { Connection conn = null; try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = sess.createProducer(queue1); MessageConsumer consumer = sess.createConsumer(queue1); conn.start(); Message mSent = sess.createTextMessage("igloo"); producer.send(mSent); sess.commit(); TextMessage mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); ProxyAssertSupport.assertFalse(mRec.getJMSRedelivered()); sess.rollback(); mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); ProxyAssertSupport.assertTrue(mRec.getJMSRedelivered()); sess.commit(); } finally { if (conn != null) { conn.close(); } } }
@Test public void testListeners() throws Exception { TestBean testBean1 = context.getBean("testBean1", TestBean.class); TestBean testBean2 = context.getBean("testBean2", TestBean.class); TestMessageListener testBean3 = context.getBean("testBean3", TestMessageListener.class); assertNull(testBean1.getName()); assertNull(testBean2.getName()); assertNull(testBean3.message); TextMessage message1 = mock(TextMessage.class); given(message1.getText()).willReturn("Test1"); MessageListener listener1 = getListener("listener1"); listener1.onMessage(message1); assertEquals("Test1", testBean1.getName()); TextMessage message2 = mock(TextMessage.class); given(message2.getText()).willReturn("Test2"); MessageListener listener2 = getListener("listener2"); listener2.onMessage(message2); assertEquals("Test2", testBean2.getName()); TextMessage message3 = mock(TextMessage.class); MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0"); listener3.onMessage(message3); assertSame(message3, testBean3.message); }
public void onMessage(Message message) { try { TextMessage msg = (TextMessage) message; System.out.format("Message: [%s] received by %s\n", msg.getText(), name); messageReceiverMap.put(msg.getText(), name); } catch (JMSException e) { e.printStackTrace(); } }
public void reset( IOperationContext context, String statements, String statementsFormat, java.util.Collection<org.openanzo.rdf.Statement> checks, java.io.Writer output) throws AnzoException { if (!combusConnection.isConnected()) { throw new AnzoException(ExceptionConstants.CLIENT.CLIENT_NOT_CONNECTED); // combusConnection.connect(); } long start = 0; if (stats.isEnabled()) { start = System.currentTimeMillis(); } try { TextMessage request = combusConnection.createMessage(); org.openanzo.combus.JMSMessageWrapper messageWrapper = new org.openanzo.combus.JMSMessageWrapper(request); messageWrapper.setProperty(SerializationConstants.operation, RESET); if (context.getAttribute(SerializationConstants.userDescription) != null) { messageWrapper.setProperty( SerializationConstants.userDescription, context.getAttribute(SerializationConstants.userDescription, String.class)); } messageWrapper.setProperty(PARAM_STATEMENTSFormat, statementsFormat); messageWrapper.setBody(statements); messageWrapper.setProperty( PARAM_CHECKSFormat, org.openrdf.rio.RDFFormat.TRIG.getDefaultMIMEType()); if (checks != null) org.openanzo.services.serialization.transport.StatementsSerializer.serialize( checks, PARAM_CHECKS, org.openrdf.rio.RDFFormat.TRIG.getDefaultMIMEType(), messageWrapper); TextMessage response = combusConnection.requestResponse( context, org.openanzo.datasource.IResetService.SERVICE_NAME, request, getTimeout()); try { if (response != null && response.getText() != null) { output.write(response.getText()); output.flush(); } } catch (IOException ioe) { throw new AnzoException(ExceptionConstants.IO.WRITE_ERROR, ioe); } catch (JMSException jmsex) { throw new AnzoException(ExceptionConstants.COMBUS.JMS_MISSING_MESSAGE_PARAMETER, jmsex); } } finally { if (stats.isEnabled()) { stats.use("reset", (System.currentTimeMillis() - start)); } } }
public void onMessage(Message message) { TextMessage msg = (TextMessage) message; try { System.out.println("received: " + msg.getText()); if (msg.getText().equals("exit")) { AsyncSimpleConsumer.catchExit = true; } } catch (JMSException ex) { ex.printStackTrace(); } }
/** * Make sure redelivered flag is set on redelivery via rollback, different setup: we close the * rolled back session and we receive the message whose acknowledgment was cancelled on a new * session. */ @Test public void testRedeliveredQueue2() throws Exception { Connection conn = null; try { conn = createConnection(); Session sendSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sendSession.createProducer(queue1); prod.send(sendSession.createTextMessage("a message")); conn.close(); conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer cons = sess.createConsumer(queue1); conn.start(); TextMessage tm = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(tm); ProxyAssertSupport.assertEquals("a message", tm.getText()); ProxyAssertSupport.assertFalse(tm.getJMSRedelivered()); ProxyAssertSupport.assertEquals(1, tm.getIntProperty("JMSXDeliveryCount")); sess.rollback(); sess.close(); Session sess2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); cons = sess2.createConsumer(queue1); tm = (TextMessage) cons.receive(1000); ProxyAssertSupport.assertEquals("a message", tm.getText()); ProxyAssertSupport.assertEquals(2, tm.getIntProperty("JMSXDeliveryCount")); ProxyAssertSupport.assertTrue(tm.getJMSRedelivered()); } finally { if (conn != null) { conn.close(); } } }
/** * test messages are acknowledged and recovered properly * * @throws Exception */ public void testClientAcknowledge() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(destination); Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); // send some messages TextMessage sent1 = producerSession.createTextMessage(); sent1.setText("msg1"); sent1.setStringProperty("str", "1"); producer.send(sent1); TextMessage sent2 = producerSession.createTextMessage(); sent2.setText("msg2"); sent2.setStringProperty("str", "2"); producer.send(sent2); TextMessage sent3 = producerSession.createTextMessage(); sent2.setText("msg3"); sent2.setStringProperty("str", "3"); producer.send(sent3); TextMessage msgTest = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); System.out.println("msgTest::" + msgTest + " // " + msgTest.getText()); TextMessage rec2 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); System.out.println("msgTest::" + rec2 + " // " + rec2.getText()); assertNull(consumer.receiveNoWait()); // ack rec2 rec2.acknowledge(); TextMessage sent4 = producerSession.createTextMessage(); sent4.setText("msg4"); producer.send(sent4); TextMessage rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); assertTrue(rec4.equals(sent4)); consumerSession.recover(); rec4 = (TextMessage) consumer.receive(RECEIVE_TIMEOUT); assertTrue(rec4.equals(sent4)); assertTrue(rec4.getJMSRedelivered()); rec4.acknowledge(); connection.close(); }
@Test public void testReceivedRollbackTopic() throws Exception { Connection conn = null; try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = sess.createProducer(ActiveMQServerTestCase.topic1); MessageConsumer consumer = sess.createConsumer(ActiveMQServerTestCase.topic1); conn.start(); log.info("sending message first time"); TextMessage mSent = sess.createTextMessage("igloo"); producer.send(mSent); log.info("sent message first time"); sess.commit(); TextMessage mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); sess.commit(); log.info("sending message again"); mSent.setText("rollback"); producer.send(mSent); log.info("sent message again"); sess.commit(); mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("rollback", mRec.getText()); sess.rollback(); TextMessage mRec2 = (TextMessage) consumer.receive(2000); sess.commit(); ProxyAssertSupport.assertNotNull(mRec2); ProxyAssertSupport.assertEquals(mRec.getText(), mRec2.getText()); } finally { if (conn != null) { conn.close(); } } }
@Test public void testReceivedRollbackQueue() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = sess.createProducer(queue1); MessageConsumer consumer = sess.createConsumer(queue1); conn.start(); TextMessage mSent = sess.createTextMessage("igloo"); producer.send(mSent); log.trace("sent1"); sess.commit(); TextMessage mRec = (TextMessage) consumer.receive(1000); ProxyAssertSupport.assertNotNull(mRec); log.trace("Got 1"); ProxyAssertSupport.assertNotNull(mRec); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); sess.commit(); mSent.setText("rollback"); producer.send(mSent); sess.commit(); log.trace("Receiving 2"); mRec = (TextMessage) consumer.receive(1000); ProxyAssertSupport.assertNotNull(mRec); log.trace("Received 2"); ProxyAssertSupport.assertNotNull(mRec); ProxyAssertSupport.assertEquals("rollback", mRec.getText()); sess.rollback(); TextMessage mRec2 = (TextMessage) consumer.receive(1000); ProxyAssertSupport.assertNotNull(mRec2); ProxyAssertSupport.assertEquals("rollback", mRec2.getText()); sess.commit(); ProxyAssertSupport.assertEquals(mRec.getText(), mRec2.getText()); conn.close(); }
/** * Receive a message from destination with timeout. * * @param destinationName destinationName * @param timeout timeout * @return message */ public String receiveTextMessageFromDestinationWithTimeout( final String destinationName, final int timeout) { if (!this.isConnected()) { throw new JmsNotConnectedException("Not connected"); } MessageConsumer consumer = getConsumer(destinationName); TextMessage message; try { if (timeout == 0) { message = (TextMessage) consumer.receiveNoWait(); } else { message = (TextMessage) consumer.receive(timeout); } if (message != null) { if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) { message.acknowledge(); } return message.getText(); } else { return null; } } catch (JMSException e) { throw new IllegalStateException("Unable to receive message from " + destinationName, e); } }
/** @see MessageListener#onMessage(Message) */ public void onMessage(Message message) { TextMessage tmsg = null; tmsg = (TextMessage) message; String parameter0 = null; String parameter1 = null; System.out.println("<sms module>"); // parsing message into opcode, and parameters String preParse; try { preParse = tmsg.getText(); String[] postParse = preParse.split("[|]+"); parameter0 = postParse[0]; parameter1 = postParse[1]; } catch (JMSException e1) { e1.printStackTrace(); } try { // TODO sendSMS(parameter0, parameter1); } catch (Exception e) { e.printStackTrace(); } }
public static Map<String, Object> parse(Message message) throws JMSException { if (message instanceof TextMessage) { TextMessage msg = (TextMessage) message; String text = msg.getText(); Date date = msg.getJMSTimestamp() == 0 ? new Date() : new Date(msg.getJMSTimestamp()); Map<String, Object> m = new HashMap<String, Object>(); m.put("_time", date); m.put("_msg_id", msg.getJMSMessageID()); m.put("line", text); return m; } else if (message instanceof MapMessage) { MapMessage msg = (MapMessage) message; Date date = msg.getJMSTimestamp() == 0 ? new Date() : new Date(msg.getJMSTimestamp()); Map<String, Object> m = new HashMap<String, Object>(); m.put("_time", date); m.put("_msg_id", msg.getJMSMessageID()); @SuppressWarnings("unchecked") Enumeration<String> e = msg.getPropertyNames(); while (e.hasMoreElements()) { String key = e.nextElement(); Object val = msg.getObjectProperty(key); m.put(key, val); } return m; } return null; }
@Override public void run() { try { // Create a ConncetionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://MSPL-08-09-D158:61616"); // Create a Connection Connection connection = connectionFactory.createConnection(); connection.start(); // Create a session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue("HELLOWORLD.TESTQ"); // Create a MessageProducer from the Session to the Topic or Queue MessageConsumer consumer = session.createConsumer(destination); Message message = consumer.receive(1000); if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); System.out.println("Received : " + text); } else { System.out.println("Received : " + message); } consumer.close(); session.close(); connection.close(); } catch (Exception e) { System.out.println("Error Occure : " + e); e.printStackTrace(); } }
protected void writeMessageResponse( PrintWriter writer, Message message, String id, String destinationName) throws JMSException, IOException { writer.print("<response id='"); writer.print(id); writer.print("'"); if (destinationName != null) { writer.print(" destination='" + destinationName + "' "); } writer.print(">"); if (message instanceof TextMessage) { TextMessage textMsg = (TextMessage) message; String txt = textMsg.getText(); if (txt != null) { if (txt.startsWith("<?")) { txt = txt.substring(txt.indexOf("?>") + 2); } writer.print(txt); } } else if (message instanceof ObjectMessage) { ObjectMessage objectMsg = (ObjectMessage) message; Object object = objectMsg.getObject(); if (object != null) { writer.print(object.toString()); } } writer.println("</response>"); }
@Test public void testDelay() throws Exception { JMSProducer producer = context.createProducer(); JMSConsumer consumer = context.createConsumer(queue1); producer.setDeliveryDelay(500); long timeStart = System.currentTimeMillis(); String strRandom = newXID().toString(); producer.send(queue1, context.createTextMessage(strRandom)); TextMessage msg = (TextMessage) consumer.receive(2500); assertNotNull(msg); long actualDelay = System.currentTimeMillis() - timeStart; assertTrue( "delay is not working, actualDelay=" + actualDelay, actualDelay >= 500 && actualDelay < 2000); assertEquals(strRandom, msg.getText()); }
public void testJMSXGroupIdCanBeSet() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "JMSXGroupID: TEST\n\n" + "Hello World" + Stomp.NULL; sendFrame(frame); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("Hello World", message.getText()); // differ from StompConnect Assert.assertEquals("TEST", message.getStringProperty("JMSXGroupID")); }
public void testSendMessage() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL; sendFrame(frame); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("Hello World", message.getText()); // Assert default priority 4 is used when priority header is not set Assert.assertEquals("getJMSPriority", 4, message.getJMSPriority()); // Make sure that the timestamp is valid - should // be very close to the current time. long tnow = System.currentTimeMillis(); long tmsg = message.getJMSTimestamp(); Assert.assertTrue(Math.abs(tnow - tmsg) < 1000); }
public static void main(String[] args) throws JMSException { // Getting JMS connection from the server ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); // Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Getting the queue 'JMSBEGINQUEUE' Destination destination = session.createQueue(subject); // MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination); // Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive(); // There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println("Received message '" + textMessage.getText() + "'"); } connection.close(); }
@Override public void run() { this.threadName = Thread.currentThread().getName(); int numMessages = Integer.parseInt( appProperties.getProperty( Constants.PROP_NUM_MESSAGES, Constants.PROP_NUM_MESSAGES_DEFAULT)); boolean printMessages = Boolean.parseBoolean( appProperties.getProperty( Constants.PROP_CONSUMER_PRINT_MESSAGES, Constants.PROP_CONSUMER_PRINT_MESSAGES_DEFAULT)); try { while (true) { TextMessage message = (TextMessage) consumer.receive(); int messageNumber = messageCounter.increment(); // Message can be null if another thread is making application exit if ((message != null) && printMessages) { String prefix = threadName + ": " + "message " + messageNumber; logger.info("{} - {}", prefix, message.getText()); } if (messageNumber == numMessages) break; } } catch (JMSException e) { logger.error("{} halted: {}", threadName, StackTraceUtil.getStackTrace(e)); } finally { if (privateConnection != null) try { privateConnection.close(); } catch (Exception e) { } } }
@Override public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); if ("SHUTDOWN".equals(text)) { LOG.info("Got the SHUTDOWN command -> exit"); producer.send(session.createTextMessage("SHUTDOWN is being performed")); } else if ("REPORT".equals(text)) { long time = System.currentTimeMillis() - start; producer.send(session.createTextMessage("Received " + count + " in " + time + "ms")); try { Thread.sleep(500); } catch (InterruptedException e) { LOG.info("Wait for the report message to be sent was interrupted"); } count = 0; } else { if (count == 0) { start = System.currentTimeMillis(); } count++; LOG.info("Received " + count + " messages."); } } } catch (JMSException e) { LOG.error("Got an JMS Exception handling message: " + message, e); } }
@JmsListener(destination = "raulQueue", containerFactory = "jmsConFactory") public void processMessages(Message msg) { try { if (msg instanceof TextMessage) { TextMessage txtMsg = (TextMessage) msg; System.out.println("Receiving message " + txtMsg.getText()); } /*ConnectionFactory connFactory=new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection connection=connFactory.createConnection(); Session session=connection.createSession(true, 0); Destination dest=new ActiveMQQueue("raulQueue"); MessageConsumer consumer=session.createConsumer(dest); TextMessage msg1=(TextMessage)consumer.receive(); System.out.println("Msg1 " +msg1.getText()); Thread.sleep(5000); TextMessage msg2=(TextMessage)consumer.receive(); System.out.println("Msg2 " +msg2.getText()); Thread.sleep(5000); TextMessage msg3=(TextMessage)consumer.receive(); System.out.println("Msg3 " +msg3.getText()); session.commit(); session.close();*/ } catch (JMSException e) { // TODO: handle exception } }
public void onMessage(final Message message) { try { // Step 9. We know the client is sending a text message so we cast TextMessage textMessage = (TextMessage) message; // Step 10. get the text from the message. String text = textMessage.getText(); System.out.println("message " + text + " received"); if (!textMessage.getJMSRedelivered()) { // Step 11. On first delivery get the transaction, take a look, and throw an exception Transaction tx = tm.getTransaction(); if (tx != null) { System.out.println("something is wrong, there should be no global transaction: " + tx); } else { System.out.println( "there is no global transaction, although the message delivery is using a local transaction"); System.out.println("let's throw an exception and see what happens"); throw new RuntimeException("DOH!"); } } else { // Step 12. Print the message System.out.println( "The message was redelivered since the message delivery used a local transaction"); } } catch (JMSException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } }
public void testSendMessageWithReceipt() throws Exception { MessageConsumer consumer = session.createConsumer(queue); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SEND\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n" + "receipt: 1234\n\n" + "Hello World" + Stomp.NULL; sendFrame(frame); String f = receiveFrame(10000); Assert.assertTrue(f.startsWith("RECEIPT")); Assert.assertTrue(f.indexOf("receipt-id:1234") >= 0); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("Hello World", message.getText()); // Make sure that the timestamp is valid - should // be very close to the current time. long tnow = System.currentTimeMillis(); long tmsg = message.getJMSTimestamp(); Assert.assertTrue(Math.abs(tnow - tmsg) < 1000); }
public void doSend() { QueueSession queueSession = null; QueueSender queueSender = null; TextMessage message = null; if (doSetup()) { try { queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); queueSender = queueSession.createSender(queue); message = queueSession.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); queueSender.send(message); } /* * Send a non-text control message indicating end of messages. */ queueSender.send(queueSession.createMessage()); } catch (JMSException e) { log.error("JMS Send Exception occurred: " + e.toString()); } finally { doCleanup(); } } }
public void testSendMessageWithCustomHeadersAndSelector() throws Exception { MessageConsumer consumer = session.createConsumer(queue, "foo = 'abc'"); String frame = "CONNECT\n" + "login: brianm\n" + "passcode: wombats\n\n" + Stomp.NULL; sendFrame(frame); frame = receiveFrame(10000); Assert.assertTrue(frame.startsWith("CONNECTED")); frame = "SEND\n" + "foo:abc\n" + "bar:123\n" + "destination:" + getQueuePrefix() + getQueueName() + "\n\n" + "Hello World" + Stomp.NULL; sendFrame(frame); TextMessage message = (TextMessage) consumer.receive(1000); Assert.assertNotNull(message); Assert.assertEquals("Hello World", message.getText()); Assert.assertEquals("foo", "abc", message.getStringProperty("foo")); Assert.assertEquals("bar", "123", message.getStringProperty("bar")); }
/** use auto acknowledge which automatically has the client say OK */ public void doReceiveAuto() { if (doSetup()) { try { queueConnection = queueConnectionFactory.createQueueConnection(); QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueReceiver queueReceiver = queueSession.createReceiver(queue); queueConnection.start(); while (true) { Message m = queueReceiver.receive(1); if (m != null) { if (m instanceof TextMessage) { TextMessage message = (TextMessage) m; log.debug("Reading message:==> " + message.getText()); } else { break; } } } } catch (JMSException e) { log.error("Listen Exception occurred: " + e.toString()); } finally { doCleanup(); } } }