Java Code Examples for org.apache.qpid.jms.JmsConnection#addConnectionListener()

The following examples show how to use org.apache.qpid.jms.JmsConnection#addConnectionListener() . 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: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseWithOpenResourcesDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(_testName.getMethodName());
    session.createConsumer(queue);
    session.createProducer(queue);

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    session.close();
    connection.close();
}
 
Example 2
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testTransactionCommitFails() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    try {
        session.commit();
        fail("Should not allow a commit while offline.");
    } catch (TransactionRolledBackException ex) {}

    connection.close();
}
 
Example 3
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseWhenDestroyCallFailsDoesNotBlock() throws Exception {
    mockPeer.setResourceDestroyFilter(new ResourceLifecycleFilter() {

        @Override
        public void onLifecycleEvent(JmsResource resource) throws Exception {
            if (resource instanceof JmsSessionInfo) {
                mockPeer.shutdownQuietly();
                throw new ProviderIOException("Failure closing session");
            }
        }
    });

    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    session.close();

    connection.close();
}
 
Example 4
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testTransactionRollbackSucceeds() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    try {
        session.rollback();
    } catch (TransactionRolledBackException ex) {
        fail("Should allow a rollback while offline.");
    }

    connection.close();
}
 
Example 5
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=20000)
public void testProducerCloseDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(_testName.getMethodName());
    MessageProducer producer = session.createProducer(queue);

    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    producer.close();
    connection.close();
}
 
Example 6
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionRecoverDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);

    session.recover();
    connection.close();
}
 
Example 7
Source File: FailoverRedirectTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 40000)
public void testFailoverHandlesRedirection() throws Exception {
    try (TestAmqpPeer rejectingPeer = new TestAmqpPeer();
         TestAmqpPeer redirectedPeer = new TestAmqpPeer();) {

        final CountDownLatch connected = new CountDownLatch(1);
        final URI redirectURI = createPeerURI(redirectedPeer);
        LOG.info("Backup peer is at: {}", redirectURI);

        redirectedPeer.expectSaslAnonymous();
        redirectedPeer.expectOpen();
        redirectedPeer.expectBegin();

        Map<Symbol, Object> redirectInfo = new HashMap<Symbol, Object>();
        redirectInfo.put(OPEN_HOSTNAME, "localhost");
        redirectInfo.put(NETWORK_HOST, "localhost");
        redirectInfo.put(PORT, redirectedPeer.getServerPort());

        rejectingPeer.rejectConnect(ConnectionError.REDIRECT, "Server is full, go away", redirectInfo);

        final JmsConnection connection = establishAnonymousConnecton(rejectingPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (isExpectedHost(redirectURI, remoteURI)) {
                    connected.countDown();
                }
            }
        });
        connection.start();

        rejectingPeer.waitForAllHandlersToComplete(1000);
        assertTrue("Should connect to backup peer", connected.await(15, TimeUnit.SECONDS));

        redirectedPeer.expectClose();
        connection.close();
        redirectedPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 8
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseWhenProviderSuddenlyClosesDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();

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

    mockPeer.silentlyCloseConnectedProviders();

    session.close();
}
 
Example 9
Source File: JmsAmqpDiscoveryTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
protected Connection createConnection() throws Exception {
    String discoveryPrefix = DiscoveryProviderFactory.DISCOVERY_OPTION_PREFIX;
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "discovery:(multicast://default)?" + discoveryPrefix + "startupMaxReconnectAttempts=25" + "&" + discoveryPrefix +"maxReconnectDelay=500");
    connection = factory.createConnection();
    jmsConnection = (JmsConnection) connection;
    jmsConnection.addConnectionListener(this);
    return connection;
}
 
Example 10
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 11
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testSessionCloseDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);
    session.close();
    connection.close();
}
 
Example 12
Source File: FailoverProviderOfflineBehaviorTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout=20000)
public void testConnectionCloseDoesNotBlock() throws Exception {
    connection = (JmsConnection) factory.createConnection();
    connection.addConnectionListener(new ConnectionInterruptionListener());
    connection.start();
    mockPeer.shutdown();
    connectionInterrupted.await(9, TimeUnit.SECONDS);
    connection.close();
}
 
Example 13
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testStartMaxReconnectAttemptsTriggeredWhenRemotesAreRejecting() throws Exception {
    try (TestAmqpPeer firstPeer = new TestAmqpPeer();
         TestAmqpPeer secondPeer = new TestAmqpPeer();
         TestAmqpPeer thirdPeer = new TestAmqpPeer();
         TestAmqpPeer fourthPeer = new TestAmqpPeer()) {

        final CountDownLatch failedConnection = new CountDownLatch(1);

        LOG.info("First peer is at: {}", createPeerURI(firstPeer));
        LOG.info("Second peer is at: {}", createPeerURI(secondPeer));
        LOG.info("Third peer is at: {}", createPeerURI(thirdPeer));
        LOG.info("Fourth peer is at: {}", createPeerURI(fourthPeer));

        firstPeer.rejectConnect(AmqpError.NOT_FOUND, "Resource could not be located", null);
        secondPeer.rejectConnect(AmqpError.NOT_FOUND, "Resource could not be located", null);
        thirdPeer.rejectConnect(AmqpError.NOT_FOUND, "Resource could not be located", null);

        // This shouldn't get hit, but if it does accept the connect so we don't pass the failed
        // to connect assertion.
        fourthPeer.expectSaslAnonymous();
        fourthPeer.expectOpen();
        fourthPeer.expectBegin();
        fourthPeer.expectClose();

        final JmsConnection connection = establishAnonymousConnecton(
            "failover.startupMaxReconnectAttempts=3&failover.reconnectDelay=15&failover.useReconnectBackOff=false",
            firstPeer, secondPeer, thirdPeer, fourthPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {

            @Override
            public void onConnectionFailure(Throwable cause) {
                LOG.info("Connection Failed: {}", cause);
                failedConnection.countDown();
            }
        });

        try {
            connection.start();
            fail("Should not be able to connect");
        } catch (JmsResourceNotFoundException jmsrnfe) {}

        // --- Failover should handle the connection close ---------------//

        assertTrue("Should reported failed", failedConnection.await(5, TimeUnit.SECONDS));

        try {
            connection.close();
        } catch (JMSException jmsEx) {}

        firstPeer.waitForAllHandlersToCompleteNoAssert(2000);
        secondPeer.waitForAllHandlersToCompleteNoAssert(2000);
        thirdPeer.waitForAllHandlersToCompleteNoAssert(2000);

        // Shut down last peer and verify no connection made to it
        fourthPeer.purgeExpectations();
        fourthPeer.close();
        assertNotNull("Peer 1 should have accepted a TCP connection", firstPeer.getClientSocket());
        assertNotNull("Peer 2 should have accepted a TCP connection", secondPeer.getClientSocket());
        assertNotNull("Peer 3 should have accepted a TCP connection", thirdPeer.getClientSocket());
        assertNull("Peer 4 should not have accepted any TCP connection", fourthPeer.getClientSocket());
    }
}
 
Example 14
Source File: FailoverWithAmqpOpenProvidedServerListIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testFailoverHandlesServerProvidedFailoverListIgnore() throws Exception {
    try (TestAmqpPeer primaryPeer = new TestAmqpPeer();) {

        final URI primaryPeerURI = createPeerURI(primaryPeer);
        LOG.info("Peer is at: {}", primaryPeerURI);

        final CountDownLatch connectedToPrimary = new CountDownLatch(1);

        // Expect the authentication as soon as the connection object is created
        primaryPeer.expectSaslAnonymous();

        String failoverParams = "?failover.maxReconnectAttempts=10&failover.amqpOpenServerListAction=IGNORE";

        // We only give it the primary peer details. It can only connect to the backup
        // peer by identifying the details in the announced failover-server-list.
        final JmsConnection connection = establishAnonymousConnecton(failoverParams, primaryPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (isExpectedHost(primaryPeerURI, remoteURI)) {
                    connectedToPrimary.countDown();
                }
            }
        });

        // Verify the existing failover URIs are as expected, the initial peer only
        List<URI> primaryPeerOnlyFailoverURIs = new ArrayList<>();
        primaryPeerOnlyFailoverURIs.add(primaryPeerURI);

        assertFailoverURIList(connection, primaryPeerOnlyFailoverURIs);

        // Set the primary up to expect the connection, have the failover list containing another server
        Map<Symbol,Object> otherPeerDetails = new HashMap<>();
        otherPeerDetails.put(NETWORK_HOST, "testhost");
        otherPeerDetails.put(PORT, "4567");

        List<Map<Symbol, Object>> failoverServerList = new ArrayList<Map<Symbol, Object>>();
        failoverServerList.add(otherPeerDetails);

        Map<Symbol,Object> serverConnectionProperties = new HashMap<Symbol, Object>();
        serverConnectionProperties.put(FAILOVER_SERVER_LIST, failoverServerList);

        primaryPeer.expectOpen(serverConnectionProperties);
        primaryPeer.expectBegin();

        // Provoke the actual AMQP connection
        connection.start();

        assertTrue("Should connect to primary peer", connectedToPrimary.await(5, TimeUnit.SECONDS));

        // Verify the existing failover URIs are as expected, still the initial peer only
        assertFailoverURIList(connection, primaryPeerOnlyFailoverURIs);

        primaryPeer.expectClose();
        connection.close();
        primaryPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 15
Source File: ConnectionConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testQueuedMessagesAreDrainedToServerSession() throws Exception {
    final int MESSAGE_COUNT = 10;
    final CountDownLatch messagesDispatched = new CountDownLatch(MESSAGE_COUNT);
    final CountDownLatch messagesArrived = new CountDownLatch(MESSAGE_COUNT);

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {

            @Override
            public void onInboundMessage(JmsInboundMessageDispatch envelope) {
                messagesDispatched.countDown();
            }
        });

        testPeer.expectBegin();

        // Create a session for our ServerSessionPool to use
        Session session = connection.createSession();
        session.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                messagesArrived.countDown();
            }
        });

        JmsServerSession serverSession = new JmsServerSession(session);
        JmsServerSessionPool sessionPool = new JmsServerSessionPool(serverSession);

        // Now the Connection consumer arrives and we give it a message
        // to be dispatched to the server session.
        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent, MESSAGE_COUNT);

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            testPeer.expectDispositionThatIsAcceptedAndSettled();
        }

        Queue queue = new JmsQueue("myQueue");
        ConnectionConsumer consumer = connection.createConnectionConsumer(queue, null, sessionPool, 100);

        assertTrue("Message didn't arrive in time", messagesDispatched.await(10, TimeUnit.SECONDS));
        assertEquals(MESSAGE_COUNT, messagesArrived.getCount());

        connection.start();

        assertTrue("Message didn't arrive in time", messagesArrived.await(10, TimeUnit.SECONDS));

        testPeer.expectDetach(true, true, true);
        consumer.close();

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 16
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testDropAndRejectAfterwardsHonorsMax() throws Exception {
    try (TestAmqpPeer firstPeer = new TestAmqpPeer();
         TestAmqpPeer secondPeer = new TestAmqpPeer();
         TestAmqpPeer thirdPeer = new TestAmqpPeer();
         TestAmqpPeer fourthPeer = new TestAmqpPeer()) {

        final CountDownLatch testConnected = new CountDownLatch(1);
        final CountDownLatch failedConnection = new CountDownLatch(1);

        // Create a peer to connect to, then one to reconnect to
        final String firstPeerURI = createPeerURI(firstPeer);

        LOG.info("First peer is at: {}", firstPeerURI);
        LOG.info("Second peer is at: {}", createPeerURI(secondPeer));
        LOG.info("Third peer is at: {}", createPeerURI(thirdPeer));
        LOG.info("Fourth peer is at: {}", createPeerURI(fourthPeer));

        firstPeer.expectSaslAnonymous();
        firstPeer.expectOpen();
        firstPeer.expectBegin();
        firstPeer.remotelyCloseConnection(true, ConnectionError.CONNECTION_FORCED, "Server is going away", 100);

        secondPeer.rejectConnect(AmqpError.NOT_FOUND, "Resource could not be located", null);
        thirdPeer.rejectConnect(AmqpError.NOT_FOUND, "Resource could not be located", null);

        // This shouldn't get hit, but if it does accept the connect so we don't pass the failed
        // to connect assertion.
        fourthPeer.expectSaslAnonymous();
        fourthPeer.expectOpen();
        fourthPeer.expectBegin();
        fourthPeer.expectClose();

        final JmsConnection connection = establishAnonymousConnecton(
            "failover.maxReconnectAttempts=2&failover.useReconnectBackOff=false", firstPeer, secondPeer, thirdPeer, fourthPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (firstPeerURI.equals(remoteURI.toString())) {
                    testConnected.countDown();
                }
            }

            @Override
            public void onConnectionFailure(Throwable cause) {
                LOG.info("Connection Failed: {}", cause);
                failedConnection.countDown();
            }
        });
        connection.start();

        assertTrue("Should connect to first peer", testConnected.await(5, TimeUnit.SECONDS));

        // --- Failover should handle the connection close ---------------//

        assertTrue("Should reported failed", failedConnection.await(5, TimeUnit.SECONDS));

        try {
            connection.close();
        } catch (JMSException jmsEx) {}

        secondPeer.waitForAllHandlersToCompleteNoAssert(2000);
        thirdPeer.waitForAllHandlersToCompleteNoAssert(2000);

        // Shut down last peer and verify no connection made to it
        fourthPeer.purgeExpectations();
        fourthPeer.close();
        assertNotNull("Peer 1 should have accepted a TCP connection", firstPeer.getClientSocket());
        assertNotNull("Peer 2 should have accepted a TCP connection", secondPeer.getClientSocket());
        assertNotNull("Peer 3 should have accepted a TCP connection", thirdPeer.getClientSocket());
        assertNull("Peer 4 should not have accepted any TCP connection", fourthPeer.getClientSocket());
    }
}
 
Example 17
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doFailoverHandlesConnectErrorInvalidFieldOnReconnectTestImpl(boolean includeContainerIdHint) throws Exception {
    try (TestAmqpPeer originalPeer = new TestAmqpPeer();
         TestAmqpPeer rejectingPeer = new TestAmqpPeer();
         TestAmqpPeer finalPeer = new TestAmqpPeer();) {

        final CountDownLatch finalConnected = new CountDownLatch(1);
        final String finalURI = createPeerURI(finalPeer);
        final DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        originalPeer.expectSaslAnonymous();
        originalPeer.expectOpen();
        originalPeer.expectBegin();
        originalPeer.dropAfterLastHandler(10);

        Map<Symbol, Object> errorInfo = null;
        if (includeContainerIdHint) {
            errorInfo = new HashMap<Symbol, Object>();
            errorInfo.put(AmqpSupport.INVALID_FIELD, AmqpSupport.CONTAINER_ID);
        }
        rejectingPeer.rejectConnect(AmqpError.INVALID_FIELD, "Client ID already in use", errorInfo);

        finalPeer.expectSaslAnonymous();
        finalPeer.expectOpen();
        finalPeer.expectBegin();

        final JmsConnection connection = establishAnonymousConnecton(originalPeer, rejectingPeer, finalPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionRestored(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (finalURI.equals(remoteURI.toString())) {
                    finalConnected.countDown();
                }
            }
        });

        try {
            connection.start();
        } catch (Exception ex) {
            fail("Should not have thrown an Exception: " + ex);
        }

        assertTrue("Should connect to final peer", finalConnected.await(5, TimeUnit.SECONDS));

        finalPeer.expectBegin();
        finalPeer.expectReceiverAttach();
        finalPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent);
        finalPeer.expectDispositionThatIsAcceptedAndSettled();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(2000);

        assertNotNull(message);

        // Shut it down
        finalPeer.expectClose();
        connection.close();
        finalPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 18
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doFailoverStopsOnNonTemporarySaslFailureTestImpl(UnsignedByte saslFailureCode) throws Exception {
    try (TestAmqpPeer originalPeer = new TestAmqpPeer();
         TestAmqpPeer rejectingPeer = new TestAmqpPeer();
         TestAmqpPeer finalPeer = new TestAmqpPeer();) {

        final CountDownLatch originalConnected = new CountDownLatch(1);
        final CountDownLatch exceptionListenerFired = new CountDownLatch(1);
        final AtomicReference<Throwable> failure = new AtomicReference<>();

        // Create a peer to connect to, then one to reconnect to
        final String originalURI = createPeerURI(originalPeer);
        final String rejectingURI = createPeerURI(rejectingPeer);
        final String finalURI = createPeerURI(finalPeer);

        LOG.info("Original peer is at: {}", originalURI);
        LOG.info("Rejecting peer is at: {}", rejectingURI);
        LOG.info("Final peer is at: {}", finalURI);

        // Expect connection to the first peer (and have it drop)
        originalPeer.expectSaslAnonymous();
        originalPeer.expectOpen();
        originalPeer.expectBegin();
        originalPeer.expectBegin();
        originalPeer.expectReceiverAttach();
        originalPeer.expectLinkFlow();
        originalPeer.dropAfterLastHandler();

        // --- Post Failover Expectations of Rejecting Peer--- //
        rejectingPeer.expectSaslFailingExchange(new Symbol[] { ANONYMOUS }, ANONYMOUS, saslFailureCode);

        // --- Post Failover Expectations of FinalPeer --- //
        // This shouldn't get hit, but if it does accept the connect so we don't pass the failed
        // to connect assertion.
        finalPeer.expectSaslAnonymous();
        finalPeer.expectOpen();
        finalPeer.expectBegin();
        finalPeer.expectBegin();

        final JmsConnection connection = establishAnonymousConnecton(originalPeer, rejectingPeer, finalPeer);
        connection.setExceptionListener(new ExceptionListener() {
            @Override
            public void onException(JMSException exception) {
                LOG.trace("JMS ExceptionListener: ", exception);
                failure.compareAndSet(null, exception);
                exceptionListenerFired.countDown();
            }
        });

        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (originalURI.equals(remoteURI.toString())) {
                    originalConnected.countDown();
                }
            }
        });
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        final MessageConsumer consumer = session.createConsumer(queue);

        assertTrue("Should connect to original peer", originalConnected.await(3, TimeUnit.SECONDS));

        assertTrue("The ExceptionListener should have been alerted", exceptionListenerFired.await(3, TimeUnit.SECONDS));
        Throwable ex = failure.get();
        assertTrue("Unexpected failure exception: " + ex, ex instanceof JMSSecurityException);

        // Verify the consumer gets marked closed
        assertTrue("consumer never closed.", Wait.waitFor(new Wait.Condition() {
            @Override
            public boolean isSatisfied() throws Exception {
                try {
                    consumer.getMessageSelector();
                } catch (IllegalStateException jmsise) {
                    return true;
                }
                return false;
            }
        }, 5000, 5));

        // Shut down last peer and verify no connection made to it
        finalPeer.purgeExpectations();
        finalPeer.close();
        assertNotNull("First peer should have accepted a TCP connection", originalPeer.getClientSocket());
        assertNotNull("Rejecting peer should have accepted a TCP connection", rejectingPeer.getClientSocket());
        assertNull("Final peer should not have accepted any TCP connection", finalPeer.getClientSocket());
    }
}
 
Example 19
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testConnectHandlesSaslTempFailure() throws Exception {
    try (TestAmqpPeer originalPeer = new TestAmqpPeer();
         TestAmqpPeer finalPeer = new TestAmqpPeer();) {

        final CountDownLatch finalConnected = new CountDownLatch(1);
        final String finalURI = createPeerURI(finalPeer);

        originalPeer.expectSaslFailingExchange(new Symbol[] { ANONYMOUS }, ANONYMOUS, SASL_SYS_TEMP);

        finalPeer.expectSaslAnonymous();
        finalPeer.expectOpen();
        finalPeer.expectBegin();

        final JmsConnection connection = establishAnonymousConnecton(originalPeer, finalPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {
            @Override
            public void onConnectionEstablished(URI remoteURI) {
                LOG.info("Connection Established: {}", remoteURI);
                if (finalURI.equals(remoteURI.toString())) {
                    finalConnected.countDown();
                }
            }
        });

        try {
            connection.start();
        } catch (Exception ex) {
            fail("Should not have thrown an Exception: " + ex);
        }

        assertTrue("Should connect to final peer", finalConnected.await(5, TimeUnit.SECONDS));

        String content = "myContent";
        final DescribedType amqpValueNullContent = new AmqpValueDescribedType(content);

        finalPeer.expectBegin();
        finalPeer.expectReceiverAttach();
        finalPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent);
        finalPeer.expectDispositionThatIsAcceptedAndSettled();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(2000);

        finalPeer.expectClose();
        connection.close();
        finalPeer.waitForAllHandlersToComplete(1000);

        assertNotNull(message);
        assertTrue(message instanceof TextMessage);
        assertEquals(content, ((TextMessage) message).getText());
    }
}
 
Example 20
Source File: ConnectionConsumerIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testConsumerRecoversAfterSessionPoolReturnsNullSession() throws Exception {
    final int MESSAGE_COUNT = 10;
    final CountDownLatch messagesDispatched = new CountDownLatch(MESSAGE_COUNT);
    final CountDownLatch messagesArrived = new CountDownLatch(MESSAGE_COUNT);

    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnection connection = (JmsConnection) testFixture.establishConnecton(testPeer);
        connection.addConnectionListener(new JmsDefaultConnectionListener() {

            @Override
            public void onInboundMessage(JmsInboundMessageDispatch envelope) {
                messagesDispatched.countDown();
            }
        });

        testPeer.expectBegin();

        // Create a session for our ServerSessionPool to use
        Session session = connection.createSession();
        session.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                messagesArrived.countDown();
            }
        });

        JmsServerSession serverSession = new JmsServerSession(session);
        JmsServerSessionPoolFirstAttemptGetsNull sessionPool = new JmsServerSessionPoolFirstAttemptGetsNull(serverSession);

        // Now the Connection consumer arrives and we give it a message
        // to be dispatched to the server session.
        DescribedType amqpValueNullContent = new AmqpValueDescribedType(null);

        testPeer.expectReceiverAttach();
        testPeer.expectLinkFlowRespondWithTransfer(null, null, null, null, amqpValueNullContent, MESSAGE_COUNT);

        for (int i = 0; i < MESSAGE_COUNT; i++) {
            testPeer.expectDispositionThatIsAcceptedAndSettled();
        }

        Queue queue = new JmsQueue("myQueue");
        ConnectionConsumer consumer = connection.createConnectionConsumer(queue, null, sessionPool, 100);

        assertTrue("Message didn't arrive in time", messagesDispatched.await(10, TimeUnit.SECONDS));
        assertEquals(MESSAGE_COUNT, messagesArrived.getCount());

        connection.start();

        assertTrue("Message didn't arrive in time", messagesArrived.await(10, TimeUnit.SECONDS));

        testPeer.expectDetach(true, true, true);
        consumer.close();

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}