javax.jms.Connection Java Examples

The following examples show how to use javax.jms.Connection. 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: ChangeSentMessageTest.java    From activemq-artemis with Apache License 2.0 7 votes vote down vote up
/**
 * test Object messages can be changed after sending with no side-affects
 *
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public void testDoChangeSentMessage() throws Exception {
   Destination destination = createDestination("test-" + ChangeSentMessageTest.class.getName());
   Connection connection = createConnection();
   connection.start();
   Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = consumerSession.createConsumer(destination);
   Session publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = publisherSession.createProducer(destination);
   HashMap<String, Integer> map = new HashMap<>();
   ObjectMessage message = publisherSession.createObjectMessage();
   for (int i = 0; i < COUNT; i++) {
      map.put(VALUE_NAME, Integer.valueOf(i));
      message.setObject(map);
      producer.send(message);
      assertTrue(message.getObject() == map);
   }
   for (int i = 0; i < COUNT; i++) {
      ObjectMessage msg = (ObjectMessage) consumer.receive();
      HashMap receivedMap = (HashMap) msg.getObject();
      Integer intValue = (Integer) receivedMap.get(VALUE_NAME);
      assertTrue(intValue.intValue() == i);
   }
}
 
Example #2
Source File: JournalPendingMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduledStats() throws Exception {
   AtomicLong publishedMessageSize = new AtomicLong();

   Connection connection = cf.createConnection();
   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
   producer.setDeliveryDelay(2000);
   producer.send(session.createTextMessage("test"));

   verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
   verifyScheduledStats(defaultQueueName, 1, publishedMessageSize.get());

   consumeTestQueueMessages(1);

   verifyPendingStats(defaultQueueName, 0, 0);
   verifyPendingDurableStats(defaultQueueName, 0, 0);
   verifyScheduledStats(defaultQueueName, 0, 0);

   connection.close();
}
 
Example #3
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslXOauth2Connection() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        // Expect a XOAUTH2 connection
        String user = "user";
        String pass = "eyB1c2VyPSJ1c2VyIiB9";

        testPeer.expectSaslXOauth2(user, pass);
        testPeer.expectOpen();

        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
        Connection connection = factory.createConnection(user, pass);
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #4
Source File: JmsInvokerClientInterceptor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Execute the given remote invocation, sending an invoker request message
 * to this accessor's target queue and waiting for a corresponding response.
 * @param invocation the RemoteInvocation to execute
 * @return the RemoteInvocationResult object
 * @throws JMSException in case of JMS failure
 * @see #doExecuteRequest
 */
protected RemoteInvocationResult executeRequest(RemoteInvocation invocation) throws JMSException {
	Connection con = createConnection();
	Session session = null;
	try {
		session = createSession(con);
		Queue queueToUse = resolveQueue(session);
		Message requestMessage = createRequestMessage(session, invocation);
		con.start();
		Message responseMessage = doExecuteRequest(session, queueToUse, requestMessage);
		if (responseMessage != null) {
			return extractInvocationResult(responseMessage);
		}
		else {
			return onReceiveTimeout(invocation);
		}
	}
	finally {
		JmsUtils.closeSession(session);
		ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), true);
	}
}
 
Example #5
Source File: JMSDurableConsumerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testDurableConsumerUnsubscribeWhileNoSubscription() throws Exception {
   Connection connection = createConnection();

   try {
      connection.start();

      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      assertTrue(Wait.waitFor(new Wait.Condition() {

         @Override
         public boolean isSatisfied() throws Exception {
            return server.getTotalConsumerCount() == 0;
         }
      }, TimeUnit.SECONDS.toMillis(20), TimeUnit.MILLISECONDS.toMillis(250)));

      try {
         session.unsubscribe("DurbaleTopic");
         fail("Should have thrown as subscription is in use.");
      } catch (JMSException ex) {
      }
   } finally {
      connection.close();
   }
}
 
Example #6
Source File: SchedulerDBVersionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Ignore("Used only when a new version of the store needs to archive it's test data.")
@Test
public void testCreateStore() throws Exception {
   JobSchedulerStoreImpl scheduler = new JobSchedulerStoreImpl();
   File dir = new File("src/test/resources/org/apache/activemq/store/schedulerDB/legacy");
   IOHelper.deleteFile(dir);
   scheduler.setDirectory(dir);
   scheduler.setJournalMaxFileLength(1024 * 1024);
   broker = createBroker(scheduler);
   broker.start();
   ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("vm://localhost");
   Connection connection = cf.createConnection();
   connection.start();
   scheduleRepeating(connection);
   connection.close();
   broker.stop();
}
 
Example #7
Source File: CreateSubscriptionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSharedDurableConsumer() throws Exception {

   server.addAddressInfo(new AddressInfo(SimpleString.toSimpleString("myTopic")).addRoutingType(RoutingType.MULTICAST));
   ConnectionFactory cf = CFUtil.createConnectionFactory(protocol, "tcp://localhost:61616");
   Connection connection = cf.createConnection();
   Session session = connection.createSession();
   Connection connecton2 = cf.createConnection();
   Session session2 = connecton2.createSession();

   try {

      Topic topic = session.createTopic("myTopic");

      MessageConsumer messageConsumer = session.createSharedDurableConsumer(topic, "consumer1");
      MessageConsumer messageConsumer2 = session2.createSharedDurableConsumer(topic, "consumer1");



      connection.close();
   } finally {
      connection.close();
      connecton2.close();
   }
}
 
Example #8
Source File: TestMDB.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #9
Source File: ClientJmsDelegate.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public void createSession(final CreateSessionCommand command)
{
    try
    {
        final Connection connection = _testConnections.get(command.getConnectionName());
        if (connection == null)
        {
            throw new DistributedTestException("No test connection found called: " + command.getConnectionName(),
                            command);
        }
        final boolean transacted = command.getAcknowledgeMode() == Session.SESSION_TRANSACTED;

        final Session newSession = connection.createSession(transacted, command.getAcknowledgeMode());
        LOGGER.debug("Created session {} with transacted = {} and acknowledgeMode = {}",
                     command.getSessionName(),
                     newSession.getTransacted(),
                     newSession.getAcknowledgeMode());

        addSession(command.getSessionName(), newSession);
        _testSessionToConnections.put(newSession, connection);
    }
    catch (final JMSException jmse)
    {
        throw new DistributedTestException("Unable to create new session: " + command, jmse);
    }
}
 
Example #10
Source File: JmsTestResource.java    From tomee with Apache License 2.0 6 votes vote down vote up
@GET
@Produces({ MediaType.TEXT_PLAIN })
@Path("/send2imq")
public Response testSend1(@QueryParam("msg") String msg) throws IOException, JMSException {
    Connection connection = imq_connectionFactory.createConnection();
    connection.start();
 
    // Create a Session
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(imq_barQueue);
    
    System.out.println("*************producer.getClass() = "+ producer.getClass());
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
 
    // Create a message
    TextMessage message = session.createTextMessage((msg!=null && !msg.isEmpty()) ? msg : "Hello World!");
 
    // Tell the producer to send the message
    producer.send(message);
 
    return Response.ok().build();
}
 
Example #11
Source File: JMSConnectionWithSecurityTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testCreateTemporaryQueueNotAuthorized() throws JMSException {
   Connection connection = createConnection(guestUser, guestPass);

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      try {
         session.createTemporaryQueue();
      } catch (JMSSecurityException jmsse) {
         instanceLog.debug("Client should have thrown a JMSSecurityException but only threw JMSException");
      }

      // Should not be fatal
      assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE));
   } finally {
      connection.close();
   }
}
 
Example #12
Source File: JobSchedulerManagementTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveNotScheduled() throws Exception {
   Connection connection = createConnection();

   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

   // Create the Browse Destination and the Reply To location
   Destination management = session.createTopic(ScheduledMessage.AMQ_SCHEDULER_MANAGEMENT_DESTINATION);

   MessageProducer producer = session.createProducer(management);

   try {

      // Send the remove request
      Message remove = session.createMessage();
      remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULER_ACTION, ScheduledMessage.AMQ_SCHEDULER_ACTION_REMOVEALL);
      remove.setStringProperty(ScheduledMessage.AMQ_SCHEDULED_ID, new IdGenerator().generateId());
      producer.send(remove);
   } catch (Exception e) {
      fail("Caught unexpected exception during remove of unscheduled message.");
   }
}
 
Example #13
Source File: OutgoingConnectionNoJTATest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleSendNoXAJMS1() throws Exception {
   Queue q = ActiveMQJMSClient.createQueue(MDBQUEUE);
   try (ClientSessionFactory sf = locator.createSessionFactory();
        ClientSession session = sf.createSession();
        ClientConsumer consVerify = session.createConsumer(MDBQUEUE);
        Connection conn = qraConnectionFactory.createConnection();
   ) {
      Session jmsSess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      session.start();
      MessageProducer producer = jmsSess.createProducer(q);
      // These next 4 lines could be written in a single line however it makes difficult for debugging
      TextMessage msgsend = jmsSess.createTextMessage("hello");
      msgsend.setStringProperty("strvalue", "hello");
      producer.send(msgsend);

      ClientMessage msg = consVerify.receive(1000);
      assertNotNull(msg);
      assertEquals("hello", msg.getStringProperty("strvalue"));
   }
}
 
Example #14
Source File: LoadClient.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected String consume() throws Exception {
   Connection con = null;
   MessageConsumer c = consumer;
   if (connectionPerMessage) {
      con = factory.createConnection();
      con.start();
      Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      c = s.createConsumer(getConsumeDestination());
   }
   TextMessage result = (TextMessage) c.receive(timeout);
   if (result != null) {
      if (audit.isDuplicate(result.getJMSMessageID())) {
         throw new JMSException("Received duplicate " + result.getText());
      }
      if (!audit.isInOrder(result.getJMSMessageID())) {
         throw new JMSException("Out of order " + result.getText());
      }

      if (connectionPerMessage) {
         Thread.sleep(SLEEP_TIME);//give the broker a chance
         con.close();
      }
   }
   return result != null ? result.getText() : null;
}
 
Example #15
Source File: ConnectionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetClientID() throws Exception {
   Connection connection = createConnection();

   final String clientID = "my-test-client-id";

   connection.setClientID(clientID);

   ProxyAssertSupport.assertEquals(clientID, connection.getClientID());

   Connection connection2 = createConnection();
   try {
      connection2.setClientID(clientID);
      Assert.fail("setClientID was expected to throw an exception");
   } catch (JMSException e) {
      // expected
   }

   connection.close();

   connection2.setClientID(clientID);
}
 
Example #16
Source File: TransactedJMSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJMSTransaction() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addComponent("jms", jmsComponent);
    camelctx.addRoutes(configureJmsRoutes());

    camelctx.start();

    PollingConsumer consumer = camelctx.getEndpoint("seda:success").createPollingConsumer();
    consumer.start();

    // Send a message to queue camel-jms-queue-one
    Connection connection = connectionFactory.createConnection();
    sendMessage(connection, JmsQueue.QUEUE_ONE.getJndiName(), "Hello Kermit");

    // The JMS transaction should have been committed and the message payload sent to the direct:success endpoint
    String result = consumer.receive(3000).getIn().getBody(String.class);
    Assert.assertNotNull(result);
    Assert.assertEquals("Hello Kermit", result);

    connection.close();
    camelctx.close();
}
 
Example #17
Source File: GeneralInteropTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendBytesMessageUsingCoreJms(String queueName, byte[] data) throws Exception {
   Connection jmsConn = null;
   try {
      jmsConn = coreCf.createConnection();
      Session session = jmsConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      BytesMessage bytesMessage = session.createBytesMessage();

      bytesMessage.writeBytes(data);
      bytesMessage.writeBoolean(true);
      bytesMessage.writeLong(99999L);
      bytesMessage.writeChar('h');
      bytesMessage.writeInt(987);
      bytesMessage.writeShort((short) 1099);
      bytesMessage.writeUTF("hellobytes");

      Queue queue = session.createQueue(queueName);
      MessageProducer producer = session.createProducer(queue);

      producer.send(bytesMessage);
   } finally {
      if (jmsConn != null) {
         jmsConn.close();
      }
   }

}
 
Example #18
Source File: JMSMessageTypesTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void testStreamMessageSendReceive(Connection producerConnection, Connection consumerConnection) throws Throwable {
   Session session = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue queue = session.createQueue(getQueueName());

   MessageProducer producer = session.createProducer(queue);
   for (int i = 0; i < NUM_MESSAGES; i++) {
      StreamMessage message = session.createStreamMessage();
      message.writeInt(i);
      message.writeBoolean(true);
      message.writeString("test");
      producer.send(message);
   }

   Session sessionConsumer = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   Queue consumerQueue = sessionConsumer.createQueue(getQueueName());
   final MessageConsumer consumer = sessionConsumer.createConsumer(consumerQueue);

   for (int i = 0; i < NUM_MESSAGES; i++) {
      StreamMessage m = (StreamMessage) consumer.receive(5000);
      Assert.assertNotNull("Could not receive message count=" + i + " on consumer", m);

      Assert.assertEquals(i, m.readInt());
      Assert.assertEquals(true, m.readBoolean());
      Assert.assertEquals("test", m.readString());
   }
}
 
Example #19
Source File: RestDeserializationTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void jmsSendMessage(Serializable value, String destName, boolean isQueue) throws JMSException {
   ConnectionFactory factory = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
   String jmsDest;
   if (isQueue) {
      jmsDest = QUEUE_QUALIFIED_PREFIX + destName;
   } else {
      jmsDest = TOPIC_QUALIFIED_PREFIX + destName;
   }
   Destination destination = ActiveMQDestination.fromPrefixedName(jmsDest);

   Connection conn = factory.createConnection();
   try {
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(destination);
      ObjectMessage message = session.createObjectMessage();
      message.setStringProperty(HttpHeaderProperty.CONTENT_TYPE, "application/xml");
      message.setObject(value);
      producer.send(message);
   } finally {
      conn.close();
   }
}
 
Example #20
Source File: CommitRollbackTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void produceMessageAndAbortTransactionByClosingSession() throws Exception
{
    final Queue queue = createQueue(getTestName());
    Connection connection = getConnection();
    try
    {
        Session transactedSession = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer transactedProducer = transactedSession.createProducer(queue);
        transactedProducer.send(transactedSession.createTextMessage("A"));
        transactedSession.close();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createProducer(queue);
        messageProducer.send(session.createTextMessage("B"));

        connection.start();
        MessageConsumer messageConsumer = session.createConsumer(queue);
        Message message = messageConsumer.receive(getReceiveTimeout());
        assertTrue("Text message should be received", message instanceof TextMessage);
        assertEquals("Unexpected message received", "B", ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}
 
Example #21
Source File: AbstractJmsListeningContainer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create a shared Connection for this container.
 * <p>The default implementation creates a standard Connection
 * and prepares it through {@link #prepareSharedConnection}.
 * @return the prepared Connection
 * @throws JMSException if the creation failed
 */
protected Connection createSharedConnection() throws JMSException {
	Connection con = createConnection();
	try {
		prepareSharedConnection(con);
		return con;
	}
	catch (JMSException ex) {
		JmsUtils.closeConnection(con);
		throw ex;
	}
}
 
Example #22
Source File: SecurityTestSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * @throws JMSException
 */
public Message doReceive(boolean fail) throws JMSException {

   connection.start();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageConsumer consumer = null;
   try {
      consumer = session.createConsumer(destination);
      if (fail) {
         fail("Expected failure due to security constraint.");
      }
   } catch (JMSException e) {
      if (fail && e.getCause() instanceof SecurityException) {
         return null;
      }
      throw e;
   }

   Connection adminConnection = factory.createConnection("system", "manager");
   connections.add(adminConnection);
   Session adminSession = adminConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   sendMessages(adminSession, destination, 1);

   Message m = consumer.receive(1000);
   assertNotNull(m);
   assertEquals("0", ((TextMessage) m).getText());
   assertNull(consumer.receiveNoWait());
   return m;

}
 
Example #23
Source File: PooledConnectionIdleEvictionsFromPoolTest.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testNotIdledWhenInUse() throws Exception {
    pooledFactory.setConnectionIdleTimeout(10);
    JmsPoolConnection connection = (JmsPoolConnection) pooledFactory.createConnection();
    Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // let connection to get idle
    TimeUnit.MILLISECONDS.sleep(20);

    // get a connection from pool again, it should be the same underlying connection
    // as before and should not be idled out since an open session exists.
    JmsPoolConnection connection2 = (JmsPoolConnection) pooledFactory.createConnection();
    assertSame(connection.getConnection(), connection2.getConnection());

    // now the session is closed even when it should not be
    try {
        // any operation on session first checks whether session is closed
        s.getTransacted();
    } catch (javax.jms.IllegalStateException e) {
        assertTrue("Session should be fine, instead: " + e.getMessage(), false);
    }

    Connection original = connection.getConnection();

    connection.close();
    connection2.close();

    // let connection to get idle
    TimeUnit.MILLISECONDS.sleep(20);

    // get a connection from pool again, it should be a new Connection instance as the
    // old one should have been inactive and idled out.
    JmsPoolConnection connection3 = (JmsPoolConnection) pooledFactory.createConnection();
    assertNotSame(original, connection3.getConnection());
}
 
Example #24
Source File: BatchedMessageListenerContainer.java    From jadira with Apache License 2.0 5 votes vote down vote up
public Connection createConnection() throws JMSException {
    if (BatchedMessageListenerContainer.this.sharedConnectionEnabled()) {
        Connection sharedCon = BatchedMessageListenerContainer.this.getSharedConnection();
        return new SingleConnectionFactory(sharedCon).createConnection();
    } else {
        return BatchedMessageListenerContainer.this.createConnection();
    }
}
 
Example #25
Source File: SingleConnectionFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testWithConnectionFactoryAndLocalExceptionListenerWithReconnect() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	TestConnection con = new TestConnection();
	given(cf.createConnection()).willReturn(con);

	TestExceptionListener listener0 = new TestExceptionListener();
	TestExceptionListener listener1 = new TestExceptionListener();
	TestExceptionListener listener2 = new TestExceptionListener();

	SingleConnectionFactory scf = new SingleConnectionFactory(cf);
	scf.setReconnectOnException(true);
	scf.setExceptionListener(listener0);
	Connection con1 = scf.createConnection();
	con1.setExceptionListener(listener1);
	assertSame(listener1, con1.getExceptionListener());
	con1.start();
	Connection con2 = scf.createConnection();
	con2.setExceptionListener(listener2);
	assertSame(listener2, con2.getExceptionListener());
	con.getExceptionListener().onException(new JMSException(""));
	con2.close();
	con1.getMetaData();
	con.getExceptionListener().onException(new JMSException(""));
	con1.close();
	scf.destroy();  // should trigger actual close

	assertEquals(2, con.getStartCount());
	assertEquals(2, con.getCloseCount());
	assertEquals(2, listener0.getCount());
	assertEquals(2, listener1.getCount());
	assertEquals(1, listener2.getCount());
}
 
Example #26
Source File: MessagingACLTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishIntoDeniedDestinationFails() throws Exception
{
    final String deniedDestinationName = "deniedQueue";
    createQueue(deniedDestinationName);

    configureACL(String.format("ACL ALLOW-LOG %s ACCESS VIRTUALHOST", USER1),
                 String.format("ACL DENY-LOG %s PUBLISH EXCHANGE name=\"*\" routingKey=\"%s\"", USER1, deniedDestinationName));


    Connection connection = getConnectionBuilder().setSyncPublish(true).setUsername(USER1).setPassword(USER1_PASSWORD).build();
    try
    {
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(session.createQueue(deniedDestinationName));
        producer.send(session.createTextMessage("test"));

        fail("Sending should fail");
    }
    catch (JMSException e)
    {
        assertJMSExceptionMessageContains(e,
                                          String.format(
                                                  "Permission PERFORM_ACTION(publish) is denied for : %s",
                                                  (!isLegacyClient() ? "Queue" : "Exchange")));
    }
}
 
Example #27
Source File: JmsAmqpDiscoveryTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
protected Connection createFailingConnection() throws JMSException {
    String discoveryPrefix = DiscoveryProviderFactory.DISCOVERY_OPTION_PREFIX;
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "discovery:(multicast://default?group=altGroup)?" + discoveryPrefix + "startupMaxReconnectAttempts=10" + "&" + discoveryPrefix +"maxReconnectDelay=100");
    connection = factory.createConnection();
    jmsConnection = (JmsConnection) connection;
    jmsConnection.addConnectionListener(this);
    jmsConnection.start();
    return connection;
}
 
Example #28
Source File: CliTestBase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
void closeConnection(ActiveMQConnectionFactory cf, Connection connection) throws Exception {
   try {
      connection.close();
      cf.close();
   } finally {
      stopServer();
   }
}
 
Example #29
Source File: JmsPoolJMSContext.java    From pooled-jms with Apache License 2.0 5 votes vote down vote up
public Connection getConnection() {
    try {
        return connection.getConnection();
    } catch (JMSException jmsex) {
        throw JMSExceptionSupport.createRuntimeException(jmsex);
    }
}
 
Example #30
Source File: MessageRoutingTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousRelayRoutingWithSubjectSetAsJMSMessageType() throws Exception
{
    assumeThat("AMQP 1.0 test", getProtocol(), is(equalTo(Protocol.AMQP_1_0)));

    prepare();

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination sendingDestination = session.createTopic(EXCHANGE_NAME);
        Destination receivingDestination = session.createQueue(QUEUE_NAME);

        Message message = session.createTextMessage("test");
        message.setJMSType(ROUTING_KEY);

        MessageProducer messageProducer = session.createProducer(null);
        messageProducer.send(sendingDestination, message);

        MessageConsumer messageConsumer = session.createConsumer(receivingDestination);
        Message receivedMessage = messageConsumer.receive(getReceiveTimeout());

        assertNotNull("Message not received", receivedMessage);
        assertEquals("test", ((TextMessage) message).getText());
    }
    finally
    {
        connection.close();
    }
}