org.apache.qpid.jms.JmsConnectionFactory Java Examples

The following examples show how to use org.apache.qpid.jms.JmsConnectionFactory. 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: NettyTcpToMockServerTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testConnectToServerWhenSaslDisabledAndServerAllowsIt() throws Exception {
    try (NettySimpleAmqpServer server = createServer(createServerOptions())) {
        server.setAllowNonSaslConnections(true);
        server.start();

        JmsConnectionFactory cf = new JmsConnectionFactory(createConnectionURI(server, "?amqp.saslLayer=false"));
        Connection connection = null;
        try {
            connection = cf.createConnection();
            connection.start();
        } catch (Exception ex) {
            LOG.info("Caught exception while attempting to connect");
            fail("Should not throw an exception when not using SASL");
        } finally {
            connection.close();
        }
    }
}
 
Example #2
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslLayerDisabledConnection() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Expect a connection with no SASL layer.
        testPeer.expectSaslLayerDisabledConnect(null);
        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?amqp.saslLayer=false");
        Connection connection = factory.createConnection();
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #3
Source File: JmsInitialContextFactoryTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultConnectionFactoriesSeeDefaultURIUpdate() throws Exception {
    String updatedDefaultURI = "amqp://example.com:1234";

    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(JmsInitialContextFactory.CONNECTION_FACTORY_DEFAULT_KEY_PREFIX + JmsConnectionFactory.REMOTE_URI_PROP, updatedDefaultURI);
    Context ctx = createInitialContext(env);

    for (String factoryName : JmsInitialContextFactory.DEFAULT_CONNECTION_FACTORY_NAMES) {
        Object o = ctx.lookup(factoryName);

        assertNotNull("No object returned", o);
        assertEquals("Unexpected class type for returned object", JmsConnectionFactory.class, o.getClass());
        assertEquals("Unexpected URI for returned factory", updatedDefaultURI, ((JmsConnectionFactory) o).getRemoteURI());
    }
}
 
Example #4
Source File: AMQP10JMSAutoConfiguration.java    From amqp-10-jms-spring-boot with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "stop")
@ConditionalOnProperty(prefix = "amqphub.amqp10jms.pool", name = "enabled", havingValue = "true", matchIfMissing = false)
public JmsPoolConnectionFactory pooledJmsConnectionFactory(
        AMQP10JMSProperties properties,
        ObjectProvider<List<AMQP10JMSConnectionFactoryCustomizer>> factoryCustomizers) {

    JmsPoolConnectionFactory pooledConnectionFactory = new JmsPoolConnectionFactory();
    pooledConnectionFactory.setConnectionFactory(
        new AMQP10JMSConnectionFactoryFactory(properties, factoryCustomizers.getIfAvailable())
            .createConnectionFactory(JmsConnectionFactory.class));

    AMQP10JMSProperties.Pool pool = properties.getPool();

    pool.configurePooledFactory(pooledConnectionFactory);

    return pooledConnectionFactory;
}
 
Example #5
Source File: FailoverIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private JmsConnection establishAnonymousConnecton(String connectionParams, String failoverParams, TestAmqpPeer... peers) throws JMSException {
    if (peers.length == 0) {
        throw new IllegalArgumentException("No test peers were given, at least 1 required");
    }

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

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

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

    return (JmsConnection) connection;
}
 
Example #6
Source File: SslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testNonSslConnectionFailsToSslServer() throws Exception {
    TransportOptions serverOptions = new TransportOptions();
    serverOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
    serverOptions.setKeyStorePassword(PASSWORD);
    serverOptions.setVerifyHost(false);

    try (NettySimpleAmqpServer server = new NettySimpleAmqpServer(serverOptions, true)) {
        server.start();

        JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + server.getServerPort() + "?jms.connectTimeout=25");

        try {
            factory.createConnection();
            fail("should not have connected");
        }
        catch (JMSException jmse) {
            String message = jmse.getMessage();
            assertNotNull(message);
            assertTrue("Unexpected message: " + message, message.contains("Timed out while waiting to connect"));
        }
    }
}
 
Example #7
Source File: FailoverProviderTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testStartupMaxReconnectAttempts() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "failover:(mock://localhost?mock.failOnConnect=true)" +
        "?failover.startupMaxReconnectAttempts=5" +
        "&failover.useReconnectBackOff=false");

    Connection connection = null;
    try {
        connection = factory.createConnection();
        connection.start();
        fail("Should have stopped after five retries.");
    } catch (JMSException ex) {
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    assertEquals(5, mockPeer.getContextStats().getProvidersCreated());
    assertEquals(5, mockPeer.getContextStats().getConnectionAttempts());
    assertEquals(5, mockPeer.getContextStats().getCloseAttempts());
}
 
Example #8
Source File: NettyTcpToMockServerTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testConnectToServer() throws Exception {
    try (NettySimpleAmqpServer server = createServer(createServerOptions())) {
        server.start();

        JmsConnectionFactory cf = new JmsConnectionFactory(createConnectionURI(server));
        Connection connection = null;
        try {
            connection = cf.createConnection();
            connection.start();
        } catch (Exception ex) {
            LOG.error("Caught exception while attempting to connect");
            fail("Should be able to connect in this simple test");
        } finally {
            connection.close();
        }
    }
}
 
Example #9
Source File: ConnectionIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testCreateConnectionWithServerSendingPreemptiveData() throws Exception {
    boolean sendServerSaslHeaderPreEmptively = true;
    try (TestAmqpPeer testPeer = new TestAmqpPeer(null, false, sendServerSaslHeaderPreEmptively);) {
        // Don't use test fixture, handle the connection directly to control sasl behaviour
        testPeer.expectSaslAnonymousWithPreEmptiveServerHeader();
        testPeer.expectOpen();
        testPeer.expectBegin();

        JmsConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
        Connection connection = factory.createConnection();
        connection.start();

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #10
Source File: JMSXUserIDPluginTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddValidatedUserAMQP() throws Exception {
   JmsConnectionFactory factory = new JmsConnectionFactory("amqp://127.0.0.1:61616");
   Connection connection = factory.createConnection();
   Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   javax.jms.Queue queue = session.createQueue(ADDRESS.toString());
   MessageProducer producer = session.createProducer(queue);
   producer.send(session.createMessage());
   connection.close();

   server.stop();
   server.start();

   connection = factory.createConnection();
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   connection.start();
   MessageConsumer consumer = session.createConsumer(queue);
   Message message = consumer.receive(5000);
   Assert.assertNotNull(message);
   Assert.assertEquals(message.getStringProperty("_AMQ_VALIDATED_USER"), "testuser");
   connection.close();
}
 
Example #11
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslAnonymousConnection() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        // Expect an ANOYMOUS connection
        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();
        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
        Connection connection = factory.createConnection();
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #12
Source File: ProxyIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private Connection establishConnecton(TestAmqpPeer testPeer, Supplier<ProxyHandler> proxyHandlerSupplier, boolean ssl, String optionsString) throws JMSException {
    testPeer.expectSaslPlain("guest", "guest");
    testPeer.expectOpen();

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

    String remoteURI = buildURI(testPeer, ssl, optionsString);
    LOG.debug("connect to {}", remoteURI);
    JmsConnectionFactory factory = new JmsConnectionFactory(remoteURI);
    factory.setExtension(JmsConnectionExtensions.PROXY_HANDLER_SUPPLIER.toString(), (connection1, remote) -> {
        return proxyHandlerSupplier;
    });
    Connection connection = factory.createConnection("guest", "guest");

    // Set a clientId to provoke the actual AMQP connection process to occur.
    connection.setClientID("clientName");

    assertNull(testPeer.getThrowable());

    return connection;
}
 
Example #13
Source File: FailoverProviderTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testSendMessagePassthrough() throws Exception {
    JmsConnectionFactory factory = new JmsConnectionFactory(
        "failover:(mock://localhost)");

    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(getTestName());
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createMessage());

    connection.close();

    assertEquals(1, mockPeer.getContextStats().getSendCalls());
}
 
Example #14
Source File: JMSClientTestSupport.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private Connection createConnection(URI remoteURI, String username, String password, String clientId, boolean start) throws JMSException {
   JmsConnectionFactory factory = new JmsConnectionFactory(remoteURI);

   Connection connection = trackJMSConnection(factory.createConnection(username, password));

   connection.setExceptionListener(new ExceptionListener() {
      @Override
      public void onException(JMSException exception) {
         exception.printStackTrace();
      }
   });

   if (clientId != null && !clientId.isEmpty()) {
      connection.setClientID(clientId);
   }

   if (start) {
      connection.start();
   }

   return connection;
}
 
Example #15
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslXOauth2Connection() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        // Expect a XOAUTH2 connection
        String user = "user";
        String pass = "eyB1c2VyPSJ1c2VyIiB9";

        testPeer.expectSaslXOauth2(user, pass);
        testPeer.expectOpen();

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

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
        Connection connection = factory.createConnection(user, pass);
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #16
Source File: JMSWebSocketConnectionTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 30000)
public void testSendLargeMessageToClientFromOpenWire() throws Exception {
   JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerQpidJMSConnectionURI());
   JmsConnection connection = (JmsConnection) factory.createConnection();

   sendLargeMessageViaOpenWire();

   try {
      Session session = connection.createSession();
      Queue queue = session.createQueue(getQueueName());
      connection.start();

      MessageConsumer consumer = session.createConsumer(queue);
      Message message = consumer.receive(1000);

      assertNotNull(message);
      assertTrue(message instanceof BytesMessage);
   } finally {
      connection.close();
   }
}
 
Example #17
Source File: SaslGssApiIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doSaslGssApiKrbConnectionTestImpl(String configScope, String clientAuthIdAtServer) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

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

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

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

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
        Connection connection = factory.createConnection("ignoredusername", null);
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #18
Source File: NettyTcpToMockServerTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testConnectToServerFailsWhenSaslDisabled() throws Exception {
    try (NettySimpleAmqpServer server = createServer(createServerOptions())) {
        server.start();

        JmsConnectionFactory cf = new JmsConnectionFactory(createConnectionURI(server, "?amqp.saslLayer=false"));
        Connection connection = null;
        try {
            connection = cf.createConnection();
            connection.start();
            fail("Should throw an exception when not using SASL");
        } catch (Exception ex) {
            LOG.info("Caught expected exception while attempting to connect");
        } finally {
            connection.close();
        }
    }
}
 
Example #19
Source File: JmsFailoverTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout=60000)
public void testStartupReconnectAttempts() throws Exception {
    URI brokerURI = new URI("failover://(amqp://localhost:5677)" +
                            "?failover.startupMaxReconnectAttempts=5" +
                            "&failover.useReconnectBackOff=false");
    JmsConnectionFactory factory = new JmsConnectionFactory(brokerURI);
    Connection connection = factory.createConnection();
    try {
        connection.start();
        fail("Should have thrown an exception of type JMSException");
    } catch (JMSException jmsEx) {
    } catch (Exception unexpected) {
        fail("Should have thrown a JMSException but threw: " + unexpected.getClass().getSimpleName());
    } finally {
        connection.close();
    }
}
 
Example #20
Source File: ConnectionIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testConnectionPropertiesContainExpectedMetaData() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        Matcher<?> connPropsMatcher = allOf(hasEntry(AmqpSupport.PRODUCT, MetaDataSupport.PROVIDER_NAME),
                hasEntry(AmqpSupport.VERSION, MetaDataSupport.PROVIDER_VERSION),
                hasEntry(AmqpSupport.PLATFORM, MetaDataSupport.PLATFORM_DETAILS));

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen(connPropsMatcher, null, false);
        testPeer.expectBegin();

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?jms.clientID=foo");
        Connection connection = factory.createConnection();

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #21
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doMechanismSelectionRestrictedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, String mechanismsOptionValue) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        testPeer.expectSaslFailingAuthentication(serverMechs, clientSelectedMech);

        String uriOptions = "?jms.clientID=myclientid";
        if(mechanismsOptionValue != null) {
            uriOptions += "&amqp.saslMechanisms=" + mechanismsOptionValue;
        }

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);
        try {
            factory.createConnection(username, password);

            fail("Excepted exception to be thrown");
        }catch (JMSSecurityException jmsse) {
            // Expected, we deliberately failed the SASL process,
            // we only wanted to verify the correct mechanism
            // was selected, other tests verify the remainder.
        }

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example #22
Source File: SaslIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslPlainConnection() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        // Expect a PLAIN connection
        String user = "user";
        String pass = "qwerty123456";

        testPeer.expectSaslPlain(user, pass);
        testPeer.expectOpen();

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

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort());
        Connection connection = factory.createConnection(user, pass);
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #23
Source File: CFUtil.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static ConnectionFactory createConnectionFactory(String protocol, String uri) {
   if (protocol.toUpperCase().equals("OPENWIRE")) {
      return new org.apache.activemq.ActiveMQConnectionFactory(uri);
   } else if (protocol.toUpperCase().equals("AMQP")) {

      if (uri.startsWith("tcp://")) {
         // replacing tcp:// by amqp://
         uri = "amqp" + uri.substring(3);
      }
      return new JmsConnectionFactory(uri);
   } else if (protocol.toUpperCase().equals("CORE") || protocol.toUpperCase().equals("ARTEMIS")) {
      return new org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory(uri);
   } else {
      throw new IllegalStateException("Unkown:" + protocol);
   }
}
 
Example #24
Source File: SaslGssApiIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testSaslGssApiKrbConnectionWithPrincipalViaJmsUsernameConnFactory() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {

        testPeer.expectSaslGSSAPI(servicePrincipal, KRB5_KEYTAB, CLIENT_PRINCIPAL_FACTORY_USERNAME + "@EXAMPLE.COM");
        testPeer.expectOpen();

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

        String uriOptions = "?sasl.options.configScope=KRB5-CLIENT-FACTORY-USERNAME-CALLBACK" + "&amqp.saslMechanisms=" + GSSAPI;
        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions);

        // No password, not needed as using keyTab.
        Connection connection = factory.createConnection(CLIENT_PRINCIPAL_FACTORY_USERNAME, null);

        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #25
Source File: JmsInitialContextFactory.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void createConnectionFactories(Hashtable<Object, Object> environment, Map<String, Object> bindings) throws NamingException {
    Map<String, String> factories = getConnectionFactoryNamesAndURIs(environment);
    Map<String, String> defaults = getConnectionFactoryDefaults(environment);
    for (Entry<String, String> entry : factories.entrySet()) {
        String name = entry.getKey();
        String uri = entry.getValue();

        JmsConnectionFactory factory = null;
        try {
            factory = createConnectionFactory(name, uri, defaults, environment);
        } catch (Exception e) {
            NamingException ne = new NamingException("Exception while creating ConnectionFactory '" + name + "'.");
            ne.initCause(e);
            throw ne;
        }

        bindings.put(name, factory);
    }
}
 
Example #26
Source File: JmsInitialContextFactory.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
protected Map<String, String> getConnectionFactoryDefaults(Map<Object, Object> environment) {
    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put(JmsConnectionFactory.REMOTE_URI_PROP, JmsConnectionFactory.getDefaultRemoteAddress());

    for (Iterator<Entry<Object, Object>> iter = environment.entrySet().iterator(); iter.hasNext();) {
        Map.Entry<Object, Object> entry = iter.next();
        String key = String.valueOf(entry.getKey());
        if (key.toLowerCase().startsWith(CONNECTION_FACTORY_DEFAULT_KEY_PREFIX)) {
            String jndiName = key.substring(CONNECTION_FACTORY_DEFAULT_KEY_PREFIX.length());
            String value = String.valueOf(entry.getValue());
            map.put(jndiName, expand(value, environment));
        }
    }

    return Collections.unmodifiableMap(map);
}
 
Example #27
Source File: IdleTimeoutIntegrationTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testAdvertisedIdleTimeoutIsHalfOfActualTimeoutValue() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        int configuredTimeout = 54320;
        int advertisedValue = configuredTimeout / 2;

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen(null, greaterThan(UnsignedInteger.valueOf(advertisedValue)), null, false);

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

        ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?amqp.idleTimeout=" + configuredTimeout);
        Connection connection = factory.createConnection();
        // Set a clientID to provoke the actual AMQP connection process to occur.
        connection.setClientID("clientName");

        testPeer.waitForAllHandlersToComplete(1000);
        assertNull(testPeer.getThrowable());

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #28
Source File: ConnectionIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void doMaxFrameSizeInfluencesOutgoingFrameSizeTestImpl(int frameSize, int bytesPayloadSize, int numFrames) throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        testPeer.expectSaslLayerDisabledConnect(equalTo(UnsignedInteger.valueOf(frameSize)));
        // Each connection creates a session for managing temporary destinations etc
        testPeer.expectBegin();

        String uri = "amqp://localhost:" + testPeer.getServerPort() + "?amqp.saslLayer=false&amqp.maxFrameSize=" + frameSize;
        ConnectionFactory factory = new JmsConnectionFactory(uri);
        Connection connection = factory.createConnection();

        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");
        MessageProducer producer = session.createProducer(queue);

        // Expect n-1 transfers of maxFrameSize
        for (int i = 1; i < numFrames; i++) {
            testPeer.expectTransfer(frameSize);
        }
        // Plus one more of unknown size (framing overhead).
        testPeer.expectTransfer(0);

        // Send the message
        byte[] orig = createBytePyload(bytesPayloadSize);
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(orig);

        producer.send(message);

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

        testPeer.waitForAllHandlersToComplete(3000);
    }
}
 
Example #29
Source File: AMQPVerifierExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) {

        final String connectionUri = ConnectorOptions.extractOption(parameters, "connectionUri");
        final String username = ConnectorOptions.extractOption(parameters, "username");
        final String password = ConnectorOptions.extractOption(parameters, "password");
        final boolean skipCertificateCheck = ConnectorOptions.extractOptionAndMap(parameters,
            "skipCertificateCheck", Boolean::parseBoolean, false);
        final String brokerCertificate = ConnectorOptions.extractOption(parameters, "brokerCertificate");
        final String clientCertificate = ConnectorOptions.extractOption(parameters, "clientCertificate");

        LOG.debug("Validating AMQP connection to {}", connectionUri);
        final AMQPUtil.ConnectionParameters connectionParameters = new AMQPUtil.ConnectionParameters(connectionUri,
                username, password, brokerCertificate, clientCertificate, skipCertificateCheck);
        JmsConnectionFactory connectionFactory = AMQPUtil.createConnectionFactory(connectionParameters);
        Connection connection = null;
        try {
            // try to create and start the JMS connection
            connection = connectionFactory.createConnection();
            connection.start();
        } catch (JMSException e) {
            final Map<String, Object> redacted = new HashMap<>(parameters);
            redacted.replace("password", "********");
            LOG.warn("Unable to connect to AMQP Broker with parameters {}, Message: {}, error code: {}",
                    redacted, e.getMessage(), e.getErrorCode(), e);
            builder.error(ResultErrorBuilder.withCodeAndDescription(
                    VerificationError.StandardCode.ILLEGAL_PARAMETER_VALUE, e.getMessage())
                    .parameterKey("connectionUri")
                    .parameterKey("username")
                    .parameterKey("password")
                    .build());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException ignored) {
                    // ignore
                }
            }
        }
    }
 
Example #30
Source File: JMSSaslExternalLDAPTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 600000)
public void testRoundTrip() throws Exception {

   final String keystore = this.getClass().getClassLoader().getResource("client_not_revoked.jks").getFile();
   final String truststore = this.getClass().getClassLoader().getResource("truststore.jks").getFile();

   String connOptions = "?amqp.saslMechanisms=EXTERNAL" + "&" +
      "transport.trustStoreLocation=" + truststore + "&" +
      "transport.trustStorePassword=changeit" + "&" +
      "transport.keyStoreLocation=" + keystore + "&" +
      "transport.keyStorePassword=changeit" + "&" +
      "transport.verifyHost=false";

   JmsConnectionFactory factory = new JmsConnectionFactory(new URI("amqps://localhost:" + 61616 + connOptions));
   Connection connection = factory.createConnection("client", null);
   connection.start();

   try {
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      javax.jms.Queue queue = session.createQueue("TEST");
      MessageConsumer consumer = session.createConsumer(queue);
      MessageProducer producer = session.createProducer(queue);

      final String text = RandomUtil.randomString();
      producer.send(session.createTextMessage(text));

      TextMessage m = (TextMessage) consumer.receive(1000);
      assertNotNull(m);
      assertEquals(text, m.getText());

   } finally {
      connection.close();
   }
}