public void testRedelivery() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_MOST_ONCE); p.send(msg()); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m1 = c.receive(); assertTrue(m1.getHeader().getFirstAcquirer().getValue()); assertFalse(m1.isSettled()); s.close(); s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m2 = c.receive(); m2.accept(); assertTrue(compareMessageData(m1, m2)); assertFalse(m2.getHeader().getFirstAcquirer().getValue()); assertNull(get(c)); conn.close(); }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
@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"); }
public static void main(String[] args) throws JMSException { AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(asyncConsumer); connection.setExceptionListener(asyncConsumer); try { while (true) { if (AsyncSimpleConsumer.catchExit) { break; } Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Sleep interrupted"); } connection.close(); }
private void route(String consumerSource, String producerTarget, String routingKey, boolean succeed) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Consumer c = s.createConsumer(consumerSource, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); Producer p = s.createProducer(producerTarget, QoS.AT_LEAST_ONCE); AMQPMessage msg = msg(); AmqpValue sentinel = new AmqpValue(new AMQPDouble(Math.random())); msg.setAmqpValue(sentinel); Properties props = new Properties(); props.setSubject(new AMQPString(routingKey)); msg.setProperties(props); p.send(msg); if (succeed) { AMQPMessage m = c.receive(); assertNotNull(m); assertEquals(sentinel.getValue().getValueString(), m.getAmqpValue().getValue().getValueString()); m.accept(); } else { assertNull(get(c)); } c.close(); p.close(); conn.close(); }
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(); } }
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(); }
public static void main(String[] args) { try { Context ctx = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); Queue queue = (Queue) ctx.lookup("inbound"); Connection con = factory.createConnection(); final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { final String type; try { type = message.getStringProperty("type"); if (type != null && type.equals("xml")) { System.out.println(((TextMessage) message).getText()); } } catch (JMSException e) { e.printStackTrace(); } } }); con.start(); } catch (Exception e) { e.printStackTrace(); } }
private void consume() { try { consumer = session.createConsumer(queue); message = consumer.receive(); } catch (JMSException e) { e.printStackTrace(); } }
private MessageConsumer establishConsumer(String broker, ActiveMQDestination consumerQueue) throws Exception { BrokerItem item = brokers.get(broker); Connection c = item.createConnection(); c.start(); Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE); return s.createConsumer(consumerQueue); }
@Override protected void makeDlqConsumer() throws Exception { dlqDestination = createDlqDestination(); dlqConnection = getConnectionFactory().createConnection("system", "manager"); dlqConnection.start(); dlqSession = dlqConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); dlqConsumer = dlqSession.createConsumer(dlqDestination); }
private void emptyQueue(String q) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Consumer c = s.createConsumer(q, CONSUMER_LINK_CREDIT, QoS.AT_MOST_ONCE, false, null); AMQPMessage m; while ((m = get(c)) != null); conn.close(); }
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 void testAtMostOnce() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_MOST_ONCE); p.send(msg()); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_MOST_ONCE, false, null); AMQPMessage m = c.receive(); assertTrue(m.isSettled()); s.close(); s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_MOST_ONCE, false, null); assertNull(get(c)); conn.close(); }
@Override public void start() { try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageConsumer = session.createConsumer(schedulerQueue); messageConsumer.setMessageListener(this); connection.start(); } catch (JMSException e) { e.printStackTrace(); } }
/** Connects to a named queue. */ public JMSQueue(ConnectionFactory connectionFactory, Destination queue) throws Exception { _connection = connectionFactory.createConnection(); _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); if (queue == null) _destination = _session.createTemporaryQueue(); else _destination = queue; _consumer = _session.createConsumer(_destination); _producer = _session.createProducer(_destination); _connection.start(); }
@Override public void init() { try { createAndStartConnection("", "", brokerUrl); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); destination = session.createQueue(destinationName); producer = session.createProducer(destination); consumer = session.createConsumer(destination); LOG.info("Initialized Queue on ActiveMQ: {}", destinationName); } catch (Exception e) { LOG.error("Error starting ActiveMQ connection for delayed queue", e); throw new RuntimeException("Error starting ActiveMQ connection for delayed queue", e); } }
private void configureListeners(Injector injector, QueueConfig... queueConfigs) throws JMSException, IllegalAccessException, InstantiationException { for (QueueConfig queueConfig : queueConfigs) { Queue queue = (Queue) jmsServer.lookup("/queue/" + queueConfig.getName()); for (int i = 0; i < queueConfig.getListenerCount(); i++) { CommandListener listener = (CommandListener) queueConfig.getCommandListenerClass().newInstance(); listener.setInjector(injector); Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); session.createConsumer(queue).setMessageListener(listener); } } consumerConnection.start(); }
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..."); } } } }
/** * Get the `MessageConsumer`. * * @param destinationName destinationName * @return JMS `MessageConsumer`. */ private MessageConsumer getConsumer(final String destinationName) { if (!consumers.containsKey(destinationName)) { Session session = getSession(); Destination destination = getDestination(destinationName); try { MessageConsumer consumer = session.createConsumer(destination); consumers.put(destinationName, consumer); } catch (JMSException e) { throw new IllegalStateException( "Unable to create consumer for destination " + destinationName, e); } } return consumers.get(destinationName); }
public void testRoundTrip() throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); p.send(msg()); p.close(); // Settlement happens here Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m = c.receive(); m.accept(); assertEquals(1, m.getData().size()); assertEquals(data(), m.getData().get(0)); conn.close(); }
/** * 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) { } } }
private void routeInvalidSource(String consumerSource) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); try { Consumer c = s.createConsumer(consumerSource, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); c.close(); fail("Source '" + consumerSource + "' should fail"); } catch (Exception e) { // no-op } finally { conn.close(); } }
private void decorationTest(DecorationProtocol d, Map<AMQPString, AMQPType> map) throws Exception { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); AMQPMessage msg = msg(); d.decorateMessage(msg, map); p.send(msg); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage recvMsg = c.receive(); recvMsg.accept(); compareMaps(map, d.getDecoration(recvMsg)); conn.close(); }
@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 void fragmentation(long FrameSize, int PayloadSize) throws UnsupportedProtocolVersionException, AMQPException, AuthenticationException, IOException { AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT); Connection conn = new Connection(ctx, host, port, false); conn.setMaxFrameSize(FrameSize); conn.connect(); Session s = conn.createSession(INBOUND_WINDOW, OUTBOUND_WINDOW); Producer p = s.createProducer(QUEUE, QoS.AT_LEAST_ONCE); AMQPMessage msg = new AMQPMessage(); msg.addData(new Data(new byte [PayloadSize])); p.send(msg); p.close(); Consumer c = s.createConsumer(QUEUE, CONSUMER_LINK_CREDIT, QoS.AT_LEAST_ONCE, false, null); AMQPMessage m = c.receive(); m.accept(); c.close(); assertEquals(PayloadSize, m.getData().get(0).getValue().length); conn.close(); }
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(); }
/** @param args the command line arguments */ public static void main(String[] args) throws NamingException, JMSException, InterruptedException { BasicConfigurator.resetConfiguration(); BasicConfigurator.configure(); try { Properties props = new Properties(); props.setProperty( Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); props.setProperty(Context.PROVIDER_URL, "tcp://miniserver.local:61616"); Context context = new InitialContext(props); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory"); FileSystemListener myListener = new FileSystemListener(); Destination destination = (Destination) context.lookup("dynamicTopics/eXistdb"); LOG.info("Destination=" + destination); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(myListener); connection.start(); LOG.info("Receiver is ready"); } catch (Throwable t) { LOG.error(t.getMessage(), t); } }