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 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(); }
/** * 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 testMessageSizeTwoDurables() throws Exception { AtomicLong publishedMessageSize = new AtomicLong(); Connection connection = new ActiveMQConnectionFactory(brokerConnectURI).createConnection(); connection.setClientID("clientId"); connection.start(); org.apache.activemq.broker.region.Topic dest = publishTestMessagesDurable( connection, new String[] {"sub1", "sub2"}, 200, publishedMessageSize, DeliveryMode.PERSISTENT); // verify the count and size SubscriptionKey subKey = new SubscriptionKey("clientId", "sub1"); verifyPendingStats(dest, subKey, 200, publishedMessageSize.get()); // consume messages just for sub1 consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize); // There is still a durable that hasn't consumed so the messages should exist SubscriptionKey subKey2 = new SubscriptionKey("clientId", "sub2"); verifyPendingStats(dest, subKey, 0, 0); verifyPendingStats(dest, subKey2, 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()); connection.stop(); }
@Test public void testSendMessage() throws Exception { ConnectionFactory connFactory = lookup("ConnectionFactory", ConnectionFactory.class); Connection conn = connFactory.createConnection(); conn.start(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue replyQueue = session.createTemporaryQueue(); TextMessage msg = session.createTextMessage("Hello world"); msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); msg.setJMSReplyTo(replyQueue); Queue queue = lookup("java:jboss/" + queueName, Queue.class); MessageProducer producer = session.createProducer(queue); producer.send(msg); MessageConsumer consumer = session.createConsumer(replyQueue); Message replyMsg = consumer.receive(5000); Assert.assertNotNull(replyMsg); if (replyMsg instanceof ObjectMessage) { Exception e = (Exception) ((ObjectMessage) replyMsg).getObject(); throw e; } Assert.assertTrue(replyMsg instanceof TextMessage); String actual = ((TextMessage) replyMsg).getText(); Assert.assertEquals("SUCCESS", actual); consumer.close(); producer.close(); session.close(); conn.stop(); }
@Override public void stop() { try { messageConsumer.close(); connection.stop(); } catch (JMSException e) { e.printStackTrace(); } }
private void shutdown() { try { _session.close(); _connection.stop(); _connection.close(); } catch (Exception e) { e.printStackTrace(System.out); } }
@Test public void testAdminConnection() throws Exception { Assert.assertEquals(2, BROKERS.size()); // ConnectionFactory factory = new // ActiveMQConnectionFactory(BrokerRegistry.getInstance().findFirst().getVmConnectorURI()); ConnectionFactory fc = new ActiveMQConnectionFactory("tcp://*****:*****@EU", "password"); consumerConnection.start(); Connection producerConnection = fp.createConnection("system@EU", "password"); producerConnection.start(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createTopic(ADMIN_TOPIC)); MessageProducer producer = producerSession.createProducer(producerSession.createTopic(ADMIN_TOPIC)); final CountDownLatch messageSignal = new CountDownLatch(1); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(javax.jms.Message message) { try { LOG.info( "Received admin message {} with content: \"{}\".", message.getJMSMessageID().toString(), ((ActiveMQTextMessage) message).getText()); messageSignal.countDown(); } catch (JMSException e) { e.printStackTrace(); } } }); Thread.sleep(200); producer.send(producerSession.createTextMessage("QQQ: $1000.00")); messageSignal.await(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(0, messageSignal.getCount()); producerConnection.stop(); consumerConnection.stop(); }
/** * 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(); } } }
@Test public void testAuthWithMultipleTransports() throws Exception { Assert.assertEquals(2, BROKERS.size()); ConnectionFactory fc = new ActiveMQConnectionFactory("tcp://localhost:62616"); ConnectionFactory fp = new ActiveMQConnectionFactory("tcp://localhost:61616"); Connection consumerConnection = fc.createConnection(); consumerConnection.start(); Connection producerConnection = fp.createConnection(); producerConnection.start(); Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = consumerSession.createConsumer(consumerSession.createQueue(DEFAULT_QUEUE)); MessageProducer producer = producerSession.createProducer(producerSession.createQueue(DEFAULT_QUEUE)); final CountDownLatch messageSignal = new CountDownLatch(1); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(javax.jms.Message message) { try { LOG.info( "Received forwarded message {} with content: \"{}\".", message.getJMSMessageID().toString(), ((ActiveMQTextMessage) message).getText()); messageSignal.countDown(); } catch (JMSException e) { e.printStackTrace(); } } }); Thread.sleep(200); producer.send(producerSession.createTextMessage("QQQ: $1000.00")); messageSignal.await(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(0, messageSignal.getCount()); producerConnection.stop(); consumerConnection.stop(); }
/** Interrompe la connessione con la destinazione JMS */ protected void stopReceiveMessages() { if (this.receiving) { try { connection.stop(); this.receiving = false; } catch (JMSException e) { System.out.println("JMSChatSubscriber: " + e.toString()); System.exit(1); } } }
@AfterMethod public void shutdownConnection() throws Exception { for (final Session session : _sessions) { session.close(); } _sessions.clear(); if (null != _connection) { _connection.stop(); _connection.close(); _connection = null; } }
public void testWithConnectionFactoryAndExceptionListener() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); ExceptionListener listener = new ChainedExceptionListener(); cf.createConnection(); cfControl.setReturnValue(con, 1); con.setExceptionListener(listener); conControl.setVoidCallable(1); con.getExceptionListener(); conControl.setReturnValue(listener, 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.setExceptionListener(listener); Connection con1 = scf.createConnection(); assertEquals(listener, con1.getExceptionListener()); con1.start(); con1.stop(); // should be ignored con1.close(); // should be ignored Connection con2 = scf.createConnection(); con2.start(); con2.stop(); // should be ignored con2.close(); // should be ignored scf.destroy(); // should trigger actual close cfControl.verify(); conControl.verify(); }
/** * close() will stop the connection first. Then it closes the subscriber, session and connection. */ public void close() { // called from threadFinished() thread log.debug("close()"); try { if (CONN != null) { CONN.stop(); } } catch (JMSException e) { log.error(e.getMessage()); } Utils.close(SUBSCRIBER, log); Utils.close(SESSION, log); Utils.close(CONN, log); }
public synchronized void pause() throws Exception { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Pausing " + this); } synchronized (lock) { paused = true; sourceConn.stop(); } if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Paused " + this); } }
public static void main(String[] args) throws Exception { InitialContext ctx = new InitialContext(); connectionFactory = (ConnectionFactory) ctx.lookup(args[0]); queue = (Queue) ctx.lookup(args[1]); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer((Destination) queue); connection.start(); TextMessage message = (TextMessage) consumer.receive(); System.out.println("Recebido: " + message.getText()); session.close(); connection.stop(); connection.close(); System.exit(0); }
private void cleanup() { // Stop the source connection try { sourceConn.stop(); } catch (Throwable ignore) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Failed to stop source connection", ignore); } } if (tx != null) { try { delistResources(tx); } catch (Throwable ignore) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Failed to delist resources", ignore); } } try { // Terminate the tx tx.rollback(); } catch (Throwable ignore) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Failed to rollback", ignore); } } } // Close the old objects try { sourceConn.close(); } catch (Throwable ignore) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Failed to close source connection", ignore); } } try { if (targetConn != null) { targetConn.close(); } } catch (Throwable ignore) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Failed to close target connection", ignore); } } }
/** * Release the given Connection, stopping it (if necessary) and eventually closing it. * * <p>Checks {@link SmartConnectionFactory#shouldStop}, if available. This is essentially a more * sophisticated version of {@link org.springframework.jms.support.JmsUtils#closeConnection}. * * @param con the Connection to release (if this is {@code null}, the call will be ignored) * @param cf the ConnectionFactory that the Connection was obtained from (may be {@code null}) * @param started whether the Connection might have been started by the application * @see SmartConnectionFactory#shouldStop * @see org.springframework.jms.support.JmsUtils#closeConnection */ public static void releaseConnection(Connection con, ConnectionFactory cf, boolean started) { if (con == null) { return; } if (started && cf instanceof SmartConnectionFactory && ((SmartConnectionFactory) cf).shouldStop(con)) { try { con.stop(); } catch (Throwable ex) { logger.debug("Could not stop JMS Connection before closing it", ex); } } try { con.close(); } catch (Throwable ex) { logger.debug("Could not close JMS Connection", ex); } }
public void stop() { if (this.tempdispatcher.size() > 0) { for (ReceiveDispatcher dispatcher : this.tempdispatcher) { try { dispatcher.stop(); } catch (Exception e) { e.printStackTrace(); } } } if (this.requestDispatcher != null) { this.requestDispatcher.stop(); } // if(this.responseDispatcher != null) // { // this.responseDispatcher.stop(); // } if (this.connection != null) try { connection.stop(); } catch (Exception e) { e.printStackTrace(); } // try // { // // connection.setClientID(null); // } // catch(Exception e) // { // e.printStackTrace(); // } try { this.connection.close(); } catch (JMSException e) { e.printStackTrace(); } }
@Test public void testServer() throws Exception { // BrokerService broker = BrokerFactory // .createBroker(JMSServer.BROKER_CLIENT); ActiveMQTopic topic = new ActiveMQTopic("topicTest"); // broker.setDestinations(new ActiveMQDestination[] { topic }); // broker.start(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(JMSServer.BROKER_CLIENT); Connection conn = factory.createConnection(); conn.start(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(topic); producer.send(session.createObjectMessage("msg test 1")); producer.send(session.createObjectMessage("msg test 2")); producer.send(session.createObjectMessage("msg test 3")); producer.send(session.createObjectMessage("msg test 4")); session.close(); conn.stop(); conn.close(); }
protected String doStartAsyncReceiving(Consumer<M> objConsumer, String messageSelector) throws DataStreamInfrastructureException { String receivingConsumerId = UUID.randomUUID().toString(); try { Connection connection = getConnection(); connection.stop(); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination, messageSelector); consumer.setMessageListener(message -> objConsumer.accept(convert(message))); receivingConsumers.put(receivingConsumerId, new DoubleValueBean<>(session, consumer)); } finally { connection.start(); } return receivingConsumerId; } catch (JMSException e) { throw new DataStreamInfrastructureException(e); } }
/** * Close the given Connection. * @param con the Connection to close */ protected void closeConnection(Connection con) { if (logger.isDebugEnabled()) { logger.debug("Closing shared JMS Connection: " + this.target); } try { try { if (this.started) { this.started = false; con.stop(); } } finally { con.close(); } } catch (javax.jms.IllegalStateException ex) { logger.debug("Ignoring Connection state exception - assuming already closed: " + ex); } catch (Throwable ex) { logger.debug("Could not close shared JMS Connection", ex); } }
/** * Close the given JMS Connection and ignore any thrown exception. This is useful for typical * <code>finally</code> blocks in manual JMS code. * * @param con the JMS Connection to close (may be <code>null</code>) * @param stop whether to call <code>stop()</code> before closing */ public static void closeConnection(Connection con, boolean stop) { if (con != null) { try { if (stop) { try { con.stop(); } finally { con.close(); } } else { con.close(); } } catch (javax.jms.IllegalStateException ex) { logger.debug("Ignoring Connection state exception - assuming already closed: " + ex); } catch (JMSException ex) { logger.debug("Could not close JMS Connection", ex); } catch (Throwable ex) { // We don't trust the JMS provider: It might throw RuntimeException or Error. logger.debug("Unexpected exception on closing JMS Connection", ex); } } }
private void run() throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url); connection = factory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = session.createTopic("topictest.messages"); control = session.createTopic("topictest.control"); publisher = session.createProducer(topic); publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); payload = new byte[size]; for (int i = 0; i < size; i++) { payload[i] = (byte) DATA[i % DATA.length]; } session.createConsumer(control).setMessageListener(this); connection.start(); long[] times = new long[batch]; for (int i = 0; i < batch; i++) { if (i > 0) { Thread.sleep(delay * 1000); } times[i] = batch(messages); System.out.println( "Batch " + (i + 1) + " of " + batch + " completed in " + times[i] + " ms."); } long min = min(times); long max = max(times); System.out.println("min: " + min + ", max: " + max + " avg: " + avg(times, min, max)); // request shutdown publisher.send(session.createTextMessage("SHUTDOWN")); connection.stop(); connection.close(); }
@Override protected void tearDown() throws Exception { connection.stop(); broker.stop(); broker.waitUntilStopped(); }
public void stop() throws JMSException, InterruptedException { running = false; if (connection != null) { connection.stop(); } }
/** * Should be called after local messaging operations are finished to save resources * * @throws JMSException */ public void stopConnection() throws JMSException { connection.stop(); }
/** * Calls Connection.stop() to stop receiving inbound messages. * * @throws JMSException */ public void stop() throws JMSException { log.debug("stop()"); CONN.stop(); }
/** * {@inheritDoc} * * @throws java.lang.Exception */ protected void stop() throws Exception { LOG.info("Stopping connection"); connection.stop(); }
public void testCachingConnectionFactory() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); MockControl txSessionControl = MockControl.createControl(Session.class); Session txSession = (Session) txSessionControl.getMock(); MockControl nonTxSessionControl = MockControl.createControl(Session.class); Session nonTxSession = (Session) nonTxSessionControl.getMock(); cf.createConnection(); cfControl.setReturnValue(con, 1); con.createSession(true, Session.AUTO_ACKNOWLEDGE); conControl.setReturnValue(txSession, 1); txSession.getTransacted(); txSessionControl.setReturnValue(true, 1); txSession.commit(); txSessionControl.setVoidCallable(1); txSession.close(); txSessionControl.setVoidCallable(1); con.createSession(false, Session.CLIENT_ACKNOWLEDGE); conControl.setReturnValue(nonTxSession, 1); nonTxSession.close(); nonTxSessionControl.setVoidCallable(1); con.start(); conControl.setVoidCallable(1); con.stop(); conControl.setVoidCallable(1); con.close(); conControl.setVoidCallable(1); cfControl.replay(); conControl.replay(); txSessionControl.replay(); nonTxSessionControl.replay(); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); Connection con1 = scf.createConnection(); Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE); session1.getTransacted(); session1.close(); // should lead to rollback session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE); session1.close(); // should be ignored con1.start(); con1.close(); // should be ignored Connection con2 = scf.createConnection(); Session session2 = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE); session2.close(); // should be ignored session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE); session2.commit(); session2.close(); // should be ignored con2.start(); con2.close(); // should be ignored scf.destroy(); // should trigger actual close cfControl.verify(); conControl.verify(); txSessionControl.verify(); nonTxSessionControl.verify(); }