public static void main(String[] args) { try { // Gets the JgetTopicName()NDI context Context jndiContext = new InitialContext(); // Looks up the administered objects ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory"); Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue"); // Creates the needed artifacts to connect to the queue Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); connection.start(); // Loops to receive the messages System.out.println("\nInfinite loop. Waiting for a message..."); while (true) { TextMessage message = (TextMessage) consumer.receive(); System.out.println("Message received: " + message.getText()); } } catch (Exception e) { e.printStackTrace(); } }
/** * 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); } }
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(); }
@Test public void testReceiveMessageTimeout() throws JMSException { JmsMessageReceiver receiver = new JmsMessageReceiver(); receiver.setConnectionFactory(connectionFactory); receiver.setDestination(destination); reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer); expect(connectionFactory.createConnection()).andReturn(connection).once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.getTransacted()).andReturn(false).once(); expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once(); expect(session.createConsumer(destination, null)).andReturn(messageConsumer).once(); expect(messageConsumer.receive(5000L)).andReturn(null).once(); connection.start(); expectLastCall().once(); replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer); try { receiver.receive(); } catch (ActionTimeoutException e) { Assert.assertTrue( e.getMessage().startsWith("Action timed out while receiving JMS message on")); return; } Assert.fail( "Missing " + CitrusRuntimeException.class + " because of receiveing message timeout"); }
private void consume() { try { consumer = session.createConsumer(queue); message = consumer.receive(); } catch (JMSException e) { e.printStackTrace(); } }
public static void main(String args[]) { Connection connection = null; try { // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); connection = factory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); LOG.info( "Start consuming messages from " + destination.toString() + " with " + MESSAGE_TIMEOUT_MILLISECONDS + "ms timeout"); // Synchronous message consumer int i = 1; while (true) { Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); LOG.info("Got " + (i++) + ". message: " + text); } } else { break; } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error("Error receiving message", t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error("Error closing connection", e); } } } }
public Value receive(Env env, @Optional("1") long timeout) throws JMSException { Message message = _consumer.receive(timeout); if (message == null) return BooleanValue.FALSE; if (message instanceof ObjectMessage) { Object object = ((ObjectMessage) message).getObject(); return env.wrapJava(object); } else if (message instanceof TextMessage) { return env.createString(((TextMessage) message).getText()); } else if (message instanceof StreamMessage) { Object object = ((StreamMessage) message).readObject(); return env.wrapJava(object); } else if (message instanceof BytesMessage) { BytesMessage bytesMessage = (BytesMessage) message; int length = (int) bytesMessage.getBodyLength(); StringValue bb = env.createBinaryBuilder(length); TempBuffer tempBuffer = TempBuffer.allocate(); int sublen; while (true) { sublen = bytesMessage.readBytes(tempBuffer.getBuffer()); if (sublen > 0) bb.append(tempBuffer.getBuffer(), 0, sublen); else break; } TempBuffer.free(tempBuffer); return bb; } else if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Enumeration mapNames = mapMessage.getMapNames(); ArrayValue array = new ArrayValueImpl(); while (mapNames.hasMoreElements()) { String name = mapNames.nextElement().toString(); Object object = mapMessage.getObject(name); array.put(env.createString(name), env.wrapJava(object)); } return array; } else { return BooleanValue.FALSE; } }
@Override public T take() throws FalconException { try { TextMessage textMessage = (TextMessage) consumer.receive(); T event = new RerunEventFactory<T>() .getRerunEvent(textMessage.getStringProperty("TYPE"), textMessage.getText()); LOG.debug("Dequeued Message: {}", event.toString()); return event; } catch (Exception e) { LOG.error("Error getting the message from ActiveMQ", e); throw new FalconException("Error getting the message from ActiveMQ: ", e); } }
public static void main(String[] args) throws JMSException { String user = env("ACTIVEMQ_USER", ""); String password = env("ACTIVEMQ_PASSWORD", ""); String host = env("ACTIVEMQ_HOST", "localhost"); int port = Integer.parseInt(env("ACTIVEMQ_PORT", "61616")); String destination = arg(args, 0, "foo.bar"); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://" + host + ":" + port); Connection connection = factory.createConnection(user, password); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = new ActiveMQQueue(destination); MessageConsumer consumer = session.createConsumer(dest); long start = System.currentTimeMillis(); long count = 1; System.out.println("Waiting for messages..."); while (true) { Message msg = consumer.receive(); if (msg instanceof TextMessage) { String body = ((TextMessage) msg).getText(); if ("THE.END".equals(body)) { long diff = System.currentTimeMillis() - start; System.out.println( String.format("Received %d in %.2f seconds", count, (1.0 * diff / 1000.0))); break; } else { if (count != msg.getIntProperty("id")) { System.out.println("mismatch: " + count + "!=" + msg.getIntProperty("id")); } count = msg.getIntProperty("id"); if (count == 0) { start = System.currentTimeMillis(); } if (count % 1000 == 0) { System.out.println(String.format("Received %d messages.", count)); } count++; } } else { System.out.println("Unexpected message type: " + msg.getClass()); } } connection.close(); }
public static void main(String[] args) { String url = BROKER_URL; if (args.length > 0) { url = args[0].trim(); } System.out.println( "\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 + "s"); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url); Connection connection = null; try { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); Queue destination = session.createQueue("test-queue?consumer.exclusive=true"); MessageConsumer consumer = session.createConsumer(destination); int i = 0; while (true) { Message message = consumer.receive(TIMEOUT); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); System.out.println("Got " + i++ + ". message: " + text); } } else { break; } } consumer.close(); session.close(); } catch (Exception e) { System.out.println("Caught exception!"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { System.out.println("Could not close an open connection..."); } } } }
/** * Receives a command from a queue synchronously. If this queue also has listeners, then commands * will be distributed across all consumers. * * @param queueName name of queue * @param timeout timeout in milliseconds. If a command is not received during a timeout, this * methods returns null. * @return command if found. If command not found, this method will block till a command is * present in queue or a timeout expires. */ public Command receiveCommand(String queueName, long timeout) { Session session = null; try { session = consumerConnection.createSession(); Queue queue = (Queue) jmsServer.lookup("/queue/" + queueName); MessageConsumer consumer = session.createConsumer(queue); return message2Command((TextMessage) consumer.receive(timeout)); } catch (Exception e) { throw new HornetNestException("Could not get command", e); } finally { try { if (session != null) session.close(); } catch (Throwable e) { } } }
@Test public void testWithMessageSelectorAndCustomTimeout() throws JMSException { JmsMessageReceiver receiver = new JmsMessageReceiver(); receiver.setConnectionFactory(connectionFactory); receiver.setDestination(destination); receiver.setReceiveTimeout(10000L); Map<String, Object> controlHeaders = new HashMap<String, Object>(); final Message<String> controlMessage = MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>") .copyHeaders(controlHeaders) .build(); Map<String, String> headers = new HashMap<String, String>(); reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer); expect(connectionFactory.createConnection()).andReturn(connection).once(); expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once(); expect(session.getTransacted()).andReturn(false).once(); expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once(); expect(session.createConsumer(destination, "Operation = 'sayHello'")) .andReturn(messageConsumer) .once(); connection.start(); expectLastCall().once(); expect(messageConsumer.receive(10000L)) .andReturn( new TextMessageImpl( "<TestRequest><Message>Hello World!</Message></TestRequest>", headers)) .once(); replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer); Message<?> receivedMessage = receiver.receiveSelected("Operation = 'sayHello'"); Assert.assertEquals(receivedMessage.getPayload(), controlMessage.getPayload()); verify(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer); }
public void run() { try { // Create a ConnectionFactory String conStr = "tcp://localhost:61616"; ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(conStr); System.out.println("Connecting..."); // Create a Connection Connection connection = connectionFactory.createConnection(); connection.start(); connection.setExceptionListener(this); // Create a Session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createTopic("TEST.FOO"); // Create a MessageConsumer from the Session to the Topic or // Queue MessageConsumer consumer = session.createConsumer(destination); while (true) { // Wait for a message 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); } } } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } }
public static void main(String[] args) throws Exception { stopMQService(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); Connection connection = connectionFactory.createConnection(); connection.start(); final Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue("my-queue"); MessageConsumer consumer = session.createConsumer(destination); /* * //listener 方式 consumer.setMessageListener(new MessageListener() { * * public void onMessage(Message msg) { MapMessage message = * (MapMessage) msg; //TODO something.... System.out.println("收到消息:" + * new Date(message.getLong("count"))); session.commit(); } * * }); Thread.sleep(30000); */ int i = 0; int num = 0; while (i < 3) { num++; MapMessage message = (MapMessage) consumer.receive(); session.commit(); // TODO something.... // System.out.println("收到消息:" + new Date(message.getLong("count"))); System.out.println("2收到第" + num + "条消息:" + message.getString("count")); // System.out.println("收到第"+num+"条消息:" + message.getString("mes")); } session.close(); connection.close(); }
public static void main(String[] args) { Connection connection = null; try { Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); Destination controlDestination = (Destination) context.lookup(CONTROL_DESTINATION_NAME); connection = factory.createConnection(); // create a session for the control producer Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer controlProducer = session.createProducer(controlDestination); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(new JmsMessageListener(session, controlProducer)); // Must have a separate session or connection for the sync MessageConsumer // per JMS spec you cannot have sync and async message consumers on the same // session Session controlSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer controlConsumer = controlSession.createConsumer(controlDestination); // calling start after the listeners have been registered connection.start(); LOG.info("Start control message consumer"); int i = 1; while (true) { // sync receive for message consumer Message message = controlConsumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); LOG.info("Got " + (i++) + ". message: " + text); if (text.startsWith("SHUTDOWN")) { break; } } } } controlConsumer.close(); controlSession.close(); consumer.close(); controlProducer.close(); session.close(); } catch (Exception e) { LOG.error(e); } finally { // got to clean up the connections and other resources! if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<html><head></head><body>"); try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Connection con = cf.createConnection(); con.start(); // don't forget to start the connection QueueSession session = (QueueSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE); // The PITsnapshot Queue is used for responses from the Players to this serverlet Queue q = (Queue) ctx.lookup("jms/PITsnapshot"); MessageConsumer reader = session.createConsumer(q); /* * Throw out old PITsnapshot messages that may have been left from past * snapshots that did not complete (because of some error). */ ObjectMessage m = null; while ((m = (ObjectMessage) reader.receiveNoWait()) != null) { System.out.println("Found an orphaned PITsnapshot message"); } // Initialize the snapshot my sending a marker to a Player sendInitSnapshot(); /* * Receive the snapshot messages from all Players. * Each snapshot is a HahsMap. Put them into an array of HashMaps * */ HashMap state[] = new HashMap[numPlayers + 1]; int stateResponses = 0; int failures = 0; while (stateResponses < numPlayers) { if ((m = (ObjectMessage) reader.receive(1000)) == null) { if (++failures > 10) { System.out.println("Not all players reported, giving up after " + stateResponses); break; } continue; } state[stateResponses++] = (HashMap) m.getObject(); } /* * For each commodity, sum the number of them reported from * each Player. Store these into a two dimensional table * that will then be used to generate the report back to the user. */ String commodity[] = {"rice", "gold", "oil"}; int total[][] = new int[numPlayers][commodity.length]; for (int c = 0; c < commodity.length; c++) { for (int p = 0; p < stateResponses; p++) { try { Integer ccount = (Integer) state[p].get(commodity[c]); if (ccount == null) { total[p][c] = 0; } else { total[p][c] = (Integer) ccount.intValue(); } } catch (Exception e) { System.out.println("Servlet threw exception " + e); } } } /* * Now turn the table of commodities, and the state from each Player * into a response to the user. */ for (int c = 0; c < commodity.length; c++) { int ctotal = 0; out.print("<h2>Commodity: " + commodity[c] + "</h2>"); out.print("<table border='1'><tr><th>Player</th><th>Quantity</th></tr>"); for (int p = 0; p < stateResponses; p++) { out.print("<tr><td>" + p + "</td><td>" + total[p][c] + "</td></tr>"); ctotal += total[p][c]; } out.print("<tr><td><b>Total</b></td><td>" + ctotal + "</td></tr>"); out.print("</table></br></br>"); } // Close the connection con.close(); out.println("</BODY></HTML>"); } catch (Exception e) { System.out.println("Servlet threw exception " + e); } finally { out.println("</body></html>"); out.close(); } }
// @Test public void testFetchGraphSimple() { try { String neId = "21100799"; String group = "bw"; // interesting for the BW String titleX = "Bandwidth"; String titleY = "bps"; int timespan = 0; // Daily /* String neId = "1005255"; String group = "cpu"; // interesting for the CPU String titleX = "CPU Utilization"; String titleY = "Utilization"; int timespan = 0; // Daily */ FetchGraphSimpleCommandMessage message = CommandMessageFactory.createRRDGraphSimpleCommandMessage( neId, group, timespan, titleX, titleY); MessageProducer producer = null; MessageConsumer consumer = null; try { // time to send the JMS request TextMessage reqMsg; Message replyMsg; producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE)); // this will uniquelly identify the request String UIID = UUID.randomUUID().toString(); reqMsg = session.createTextMessage(); reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchGraphSimple"); reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID); String body = JsonUtil.getInstance().toJSON(message); reqMsg.setText(body); logger.info("SEND:\n" + body); producer.send(reqMsg); consumer = session.createConsumer( new HornetQQueue(SERVICE_REPLY_QUEUE), "ServiceRRD_correlation_id = '" + UIID + "'"); replyMsg = consumer.receive(30000); if (replyMsg == null) { logger.info("ServiceRRD timeout on receive()"); } else { if (replyMsg instanceof BytesMessage) { BytesMessage graphStream = (BytesMessage) replyMsg; byte[] graph = new byte[(int) graphStream.getBodyLength()]; graphStream.readBytes(graph); FileOutputStream image = new FileOutputStream( "/Users/cvasilak/Temp/svc-rrd-images/" + neId + "_" + group + "_" + timespan + ".png"); image.write(graph); image.close(); logger.info("image retrieved and saved!"); } else if (replyMsg instanceof TextMessage) { // the server responded with an error logger.info(((TextMessage) replyMsg).getText()); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (producer != null) producer.close(); if (consumer != null) consumer.close(); } catch (JMSException e) { } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public int run() throws Exception { // Default values of command line arguments String host = DEFAULT_HOST; int port = DEFAULT_PORT; String user = DEFAULT_USER; String pass = DEFAULT_PASS; String destination = DEFAULT_DESTINATION; String file = ""; // No default -- if not given, don't read/write file int sleep = 0; boolean showpercent = false; int batchSize = 0; int length = 500; // Length of message generated internally String properties = ""; String format = "short"; String durable = null; int n = 1; // n is the number of messages to process, or a specific // message number, depending on content String url = ""; // No default -- if not given, don't use it String[] nonSwitchArgs = cl.getArgs(); if (nonSwitchArgs.length > 0) n = Integer.parseInt(nonSwitchArgs[0]); String _destination = cl.getOptionValue("destination"); if (_destination != null) destination = _destination; String _host = cl.getOptionValue("host"); if (_host != null) host = _host; String _port = cl.getOptionValue("port"); if (_port != null) port = Integer.parseInt(_port); String _file = cl.getOptionValue("file"); if (_file != null) file = _file; String _user = cl.getOptionValue("user"); if (_user != null) user = _user; String _pass = cl.getOptionValue("password"); if (_pass != null) pass = _pass; String _url = cl.getOptionValue("url"); if (_url != null) url = _url; String _sleep = cl.getOptionValue("sleep"); if (_sleep != null) sleep = Integer.parseInt(_sleep); if (cl.hasOption("percent")) showpercent = true; String _batchSize = cl.getOptionValue("batch"); if (_batchSize != null) batchSize = Integer.parseInt(_batchSize); String _L = cl.getOptionValue("length"); if (_L != null) length = Integer.parseInt(_L); String _properties = cl.getOptionValue("properties"); if (_properties != null) properties = _properties; String _durable = cl.getOptionValue("durable"); if (_durable != null) durable = _durable; boolean batch = false; if (batchSize != 0) batch = true; String _format = cl.getOptionValue("format"); if (_format != null) format = _format; ActiveMQConnectionFactory factory = getFactory(host, port, url); Connection connection = factory.createConnection(user, pass); if (durable != null) connection.setClientID(durable); connection.start(); Session session = connection.createSession(batch, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(destination); MessageConsumer consumer = null; if (durable != null) consumer = session.createDurableSubscriber(topic, "amqutil"); else consumer = session.createConsumer(topic); int oldpercent = 0; for (int i = 0; i < n; i++) { javax.jms.Message message = consumer.receive(); if (batch) if ((i + 1) % batchSize == 0) session.commit(); if (sleep != 0) Thread.sleep(sleep); JMSUtil.outputMessage(format, message, file); if (showpercent) { int percent = i * 100 / n; if (percent != oldpercent) System.out.println("" + percent + "%"); oldpercent = percent; } } if (batch) session.commit(); connection.close(); return 0; }
@Test public void testFetchLast() { try { String neId = "1005255"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES) KLNNMS05(cpuusage=YES // bususage=YES) // String neId = "1006119"; // KLNNMS02(cpuusage=YES cpu1min=YES memutil=YES // KLNNMS05(cpuusage=NO bususage=NO) Set<String> rras = new HashSet<String>(); // klnnms02 rras.add("cpu5sec"); rras.add("cpu1min"); rras.add("memutil"); // klnnms05 rras.add("cpuusage"); rras.add("bususage"); FetchLastCommandMessage message = CommandMessageFactory.createRRDLastCommandMessage(neId, "AVERAGE", 0, 0, null, rras); MessageProducer producer = null; MessageConsumer consumer = null; // time to send the JMS request try { TextMessage reqMsg, replyMsg; producer = session.createProducer(new HornetQQueue(SERVICE_QUEUE)); // this will uniquelly identify the request String UIID = UUID.randomUUID().toString(); reqMsg = session.createTextMessage(); reqMsg.setStringProperty("ServiceRRD_msg_type", "fetchLast"); reqMsg.setStringProperty("ServiceRRD_correlation_id", UIID); String body = JsonUtil.getInstance().toJSON(message); reqMsg.setText(body); logger.info("SEND:\n" + body); producer.send(reqMsg); consumer = session.createConsumer( new HornetQQueue(SERVICE_REPLY_QUEUE), "ServiceRRD_correlation_id = '" + UIID + "'"); replyMsg = (TextMessage) consumer.receive(30000); if (replyMsg == null) { logger.info("ServiceRRD timeout on receive()"); } else { logger.info("REPLY:\n" + replyMsg.getText()); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (producer != null) producer.close(); if (consumer != null) consumer.close(); } catch (JMSException e) { } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void main(String... args) throws Exception { ConnectionFactory connectionFactory = null; Connection connection = null; Session session = null; MessageProducer producer = null; MessageConsumer consumer = null; Destination destination = null; TextMessage message = null; Context context = null; try { // Set up the context for the JNDI lookup final Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); env.put(Context.PROVIDER_URL, System.getProperty(Context.PROVIDER_URL, PROVIDER_URL)); env.put(Context.SECURITY_PRINCIPAL, System.getProperty("username", DEFAULT_USERNAME)); env.put(Context.SECURITY_CREDENTIALS, System.getProperty("password", DEFAULT_PASSWORD)); context = new InitialContext(env); // Perform the JNDI lookups String connectionFactoryString = System.getProperty("connection.factory", DEFAULT_CONNECTION_FACTORY); log.info("Attempting to acquire connection factory \"" + connectionFactoryString + "\""); connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryString); log.info("Found connection factory \"" + connectionFactoryString + "\" in JNDI"); String destinationString = System.getProperty("destination", DEFAULT_DESTINATION); log.info("Attempting to acquire destination \"" + destinationString + "\""); destination = (Destination) context.lookup(destinationString); log.info("Found destination \"" + destinationString + "\" in JNDI"); // Create the JMS connection, session, producer, and consumer connection = connectionFactory.createConnection( System.getProperty("username", DEFAULT_USERNAME), System.getProperty("password", DEFAULT_PASSWORD)); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(destination); consumer = session.createConsumer(destination); connection.start(); int count = Integer.parseInt(System.getProperty("message.count", DEFAULT_MESSAGE_COUNT)); String content = System.getProperty("message.content", DEFAULT_MESSAGE); log.info("Sending " + count + " messages with content: " + content); // Send the specified number of messages for (int i = 0; i < count; i++) { message = session.createTextMessage(content); producer.send(message); } // Then receive the same number of messages that were sent for (int i = 0; i < count; i++) { message = (TextMessage) consumer.receive(5000); log.info("Received message with content " + message.getText()); } } catch (Exception exception) { log.severe(exception.getMessage()); throw exception; } finally { if (context != null) { context.close(); } // closing the connection takes care of the session, producer, and consumer if (connection != null) { connection.close(); } } }