public void testWithConnectionFactoryAndClientId() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); cf.createConnection(); cfControl.setReturnValue(con, 1); con.setClientID("myId"); conControl.setVoidCallable(1); con.start(); conControl.setVoidCallable(1); con.stop(); conControl.setVoidCallable(1); con.close(); conControl.setVoidCallable(1); cfControl.replay(); conControl.replay(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); Connection con1 = scf.createConnection(); con1.start(); con1.close(); // should be ignored Connection con2 = scf.createConnection(); con2.start(); con2.close(); // should be ignored scf.destroy(); // should trigger actual close cfControl.verify(); conControl.verify(); }
public void testWithConnection() throws JMSException { MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); con.start(); conControl.setVoidCallable(1); con.stop(); conControl.setVoidCallable(1); con.close(); conControl.setVoidCallable(1); conControl.replay(); SingleConnectionFactory scf = new SingleConnectionFactory(con); Connection con1 = scf.createConnection(); con1.start(); con1.stop(); // should be ignored con1.close(); // should be ignored Connection con2 = scf.createConnection(); con2.start(); // should be ignored con2.stop(); // should be ignored con2.close(); // should be ignored scf.destroy(); // should trigger actual close conControl.verify(); }
public void onMessage(Message message) { if (!started) { startLatch.countDown(); started = true; } try { int foo = message.getIntProperty("foo"); if (foo != count) { e = new Exception("received out of order expected " + count + " received " + foo); failed = true; conn.close(); } count++; } catch (JMSException e) { this.e = e; failed = true; try { conn.close(); } catch (JMSException e1) { e1 .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } }
@Test public void testSendnReceiveAuthorization() throws Exception { Connection sendingConn = null; Connection receivingConn = null; // Sender try { Destination dest = new ActiveMQQueue(queueName); receivingConn = factory.createConnection("openwireReceiver", "ReCeIvEr"); receivingConn.start(); sendingConn = factory.createConnection("openwireSender", "SeNdEr"); sendingConn.start(); Session sendingSession = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session receivingSession = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage message = sendingSession.createTextMessage("Hello World"); MessageProducer producer = null; producer = receivingSession.createProducer(dest); try { producer.send(message); } catch (JMSSecurityException e) { // expected producer.close(); } producer = sendingSession.createProducer(dest); producer.send(message); MessageConsumer consumer = null; try { consumer = sendingSession.createConsumer(dest); } catch (JMSSecurityException e) { // expected } consumer = receivingSession.createConsumer(dest); TextMessage received = (TextMessage) consumer.receive(); assertNotNull(received); assertEquals("Hello World", received.getText()); } finally { if (sendingConn != null) { sendingConn.close(); } if (receivingConn != null) { receivingConn.close(); } } }
/** * Send some messages. Receive them in a transacted session. Commit the receiving session Close * the connection Create a new connection, session and consumer - verify messages are not * redelivered */ @Test public void testAckCommitQueue() throws Exception { Connection conn = null; try { conn = createConnection(); Session producerSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSess.createProducer(queue1); Session consumerSess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = consumerSess.createConsumer(queue1); conn.start(); final int NUM_MESSAGES = 10; // Send some messages for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } int count = 0; while (true) { Message m = consumer.receive(500); if (m == null) { break; } count++; } ProxyAssertSupport.assertEquals(NUM_MESSAGES, count); consumerSess.commit(); conn.stop(); consumer.close(); conn.close(); conn = createConnection(); consumerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = consumerSess.createConsumer(queue1); conn.start(); Message m = consumer.receive(500); ProxyAssertSupport.assertNull(m); } finally { if (conn != null) { conn.close(); } } }
/** * 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(); } } }
/** Stops this JMS server. */ public void stop() { try { consumerConnection.close(); } catch (Exception e) { } try { producerConnection.close(); } catch (Exception e) { } try { jmsServer.stop(); } catch (Exception e) { } }
public void sendMessage(Order order) { ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616"); Queue queue = new ActiveMQQueue("sequence"); Connection conn = null; Session sen = null; MessageProducer producer = null; TextMessage msg = null; JSONMapper mapper = new JSONMapper(); Destination des = null; try { conn = factory.createConnection(); sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = sen.createProducer(queue); conn.start(); String str = mapper.writeObjectAsString(order); System.out.println(str); msg = sen.createTextMessage(str); producer.send(msg); producer.close(); sen.close(); conn.close(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void produceMsg(String text) throws Exception { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); // Create a Connection Connection connection = connectionFactory.createConnection(); connection.start(); // Create a Session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue("TEST.FOO"); // Create a MessageProducer from the Session to the Topic or Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Create a messages TextMessage message = session.createTextMessage(text); producer.send(message); // Clean up session.close(); connection.close(); }
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 Mail receiveMail() { ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); Destination destination = new ActiveMQQueue("mail.queue"); Connection conn = null; try { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); conn.start(); MapMessage message = (MapMessage) consumer.receive(); Mail mail = new Mail(); mail.setFrom(message.getString("from")); mail.setTo(message.getString("to")); mail.setSubject(message.getString("subject")); mail.setContent(message.getString("content")); mail.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getString("date"))); session.close(); return mail; } catch (JMSException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (JMSException e) { } } } }
/** Close the given connection safely and log any exception caught. */ protected void closeConnection(Connection conn) { try { conn.close(); } catch (JMSException jmsExc) { LOG.info("failed to cleanup connection", jmsExc); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Connection connection = null; out.write("<h1>Produce JMS ObjectMessages</h1>"); try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); ObjectMessage message = session.createObjectMessage(); MyResource resource = new MyResource("This is my resource"); message.setObject(resource); producer.send(message); out.write("<p>Send JMS Message with object: " + resource + "</p>"); } catch (JMSException e) { e.printStackTrace(); out.write("<h2>A problem occurred during the delivery of this message</h2>"); out.write("</br>"); out.write( "<p><i>Go your the JBoss Application Server console or Server log to see the error stack trace</i></p>"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } if (out != null) { out.close(); } } }
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(); }
public void send(Scenario scenario) throws Exception { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl()); connection = factory.createConnection(); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); ActiveMQQueue destination = new ActiveMQQueue(scenario.getInputQueue()); MessageProducer producer = null; try { producer = session.createProducer(destination); scenario.send(session, producer); } finally { if (producer != null) { producer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
public static void main(String[] args) { try { Parameters parameters = new Parameters(args); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(parameters.url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic destination = session.createTopic(parameters.topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); String messageBody = IOUtils.toString(new FileReader(parameters.message)); TextMessage message = session.createTextMessage(messageBody); message.setStringProperty("Channel", parameters.channel); message.setJMSExpiration(parameters.expiration); LOG.info("Sent message: {}", message); producer.send(message); session.close(); connection.close(); } catch (Exception e) { LOG.error("Producing interrupted", e); } }
/** * Send a command via JMS. * * <p>Note: Opens and closes the connection per invocation of this method which, when run outside * a JavaEE container, is not very efficient. * * @param command * @throws JMSException */ public void sendCommandMessage(Command command) throws JMSException { Connection connection = null; Session session = null; try { connection = connectionFactory.createConnection(); session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE); // Construct a JMS "TextMessage" final TextMessage newMessage = session.createTextMessage(); newMessage.setStringProperty("issuer", command.getIssuer()); newMessage.setStringProperty("type", command.getType()); newMessage.setText(command.getPayload()); // Send the message final MessageProducer producer = session.createProducer(this.commandQueue); producer.send(newMessage); if (TRANSACTIONAL) { // JavaEE containers would manage this session.commit(); } } finally { if (connection != null) { try { if (session != null) { session.close(); } connection.stop(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } }
@Override @Test(timeout = 30000) public void testMessageSizeOneDurablePartialConsumption() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); // verify the count and size - durable is offline so all 200 should be pending since none are in // prefetch verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 verifyStoreStats(dest, 100, publishedMessageSize.get()); // consume all messages consumeDurableTestMessages(connection, "sub1", 50, publishedMessageSize); // All messages should now be gone verifyPendingStats(dest, subKey, 150, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 // verify the size is at least as big as 100 messages times the minimum of 100 size verifyStoreStats(dest, 100, 100 * 100); connection.close(); }
@Test public void testReconnectMultipleTimesWithSameClientID() throws Exception { try { sameIdConnection = (ActiveMQConnection) this.factory.createConnection(); useConnection(sameIdConnection); // now lets create another which should fail for (int i = 1; i < 11; i++) { Connection connection2 = this.factory.createConnection(); try { useConnection(connection2); fail("Should have thrown InvalidClientIDException on attempt" + i); } catch (InvalidClientIDException e) { System.err.println("Caught expected: " + e); } finally { connection2.close(); } } // now lets try closing the original connection and creating a new // connection with the same ID sameIdConnection.close(); sameIdConnection = (ActiveMQConnection) factory.createConnection(); useConnection(connection); } finally { if (sameIdConnection != null) { sameIdConnection.close(); } } }
@Override @Test(timeout = 30000) public void testMessageSizeOneDurable() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // The expected value is only 100 because for durables a LRUCache is being used // with a max size of 100 verifyStoreStats(dest, 100, publishedMessageSize.get()); // consume 100 messages consumeDurableTestMessages(connection, "sub1", 100, publishedMessageSize); // 100 should be left verifyPendingStats(dest, subKey, 100, publishedMessageSize.get()); verifyStoreStats(dest, 100, publishedMessageSize.get()); connection.close(); }
@Test public void testNetworkedBrokerDetach() throws Exception { LOG.info("Creating Consumer on the networked broker ..."); // Create a consumer on the networked broker ConnectionFactory consFactory = createConnectionFactory(networkedBroker); Connection consConn = consFactory.createConnection(); Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); for (int i = 0; i < NUM_CONSUMERS; i++) { consSession.createConsumer(destination); } assertTrue( "got expected consumer count from mbean within time limit", verifyConsumerCount(1, destination, broker)); LOG.info("Stopping Consumer on the networked broker ..."); // Closing the connection will also close the consumer consConn.close(); // We should have 0 consumer for the queue on the local broker assertTrue( "got expected 0 count from mbean within time limit", verifyConsumerCount(0, destination, broker)); }
@Test public void testSendReceiveMessage() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); // Make persistent to make sure message gets serialized prod.setDeliveryMode(DeliveryMode.PERSISTENT); MessageConsumer cons = sess.createConsumer(queue1); TestMessage tm = new TestMessage(123, false); ObjectMessage om = sess.createObjectMessage(); om.setObject(tm); conn.start(); prod.send(om); ObjectMessage om2 = (ObjectMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(om2); TestMessage tm2 = (TestMessage) om2.getObject(); ProxyAssertSupport.assertEquals(123, tm2.getID()); conn.close(); }
/** * Check a session is rollbacked on a Session close(); * * @throws Exception */ public void xtestTransactionRollbackOnSessionClose() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = null; if (topic) { consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); } else { consumer = consumerSession.createConsumer(destination); } Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); TextMessage sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg1"); producer.send(sentMsg); producerSession.commit(); Message recMsg = consumer.receive(RECEIVE_TIMEOUT); assertFalse(recMsg.getJMSRedelivered()); consumerSession.close(); consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = consumerSession.createConsumer(destination); recMsg = consumer.receive(RECEIVE_TIMEOUT); consumerSession.commit(); assertTrue(recMsg.equals(sentMsg)); connection.close(); }
@Test public void testCompositeDestConsumer() throws Exception { final int numDests = 20; final int numMessages = 200; StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < numDests; i++) { if (stringBuffer.length() != 0) { stringBuffer.append(','); } stringBuffer.append("ST." + i); } stringBuffer.append("?consumer.prefetchSize=100"); ActiveMQQueue activeMQQueue = new ActiveMQQueue(stringBuffer.toString()); ConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI()); Connection connection = factory.createConnection(); connection.start(); MessageProducer producer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(activeMQQueue); for (int i = 0; i < numMessages; i++) { producer.send(new ActiveMQTextMessage()); } MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(activeMQQueue); try { for (int i = 0; i < numMessages * numDests; i++) { assertNotNull("recieved:" + i, consumer.receive(4000)); } } finally { connection.close(); } }
/* * Initiate the snapshot by sending a Marker message to one of the Players (Player0) * Any Player could have been used to initiate the snapshot. */ private void sendInitSnapshot() { try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Queue q = (Queue) ctx.lookup("jms/PITplayer0"); Connection con = cf.createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer writer = session.createProducer(q); /* * As part of the snapshot algorithm, players need to record * what other Players they receive markers from. * "-1" indicates to the PITplayer0 that this marker is coming from * the monitor, not another Player. */ Marker m = new Marker(-1); ObjectMessage msg = session.createObjectMessage(m); System.out.println("Initiating Snapshot"); writer.send(msg); con.close(); } catch (JMSException e) { System.out.println("JMS Exception thrown" + e); } catch (Throwable e) { System.out.println("Throwable thrown" + e); } }
@Override public void tearDown() throws Exception { if (dlqConnection != null) { dlqConnection.close(); } super.tearDown(); }
@Test public void testCreateTopic() throws Exception { liveJMSService.createTopic(true, "topic", "/topic/t1"); assertNotNull(ctx1.lookup("//topic/t1")); ActiveMQConnectionFactory jbcf = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, livetc); jbcf.setReconnectAttempts(-1); Connection conn = null; try { conn = JMSUtil.createConnectionAndWaitForTopology(jbcf, 2, 5); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); ClientSession coreSession = ((ActiveMQSession) sess).getCoreSession(); JMSUtil.crash(liveService, coreSession); assertNotNull(ctx2.lookup("/topic/t1")); } finally { if (conn != null) { conn.close(); } } }
public void sendMessage(final String textMessage) throws Exception { // Connection connection = null; // Session session = null; try { // Create a message String text = "DID IT WORK?! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); TextMessage message = session.createTextMessage(text); String timestamp = DateFormater.format(message.getJMSExpiration()); // Tell the producer to send the message System.out.printf( "Sent message: %s : %s [%s]%n", message.hashCode(), Thread.currentThread().getName(), timestamp); // producer.setTimeToLive(DateTimeConstants.MILLIS_PER_HOUR); send(message); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } finally { if (connection != null) { connection.close(); if (session != null) { session.close(); } } } }
@After public void tearDown() throws Exception { producer.close(); session.close(); connection.close(); broker.stop(); }
protected void finalize() { try { _connection.close(); } catch (JMSException e) { // intentionally left empty } }