List of usage examples for javax.jms Connection stop
void stop() throws JMSException;
From source file:com.linagora.obm.sync.TestQueueManager.java
private void shutdownQueueManager() { for (Session s : sessions) { try {/* w w w . java 2s . co m*/ s.close(); } catch (JMSException e) { logger.error(e.getMessage(), e); } } for (Connection c : connections) { try { c.stop(); } catch (JMSException e) { logger.error(e.getMessage(), e); } try { c.close(); } catch (JMSException e) { logger.error(e.getMessage(), e); } } try { queueManager.stop(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:com.nesscomputing.jms.activemq.ServiceDiscoveryTransportFactoryTest.java
@Test public void testDiscoveryUri() throws Exception { final ServiceInformation vmbrokerInfo = new ServiceInformation("vmbroker", null, UUID.randomUUID(), ImmutableMap.of("uri", "vm://disco-test-broker-" + uniqueId)); final Config config = Config .getFixedConfig(ImmutableMap.of("ness.jms.connection-url", "srvc://vmbroker?discoveryId=%s")); Guice.createInjector(new AbstractModule() { @Override/* w w w .j a va 2 s.c om*/ protected void configure() { binder().requireExplicitBindings(); binder().disableCircularProxies(); install(new ConfigModule(config)); install(new JmsModule(config, "test")); install(new DiscoveryJmsModule(config)); bind(ReadOnlyDiscoveryClient.class).toInstance( MockedReadOnlyDiscoveryClient.builder().addServiceInformation(vmbrokerInfo).build()); } }).injectMembers(this); final ConnectionFactory directFactory = new ActiveMQConnectionFactory( "vm://disco-test-broker-" + uniqueId + "?broker.persistent=false"); final Connection directConnection = directFactory.createConnection(); directConnection.start(); try { sendTestMessage(directConnection); consumeTestMessage(); } finally { directConnection.stop(); directConnection.close(); } }
From source file:com.opengamma.examples.analyticservice.ExampleAnalyticServiceUsage.java
@Override protected void doRun() throws Exception { CommandLine commandLine = getCommandLine(); String activeMQUrl = commandLine.getOptionValue(ACTIVE_MQ_OPTION); String destinationName = commandLine.getOptionValue(QUEUE_OPTION); ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(activeMQUrl); activeMQConnectionFactory.setWatchTopicAdvisories(false); PooledConnectionFactory jmsConnectionFactory = new PooledConnectionFactory(activeMQConnectionFactory); jmsConnectionFactory.start();// w w w . ja va 2 s . co m JmsConnectorFactoryBean jmsConnectorFactoryBean = new com.opengamma.util.jms.JmsConnectorFactoryBean(); jmsConnectorFactoryBean.setName("StandardJms"); jmsConnectorFactoryBean.setConnectionFactory(jmsConnectionFactory); jmsConnectorFactoryBean.setClientBrokerUri(URI.create(activeMQUrl)); JmsConnector jmsConnector = jmsConnectorFactoryBean.getObjectCreating(); ByteArrayFudgeMessageReceiver fudgeReceiver = new ByteArrayFudgeMessageReceiver(new FudgeMessageReceiver() { @Override public void messageReceived(FudgeContext fudgeContext, FudgeMsgEnvelope msgEnvelope) { FudgeMsg message = msgEnvelope.getMessage(); s_logger.debug("received {}", message); } }, s_fudgeContext); final JmsByteArrayMessageDispatcher jmsDispatcher = new JmsByteArrayMessageDispatcher(fudgeReceiver); Connection connection = jmsConnector.getConnectionFactory().createConnection(); connection.start(); pushTrade("ARG", connection, destinationName, jmsConnector, jmsDispatcher); Thread.sleep(WAIT_BTW_TRADES); pushTrade("MMM", connection, destinationName, jmsConnector, jmsDispatcher); Thread.sleep(WAIT_BTW_TRADES * 10); connection.stop(); jmsConnectionFactory.stop(); }
From source file:com.nesscomputing.jms.activemq.ServiceDiscoveryTransportFactoryTest.java
private void consumeTestMessage() throws Exception { final Connection connection = factory.createConnection(); connection.start();/*from w w w. ja va2 s. c o m*/ try { final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = session.createConsumer(session.createQueue(QNAME)); final Message message = consumer.receive(1000); LOG.info(ObjectUtils.toString(message, "<no message>")); Assert.assertEquals(uniqueId, ((TextMessage) message).getText()); } finally { connection.stop(); connection.close(); } }
From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("queue.QUEUE", "BasicQueue"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up queue Destination queue = (Destination) context.lookup("QUEUE"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side separately with minimal clutter {// www.j a va2 s . c o m // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(queue); // Send messages for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } { // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer MessageConsumer consumer = session.createConsumer(queue); // create a listener callback to receive the messages consumer.setMessageListener(message -> { try { // receives message is passed to callback System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter message.getJMSMessageID()); message.acknowledge(); } catch (Exception e) { logger.error(e); } }); // wait on the main thread until all sent messages have been received while (totalReceived.get() < totalSend) { Thread.sleep(1000); } consumer.close(); session.close(); connection.stop(); connection.close(); } System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java
public void run(String connectionString) throws Exception { // The connection string builder is the only part of the azure-servicebus SDK library // we use in this JMS sample and for the purpose of robustly parsing the Service Bus // connection string. ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString); // set up the JNDI context Hashtable<String, String> hashtable = new Hashtable<>(); hashtable.put("connectionfactory.SBCF", "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true"); hashtable.put("topic.TOPIC", "BasicTopic"); hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1"); hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2"); hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3"); hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory"); Context context = new InitialContext(hashtable); ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF"); // Look up the topic Destination topic = (Destination) context.lookup("TOPIC"); // we create a scope here so we can use the same set of local variables cleanly // again to show the receive side seperately with minimal clutter {/*from ww w . ja v a 2 s. c o m*/ // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start(); // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create producer MessageProducer producer = session.createProducer(topic); // Send messaGES for (int i = 0; i < totalSend; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(String.valueOf(i).getBytes()); producer.send(message); System.out.printf("Sent message %d.\n", i + 1); } producer.close(); session.close(); connection.stop(); connection.close(); } // Look up the subscription (pretending it's a queue) receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2"); receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3"); System.out.printf("Received all messages, exiting the sample.\n"); System.out.printf("Closing queue client.\n"); }
From source file:org.calrissian.mango.jms.stream.JmsFileTransferSupportTest.java
public void testFullCycle() throws Exception { try {/*from ww w. j a v a2s . c om*/ URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() { @Override public URLStreamHandler createURLStreamHandler(String protocol) { if ("testprot".equals(protocol)) return new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) throws IOException { return new URLConnection(u) { @Override public void connect() throws IOException { } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(TEST_STR.getBytes()); } @Override public String getContentType() { return "content/notnull"; } }; } }; return null; } }); } catch (Error ignored) { } final ActiveMQTopic ft = new ActiveMQTopic("testFileTransfer"); ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor(); te.initialize(); JmsFileSenderListener listener = new JmsFileSenderListener(); final String hashAlgorithm = "MD5"; listener.setHashAlgorithm(hashAlgorithm); listener.setStreamRequestDestination(ft); listener.setPieceSize(9); listener.setTaskExecutor(te); ConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); cf = new SingleTopicConnectionFactory(cf, "test"); JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(cf); jmsTemplate.setReceiveTimeout(60000); listener.setJmsTemplate(jmsTemplate); Connection conn = cf.createConnection(); conn.start(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = sess.createConsumer(ft); consumer.setMessageListener(listener); JmsFileReceiver receiver = new JmsFileReceiver(); receiver.setHashAlgorithm(hashAlgorithm); receiver.setStreamRequestDestination(ft); receiver.setJmsTemplate(jmsTemplate); receiver.setPieceSize(9); JmsFileReceiverInputStream stream = (JmsFileReceiverInputStream) receiver.receiveStream("testprot:test"); StringBuilder buffer = new StringBuilder(); int read; while ((read = stream.read()) >= 0) { buffer.append((char) read); } stream.close(); assertEquals(TEST_STR, buffer.toString()); conn.stop(); }
From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java
private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf, String name) throws NamingException, JMSException, InterruptedException { AtomicInteger totalReceived = new AtomicInteger(0); System.out.printf("Subscription %s: \n", name); Destination subscription = (Destination) context.lookup(name); // Create Connection Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey()); connection.start();/*from w w w. jav a 2 s. c o m*/ // Create Session, no transaction, client ack Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create consumer MessageConsumer consumer = session.createConsumer(subscription); // Set callback listener. Gets called for each received message. consumer.setMessageListener(message -> { try { System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter message.getJMSMessageID()); message.acknowledge(); } catch (Exception e) { System.out.printf("%s", e.toString()); } }); // wait on the main thread until all sent messages have been received while (totalReceived.get() < totalSend) { Thread.sleep(1000); } consumer.close(); session.close(); connection.stop(); connection.close(); }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Gets an MQ message off a specified queue and returns it as an * <code>Object</code> to the requestor for further processing. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param responseQueue - The request queue name to put the message on * @param timeout - How long to wait for a connection or response * @param messageId - The JMS correlation ID of the message the response is associated with * @return <code>Object</code> - The serializable data returned by the MQ request * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *//*from ww w. j a v a2 s .co m*/ public static final synchronized Object getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException { final String methodName = MQUtils.CNAME + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", responseQueue); DEBUGGER.debug("Value: {}", timeout); DEBUGGER.debug("Value: {}", messageId); } Connection conn = null; Session session = null; Object response = null; Context envContext = null; MessageConsumer consumer = null; ConnectionFactory connFactory = null; try { try { InitialContext initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } if (envContext != null) { try { consumer = session.createConsumer((Destination) envContext.lookup(responseQueue), "JMSCorrelationID='" + messageId + "'"); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createQueue(responseQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'"); } if (DEBUG) { DEBUGGER.debug("MessageConsumer: {}", consumer); } ObjectMessage message = (ObjectMessage) consumer.receive(timeout); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } if (message == null) { throw new UtilityException("Failed to retrieve message within the timeout specified."); } response = message.getObject(); message.acknowledge(); if (DEBUG) { DEBUGGER.debug("Object: {}", response); } } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return response; }
From source file:com.cws.esolutions.core.utils.MQUtils.java
/** * Puts an MQ message on a specified queue and returns the associated * correlation ID for retrieval upon request. * * @param connName - The connection name to utilize * @param authData - The authentication data to utilize, if required * @param requestQueue - The request queue name to put the message on * @param targetHost - The target host for the message * @param value - The data to place on the request. MUST be <code>Serialiable</code> * @return <code>String</code> - the JMS correlation ID associated with the message * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing *///from ww w. j a v a 2 s . c o m public static final synchronized String sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException { final String methodName = MQUtils.CNAME + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", connName); DEBUGGER.debug("Value: {}", requestQueue); DEBUGGER.debug("Value: {}", targetHost); DEBUGGER.debug("Value: {}", value); } Connection conn = null; Session session = null; Context envContext = null; InitialContext initCtx = null; MessageProducer producer = null; ConnectionFactory connFactory = null; final String correlationId = RandomStringUtils.randomAlphanumeric(64); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } try { try { initCtx = new InitialContext(); envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT); connFactory = (ConnectionFactory) envContext.lookup(connName); } catch (NamingException nx) { // we're probably not in a container connFactory = new ActiveMQConnectionFactory(connName); } if (DEBUG) { DEBUGGER.debug("ConnectionFactory: {}", connFactory); } if (connFactory == null) { throw new UtilityException("Unable to create connection factory for provided name"); } // Create a Connection conn = connFactory.createConnection(authData.get(0), PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3), Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6), authData.get(7), authData.get(8))); conn.start(); if (DEBUG) { DEBUGGER.debug("Connection: {}", conn); } // Create a Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); if (DEBUG) { DEBUGGER.debug("Session: {}", session); } // Create a MessageProducer from the Session to the Topic or Queue if (envContext != null) { try { producer = session.createProducer((Destination) envContext.lookup(requestQueue)); } catch (NamingException nx) { throw new UtilityException(nx.getMessage(), nx); } } else { Destination destination = session.createTopic(requestQueue); if (DEBUG) { DEBUGGER.debug("Destination: {}", destination); } producer = session.createProducer(destination); } if (producer == null) { throw new JMSException("Failed to create a producer object"); } producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); if (DEBUG) { DEBUGGER.debug("MessageProducer: {}", producer); } ObjectMessage message = session.createObjectMessage(true); message.setJMSCorrelationID(correlationId); message.setStringProperty("targetHost", targetHost); if (DEBUG) { DEBUGGER.debug("correlationId: {}", correlationId); } message.setObject(value); if (DEBUG) { DEBUGGER.debug("ObjectMessage: {}", message); } producer.send(message); } catch (JMSException jx) { throw new UtilityException(jx.getMessage(), jx); } finally { try { // Clean up if (!(session == null)) { session.close(); } if (!(conn == null)) { conn.close(); conn.stop(); } } catch (JMSException jx) { ERROR_RECORDER.error(jx.getMessage(), jx); } } return correlationId; }