Java Code Examples for javax.jms.ConnectionFactory#createConnection()

The following examples show how to use javax.jms.ConnectionFactory#createConnection() . 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: ClientJmsDelegate.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public void createConnection(final CreateConnectionCommand command)
{
    try
    {
        final ConnectionFactory connectionFactory = (ConnectionFactory) _context.lookup(command
                        .getConnectionFactoryName());
        final Connection newConnection = connectionFactory.createConnection();
        addConnection(command.getConnectionName(), newConnection);
        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("Connection " + command.getConnectionName() + " is created " + metaDataToString(newConnection.getMetaData()));
        }
    }
    catch (final NamingException ne)
    {
        throw new DistributedTestException("Unable to lookup factoryName: " + command.getConnectionFactoryName(),
                        ne);
    }
    catch (final JMSException jmse)
    {
        throw new DistributedTestException("Unable to create connection: " + command.getConnectionName()
                        + " (using factory name: " + command.getConnectionFactoryName() + ")", jmse);
    }
}
 
Example 2
Source File: SaslGssApiIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doSaslGssApiKrbConnectionTestImpl(String configScope, String clientAuthIdAtServer) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        testPeer.expectSaslGSSAPI(servicePrincipal, KRB5_KEYTAB, clientAuthIdAtServer);
        testPeer.expectOpen();

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

        String uriOptions = "?amqp.saslMechanisms=" + GSSAPI;
        if(configScope != null) {
            uriOptions += "&sasl.options.configScope=" + configScope;
        }

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
        Connection connection = factory.createConnection("ignoredusername", null);
        // 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 3
Source File: PooledConnectionTempQueueTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
private void sendWithReplyToTemp(ConnectionFactory cf, String serviceQueue) throws JMSException, InterruptedException {
    Connection connection = cf.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();
        TextMessage msg = session.createTextMessage("Request");
        msg.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(serviceQueue));
        producer.send(msg);

        MessageConsumer consumer = session.createConsumer(tempQueue);
        Message replyMsg = consumer.receive();
        assertNotNull(replyMsg);

        LOG.debug("Reply message: {}", replyMsg);

        consumer.close();

        producer.close();
        session.close();
    } finally {
        connection.close();
    }
}
 
Example 4
Source File: SpringConsumer.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void start() throws JMSException {
   String selector = "next = '" + myId + "'";

   try {
      ConnectionFactory factory = template.getConnectionFactory();
      final Connection c = connection = factory.createConnection();

      // we might be a reusable connection in spring
      // so lets only set the client ID once if its not set
      synchronized (c) {
         if (c.getClientID() == null) {
            c.setClientID(myId);
         }
      }

      connection.start();

      session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
      consumer = session.createConsumer(destination, selector, false);
      consumer.setMessageListener(this);
   } catch (JMSException ex) {
      LOG.error("", ex);
      throw ex;
   }
}
 
Example 5
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private JmsConnection establishAnonymousConnecton(String connectionParams, String failoverParams, TestAmqpPeer... peers) throws JMSException {
    if (peers.length == 0) {
        throw new IllegalArgumentException("No test peers were given, at least 1 required");
    }

    String remoteURI = "failover:(";
    boolean first = true;
    for (TestAmqpPeer peer : peers) {
        if (!first) {
            remoteURI += ",";
        }
        remoteURI += createPeerURI(peer, connectionParams);
        first = false;
    }

    if (failoverParams == null) {
        remoteURI += ")?failover.maxReconnectAttempts=10";
    } else {
        remoteURI += ")?" + failoverParams;
    }

    ConnectionFactory factory = new JmsConnectionFactory(remoteURI);
    Connection connection = factory.createConnection();

    return (JmsConnection) connection;
}
 
Example 6
Source File: PooledConnectionTest.java    From pooled-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testSetClientIDAfterConnectionStart() throws Exception {
    LOG.debug("running testRepeatedSetClientIDCalls()");

    ConnectionFactory cf = createPooledConnectionFactory();
    Connection conn = cf.createConnection();

    // test: try to call setClientID() after start()
    // should result in an exception
    try {
        conn.start();
        conn.setClientID("newID3");
        fail("Calling setClientID() after start() must raise a JMSException.");
    } catch (IllegalStateException ise) {
        LOG.debug("Correctly received " + ise);
    } finally {
        conn.close();
        ((JmsPoolConnectionFactory) cf).stop();
    }

    LOG.debug("Test finished.");
}
 
Example 7
Source File: SecurityTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * user/pwd with preconfigured clientID, should return preconf
 */
@Test
public void testPreConfClientID() throws Exception {
   Connection conn = null;
   try {
      ActiveMQServerTestCase.deployConnectionFactory("dilbert-id", "preConfcf", "preConfcf");
      ConnectionFactory cf = (ConnectionFactory) getInitialContext().lookup("preConfcf");
      conn = cf.createConnection("guest", "guest");
      String clientID = conn.getClientID();
      ProxyAssertSupport.assertEquals("Invalid ClientID", "dilbert-id", clientID);
   } finally {
      if (conn != null) {
         conn.close();
      }
      ActiveMQServerTestCase.undeployConnectionFactory("preConfcf");
   }
}
 
Example 8
Source File: ArtemisJMSClientFeatureIT.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testArtemisJMSClient() throws Exception {
   // setup connection
   ConnectionFactory cf = new ActiveMQJMSConnectionFactory("tcp://localhost:61616");
   try (Connection connection = cf.createConnection()) {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      connection.start();
      Queue queue = ActiveMQJMSClient.createQueue("artemisJMSClientFeatureITQueue");
      MessageProducer producer = session.createProducer(queue);
      // send message
      String textMessage = "This is a text message";
      TextMessage message = session.createTextMessage(textMessage);
      producer.send(message);

      // receive message and assert
      MessageConsumer messageConsumer = session.createConsumer(queue);
      TextMessage messageReceived = (TextMessage) messageConsumer.receive(100);
      assertEquals(textMessage, messageReceived.getText());
   }
}
 
Example 9
Source File: NumberOfDestinationsTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public void testDestinations() throws Exception {
   ConnectionFactory factory = createConnectionFactory();
   Connection connection = factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   MessageProducer mp = session.createProducer(null);
   for (int j = 0; j < NUMBER_OF_DESTINATIONS; j++) {
      Destination dest = getDestination(session);

      for (int i = 0; i < MESSAGE_COUNT; i++) {
         Message msg = session.createTextMessage("test" + i);
         mp.send(dest, msg);

      }
      if (j % 500 == 0) {
         LOG.info("Iterator " + j);
      }
   }

   connection.close();
}
 
Example 10
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 11
Source File: AndesJMSPublisher.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JMS publisher with a given configuration.
 *
 * @param config          The configuration
 * @param createPublisher Creates connection, session and sender.
 * @throws NamingException
 * @throws JMSException
 */
public AndesJMSPublisher(AndesJMSPublisherClientConfiguration config, boolean createPublisher)
        throws NamingException, JMSException {
    super(config);

    // Sets the configuration
    this.publisherConfig = config;

    if (null != config.getMessagesContentToSet()) {
        this.messageContent = config.getMessagesContentToSet();
    }

    // Creates a JMS connection, sessions and sender
    if (createPublisher) {
        ConnectionFactory connFactory = (ConnectionFactory) super.getInitialContext()
                .lookup(AndesClientConstants.CF_NAME);
        connection = connFactory.createConnection();
        connection.start();
        if(config.isTransactionalSession()) {
            this.session = connection.createSession(true, 0);
        } else {
            this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        }

        Destination destination = (Destination) super.getInitialContext()
                .lookup(this.publisherConfig.getDestinationName());
        this.sender = this.session.createProducer(destination);
    }
}
 
Example 12
Source File: MdbProxy.java    From tomee with Apache License 2.0 5 votes vote down vote up
public MdbInvocationHandler(final ConnectionFactory connectionFactory, final String requestQueueName) throws JMSException {
    // open a connection
    connection = connectionFactory.createConnection();
    connection.start();

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

    // create the request queue
    requestQueue = session.createQueue(requestQueueName);

    // create a producer which is used to send requests
    producer = session.createProducer(requestQueue);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
 
Example 13
Source File: MdbProxy.java    From tomee with Apache License 2.0 5 votes vote down vote up
public MdbInvocationHandler(final ConnectionFactory connectionFactory, final String requestQueueName) throws JMSException {
    // open a connection
    connection = connectionFactory.createConnection();
    connection.start();

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

    // create the request queue
    final Destination requestQueue = session.createQueue(requestQueueName);

    // create a producer which is used to send requests
    producer = session.createProducer(requestQueue);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
}
 
Example 14
Source File: VirtualTopicMappingExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
   Connection connection = null;
   try {

      ConnectionFactory cf = new ActiveMQConnectionFactory();

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

      //create consumer on queue that is used by the Virtual Topic
      Queue queue = session.createQueue("Consumer.A.VirtualTopic.Orders");
      MessageConsumer messageConsumer = session.createConsumer(queue);
      connection.start();

      //send message to virtual topic
      Topic topic = session.createTopic("VirtualTopic.Orders");
      MessageProducer producer = session.createProducer(topic);
      TextMessage message = session.createTextMessage("This is a text message");
      producer.send(message);

      System.out.println("Sent message with ID: " + message.getJMSMessageID() + " to Topic: " + topic.getTopicName());

      //consume the message from the backing queue
      TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);

      if (messageReceived != null) {
         System.out.println("Received message with ID: " + messageReceived.getJMSMessageID() + " from Queue: " + queue.getQueueName());
      } else {
         //unexpected outcome
         throw new RuntimeException("EXAMPLE FAILED - No message received from Queue: " + queue.getQueueName());
      }
   } finally {
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 15
Source File: DelegatingConnectionFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public QueueConnection createQueueConnection(String username, String password) throws JMSException {
	ConnectionFactory target = obtainTargetConnectionFactory();
	if (target instanceof QueueConnectionFactory) {
		return ((QueueConnectionFactory) target).createQueueConnection(username, password);
	}
	else {
		Connection con = target.createConnection(username, password);
		if (!(con instanceof QueueConnection)) {
			throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
		}
		return (QueueConnection) con;
	}
}
 
Example 16
Source File: PendingDeliveriesTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static void main(String[] arg) {
   if (arg.length != 3) {
      System.err.println("Usage:: URI destinationName cleanShutdown");
      System.exit(-1);
   }

   String uri = arg[0];
   String destinationName = arg[1];
   boolean cleanShutdown = Boolean.valueOf(arg[2]);

   ConnectionFactory factory;

   factory = createCF(uri);

   try {
      Connection connection = factory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = session.createQueue(destinationName);

      System.err.println("***** " + destination);
      connection.start();
      MessageConsumer consumer = session.createConsumer(destination);
      MessageProducer producer = session.createProducer(destination);

      for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
         producer.send(session.createTextMessage("hello"));
      }

      System.err.println("CleanShutdown::" + cleanShutdown);

      if (cleanShutdown) {
         consumer.close();
         connection.close();
      }

      System.exit(0);

   } catch (Throwable e) {
      e.printStackTrace();
      System.exit(-1);
   }

}
 
Example 17
Source File: CursorSupport.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException {
   Connection connection = fac.createConnection();
   connection.setClientID("testConsumer");
   connection.start();
   return connection;
}
 
Example 18
Source File: DtxStartPositiveTestCase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if publishing messages works correctly with session suspending and resuming.Steps are,
 * 1. Using a distributed transaction a message is published to a queue and session is suspended
 * 2. Subscribe to the published queue and see if any message is received.
 * 3. Resume the suspended session and publish another message and commit
 * 4. Subscribe to the queue and see if two messages are received
 */
@Test(groups = { "wso2.mb", "dtx" })
public void suspendResumeQueuePublishTestCase()
        throws NamingException, JMSException, XAException, XPathExpressionException {
    String queueName = "DtxStartPositiveTestCaseSuspendResumeQueuePublishTestCase";

    InitialContext initialContext = JMSClientHelper.createInitialContextBuilder("admin", "admin", "localhost",
            getAMQPPort()).withQueue(queueName).build();

    // Publish to queue and rollback
    XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY);

    XAConnection xaConnection = connectionFactory.createXAConnection();
    xaConnection.start();
    XASession xaSession = xaConnection.createXASession();

    XAResource xaResource = xaSession.getXAResource();
    Session session = xaSession.getSession();

    Destination xaTestQueue = (Destination) initialContext.lookup(queueName);
    session.createQueue(queueName);
    MessageProducer producer = session.createProducer(xaTestQueue);

    Xid xid = JMSClientHelper.getNewXid();

    xaResource.start(xid, XAResource.TMNOFLAGS);
    producer.send(session.createTextMessage("Test 1"));
    xaResource.end(xid, XAResource.TMSUSPEND);

    // subscribe and see if the message is received
    ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext
            .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY);
    Connection queueConnection = queueConnectionFactory.createConnection();
    queueConnection.start();
    Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer messageConsumer = queueSession.createConsumer(xaTestQueue);

    // wait 5 seconds
    Message receive = messageConsumer.receive(5000);
    Assert.assertNull(receive, "Message received. Message was not rolled back");


    xaResource.start(xid, XAResource.TMRESUME);
    producer.send(session.createTextMessage("Test 2"));
    xaResource.end(xid, XAResource.TMSUCCESS);

    xaResource.prepare(xid);
    xaResource.commit(xid, false);

    session.close();
    xaConnection.close();

    receive = messageConsumer.receive(5000);
    Assert.assertNotNull(receive, "Message not received");

    receive = messageConsumer.receive(5000);
    Assert.assertNotNull(receive, "Message not received");

    queueConnection.close();
}
 
Example 19
Source File: JMSIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageProviderRouteWithClientAck() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .transform(simple("Hello ${body}"))
            .toF("jms:queue:%s?connectionFactory=ConnectionFactory", QUEUE_NAME);
        }
    });

    final List<String> result = new ArrayList<>();
    final CountDownLatch latch = new CountDownLatch(4);

    camelctx.start();
    try {
        // Get the message from the queue
        ConnectionFactory cfactory = (ConnectionFactory) initialctx.lookup("java:/ConnectionFactory");
        Connection connection = cfactory.createConnection();
        final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Destination destination = (Destination) initialctx.lookup(QUEUE_JNDI_NAME);
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {
            @Override
            public synchronized void onMessage(Message message) {
                TextMessage text = (TextMessage) message;
                long count = latch.getCount();
                try {
                    // always append the message text
                    result.add(text.getText() + " " + (5 - count));

                    if (count == 4) {
                        // do nothing on first
                    } else if (count == 3) {
                        // recover causing a redelivery
                        session.recover();
                    } else {
                        // ackknowledge
                        message.acknowledge();
                    }
                } catch (JMSException ex) {
                    result.add(ex.getMessage());
                }
                latch.countDown();
            }
        });
        connection.start();

        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            producer.asyncSendBody("direct:start", "Message");
            producer.asyncSendBody("direct:start", "Message");

            Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
            Assert.assertEquals("Four messages", 4, result.size());
            Assert.assertEquals("Hello Message 1", result.get(0));
            Assert.assertEquals("Hello Message 2", result.get(1));
            Assert.assertEquals("Hello Message 3", result.get(2));
            Assert.assertEquals("Hello Message 4", result.get(3));
        } finally {
            connection.close();
        }
    } finally {
        camelctx.close();
    }
}
 
Example 20
Source File: JmsProvider.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public Connection createConnection(String route, UserCredentials credentials, String cliID, Address address) throws Exception {
    context = createContext(route, credentials, cliID, address);
    ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionFactory");
    connection = connectionFactory.createConnection();
    return connection;
}