Java Code Examples for javax.jms.QueueConnectionFactory#createQueueConnection()

The following examples show how to use javax.jms.QueueConnectionFactory#createQueueConnection() . 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: UserCredentialsConnectionFactoryAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation delegates to the {@code createQueueConnection(username, password)}
 * method of the target QueueConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createQueueConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.QueueConnectionFactory#createQueueConnection(String, String)
 * @see javax.jms.QueueConnectionFactory#createQueueConnection()
 */
protected QueueConnection doCreateQueueConnection(
		@Nullable String username, @Nullable String password) throws JMSException {

	ConnectionFactory target = obtainTargetConnectionFactory();
	if (!(target instanceof QueueConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
	}
	QueueConnectionFactory queueFactory = (QueueConnectionFactory) target;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createQueueConnection(username, password);
	}
	else {
		return queueFactory.createQueueConnection();
	}
}
 
Example 2
Source File: UserCredentialsConnectionFactoryAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * This implementation delegates to the {@code createQueueConnection(username, password)}
 * method of the target QueueConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createQueueConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.QueueConnectionFactory#createQueueConnection(String, String)
 * @see javax.jms.QueueConnectionFactory#createQueueConnection()
 */
protected QueueConnection doCreateQueueConnection(
		@Nullable String username, @Nullable String password) throws JMSException {

	ConnectionFactory target = obtainTargetConnectionFactory();
	if (!(target instanceof QueueConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
	}
	QueueConnectionFactory queueFactory = (QueueConnectionFactory) target;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createQueueConnection(username, password);
	}
	else {
		return queueFactory.createQueueConnection();
	}
}
 
Example 3
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 4
Source File: JmsTypeHeaderInboundEndpointTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Send a message to testInboundQueue queue
 *
 * @throws Exception
 */
private void sendMessage() throws Exception {
    InitialContext initialContext = JmsClientHelper.getActiveMqInitialContext();
    QueueConnectionFactory connectionFactory
            = (QueueConnectionFactory) initialContext.lookup(JmsClientHelper.QUEUE_CONNECTION_FACTORY);
    QueueConnection queueConnection = connectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    QueueSender sender = queueSession.createSender(queueSession.createQueue(QUEUE_NAME));

    String message = "<?xml version='1.0' encoding='UTF-8'?>" +
            "    <ser:getQuote xmlns:ser=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\"> " +
            "      <ser:request>" +
            "        <xsd:symbol>IBM</xsd:symbol>" +
            "      </ser:request>" +
            "    </ser:getQuote>";
    try {
        TextMessage jmsMessage = queueSession.createTextMessage(message);
        jmsMessage.setJMSType("incorrecttype");
        sender.send(jmsMessage);
    } finally {
        queueConnection.close();
    }
}
 
Example 5
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 6
Source File: AbstractJMSProvider.java    From perf-harness with MIT License 6 votes vote down vote up
public QueueConnection getQueueConnection(QueueConnectionFactory qcf)
		throws JMSException {

	final QueueConnection qc;
	final String username = Config.parms.getString("us");
	if (username != null && username.length() != 0) {
		Log.logger.log(Level.INFO, "getQueueConnection(): authenticating as \"" + username + "\"");
		final String password = Config.parms.getString("pw");
		qc = qcf.createQueueConnection(username, password);
	} else {
		qc = qcf.createQueueConnection();
	}

	return qc;

}
 
Example 7
Source File: JMSWrapper.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Dynamically creates a topic. This goes against the normal idea
    * that JMS queues and topics should managed administratively, using
    * management tools. But for some applications this would be too 
    * burdensome. The user would have to additionally know about the
    * administration tools as well. Given that might be creating quite
    * a few AVL feeds, each one being a separate topic, this could be
    * a real nuisance.
    * 
 * @param topicName
 * @return true if topic created successfully
 * @throws JMSException
 */
private boolean createTopic(String topicName) throws JMSException {
	QueueConnectionFactory queueConnectionFactory = 
			(QueueConnectionFactory) connectionFactory;
	QueueConnection connection = queueConnectionFactory.createQueueConnection();

	Queue managementQueue = HornetQJMSClient.createQueue("hornetq.management");
	QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	connection.start();
	Message message = session.createMessage();
	JMSManagementHelper.putOperationInvocation(message, 
			"jms.server", 
			"createTopic", // management command
			topicName,     // Name in hornetq
			topicName);    // JNDI name. This peculiar seemingly undocumented 
						   // parameter is needed so that can use JNDI to access 
	                       // the dynamically created topic. Found info on doing 
	                       // this at https://community.jboss.org/thread/165355 .
	QueueRequestor requestor = new QueueRequestor(session, managementQueue);

	// Determine if was successful
	Message reply = requestor.request(message);
	boolean topicCreated = JMSManagementHelper.hasOperationSucceeded(reply);
	
	if (topicCreated)
		logger.info("Dynamically created topic \"" + topicName + "\"");
	else
		logger.error("Failed to dynamically created topic \"" + topicName + "\"");
	
	// Return whether successful
	return topicCreated;
}
 
Example 8
Source File: MDDProducer.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private void sendBytesMessage(String destName, byte[] buffer) throws Exception {

        InitialContext ic = getInitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ic.lookup("ConnectionFactory");
        QueueConnection connection = queueConnectionFactory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        BytesMessage bm = session.createBytesMessage();
        bm.writeBytes(buffer);
        QueueSender sender = session.createSender((Queue) ic.lookup(destName));
        sender.send(bm);
        sender.close();
        session.close();
        connection.close();
    }
 
Example 9
Source File: ConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Test that ConnectionFactory can be cast to QueueConnectionFactory and QueueConnection can be
 * created.
 */
@Test
public void testQueueConnectionFactory() throws Exception {
   deployConnectionFactory(0, JMSFactoryType.QUEUE_CF, "CF_QUEUE_XA_FALSE", "/CF_QUEUE_XA_FALSE");
   QueueConnectionFactory qcf = (QueueConnectionFactory) ic.lookup("/CF_QUEUE_XA_FALSE");
   QueueConnection qc = qcf.createQueueConnection();
   qc.close();
   undeployConnectionFactory("CF_QUEUE_XA_FALSE");
}
 
Example 10
Source File: PTPTestCase.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Create all administrated objects connections and sessions ready to use for tests.
 * <br />
 * Start connections.
 */
@Override
@Before
public void setUp() throws Exception {
   super.setUp();

   try {
      // ...and creates administrated objects and binds them
      admin.createQueueConnectionFactory(PTPTestCase.QCF_NAME);
      admin.createQueue(PTPTestCase.QUEUE_NAME);

      Context ctx = admin.createContext();

      senderQCF = (QueueConnectionFactory) ctx.lookup(PTPTestCase.QCF_NAME);
      senderQueue = (Queue) ctx.lookup(PTPTestCase.QUEUE_NAME);
      senderConnection = senderQCF.createQueueConnection();
      senderSession = senderConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      sender = senderSession.createSender(senderQueue);

      receiverQCF = (QueueConnectionFactory) ctx.lookup(PTPTestCase.QCF_NAME);
      receiverQueue = (Queue) ctx.lookup(PTPTestCase.QUEUE_NAME);
      receiverConnection = receiverQCF.createQueueConnection();
      receiverSession = receiverConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      receiver = receiverSession.createReceiver(receiverQueue);

      senderConnection.start();
      receiverConnection.start();
      // end of client step
   } catch (Exception e) {
      throw new RuntimeException(e);
   }
}
 
Example 11
Source File: AndesJMSConsumer.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a queue connection, session and receiver.
 *
 * @throws NamingException
 * @throws JMSException
 */
private void createQueueConnection() throws NamingException, JMSException {
    // Creates a queue connection, sessions and receiver
    QueueConnectionFactory connFactory = (QueueConnectionFactory) super.getInitialContext()
            .lookup(AndesClientConstants.CF_NAME);
    QueueConnection queueConnection = connFactory.createQueueConnection();
    queueConnection.start();
    QueueSession queueSession;

    // Sets acknowledgement mode
    if (QueueSession.SESSION_TRANSACTED == this.consumerConfig.getAcknowledgeMode().getType()) {
        queueSession = queueConnection
                .createQueueSession(true, this.consumerConfig.getAcknowledgeMode().getType());
    } else {
        queueSession = queueConnection
                .createQueueSession(false, this.consumerConfig.getAcknowledgeMode().getType());
    }

    Queue queue =
            (Queue) super.getInitialContext().lookup(this.consumerConfig.getDestinationName());
    connection = queueConnection;
    session = queueSession;

    // If selectors exists
    if (null != this.consumerConfig.getSelectors()) {
        receiver = queueSession.createReceiver(queue, this.consumerConfig.getSelectors());
    } else {
        receiver = queueSession.createReceiver(queue);
    }
}
 
Example 12
Source File: UserCredentialsConnectionFactoryAdapter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * This implementation delegates to the {@code createQueueConnection(username, password)}
 * method of the target QueueConnectionFactory, passing in the specified user credentials.
 * If the specified username is empty, it will simply delegate to the standard
 * {@code createQueueConnection()} method of the target ConnectionFactory.
 * @param username the username to use
 * @param password the password to use
 * @return the Connection
 * @see javax.jms.QueueConnectionFactory#createQueueConnection(String, String)
 * @see javax.jms.QueueConnectionFactory#createQueueConnection()
 */
protected QueueConnection doCreateQueueConnection(String username, String password) throws JMSException {
	Assert.state(this.targetConnectionFactory != null, "'targetConnectionFactory' is required");
	if (!(this.targetConnectionFactory instanceof QueueConnectionFactory)) {
		throw new javax.jms.IllegalStateException("'targetConnectionFactory' is not a QueueConnectionFactory");
	}
	QueueConnectionFactory queueFactory = (QueueConnectionFactory) this.targetConnectionFactory;
	if (StringUtils.hasLength(username)) {
		return queueFactory.createQueueConnection(username, password);
	}
	else {
		return queueFactory.createQueueConnection();
	}
}
 
Example 13
Source File: JmsQueueListener.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public synchronized void load() throws GenericServiceException {
    try {
        InitialContext jndi = JNDIContextFactory.getInitialContext(jndiServer);
        QueueConnectionFactory factory = (QueueConnectionFactory) jndi.lookup(jndiName);

        if (factory != null) {
            con = factory.createQueueConnection(userName, password);
            con.setExceptionListener(this);
            session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            queue = (Queue) jndi.lookup(queueName);
            if (queue != null) {
                QueueReceiver receiver = session.createReceiver(queue);

                receiver.setMessageListener(this);
                con.start();
                this.setConnected(true);
                Debug.logInfo("Listening to queue [" + queueName + "]...", module);
            } else {
                throw new GenericServiceException("Queue lookup failed.");
            }
        } else {
            throw new GenericServiceException("Factory (broker) lookup failed.");
        }
    } catch (NamingException ne) {
        throw new GenericServiceException("JNDI lookup problems; listener not running.", ne);
    } catch (JMSException je) {
        throw new GenericServiceException("JMS internal error; listener not running.", je);
    } catch (GeneralException ge) {
        throw new GenericServiceException("Problems with InitialContext; listener not running.", ge);
    }
}
 
Example 14
Source File: JmsInvoker.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public JmsInvoker(Class<T> type, URL url, QueueConnectionFactory queueConnectionFactory, Queue queue) {
	super(type, url);
	this.queueConnectionFactory = queueConnectionFactory;
	this.queue = queue;
	try {
		this.queueConnection = queueConnectionFactory.createQueueConnection();
		this.queueConnection.start();
	} catch (JMSException e) {
		throw new RpcException(e);
	}
	timeout = url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
}
 
Example 15
Source File: ExternalEventListener.java    From mdw with Apache License 2.0 4 votes vote down vote up
public void run() {
    QueueConnection connection = null;
    StandardLogger logger = LoggerUtil.getStandardLogger();
    try {
        String txt = message.getText();
        if (logger.isDebugEnabled()) {
            logger.debug("JMS Listener receives request: " + txt);
        }
        String resp;
        ListenerHelper helper = new ListenerHelper();
        Map<String, String> metaInfo = new HashMap<>();
        metaInfo.put(Listener.METAINFO_PROTOCOL, Listener.METAINFO_PROTOCOL_JMS);
        metaInfo.put(Listener.METAINFO_REQUEST_PATH, getQueueName());
        metaInfo.put(Listener.METAINFO_SERVICE_CLASS, this.getClass().getName());
        metaInfo.put(Listener.METAINFO_REQUEST_ID, message.getJMSMessageID());
        metaInfo.put(Listener.METAINFO_CORRELATION_ID, message.getJMSCorrelationID());
        if (message.getJMSReplyTo() != null)
            metaInfo.put("ReplyTo", message.getJMSReplyTo().toString());

            resp = helper.processRequest(txt, metaInfo);
            Queue respQueue = (Queue) message.getJMSReplyTo();
            String correlId = message.getJMSCorrelationID();
            if (resp != null && respQueue != null) {
                // String msgId = jmsMessage.getJMSMessageID();
                QueueConnectionFactory qcf
                    = JMSServices.getInstance().getQueueConnectionFactory(null);
                connection = qcf.createQueueConnection();

                Message respMsg;
                try (QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE)) {
                    try (QueueSender sender = session.createSender(respQueue)) {
                        respMsg = session.createTextMessage(resp);
                        respMsg.setJMSCorrelationID(correlId);
                        sender.send(respMsg);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("JMS Listener sends response (corr id='" +
                            correlId + "'): " + resp);
                }
            }

    }
    catch (Throwable ex) {
        logger.error(ex.getMessage(), ex);
    }
    finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}
 
Example 16
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 17
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 18
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 19
Source File: ConnectionFactoryTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectionTypes() throws Exception {
   deployConnectionFactory(0, JMSFactoryType.CF, "ConnectionFactory", "/ConnectionFactory");
   deployConnectionFactory(0, JMSFactoryType.QUEUE_XA_CF, "CF_QUEUE_XA_TRUE", "/CF_QUEUE_XA_TRUE");
   deployConnectionFactory(0, JMSFactoryType.XA_CF, "CF_XA_TRUE", "/CF_XA_TRUE");
   deployConnectionFactory(0, JMSFactoryType.QUEUE_CF, "CF_QUEUE", "/CF_QUEUE");
   deployConnectionFactory(0, JMSFactoryType.TOPIC_CF, "CF_TOPIC", "/CF_TOPIC");
   deployConnectionFactory(0, JMSFactoryType.TOPIC_XA_CF, "CF_TOPIC_XA_TRUE", "/CF_TOPIC_XA_TRUE");

   Connection genericConnection = null;
   XAConnection xaConnection = null;
   QueueConnection queueConnection = null;
   TopicConnection topicConnection = null;
   XAQueueConnection xaQueueConnection = null;
   XATopicConnection xaTopicConnection = null;

   ConnectionFactory genericFactory = (ConnectionFactory) ic.lookup("/ConnectionFactory");
   genericConnection = genericFactory.createConnection();
   assertConnectionType(genericConnection, "generic");

   XAConnectionFactory xaFactory = (XAConnectionFactory) ic.lookup("/CF_XA_TRUE");
   xaConnection = xaFactory.createXAConnection();
   assertConnectionType(xaConnection, "xa");

   QueueConnectionFactory queueCF = (QueueConnectionFactory) ic.lookup("/CF_QUEUE");
   queueConnection = queueCF.createQueueConnection();
   assertConnectionType(queueConnection, "queue");

   TopicConnectionFactory topicCF = (TopicConnectionFactory) ic.lookup("/CF_TOPIC");
   topicConnection = topicCF.createTopicConnection();
   assertConnectionType(topicConnection, "topic");

   XAQueueConnectionFactory xaQueueCF = (XAQueueConnectionFactory) ic.lookup("/CF_QUEUE_XA_TRUE");
   xaQueueConnection = xaQueueCF.createXAQueueConnection();
   assertConnectionType(xaQueueConnection, "xa-queue");

   XATopicConnectionFactory xaTopicCF = (XATopicConnectionFactory) ic.lookup("/CF_TOPIC_XA_TRUE");
   xaTopicConnection = xaTopicCF.createXATopicConnection();
   assertConnectionType(xaTopicConnection, "xa-topic");

   genericConnection.close();
   xaConnection.close();
   queueConnection.close();
   topicConnection.close();
   xaQueueConnection.close();
   xaTopicConnection.close();

   undeployConnectionFactory("ConnectionFactory");
   undeployConnectionFactory("CF_QUEUE_XA_TRUE");
   undeployConnectionFactory("CF_XA_TRUE");
   undeployConnectionFactory("CF_QUEUE");
   undeployConnectionFactory("CF_TOPIC");
   undeployConnectionFactory("CF_TOPIC_XA_TRUE");
}
 
Example 20
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();
}