List of usage examples for javax.jms Connection createSession
Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;
From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java
private String requestParse(final Long documentId, final String content) { Connection connection = null; Session session = null;//from w w w . j a v a 2 s .c o m MessageProducer producer = null; // set up JMS connection, session, consumer, producer try { connection = this.connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(this.requestQueue); logger.info("Sending parse request, document ID: " + documentId); final TextMessage textMessage = session.createTextMessage(content); textMessage.setJMSReplyTo(this.responseQueue); textMessage.setLongProperty(DOCUMENT_ID, documentId); producer.send(textMessage); } catch (JMSException e) { throw new RuntimeException(e); } finally { try { if (producer != null) { producer.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } catch (JMSException e) { throw new RuntimeException(e); } } return content; }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridgeBrokers(SPOKE, HUB);/* www .j a v a 2 s . c o m*/ startAllBrokers(); // Setup connection URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); remoteConsumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { TextMessage textMsg = (TextMessage) msg; receivedMsgs++; LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); // allow subscription information to flow back to Spoke sleep(1000); // Setup producer MessageProducer localProducer = sesHub.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { sleep(50); if (i == 50 || i == 150) { if (simulateStalledNetwork) { socketProxy.pause(); } else { socketProxy.close(); } networkDownTimeStart = System.currentTimeMillis(); } else if (networkDownTimeStart > 0) { // restart after NETWORK_DOWN_TIME seconds sleep(NETWORK_DOWN_TIME); networkDownTimeStart = 0; if (simulateStalledNetwork) { socketProxy.goOn(); } else { socketProxy.reopen(); } } else { // slow message production to allow bridge to recover and limit message duplication sleep(500); } Message test = sesHub.createTextMessage("test-" + i); localProducer.send(test); } LOG.info("waiting for messages to flow"); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return receivedMsgs >= MESSAGE_COUNT; } }); assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); brokers.get(HUB).broker.deleteAllMessages(); brokers.get(SPOKE).broker.deleteAllMessages(); conHub.close(); conSpoke.close(); }
From source file:org.jbpm.ejb.CommandListenerBean.java
private void sendResult(Serializable result, Destination destination, String correlationId) throws JMSException { if (log.isDebugEnabled()) log.debug("sending " + result + " to " + destination); Connection jmsConnection = jmsConnectionFactory.createConnection(); try {/*from w w w . jav a 2 s.c o m*/ /* * if the connection supports xa, the session will be transacted, else the session will * auto acknowledge; in either case no explicit transaction control must be performed - * see ejb 2.1 - 17.3.5 */ Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Message resultMessage = jmsSession.createObjectMessage(result); resultMessage.setJMSCorrelationID(correlationId); MessageProducer producer = jmsSession.createProducer(destination); producer.send(resultMessage); } finally { // there is no need to close the sessions and producers of a closed connection // http://download.oracle.com/javaee/1.4/api/javax/jms/Connection.html#close() try { jmsConnection.close(); } catch (JMSException e) { log.warn("failed to close jms connection", e); } } }
From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java
protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name) throws Exception { conn.setClientID(name);// w w w . j a va2 s .c o m connections.add(conn); conn.start(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name); return consumer; }
From source file:ProducerTool.java
public void run() { Connection connection = null; try {//from w w w . j av a 2s .c om // Create the connection. ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); connection = connectionFactory.createConnection(); connection.start(); // Create the session Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); if (topic) { destination = session.createTopic(subject); } else { destination = session.createQueue(subject); } // Create the producer. MessageProducer producer = session.createProducer(destination); if (persistent) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } if (timeToLive != 0) { producer.setTimeToLive(timeToLive); } // Start sending messages sendLoop(session, producer); System.out.println("[" + this.getName() + "] Done."); synchronized (lockResults) { ActiveMQConnection c = (ActiveMQConnection) connection; System.out.println("[" + this.getName() + "] Results:\n"); c.getConnectionStats().dump(new IndentPrinter()); } } catch (Exception e) { System.out.println("[" + this.getName() + "] Caught: " + e); e.printStackTrace(); } finally { try { connection.close(); } catch (Throwable ignore) { } } }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
private void sendMessage(BrokerService brokerService, String body) throws Exception { TransportConnector connector = brokerService.getTransportConnectors().get(0); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri()); Connection connection = factory.createConnection(); try {//from w w w .j a v a2s. co m connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("FOO")); producer.send(session.createTextMessage(body)); } finally { connection.close(); } }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception { ArrayList<String> rc = new ArrayList<String>(); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( "tcp://localhost:" + connectPort(brokerService)); Connection connection = factory.createConnection(); try {/*from w w w . j a v a 2 s . c o m*/ connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); QueueBrowser browser = session.createBrowser(session.createQueue("FOO")); Enumeration enumeration = browser.getEnumeration(); while (enumeration.hasMoreElements()) { TextMessage textMessage = (TextMessage) enumeration.nextElement(); rc.add(textMessage.getText()); } } finally { connection.close(); } return rc; }
From source file:org.sofun.core.messaging.SofunMessagingServiceImpl.java
@Override public void sendMessage(Serializable message, String destination) { Connection connection = null; Session session = null;/*from w w w .j av a2s. co m*/ MessageProducer sender = null; Queue q = getQueueFor(destination); if (q == null) { log.error("Cannot find associated queue for destination=" + destination); } try { connection = connFactory.createConnection(SofunMessagingCredentials.USERNAME, SofunMessagingCredentials.PASSWORD); session = connection.createSession(true, 0); sender = session.createProducer(q); ObjectMessage msg = session.createObjectMessage(message); sender.send(msg); } catch (Exception e) { log.error(e.getMessage()); } finally { try { if (sender != null) { sender.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } catch (JMSException e) { log.error(e.getMessage()); } } }
From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java
/** * {@inheritDoc}/* w w w.ja v a 2 s. c om*/ * */ @Override public String[] executeInternal(final TaskExecutionEnv env, final SendType config, final Map<String, Properties> idPropertyMap) throws TaskExecutionException, BlackboardAccessException, RecordFilterNotFoundException { Connection connection = null; Session session = null; try { // get cached connection, if do not cache connections -> socket error when many records pushed connection = env.getServices().getBrokerConnections().getConnection(config, true); connection.start(); session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); final Destination destination = session.createQueue(config.getQueue()); final MessageProducer producer = session.createProducer(destination); if (config.isPersistentDelivery()) { producer.setDeliveryMode(DeliveryMode.PERSISTENT); } else { producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } final Iterator<Entry<String, Properties>> entries = idPropertyMap.entrySet().iterator(); while (entries.hasNext()) { final Entry<String, Properties> entry = entries.next(); // get message record, optionally a filtered copy. final Record record = createMessageRecord(entry.getKey(), config, env); // prepare queue message. messages are actually sent on session.commit() below. producer.send(createMessage(config, record, entry.getValue(), session)); } // we must commit here so that the message consumer find the correct record version in storages. env.getBlackboard().commit(); env.setCommitRequired(false); // finally send the messages. session.commit(); return idPropertyMap.keySet().toArray(new String[idPropertyMap.size()]); } catch (final Throwable e) { _log.error(msg("Error"), e); rollbackQuietly(session); throw new TaskExecutionException(e); } finally { closeQuietly(session); closeQuietly(connection); } }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore//w w w . ja v a 2s.c om public void testReplicationQuorumLoss() throws Throwable { System.out.println("======================================"); System.out.println(" Start 2 ActiveMQ nodes."); System.out.println("======================================"); startBrokerAsync(createBrokerNode("node-1", port)); startBrokerAsync(createBrokerNode("node-2", port)); BrokerService master = waitForNextMaster(); System.out.println("======================================"); System.out.println(" Start the producer and consumer"); System.out.println("======================================"); final AtomicBoolean stopClients = new AtomicBoolean(false); final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100); final AtomicLong receivedCounter = new AtomicLong(); final AtomicLong sentCounter = new AtomicLong(); Thread producer = startFailoverClient("producer", new Client() { @Override public void execute(Connection connection) throws Exception { Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("test")); long actual = 0; while (!stopClients.get()) { TextMessage msg = session.createTextMessage("Hello World"); msg.setLongProperty("id", actual++); producer.send(msg); sentCounter.incrementAndGet(); } } }); Thread consumer = startFailoverClient("consumer", new Client() { @Override public void execute(Connection connection) throws Exception { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue("test")); long expected = 0; while (!stopClients.get()) { Message msg = consumer.receive(200); if (msg != null) { long actual = msg.getLongProperty("id"); if (actual != expected) { errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected); } msg.acknowledge(); expected = actual + 1; receivedCounter.incrementAndGet(); } } } }); try { assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); System.out.println("======================================"); System.out.println(" Master should stop once the quorum is lost."); System.out.println("======================================"); ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum. assertStopsWithin(master, 10, TimeUnit.SECONDS); assertNull(errors.poll()); // clients should not see an error since they are failover clients. stopped.add(master); System.out.println("======================================"); System.out.println(" Restart the slave. Clients should make progress again.."); System.out.println("======================================"); startBrokersAsync(createBrokerNodes(stopped)); assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { // Wait for the clients to stop.. stopClients.set(true); producer.join(); consumer.join(); } }