Java Code Examples for javax.jms.Session#close()
The following examples show how to use
javax.jms.Session#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestMDB.java From tracee with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void onMessage(Message message) { final TextMessage incomingMessage = (TextMessage) message; Connection connection = null; Session session = null; try { connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer producer = TraceeMessageWriter.wrap(session.createProducer(responses)); producer.setDeliveryMode(DeliveryMode.PERSISTENT); final TextMessage responseMessage = session.createTextMessage(incomingMessage.getText()); producer.send(responseMessage); } catch (JMSException e) { throw new IllegalStateException(e); } finally { try { if (session != null) session.close(); if (connection != null) connection.close(); } catch (JMSException ignored) { } } }
Example 2
Source File: CachingConnectionFactory.java From java-technology-stack with MIT License | 6 votes |
/** * Resets the Session cache as well. */ @Override public void resetConnection() { this.active = false; synchronized (this.cachedSessions) { for (LinkedList<Session> sessionList : this.cachedSessions.values()) { synchronized (sessionList) { for (Session session : sessionList) { try { session.close(); } catch (Throwable ex) { logger.trace("Could not close cached JMS Session", ex); } } } } this.cachedSessions.clear(); } // Now proceed with actual closing of the shared Connection... super.resetConnection(); this.active = true; }
Example 3
Source File: JmsClient.java From ats-framework with Apache License 2.0 | 5 votes |
private synchronized Session loadSession( final boolean transacted, final int acknowledgeMode ) throws JMSException { final Session s = session; if (s != null) { if ( (s.getTransacted() == transacted) && (s.getAcknowledgeMode() == acknowledgeMode)) { return s; } s.close(); } final Session newSession = loadConnection().createSession(transacted, acknowledgeMode); session = newSession; return newSession; }
Example 4
Source File: TestGetJMSQueue.java From localization_nifi with Apache License 2.0 | 5 votes |
@Test public void testSendStreamToQueue() throws Exception { PutJMS putJms = new PutJMS(); TestRunner putRunner = TestRunners.newTestRunner(putJms); putRunner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER); putRunner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false"); putRunner.setProperty(JmsProperties.DESTINATION_TYPE, JmsProperties.DESTINATION_TYPE_QUEUE); putRunner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing"); putRunner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO); WrappedMessageProducer wrappedProducer = JmsFactory.createMessageProducer(putRunner.getProcessContext(), true); final Session jmsSession = wrappedProducer.getSession(); final MessageProducer producer = wrappedProducer.getProducer(); final StreamMessage message = jmsSession.createStreamMessage(); message.writeBytes("Hello Stream".getBytes()); producer.send(message); jmsSession.commit(); GetJMSQueue getJmsQueue = new GetJMSQueue(); TestRunner runner = TestRunners.newTestRunner(getJmsQueue); runner.setProperty(JmsProperties.JMS_PROVIDER, JmsProperties.ACTIVEMQ_PROVIDER); runner.setProperty(JmsProperties.URL, "vm://localhost?broker.persistent=false"); runner.setProperty(JmsProperties.DESTINATION_NAME, "queue.testing"); runner.setProperty(JmsProperties.ACKNOWLEDGEMENT_MODE, JmsProperties.ACK_MODE_AUTO); runner.run(); List<MockFlowFile> flowFiles = runner .getFlowFilesForRelationship(new Relationship.Builder().name("success").build()); assertTrue(flowFiles.size() == 1); MockFlowFile successFlowFile = flowFiles.get(0); successFlowFile.assertContentEquals("Hello Stream"); successFlowFile.assertAttributeEquals("jms.JMSDestination", "queue.testing"); producer.close(); jmsSession.close(); }
Example 5
Source File: JAXRSJmsTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testPutBookOneWayWithWebClient() throws Exception { // setup the the client String endpointAddressUrlEncoded = "jms:jndi:dynamicQueues/test.jmstransport.text" + "?replyToName=dynamicQueues/test.jmstransport.response" + "&jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory" + "&jndiURL=tcp://localhost:" + JMS_PORT; WebClient client = WebClient.create(endpointAddressUrlEncoded); WebClient.getConfig(client).getRequestContext() .put(org.apache.cxf.message.Message.REQUEST_URI, "/bookstore/oneway"); client.header("OnewayRequest", "true"); Response r = client.type("application/xml").put(new Book("OneWay From WebClient", 129L)); assertEquals(202, r.getStatus()); assertFalse(r.hasEntity()); Context ctx = getContext(); ConnectionFactory factory = (ConnectionFactory)ctx.lookup("ConnectionFactory"); Destination replyToDestination = (Destination)ctx.lookup("dynamicQueues/test.jmstransport.response"); Connection connection = null; try { connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); checkBookInResponse(session, replyToDestination, 129L, "OneWay From WebClient"); session.close(); } finally { close(connection); } }
Example 6
Source File: JmsClientAckTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
/** * Tests if acknowledged messages are being consumed. * * @throws JMSException */ @Test public void testLastMessageAcked() throws JMSException { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = session.createQueue(getQueueName()); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Hello")); producer.send(session.createTextMessage("Hello2")); producer.send(session.createTextMessage("Hello3")); // Consume the message... MessageConsumer consumer = session.createConsumer(queue); Message msg = consumer.receive(1000); assertNotNull(msg); msg = consumer.receive(1000); assertNotNull(msg); msg = consumer.receive(1000); assertNotNull(msg); msg.acknowledge(); // Reset the session. session.close(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Attempt to Consume the message... consumer = session.createConsumer(queue); msg = consumer.receive(1000); assertNull(msg); session.close(); }
Example 7
Source File: RdbmsMandatoryAccessControlForQueuesTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Parameters({"broker-hostname", "broker-port", "test-username", "test-password"}) @Test(priority = 1, description = "create and publish to a queue by a user who does not have queues:create and " + "queues:publish scopes", expectedExceptions = JMSException.class, expectedExceptionsMessageRegExp = ".*error code 403: access refused.*") public void testCreateAndPublishByTestUser(String brokerHostname, String port, String testUsername, String testPassword) throws NamingException, JMSException { String queueName = "testCreateAndPublishScopeByTestUser"; InitialContext initialContextForQueue = ClientHelper .getInitialContextBuilder(testUsername, testPassword, brokerHostname, port) .withQueue(queueName) .build(); ConnectionFactory connectionFactory = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY); Connection connection = connectionFactory.createConnection(); connection.start(); Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = producerSession.createQueue(queueName); MessageProducer producer = producerSession.createProducer(queue); int numberOfMessages = 1; for (int i = 0; i < numberOfMessages; i++) { producer.send(producerSession.createTextMessage("Test message " + i)); } producerSession.close(); connection.close(); }
Example 8
Source File: JmsRollbackRedeliveryTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Test public void testRedeliveryPropertyWithNoRollback() throws Exception { final int numMessages = 1; ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); Connection connection = connectionFactory.createConnection(); connection.start(); populateDestination(numMessages, destinationName, connection); connection.close(); { AtomicInteger received = new AtomicInteger(); final int maxRetries = new RedeliveryPolicy().getMaximumRedeliveries(); while (received.get() < maxRetries) { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(true, Session.SESSION_TRANSACTED); Destination destination = session.createQueue(destinationName); MessageConsumer consumer = session.createConsumer(destination); TextMessage msg = (TextMessage) consumer.receive(2000); if (msg != null) { LOG.info("Received message " + msg.getText() + " (" + received.getAndIncrement() + ")" + msg.getJMSMessageID()); assertEquals("redelivery property matches deliveries", received.get(), msg.getLongProperty("JMSXDeliveryCount")); } session.close(); connection.close(); } connection = connectionFactory.createConnection(); connection.start(); consumeMessage(connection, maxRetries + 1); } }
Example 9
Source File: FieldInjectionSingletonBean.java From tomee with Apache License 2.0 | 5 votes |
private void testJmsConnection(final javax.jms.Connection connection) throws JMSException { final Session session = connection.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); final Topic topic = session.createTopic("test"); final MessageProducer producer = session.createProducer(topic); producer.send(session.createMessage()); producer.close(); session.close(); connection.close(); }
Example 10
Source File: JMSMessageTypesTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Test(timeout = 60000) public void testAddressControlSendMessage() throws Exception { SimpleString address = RandomUtil.randomSimpleString(); server.createQueue(new QueueConfiguration(address).setRoutingType(RoutingType.ANYCAST)); AddressControl addressControl = ManagementControlHelper.createAddressControl(address, mBeanServer); Assert.assertEquals(1, addressControl.getQueueNames().length); addressControl.sendMessage(null, org.apache.activemq.artemis.api.core.Message.BYTES_TYPE, Base64.encodeBytes("test".getBytes()), false, fullUser, fullPass); Wait.assertEquals(1, addressControl::getMessageCount); Connection connection = createConnection("myClientId"); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(address.toString()); MessageConsumer consumer = session.createConsumer(queue); Message message = consumer.receive(5000); assertNotNull(message); byte[] buffer = new byte[(int)((BytesMessage)message).getBodyLength()]; ((BytesMessage)message).readBytes(buffer); assertEquals("test", new String(buffer)); session.close(); connection.close(); } finally { if (connection != null) { connection.close(); } } }
Example 11
Source File: CommitRollbackTest.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Test public void receiveMessageAndAbortTransactionByClosingSession() throws Exception { final Queue queue = createQueue(getTestName()); Connection connection = getConnection(); try { Utils.sendTextMessage(connection, queue, "A"); connection.start(); Session transactedSession = connection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer transactedConsumer = transactedSession.createConsumer(queue); Message message = transactedConsumer.receive(getReceiveTimeout()); assertTrue("Text message should be received", message instanceof TextMessage); TextMessage textMessage = (TextMessage) message; assertEquals("Unexpected message received", "A", textMessage.getText()); transactedSession.close(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(queue); Message message2 = messageConsumer.receive(getReceiveTimeout()); assertTrue("Text message should be received", message2 instanceof TextMessage); assertEquals("Unexpected message received", "A", ((TextMessage) message2).getText()); } finally { connection.close(); } }
Example 12
Source File: JmsOfflineBehaviorTests.java From qpid-jms with Apache License 2.0 | 5 votes |
@Test(timeout=60000) public void testSessionCloseWithOpenResourcesDoesNotBlock() throws Exception { URI brokerURI = new URI(getAmqpFailoverURI()); Connection connection = createAmqpConnection(brokerURI); connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Queue queue = session.createQueue(name.getMethodName()); session.createConsumer(queue); session.createProducer(queue); stopPrimaryBroker(); session.close(); connection.close(); }
Example 13
Source File: RejectOverflowPolicyTest.java From qpid-broker-j with Apache License 2.0 | 4 votes |
private void verifyOverflowPolicyRejectingSecondMessage(final Queue queue) throws NamingException, JMSException { final Connection producerConnection = getConnectionBuilder().setSyncPublish(true).build(); try { final Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Message firstMessage = nextMessage(0, producerSession); final Message secondMessage = nextMessage(1, producerSession); try { final MessageProducer producer = producerSession.createProducer(queue); producer.send(firstMessage); try { producer.send(secondMessage); fail("Message send should fail due to reject policy"); } catch (JMSException e) { // pass } } finally { producerSession.close(); } final Session producerSession2 = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageProducer producer2 = producerSession2.createProducer(queue); final Connection consumerConnection = getConnection(); try { Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = consumerSession.createConsumer(queue); consumerConnection.start(); Message message = consumer.receive(getReceiveTimeout()); assertNotNull("Message is not received", message); assertEquals(0, message.getIntProperty(INDEX)); consumerSession.commit(); producer2.send(secondMessage); Message message2 = consumer.receive(getReceiveTimeout()); assertNotNull("Message is not received", message2); assertEquals(1, message2.getIntProperty(INDEX)); consumerSession.commit(); } finally { consumerConnection.close(); } } finally { producerConnection.close(); } }
Example 14
Source File: ConnectionTest.java From activemq-artemis with Apache License 2.0 | 4 votes |
@Test public void testTXTypeInvalid() throws Exception { conn = cf.createConnection(); Session sess = conn.createSession(false, Session.SESSION_TRANSACTED); assertEquals(Session.AUTO_ACKNOWLEDGE, sess.getAcknowledgeMode()); sess.close(); TopicSession tpSess = ((TopicConnection) conn).createTopicSession(false, Session.SESSION_TRANSACTED); assertEquals(Session.AUTO_ACKNOWLEDGE, tpSess.getAcknowledgeMode()); tpSess.close(); QueueSession qSess = ((QueueConnection) conn).createQueueSession(false, Session.SESSION_TRANSACTED); assertEquals(Session.AUTO_ACKNOWLEDGE, qSess.getAcknowledgeMode()); qSess.close(); }
Example 15
Source File: DurableSubProcessTest.java From activemq-artemis with Apache License 2.0 | 4 votes |
private void process(long millis) throws JMSException { long end = System.currentTimeMillis() + millis; long hardEnd = end + 2000; // wait to finish the transaction. boolean inTransaction = false; int transCount = 0; LOG.info(toString() + " ONLINE."); Connection con = openConnection(); Session sess = con.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = sess.createDurableSubscriber(topic, SUBSCRIPTION_NAME, selector, false); try { do { long max = end - System.currentTimeMillis(); if (max <= 0) { if (!inTransaction) break; max = hardEnd - System.currentTimeMillis(); if (max <= 0) exit("" + this + " failed: Transaction is not finished."); } Message message = consumer.receive(max); if (message == null) continue; onClientMessage(message); if (message.propertyExists("COMMIT")) { message.acknowledge(); LOG.info("Received Trans[id=" + message.getIntProperty("TRANS") + ", count=" + transCount + "] in " + this + "."); inTransaction = false; transCount = 0; } else { inTransaction = true; transCount++; } } while (true); } finally { sess.close(); con.close(); LOG.info(toString() + " OFFLINE."); // Check if the messages are in the waiting // list for long time. Message topMessage = waitingList.peek(); if (topMessage != null) checkDeliveryTime(topMessage); } }
Example 16
Source File: ClientIDNullTestCase.java From product-ei with Apache License 2.0 | 4 votes |
/** * Tests if sending and receiving topic message works correctly without a client ID.Steps are, * 1. Using a non transacted session to publish a message to queue * 2. Subscribe to the published queue and see if the message is received. */ @Test(groups = { "wso2.mb", "dtx" }) public void performClientTopicTestCase() throws NamingException, JMSException, XAException, XPathExpressionException, InterruptedException { String topicName = "ClientIDNullTestCasePerformClientTopicTestCase"; InitialContext initialContext = JMSClientHelper.createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort()) .withNoClientId() .withTopic(topicName) .build(); // Publish to queue and rollback ConnectionFactory connectionFactory = (ConnectionFactory) initialContext .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY); Destination xaTestQueue = (Destination) initialContext.lookup(topicName); // subscribe and see if the message is received Connection subscriberConnection = connectionFactory.createConnection(); subscriberConnection.start(); Session subscriberSession = subscriberConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = subscriberSession.createConsumer(xaTestQueue); Connection publisherConnection = connectionFactory.createConnection(); publisherConnection.start(); Session publisherSession = publisherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = publisherSession.createProducer(xaTestQueue); producer.send(publisherSession.createTextMessage("Test 1")); publisherSession.close(); publisherConnection.close(); TimeUnit.SECONDS.sleep(10); // wait 5 seconds Message receive = messageConsumer.receive(5000); Assert.assertNotNull(receive, "Message was not received."); subscriberConnection.close(); }
Example 17
Source File: JmsIOTest.java From beam with Apache License 2.0 | 4 votes |
@Test public void testCheckpointMarkSafety() throws Exception { final int messagesToProcess = 100; // we are using no prefetch here // prefetch is an ActiveMQ feature: to make efficient use of network resources the broker // utilizes a 'push' model to dispatch messages to consumers. However, in the case of our // test, it means that we can have some latency between the receiveNoWait() method used by // the consumer and the prefetch buffer populated by the broker. Using a prefetch to 0 means // that the consumer will poll for message, which is exactly what we want for the test. // We are also sending message acknowledgements synchronously to ensure that they are // processed before any subsequent assertions. Connection connection = connectionFactoryWithSyncAcksAndWithoutPrefetch.createConnection(USERNAME, PASSWORD); connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Fill the queue with messages MessageProducer producer = session.createProducer(session.createQueue(QUEUE)); for (int i = 0; i < messagesToProcess; i++) { producer.send(session.createTextMessage("test " + i)); } producer.close(); session.close(); connection.close(); // create a JmsIO.Read with a decorated ConnectionFactory which will introduce a delay in // sending // acknowledgements - this should help uncover threading issues around checkpoint management. JmsIO.Read spec = JmsIO.read() .withConnectionFactory( withSlowAcks(connectionFactoryWithSyncAcksAndWithoutPrefetch, 10)) .withUsername(USERNAME) .withPassword(PASSWORD) .withQueue(QUEUE); JmsIO.UnboundedJmsSource source = new JmsIO.UnboundedJmsSource(spec); JmsIO.UnboundedJmsReader reader = source.createReader(null, null); // start the reader and move to the first record assertTrue(reader.start()); // consume half the messages (NB: start already consumed the first message) for (int i = 0; i < (messagesToProcess / 2) - 1; i++) { assertTrue(reader.advance()); } // the messages are still pending in the queue (no ACK yet) assertEquals(messagesToProcess, count(QUEUE)); // we finalize the checkpoint for the already-processed messages while simultaneously consuming // the remainder of // messages from the queue Thread runner = new Thread( () -> { try { for (int i = 0; i < messagesToProcess / 2; i++) { assertTrue(reader.advance()); } } catch (IOException ex) { throw new RuntimeException(ex); } }); runner.start(); reader.getCheckpointMark().finalizeCheckpoint(); // Concurrency issues would cause an exception to be thrown before this method exits, failing // the test runner.join(); }
Example 18
Source File: DurableSubscriptionOffline1Test.java From activemq-artemis with Apache License 2.0 | 4 votes |
@Test public void testConsumeOnlyMatchedMessages() throws Exception { // create durable subscription Connection con = createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); session.close(); con.close(); // send messages con = createConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(null); int sent = 0; for (int i = 0; i < 10; i++) { boolean filter = i % 2 == 1; if (filter) sent++; Message message = session.createMessage(); message.setStringProperty("filter", filter ? "true" : "false"); producer.send(topic, message); } session.close(); con.close(); // consume messages con = createConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createDurableSubscriber(topic, "SubsId", "filter = 'true'", true); DurableSubscriptionOfflineTestListener listener = new DurableSubscriptionOfflineTestListener(); consumer.setMessageListener(listener); Thread.sleep(3 * 1000); session.close(); con.close(); assertEquals(sent, listener.count); }
Example 19
Source File: SessionTest.java From activemq-artemis with Apache License 2.0 | 3 votes |
@Test public void testCloseInTransaction() throws Exception { // send a message to the queue Connection conn = getConnectionFactory().createConnection(); Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); s.createProducer(queue1).send(s.createTextMessage("bex")); conn.close(); conn = getConnectionFactory().createConnection(); Session session = conn.createSession(true, -1); conn.start(); TextMessage m = (TextMessage) session.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("bex", m.getText()); // make sure the acknowledment hasn't been sent to the channel assertRemainingMessages(1); // close the session session.close(); // JMS 1.1 4.4.1: "Closing a transacted session must roll back its transaction in progress" assertRemainingMessages(1); conn.close(); // make sure I can still get the right message conn = getConnectionFactory().createConnection(); s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); conn.start(); TextMessage rm = (TextMessage) s.createConsumer(queue1).receive(1000); ProxyAssertSupport.assertEquals("bex", rm.getText()); conn.close(); }
Example 20
Source File: AcknowledgementTest.java From activemq-artemis with Apache License 2.0 | 2 votes |
@Test public void testMessageListenerDupsOK() throws Exception { Connection conn = createConnection(); Session sessSend = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(queue1); log.trace("Sending messages"); TextMessage tm1 = sessSend.createTextMessage("a"); TextMessage tm2 = sessSend.createTextMessage("b"); TextMessage tm3 = sessSend.createTextMessage("c"); prod.send(tm1); prod.send(tm2); prod.send(tm3); log.trace("Sent messages"); sessSend.close(); assertRemainingMessages(3); conn.start(); Session sessReceive = conn.createSession(false, Session.DUPS_OK_ACKNOWLEDGE); log.trace("Creating consumer"); MessageConsumer cons = sessReceive.createConsumer(queue1); log.trace("Created consumer"); MessageListenerDupsOK listener = new MessageListenerDupsOK(sessReceive); log.trace("Setting message listener"); cons.setMessageListener(listener); log.trace("Set message listener"); listener.waitForMessages(); cons.close(); assertRemainingMessages(0); ProxyAssertSupport.assertFalse(listener.failed); }