Search in sources :

Example 41 with Connection

use of javax.jms.Connection in project karaf by apache.

the class PooledConnectionFactory method initConnectionsPool.

public void initConnectionsPool() {
    if (this.connectionsPool == null) {
        this.connectionsPool = new GenericKeyedObjectPool<>(new KeyedPooledObjectFactory<ConnectionKey, ConnectionPool>() {

            @Override
            public void activateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
            }

            @Override
            public void destroyObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
                try {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Destroying connection: {}", connection);
                    }
                    connection.getObject().close();
                } catch (Exception e) {
                    LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.", e);
                }
            }

            @Override
            public PooledObject<ConnectionPool> makeObject(ConnectionKey key) throws Exception {
                Connection delegate = createConnection(key);
                ConnectionPool connection = createConnectionPool(delegate);
                connection.setIdleTimeout(getIdleTimeout());
                connection.setExpiryTimeout(getExpiryTimeout());
                connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection());
                connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
                if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) {
                    connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout());
                }
                connection.setUseAnonymousProducers(isUseAnonymousProducers());
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Created new connection: {}", connection);
                }
                return new DefaultPooledObject<>(connection);
            }

            @Override
            public void passivateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
            }

            @Override
            public boolean validateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) {
                if (connection != null && connection.getObject() != null && connection.getObject().expiredCheck()) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Connection has expired: {} and will be destroyed", connection);
                    }
                    return false;
                }
                return true;
            }
        });
        // Set max idle (not max active) since our connections always idle in the pool.
        this.connectionsPool.setMaxIdlePerKey(1);
        // We always want our validate method to control when idle objects are evicted.
        this.connectionsPool.setTestOnBorrow(true);
        this.connectionsPool.setTestWhileIdle(true);
    }
}
Also used : DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) PooledObject(org.apache.commons.pool2.PooledObject) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) Connection(javax.jms.Connection) TopicConnection(javax.jms.TopicConnection) QueueConnection(javax.jms.QueueConnection) KeyedPooledObjectFactory(org.apache.commons.pool2.KeyedPooledObjectFactory) JMSException(javax.jms.JMSException)

Example 42 with Connection

use of javax.jms.Connection in project wildfly by wildfly.

the class LookupTestCase method lookupConnectionFactory.

private void lookupConnectionFactory(Context context, String name) throws Exception {
    ConnectionFactory cf = (ConnectionFactory) context.lookup(name);
    assertNotNull(cf);
    Connection conn = cf.createConnection("guest", "guest");
    conn.close();
}
Also used : ConnectionFactory(javax.jms.ConnectionFactory) Connection(javax.jms.Connection)

Example 43 with Connection

use of javax.jms.Connection in project wildfly by wildfly.

the class SendMessagesTestCase method testShutdown.

@Test
public void testShutdown(@ArquillianResource @OperateOnDeployment("singleton") ManagementClient client) throws Exception {
    Connection connection = null;
    try {
        deployer.deploy("mdb");
        ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/RemoteConnectionFactory");
        Queue queue = (Queue) ctx.lookup(QUEUE_SEND);
        connection = cf.createConnection("guest", "guest");
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue replyQueue = session.createTemporaryQueue();
        MessageProducer sender = session.createProducer(queue);
        MessageConsumer receiver = session.createConsumer(replyQueue);
        connection.start();
        // we do not assume message order since the 1st message will be redelivered
        // after redeployment (as the MDB is interrupted on 1st delivery)
        Set<String> expected = new TreeSet<String>();
        sendMessage(session, sender, replyQueue, "await");
        expected.add("Reply: await");
        // synchronize receiving message
        int awaitInt = awaitSingleton("await before undeploy");
        log.debug("testsuite: first awaitSingleton() returned: " + awaitInt);
        Future<?> undeployed = executor.submit(undeployTask());
        for (int i = 1; i <= 50; i++) {
            String msg = this.getClass().getSimpleName() + " 50loop: " + i;
            // should be bounced by BlockContainerShutdownInterceptor
            sendMessage(session, sender, replyQueue, msg);
            expected.add("Reply: " + msg);
        }
        log.debug("Sent 50 messages during MDB is undeploying");
        // synchronize with transaction timeout
        awaitInt = awaitSingleton("await after undeploy");
        log.debug("testsuite: second awaitSingleton() returned: " + awaitInt);
        undeployed.get(UNDEPLOYED_WAIT_S, SECONDS);
        // deploying via management client, arquillian deployer does not work for some reason
        final ModelNode deployAddr = new ModelNode();
        deployAddr.get(ClientConstants.OP_ADDR).add("deployment", MESSAGE_DRIVEN_BEAN + ".jar");
        deployAddr.get(ClientConstants.OP).set("deploy");
        applyUpdate(deployAddr, managementClient.getControllerClient());
        for (int i = 1; i <= 10; i++) {
            String msg = this.getClass().getSimpleName() + "10loop: " + i;
            sendMessage(session, sender, replyQueue, msg);
            expected.add("Reply: " + msg);
        }
        log.debug("Sent 10 more messages");
        Set<String> received = new TreeSet<String>();
        for (int i = 1; i <= (1 + 50 + 10 + 1); i++) {
            Message msg = receiver.receive(SECONDS.toMillis(RECEIVE_WAIT_S));
            assertNotNull("did not receive message with ordered number " + i + " in " + SECONDS.toMillis(RECEIVE_WAIT_S) + " seconds", msg);
            String text = ((TextMessage) msg).getText();
            received.add(text);
            log.trace(i + ": " + text);
        }
        assertNull(receiver.receiveNoWait());
        assertEquals(expected, received);
    } finally {
        if (connection != null) {
            connection.close();
        }
        deployer.undeploy("mdb");
    }
}
Also used : MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) Connection(javax.jms.Connection) ConnectionFactory(javax.jms.ConnectionFactory) TreeSet(java.util.TreeSet) MessageProducer(javax.jms.MessageProducer) ModelNode(org.jboss.dmr.ModelNode) Queue(javax.jms.Queue) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session) Test(org.junit.Test)

Example 44 with Connection

use of javax.jms.Connection in project wildfly by wildfly.

the class MDBTestCase method doDeliveryActive.

private void doDeliveryActive(Destination destination, String mdbName) throws Exception {
    // ReplyingMDB has been deployed with deliveryActive set to false
    assertMDBDeliveryIsActive(mdbName, false);
    Connection connection = null;
    try {
        connection = cf.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue replyQueue = session.createTemporaryQueue();
        // send a message to the MDB
        MessageProducer producer = session.createProducer(destination);
        Message message = session.createMessage();
        message.setJMSReplyTo(replyQueue);
        producer.send(message);
        // the MDB did not reply to the message because its delivery is not active
        MessageConsumer consumer = session.createConsumer(replyQueue);
        Message reply = consumer.receive(TIMEOUT);
        assertNull(reply);
        executeMDBOperation(mdbName, "start-delivery");
        assertMDBDeliveryIsActive(mdbName, true);
        // WFLY-4470 check duplicate message when start delivery twice. Last assertNull(reply) should still be valid
        executeMDBOperation(mdbName, "start-delivery");
        // the message was delivered to the MDB which replied
        reply = consumer.receive(TIMEOUT);
        assertNotNull(reply);
        assertEquals(message.getJMSMessageID(), reply.getJMSCorrelationID());
        executeMDBOperation(mdbName, "stop-delivery");
        assertMDBDeliveryIsActive(mdbName, false);
        // send again a message to the MDB
        message = session.createMessage();
        message.setJMSReplyTo(replyQueue);
        producer.send(message);
        // the MDB did not reply to the message because its delivery is not active
        reply = consumer.receive(TIMEOUT);
        assertNull(reply);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}
Also used : MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) Connection(javax.jms.Connection) TemporaryQueue(javax.jms.TemporaryQueue) MessageProducer(javax.jms.MessageProducer) Session(javax.jms.Session)

Example 45 with Connection

use of javax.jms.Connection in project wildfly by wildfly.

the class ReplyUtil method reply.

public static void reply(ConnectionFactory factory, Message message) {
    Connection connection = null;
    try {
        connection = factory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final Destination destination = message.getJMSReplyTo();
        // ignore messages that need no reply
        if (destination == null)
            return;
        final MessageProducer replyProducer = session.createProducer(destination);
        final Message replyMsg = session.createMessage();
        replyMsg.setJMSCorrelationID(message.getJMSMessageID());
        replyProducer.send(replyMsg);
        replyProducer.close();
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
}
Also used : Destination(javax.jms.Destination) Message(javax.jms.Message) Connection(javax.jms.Connection) JMSException(javax.jms.JMSException) MessageProducer(javax.jms.MessageProducer) Session(javax.jms.Session)

Aggregations

Connection (javax.jms.Connection)124 Session (javax.jms.Session)88 Test (org.junit.Test)62 MessageProducer (javax.jms.MessageProducer)46 ConnectionFactory (javax.jms.ConnectionFactory)44 Message (javax.jms.Message)38 MessageConsumer (javax.jms.MessageConsumer)38 JMSException (javax.jms.JMSException)32 TextMessage (javax.jms.TextMessage)32 QueueConnection (javax.jms.QueueConnection)22 TopicConnection (javax.jms.TopicConnection)22 Destination (javax.jms.Destination)15 Queue (javax.jms.Queue)12 QueueConnectionFactory (javax.jms.QueueConnectionFactory)11 TopicConnectionFactory (javax.jms.TopicConnectionFactory)11 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)7 JmsTemplate (org.springframework.jms.core.JmsTemplate)7 TransactionStatus (org.springframework.transaction.TransactionStatus)7 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)7 TransactionAttribute (javax.ejb.TransactionAttribute)4