Java Code Examples for javax.jms.QueueSession#createQueue()

The following examples show how to use javax.jms.QueueSession#createQueue() . 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: ConnectionsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a AMQP connection with the number of channels specified, registered on top of it.
 *
 * @param numberOfChannels number of channels to be created using the connection
 * @param userName         admin user
 * @param password         admin password
 * @param hostName         localhost
 * @param port             the AMQP port for which the broker listens to
 * @return the created JMS connection
 * @throws NamingException if an error occurs while creating the context/connection factory using given properties.
 * @throws JMSException    if an error occurs while creating/starting the connection/session
 */
private Connection createConnection(int numberOfChannels, String userName, String password, String hostName,
                                    String port) throws NamingException, JMSException {

    InitialContext initialContext
            = ClientHelper.getInitialContextBuilder(userName, password, hostName, port).build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();
    for (int i = 0; i < numberOfChannels; i++) {
        QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        /*
          For each channel, create a number of consumers that is equal to the channel number.
          e.g. if the channel count is 3, channel1 has 1 consumer, channel2 has 2 consumers and channel3 has 3
          consumers
        */
        for (int j = 0; j < i; j++) {
            Queue queue = session.createQueue("queue");
            session.createReceiver(queue);
        }
    }
    return connection;
}
 
Example 2
Source File: CloseCmdTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a AMQP connection with the number of channels specified, registered on top of it.
 *
 * @param numberOfChannels number of channels to be created using the connection
 * @param userName         admin user
 * @param password         admin password
 * @param hostName         localhost
 * @param port             the AMQP port for which the broker listens to
 * @return the created JMS connection
 * @throws NamingException if an error occurs while creating the context/connection factory using given properties.
 * @throws JMSException    if an error occurs while creating/starting the connection/session
 */
private Connection createConnection(int numberOfChannels, String userName, String password, String hostName,
                                    String port) throws NamingException, JMSException {

    InitialContext initialContext
            = ClientHelper.getInitialContextBuilder(userName, password, hostName, port).build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();
    for (int i = 0; i < numberOfChannels; i++) {
        QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

        /*
          For each channel, create a number of consumers that is equal to the channel number.
          e.g. if the channel count is 3, channel1 has 1 consumer, channel2 has 2 consumers and channel3 has 3
          consumers
        */
        for (int j = 0; j < i; j++) {
            Queue queue = session.createQueue("queue");
            session.createReceiver(queue);
        }
    }
    return connection;
}
 
Example 3
Source File: QueueSenderTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
public void anonymousSenderSendToUnknownQueue() throws Exception
{
    QueueConnection connection = ((QueueConnection) getConnectionBuilder().setSyncPublish(true).build());

    try
    {
        QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue invalidDestination = session.createQueue("unknown");

        try
        {
            QueueSender sender = session.createSender(null);
            sender.send(invalidDestination, session.createMessage());
            fail("Exception not thrown");
        }
        catch (InvalidDestinationException e)
        {
            //PASS
        }
    }
    finally
    {
        connection.close();
    }
}
 
Example 4
Source File: JmsQueueSenderTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateQueueSender() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
    QueueConnection connection = factory.createQueueConnection();
    assertNotNull(connection);

    QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    assertNotNull(session);
    Queue queue = session.createQueue(name.getMethodName());
    QueueSender sender = session.createSender(queue);
    assertNotNull(sender);

    QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
    assertEquals(0, proxy.getQueueSize());
    connection.close();
}
 
Example 5
Source File: QueueSenderTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void sendToUnknownQueue() throws Exception
{
    QueueConnection connection = ((QueueConnection) getConnectionBuilder().build());

    try
    {
        QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue invalidDestination = session.createQueue("unknown");

        try
        {
            QueueSender sender = session.createSender(invalidDestination);
            sender.send(session.createMessage());
            fail("Exception not thrown");
        }
        catch (InvalidDestinationException e)
        {
            //PASS
        }
    }
    finally
    {
        connection.close();
    }
}
 
Example 6
Source File: JNDI.java    From perf-harness with MIT License 5 votes vote down vote up
/**
 * <b>JMS 1.0.2</b>
 * @return A valid Queue object created either from JNDI lookup or directly from the given session.
 */
public DestinationWrapper<Queue> lookupQueue(String uri, QueueSession session) throws JMSException, NamingException {
	if ( usingJNDI ) {
		return lookupQueueFromJNDI( uri );
	} else {
		return new DestinationWrapper<Queue>( uri, session.createQueue( uri ) );
	}
}
 
Example 7
Source File: JmsQueueSenderClosedTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
protected void createTestResources() throws Exception {
    connection = createQueueConnectionToMockProvider();
    QueueSession session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue(_testName.getMethodName());
    sender = session.createSender(destination);
    sender.close();
}
 
Example 8
Source File: JmsQueueReceiverClosedTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
protected void createTestResources() throws Exception {
    connection = createQueueConnectionToMockProvider();
    QueueSession session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue destination = session.createQueue(_testName.getMethodName());
    receiver = session.createReceiver(destination);
    receiver.close();
}
 
Example 9
Source File: QueuesRestApiTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testSpecificQueueRetrieval(String username, String password, String hostname, String port)
        throws JMSException, NamingException, IOException {

    String queueName = "testSpecificQueueRetrieval";

    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver = queueSession.createReceiver(queue);

    // Test queue retrieval through REST API
    HttpGet httpGet = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/" + queueName);
    ClientHelper.setAuthHeader(httpGet, username, password);
    CloseableHttpResponse response = client.execute(httpGet);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK, "Incorrect status code.");

    String body = EntityUtils.toString(response.getEntity());
    QueueMetadata queueMetadata = objectMapper.readValue(body, QueueMetadata.class);

    Assert.assertEquals(queueMetadata.getName(), queueName, "Incorrect queue name.");
    Assert.assertEquals(queueMetadata.getConsumerCount().intValue(), 1, "JMS consumer should be present.");
    Assert.assertTrue(queueMetadata.isDurable());
    Assert.assertEquals(queueMetadata.getSize().intValue(), 0, "Queue should be empty.");
    Assert.assertFalse(queueMetadata.isAutoDelete());

    receiver.close();
    queueSession.close();
    connection.close();
}
 
Example 10
Source File: ConsumersRestApiTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testRetrieveConsumerList(String username, String password,
                                     String hostname, String port) throws Exception {
    String queueName = "testSpecificQueueRetrieval";


    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver1 = queueSession.createReceiver(queue);
    QueueReceiver receiver2 = queueSession.createReceiver(queue);

    HttpGet httpGet = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers");
    ClientHelper.setAuthHeader(httpGet, username, password);

    CloseableHttpResponse response = client.execute(httpGet);
    String body = EntityUtils.toString(response.getEntity());

    ConsumerMetadata[] consumers = objectMapper.readValue(body, ConsumerMetadata[].class);
    for (ConsumerMetadata consumerMetadata : consumers) {
        validateTransportPropertyExistence(consumerMetadata);
    }

    Assert.assertEquals(consumers.length, 2, "Number of consumers returned is incorrect.");

    receiver1.close();
    receiver2.close();
    queueSession.close();
    connection.close();
}
 
Example 11
Source File: ConsumersRestApiTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testSpecificConsumerRetrieval(String username, String password,
                                          String hostname, String port) throws Exception {
    String queueName = "testSpecificConsumerRetrieval";

    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver = queueSession.createReceiver(queue);

    HttpGet getAllConsumers = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers");
    ClientHelper.setAuthHeader(getAllConsumers, username, password);

    CloseableHttpResponse response = client.execute(getAllConsumers);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String body = EntityUtils.toString(response.getEntity());

    ConsumerMetadata[] consumers = objectMapper.readValue(body, ConsumerMetadata[].class);

    Assert.assertTrue(consumers.length > 0, "Number of consumers returned is incorrect.");

    int id = consumers[0].getId();
    validateTransportPropertyExistence(consumers[0]);
    HttpGet getConsumer = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/"
                                              + queueName + "/consumers/" + id);
    ClientHelper.setAuthHeader(getConsumer, username, password);

    response = client.execute(getConsumer);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
    String consumerString = EntityUtils.toString(response.getEntity());
    ConsumerMetadata consumerMetadata = objectMapper.readValue(consumerString, ConsumerMetadata.class);

    Assert.assertEquals(consumerMetadata.getId().intValue(), id, "incorrect message id");

    receiver.close();
    queueSession.close();
    connection.close();
}
 
Example 12
Source File: ConsumersRestApiTest.java    From ballerina-message-broker with Apache License 2.0 4 votes vote down vote up
@Parameters({"admin-username", "admin-password", "broker-hostname", "broker-port"})
@Test
public void testNonExistingConsumer(String username, String password,
                                    String hostname, String port) throws Exception {

    String queueName = "testNonExistingConsumer";

    // Create a durable queue using a JMS client
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder(username, password, hostname, port)
            .withQueue(queueName)
            .build();

    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    QueueConnection connection = connectionFactory.createQueueConnection();
    connection.start();

    QueueSession queueSession = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = queueSession.createQueue(queueName);
    QueueReceiver receiver1 = queueSession.createReceiver(queue);

    HttpGet getAllConsumers = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers");
    ClientHelper.setAuthHeader(getAllConsumers, username, password);

    CloseableHttpResponse response = client.execute(getAllConsumers);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK,
                        "Incorrect status code");
    String consumerArray = EntityUtils.toString(response.getEntity());
    ConsumerMetadata[] consumers = objectMapper.readValue(consumerArray, ConsumerMetadata[].class);

    Assert.assertEquals(consumers.length, 1, "There should be a single consumer");
    int id = consumers[0].getId();
    receiver1.close();

    HttpGet getConsumer = new HttpGet(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH
                                          + "/" + queueName + "/consumers/" + String.valueOf(id));
    ClientHelper.setAuthHeader(getConsumer, username, password);

    response = client.execute(getConsumer);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND);

    String errorMessage = EntityUtils.toString(response.getEntity());
    Error error = objectMapper.readValue(errorMessage, Error.class);

    Assert.assertFalse(error.getMessage().isEmpty(), "Error message should be non empty.");
    queueSession.close();
    connection.close();
}
 
Example 13
Source File: ArtemisFeatureTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 5 * 60 * 1000)
public void test() throws Throwable {
   executeCommand("bundle:list");

   withinReason(new Callable<Boolean>() {
      @Override
      public Boolean call() throws Exception {
         assertTrue("artemis bundle installed", verifyBundleInstalled("artemis-server-osgi"));
         return true;
      }
   });

   Object service = waitForService("(objectClass=org.apache.activemq.artemis.core.server.ActiveMQServer)", 30000);
   assertNotNull(service);
   log.debug("have service " + service);

   executeCommand("service:list -n");

   Connection connection = null;
   try {
      JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:5672");
      connection = factory.createConnection(USER, PASSWORD);
      connection.start();

      QueueSession sess = (QueueSession) connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
      Queue queue = sess.createQueue("exampleQueue");
      MessageProducer producer = sess.createProducer(queue);
      producer.send(sess.createTextMessage("TEST"));

      // Test browsing
      try (QueueBrowser browser = sess.createBrowser(queue)) {
         Enumeration messages = browser.getEnumeration();
         while (messages.hasMoreElements()) {
            messages.nextElement();
         }
      }

      // Test management
      Queue managementQueue = sess.createQueue("activemq.management");
      QueueRequestor requestor = new QueueRequestor(sess, managementQueue);
      connection.start();
      TextMessage m = sess.createTextMessage();
      m.setStringProperty("_AMQ_ResourceName", "broker");
      m.setStringProperty("_AMQ_OperationName", "getQueueNames");
      m.setText("[\"ANYCAST\"]");
      Message reply = requestor.request(m);
      String json = ((TextMessage) reply).getText();
      JsonArray array = Json.createReader(new StringReader(json)).readArray();
      List<JsonString> queues = (List<JsonString>) array.get(0);
      assertNotNull(queues);
      assertFalse(queues.isEmpty());

      MessageConsumer consumer = sess.createConsumer(queue);
      Message msg = consumer.receive(5000);
      assertNotNull(msg);
   } finally {
      if (connection != null) {
         connection.close();
      }
   }
}
 
Example 14
Source File: AzureServiceBusEventsListnerTest.java    From oneops with Apache License 2.0 3 votes vote down vote up
private void sendMessageToServer() throws JMSException, IOException {

		QueueConnection queueConn = (QueueConnection) connectionFactory.createConnection();
		queueConn.start();

		QueueSession queueSession = queueConn.createQueueSession(false, Session.DUPS_OK_ACKNOWLEDGE);

		Destination destination = queueSession.createQueue(jmsQueue);

		MessageProducer queueSender = queueSession.createProducer(destination);
		queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		Message message = queueSession.createTextMessage(createMessage());
		queueSender.send(message);

	}
 
Example 15
Source File: AzureServiceBusEventsListnerTest.java    From oneops with Apache License 2.0 3 votes vote down vote up
public void startListner() throws JMSException {

		QueueConnection queueConn = (QueueConnection) connectionFactory.createConnection();
		QueueSession queueSession = queueConn.createQueueSession(false, Session.DUPS_OK_ACKNOWLEDGE);

		Destination destination = queueSession.createQueue("TESTQUEUE");

		MessageConsumer consumer = queueSession.createConsumer(destination);

		azureServiceBusEventsListner.setAzureEventsHandler(azureEventsHandler);
		consumer.setMessageListener(azureServiceBusEventsListner);
		queueConn.start();

	}