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; }
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; }
public static void main(final String[] args) throws Exception { InitialContext initialContext = null; Connection connection = null; try { // Step 1. Create an initial context to perform the JNDI lookup. final Properties env = new Properties(); env.put( Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); env.put(Context.PROVIDER_URL, "remote://localhost:4447"); env.put(Context.SECURITY_PRINCIPAL, "guest"); env.put(Context.SECURITY_CREDENTIALS, "password"); env.put("jboss.naming.client.ejb.context", true); initialContext = new InitialContext(env); // Step 2. Lookup the EJB SendMessageService service = (SendMessageService) initialContext.lookup( "java:ejb/SendMessageBean!org.hornetq.javaee.example.server.SendMessageService"); // Step 3. Create the DB table which will be updated service.createTable(); // Step 4. Invoke the sendAndUpdate method service.sendAndUpdate("This is a text message"); System.out.println("invoked the EJB service"); // Step 5. Lookup the JMS connection factory ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("jms/RemoteConnectionFactory"); // Step 6. Lookup the queue Queue queue = (Queue) initialContext.lookup("jms/queues/testQueue"); // Step 7. Create a connection, a session and a message consumer for the queue connection = cf.createConnection("guest", "password"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); // Step 8. Start the connection connection.start(); // Step 9. Receive the message sent by the EJB TextMessage messageReceived = (TextMessage) consumer.receive(5000); System.out.println( "Received message: " + messageReceived.getText() + " (" + messageReceived.getJMSMessageID() + ")"); } finally { // Step 10. Be sure to close the resources! if (initialContext != null) { initialContext.close(); } if (connection != null) { connection.close(); } } }
/** * Sends a message to a destination or manage subscriptions. If the the content type of the POST * is <code>application/x-www-form-urlencoded</code>, then the form parameters "destination", * "message" and "type" are used to pass a message or a subscription. If multiple messages or * subscriptions are passed in a single post, then additional parameters are shortened to "dN", * "mN" and "tN" where N is an index starting from 1. The type is either "send", "listen" or * "unlisten". For send types, the message is the text of the TextMessage, otherwise it is the ID * to be used for the subscription. If the content type is not <code> * application/x-www-form-urlencoded</code>, then the body of the post is sent as the message to a * destination that is derived from a query parameter, the URL or the default destination. * * @param request * @param response * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // lets turn the HTTP post into a JMS Message AjaxWebClient client = getAjaxWebClient(request); String messageIds = ""; synchronized (client) { if (LOG.isDebugEnabled()) { LOG.debug( "POST client=" + client + " session=" + request.getSession().getId() + " clientId=" + request.getParameter("clientId") + " info=" + request.getPathInfo() + " contentType=" + request.getContentType()); // dump(request.getParameterMap()); } int messages = 0; // loop until no more messages while (true) { // Get the message parameters. Multiple messages are encoded // with more compact parameter names. String destinationName = request.getParameter(messages == 0 ? "destination" : ("d" + messages)); if (destinationName == null) { destinationName = request.getHeader("destination"); } String message = request.getParameter(messages == 0 ? "message" : ("m" + messages)); String type = request.getParameter(messages == 0 ? "type" : ("t" + messages)); if (destinationName == null || message == null || type == null) { break; } try { Destination destination = getDestination(client, request, destinationName); if (LOG.isDebugEnabled()) { LOG.debug( messages + " destination=" + destinationName + " message=" + message + " type=" + type); LOG.debug(destination + " is a " + destination.getClass().getName()); } messages++; if ("listen".equals(type)) { AjaxListener listener = client.getListener(); Map<MessageAvailableConsumer, String> consumerIdMap = client.getIdMap(); Map<MessageAvailableConsumer, String> consumerDestinationNameMap = client.getDestinationNameMap(); client.closeConsumer(destination); // drop any existing // consumer. MessageAvailableConsumer consumer = (MessageAvailableConsumer) client.getConsumer(destination, request.getHeader(WebClient.selectorName)); consumer.setAvailableListener(listener); consumerIdMap.put(consumer, message); consumerDestinationNameMap.put(consumer, destinationName); if (LOG.isDebugEnabled()) { LOG.debug("Subscribed: " + consumer + " to " + destination + " id=" + message); } } else if ("unlisten".equals(type)) { Map<MessageAvailableConsumer, String> consumerIdMap = client.getIdMap(); Map<MessageAvailableConsumer, String> consumerDestinationNameMap = client.getDestinationNameMap(); MessageAvailableConsumer consumer = (MessageAvailableConsumer) client.getConsumer(destination, request.getHeader(WebClient.selectorName)); consumer.setAvailableListener(null); consumerIdMap.remove(consumer); consumerDestinationNameMap.remove(consumer); client.closeConsumer(destination); if (LOG.isDebugEnabled()) { LOG.debug("Unsubscribed: " + consumer); } } else if ("send".equals(type)) { TextMessage text = client.getSession().createTextMessage(message); appendParametersToMessage(request, text); client.send(destination, text); messageIds += text.getJMSMessageID() + "\n"; if (LOG.isDebugEnabled()) { LOG.debug("Sent " + message + " to " + destination); } } else { LOG.warn("unknown type " + type); } } catch (JMSException e) { LOG.warn("jms", e); } } } if ("true".equals(request.getParameter("poll"))) { try { // TODO return message IDs doMessages(client, request, response); } catch (JMSException e) { throw new ServletException("JMS problem: " + e, e); } } else { // handle simple POST of a message if (request.getContentLength() != 0 && (request.getContentType() == null || !request .getContentType() .toLowerCase() .startsWith("application/x-www-form-urlencoded"))) { try { Destination destination = getDestination(client, request); String body = getPostedMessageBody(request); TextMessage message = client.getSession().createTextMessage(body); appendParametersToMessage(request, message); client.send(destination, message); if (LOG.isDebugEnabled()) { LOG.debug("Sent to destination: " + destination + " body: " + body); } messageIds += message.getJMSMessageID() + "\n"; } catch (JMSException e) { throw new ServletException(e); } } response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().print(messageIds); } }
private void messageIDInHeader(boolean on) throws Exception { BridgeImpl bridge = null; Connection connSource = null; Connection connTarget = null; try { final int NUM_MESSAGES = 10; bridge = new BridgeImpl( cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, QualityOfServiceMode.AT_MOST_ONCE, 1, -1, null, null, on); bridge.start(); connSource = cf0.createConnection(); connTarget = cf1.createConnection(); log.trace("Sending " + NUM_MESSAGES + " messages"); List ids1 = new ArrayList(); Session sessSource = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSource.createProducer(sourceQueue); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = sessSource.createTextMessage("message" + i); // We add some headers to make sure they get passed through ok tm.setStringProperty("wib", "uhuh"); tm.setBooleanProperty("cheese", true); tm.setIntProperty("Sausages", 23); // We add some JMSX ones too tm.setStringProperty("JMSXGroupID", "mygroup543"); tm.setIntProperty("JMSXGroupSeq", 777); prod.send(tm); ids1.add(tm.getJMSMessageID()); } log.trace("Sent the first messages"); Session sessTarget = connTarget.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer cons = sessTarget.createConsumer(targetQueue); connTarget.start(); List msgs = new ArrayList(); for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(5000); assertNotNull(tm); assertEquals("message" + i, tm.getText()); assertEquals("uhuh", tm.getStringProperty("wib")); assertTrue(tm.getBooleanProperty("cheese")); assertEquals(23, tm.getIntProperty("Sausages")); assertEquals("mygroup543", tm.getStringProperty("JMSXGroupID")); assertEquals(777, tm.getIntProperty("JMSXGroupSeq")); if (on) { String header = tm.getStringProperty(JBossMessage.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST); assertNotNull(header); assertEquals(ids1.get(i), header); msgs.add(tm); } } if (on) { // Now we send them again back to the source Iterator iter = msgs.iterator(); List ids2 = new ArrayList(); while (iter.hasNext()) { Message msg = (Message) iter.next(); prod.send(msg); ids2.add(msg.getJMSMessageID()); } // And consume them again for (int i = 0; i < NUM_MESSAGES; i++) { TextMessage tm = (TextMessage) cons.receive(5000); assertNotNull(tm); assertEquals("message" + i, tm.getText()); assertEquals("uhuh", tm.getStringProperty("wib")); assertTrue(tm.getBooleanProperty("cheese")); assertEquals(23, tm.getIntProperty("Sausages")); assertEquals("mygroup543", tm.getStringProperty("JMSXGroupID")); assertEquals(777, tm.getIntProperty("JMSXGroupSeq")); String header = tm.getStringProperty(JBossMessage.JBOSS_MESSAGING_BRIDGE_MESSAGE_ID_LIST); assertNotNull(header); assertEquals(ids1.get(i) + "," + ids2.get(i), header); } } } finally { if (bridge != null) { bridge.stop(); } if (connSource != null) { connSource.close(); } if (connTarget != null) { connTarget.close(); } } }
public static void main(final String[] args) throws Exception { if (args.length != 2) { throw new IllegalArgumentException( "JMSBridgeExample needs 2 arguments: <source server> <target server>"); } String sourceServer = args[0]; String targetServer = args[1]; System.out.println( "client will publish messages to " + sourceServer + " and receives message from " + targetServer); // Step 1. Create JNDI contexts for source and target servers InitialContext sourceContext = JMSBridgeExample.createContext(sourceServer); InitialContext targetContext = JMSBridgeExample.createContext(targetServer); Hashtable<String, String> sourceJndiParams = createJndiParams(sourceServer); Hashtable<String, String> targetJndiParams = createJndiParams(targetServer); // Step 2. Create and start a JMS Bridge // Note, the Bridge needs a transaction manager, in this instance we will use the JBoss TM JMSBridge jmsBridge = new JMSBridgeImpl( new JNDIConnectionFactoryFactory(sourceJndiParams, "/source/ConnectionFactory"), new JNDIConnectionFactoryFactory(targetJndiParams, "/target/ConnectionFactory"), new JNDIDestinationFactory(sourceJndiParams, "/source/topic"), new JNDIDestinationFactory(targetJndiParams, "/target/queue"), null, null, null, null, null, 5000, 10, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 1, -1, null, null, true); jmsBridge.setTransactionManager(new TransactionManagerImple()); Connection sourceConnection = null; Connection targetConnection = null; try { jmsBridge.start(); // Step 3. Lookup the *source* JMS resources ConnectionFactory sourceConnectionFactory = (ConnectionFactory) sourceContext.lookup("/client/ConnectionFactory"); Topic sourceTopic = (Topic) sourceContext.lookup("/source/topic"); // Step 4. Create a connection, a session and a message producer for the *source* topic sourceConnection = sourceConnectionFactory.createConnection(); Session sourceSession = sourceConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer sourceProducer = sourceSession.createProducer(sourceTopic); // Step 5. Create and send a text message to the *source* queue TextMessage message = sourceSession.createTextMessage( "this is a text message sent at " + System.currentTimeMillis()); sourceProducer.send(message); System.out.format( "Sent message to %s: %s\n", ((Topic) message.getJMSDestination()).getTopicName(), message.getText()); System.out.format("Message ID : %s\n", message.getJMSMessageID()); // Step 6. Close the *source* connection sourceConnection.close(); // Step 7. Lookup the *target* JMS resources ConnectionFactory targetConnectionFactory = (ConnectionFactory) targetContext.lookup("/client/ConnectionFactory"); Queue targetQueue = (Queue) targetContext.lookup("/target/queue"); // Step 8. Create a connection, a session and a message consumer for the *target* queue targetConnection = targetConnectionFactory.createConnection(); Session targetSession = targetConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer targetConsumer = targetSession.createConsumer(targetQueue); // Step 9. Start the connection to receive messages from the *target* queue targetConnection.start(); // Step 10. Receive a message from the *target* queue TextMessage messageReceived = (TextMessage) targetConsumer.receive(5000); System.out.format( "\nReceived from %s: %s\n", ((Queue) messageReceived.getJMSDestination()).getQueueName(), messageReceived.getText()); // Step 11. Display the received message's ID and this "bridged" message ID System.out.format("Message ID : %s\n", messageReceived.getJMSMessageID()); System.out.format( "Bridged Message ID : %s\n", messageReceived.getStringProperty("HQ_BRIDGE_MSG_ID_LIST")); } finally { // Step 12. Be sure to close the resources! if (jmsBridge != null) { jmsBridge.stop(); } if (sourceContext != null) { sourceContext.close(); } if (targetContext != null) { targetContext.close(); } if (sourceConnection != null) { sourceConnection.close(); } if (targetConnection != null) { targetConnection.close(); } } }
public void doTestDLQAfterBlock(ActiveMQDestination destination) throws Exception { ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory(); RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy(); // Immediately sent to the DLQ on rollback, no redelivery redeliveryPolicy.setMaximumRedeliveries(0); factory.setRedeliveryPolicy(redeliveryPolicy); // Separate connection for consumer so it will not be blocked by filler thread // sending when it blocks connection = (ActiveMQConnection) factory.createConnection(); connections.add(connection); connection.setClientID("someId"); connection.start(); final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = destination.isQueue() ? consumerSession.createConsumer(destination) : consumerSession.createDurableSubscriber((Topic) destination, "Durable"); connection = (ActiveMQConnection) factory.createConnection(); connections.add(connection); connection.start(); final Session session = connection.createSession(true, Session.SESSION_TRANSACTED); final MessageProducer producer = session.createProducer(destination); final AtomicBoolean done = new AtomicBoolean(true); final AtomicBoolean keepGoing = new AtomicBoolean(true); final CountDownLatch fillerStarted = new CountDownLatch(1); final AtomicLong sent = new AtomicLong(0); Thread thread = new Thread("Filler") { int i; @Override public void run() { while (keepGoing.get()) { done.set(false); fillerStarted.countDown(); try { producer.send(session.createTextMessage(oneKb + ++i)); if (i % 10 == 0) { session.commit(); sent.getAndAdd(10); LOG.info("committed/sent: " + sent.get()); } LOG.info("sent: " + i); } catch (JMSException e) { } } } }; thread.start(); assertTrue("filler started..", fillerStarted.await(20, TimeUnit.SECONDS)); waitForBlocked(done); // consume and rollback some so message gets to DLQ connection = (ActiveMQConnection) factory.createConnection(); connections.add(connection); connection.start(); TextMessage msg; int received = 0; for (; received < sent.get(); ++received) { msg = (TextMessage) consumer.receive(4000); if (msg == null) { LOG.info("received null on count: " + received); break; } LOG.info("received: " + received + ", msg: " + msg.getJMSMessageID()); if (received % 5 == 0) { if (received % 3 == 0) { // force the use of the DLQ which will use some more store LOG.info("rollback on : " + received); consumerSession.rollback(); } else { LOG.info("commit on : " + received); consumerSession.commit(); } } } LOG.info("Done:: sent: " + sent.get() + ", received: " + received); keepGoing.set(false); assertTrue("some were sent:", sent.get() > 0); assertEquals("received what was committed", sent.get(), received); }