Java Code Examples for com.rabbitmq.client.ConnectionFactory#useSslProtocol()

The following examples show how to use com.rabbitmq.client.ConnectionFactory#useSslProtocol() . 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: ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java    From product-ei with Apache License 2.0 9 votes vote down vote up
/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol();

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example 2
Source File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 8 votes vote down vote up
@Bean
@DependsOn("amqpBroker")
CachingConnectionFactory connectionFactory() {
    log.info("Creating connection factory for MQ broker...");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(hostname);
    cf.setPort(port);
    cf.setUsername(userName);
    cf.setPassword(password);
    cf.setVirtualHost(virtualHost);
    cf.setAutomaticRecoveryEnabled(false);
    if (useSSL) {
        try {
            cf.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            //TODO don't throw raw exceptions
            throw new RuntimeException(e);
        }
    }

    log.info("Connection factory created.");
    return new CachingConnectionFactory(cf);
}
 
Example 3
Source File: RabbitMQEventBus.java    From cloudstack with Apache License 2.0 8 votes vote down vote up
private synchronized Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException, IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setHost(amqpHost);
        factory.setPort(port);

        if (virtualHost != null && !virtualHost.isEmpty()) {
            factory.setVirtualHost(virtualHost);
        } else {
            factory.setVirtualHost("/");
        }

        if (useSsl != null && !useSsl.isEmpty() && useSsl.equalsIgnoreCase("true")) {
            factory.useSslProtocol(secureProtocol);
        }
        Connection connection = factory.newConnection();
        connection.addShutdownListener(disconnectHandler);
        connection.addBlockedListener(blockedConnectionHandler);
        s_connection = connection;
        return s_connection;
}
 
Example 4
Source File: ConnectionBasedRabbitConnectionFactoryFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ConnectionFactory createConnectionFactory(final Connection connection,
        final ExceptionHandler exceptionHandler) {
    checkNotNull(connection, "Connection");
    checkNotNull(exceptionHandler, "Exception Handler");

    try {
        final ConnectionFactory connectionFactory = new CustomConnectionFactory();
        if (SECURE_AMQP_SCHEME.equalsIgnoreCase(connection.getProtocol())) {
            if (connection.isValidateCertificates()) {
                final SSLContextCreator sslContextCreator =
                        SSLContextCreator.fromConnection(connection, null);
                connectionFactory.useSslProtocol(sslContextCreator.withoutClientCertificate());
            } else {
                // attention: this accepts all certificates whether they are valid or not
                connectionFactory.useSslProtocol();
            }
        }

        connectionFactory.setUri(connection.getUri());

        // this makes no difference as the used newmotion client always sets the AutomaticRecoveryEnabled to false:
        connectionFactory.setAutomaticRecoveryEnabled(connection.isFailoverEnabled());

        connectionFactory.setExceptionHandler(exceptionHandler);

        configureConnectionFactory(connectionFactory, connection.getSpecificConfig());

        return connectionFactory;
    } catch (final NoSuchAlgorithmException | KeyManagementException | URISyntaxException e) {
        LOGGER.warn(e.getMessage());
        throw new IllegalStateException("Failed to create RabbitMQ connection factory.", e);
    }
}
 
Example 5
Source File: AbstractAMQPProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Creates {@link Connection} to AMQP system.
 */
private Connection createConnection(ProcessContext context) {
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(context.getProperty(HOST).getValue());
    cf.setPort(Integer.parseInt(context.getProperty(PORT).getValue()));
    cf.setUsername(context.getProperty(USER).getValue());
    cf.setPassword(context.getProperty(PASSWORD).getValue());
    String vHost = context.getProperty(V_HOST).getValue();
    if (vHost != null) {
        cf.setVirtualHost(vHost);
    }

    // handles TLS/SSL aspects
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();
    final SSLContext sslContext;

    if (sslService != null) {
        final SSLContextService.ClientAuth clientAuth;
        if (StringUtils.isBlank(rawClientAuth)) {
            clientAuth = SSLContextService.ClientAuth.REQUIRED;
        } else {
            try {
                clientAuth = SSLContextService.ClientAuth.valueOf(rawClientAuth);
            } catch (final IllegalArgumentException iae) {
                throw new ProviderCreationException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                        rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
            }
        }
        sslContext = sslService.createSSLContext(clientAuth);
    } else {
        sslContext = null;
    }

    // check if the ssl context is set and add it to the factory if so
    if (sslContext != null) {
        cf.useSslProtocol(sslContext);
    }

    try {
        Connection connection = cf.newConnection();
        return connection;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to establish connection with AMQP Broker: " + cf.toString(), e);
    }
}
 
Example 6
Source File: ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation() + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example 7
Source File: DefaultChannelFactory.java    From rxrabbit with MIT License 4 votes vote down vote up
private synchronized Connection createConnection(ChannelType connectionType) throws ConnectionFailureException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    settings.getClient_properties().put("connection_type", connectionType.toString());
    settings.getClient_properties().put("connect_time", sdf.format(startTime)+"Z");

    ConnectionFactory cf = new ConnectionFactory();
    cf.setRequestedHeartbeat(settings.getHeartbeat());
    cf.setConnectionTimeout(settings.getConnection_timeout_millis());
    cf.setShutdownTimeout(settings.getShutdown_timeout_millis());
    cf.setRequestedFrameMax(settings.getFrame_max());
    cf.setHandshakeTimeout(settings.getHandshake_timeout_millis());
    cf.setClientProperties((Map)settings.getClient_properties());
    //cf.setSocketConfigurator(); NOTE is this worth investigating??
    cf.setRequestedChannelMax(0);//Hard coded ..
    cf.setAutomaticRecoveryEnabled(false);//Hard coded ..
    cf.setTopologyRecoveryEnabled(false);//Hard coded ..

    Exception lastException = null;
    Connection connection = null;
    for (BrokerAddresses.BrokerAddress address : addresses) {
        cf.setPassword(address.password);
        cf.setUsername(address.username);
        cf.setPort(address.port);
        cf.setHost(address.host);
        cf.setVirtualHost(address.virtualHost);
        try {
            if(address.scheme.toLowerCase().equals("amqps")){
                cf.useSslProtocol();
                cf.setSocketFactory(SSLSocketFactory.getDefault()); //Because rabbit uses NoopTrustStore by default...
            }
            log.infoWithParams("Creating "+connectionType+" connection to broker ...",
                    "address", address.toString(),
                    "settings", settings.toString());
            connection = cf.newConnection();
            boolean isOpen = connection.isOpen();
            if(!isOpen){
                continue;
            }
            break;
        } catch (Exception e) {
            log.debugWithParams("Failed to createConnection to broker",
                    "address", address.toString());
            lastException = e;
        }
    }

    if(connection == null){
        throw new ConnectionFailureException(cf, lastException);
    }

    conToChannel.put(connectionType,
            new ConnectionInfo(
                    connection,
                    new ArrayList<ChannelImpl>(),
                    settings.getClient_properties(),
                    connectionType)
    );
    log.infoWithParams("Successfully created "+connectionType+" connection to broker.",
            "address", addresses.get(0).toString(),
            "localPort", ((AMQConnection) connection).getLocalPort(),
            "settings", settings.toString());

    return connection;

}
 
Example 8
Source File: SharedRabbitMQResource.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doInitialize(
    final ResourceSpecifier aSpecifier, final Map<String, Object> aAdditionalParams)
    throws ResourceInitializationException {
  try {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);
    factory.setHost(host);
    factory.setPort(port);

    if (useHttps) {
      if (trustAll) {
        factory.useSslProtocol();
      } else {

        try (FileInputStream keystoreStream = new FileInputStream(keystorePath);
            FileInputStream trustStoreStream = new FileInputStream(truststorePath); ) {

          KeyStore ks = KeyStore.getInstance("PKCS12");
          ks.load(keystoreStream, keystorePass.toCharArray());

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          kmf.init(ks, keystorePass.toCharArray());

          KeyStore tks = KeyStore.getInstance("JKS");
          tks.load(trustStoreStream, truststorePass.toCharArray());

          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
          tmf.init(tks);

          SSLContext c = SSLContext.getInstance(sslProtocol);
          c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

          factory.useSslProtocol(c);
        }
      }
    }

    connection = factory.newConnection();
  } catch (final Exception e) {
    throw new ResourceInitializationException(
        new BaleenException("Error connecting to RabbitMQ", e));
  }

  getMonitor().info("Initialised shared RabbitMQ resource");
  return true;
}
 
Example 9
Source File: ConnectionFactoryProducer.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Produces
@ApplicationScoped
public ConnectionFactory createConnectionFactory(RabbitMQConfiguration rabbitMQConfiguration) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(rabbitMQConfiguration.isAutomaticRecovery());
    connectionFactory.setClientProperties(rabbitMQConfiguration.getClientProperties());
    connectionFactory.setConnectionTimeout(rabbitMQConfiguration.getConnectionTimeout());
    connectionFactory.setExceptionHandler(rabbitMQConfiguration.getExceptionHandler());
    connectionFactory.setHandshakeTimeout(rabbitMQConfiguration.getHandshakeTimeout());
    connectionFactory.setHeartbeatExecutor(rabbitMQConfiguration.getHeartbeatExecutor());
    connectionFactory.setMetricsCollector(rabbitMQConfiguration.getMetricsCollector());
    connectionFactory.setHost(rabbitMQConfiguration.getHost());
    connectionFactory.setNetworkRecoveryInterval(rabbitMQConfiguration.getNetworkRecoveryInterval());
    if(rabbitMQConfiguration.isNio()) {
        connectionFactory.useNio();
        connectionFactory.setNioParams(rabbitMQConfiguration.getNioParams());
    }
    connectionFactory.setPassword(rabbitMQConfiguration.getPassword());
    connectionFactory.setPort(rabbitMQConfiguration.getPort());
    connectionFactory.setRequestedChannelMax(rabbitMQConfiguration.getRequestedChannelMax());
    connectionFactory.setRequestedFrameMax(rabbitMQConfiguration.getRequestedFrameMax());
    connectionFactory.setRequestedHeartbeat(rabbitMQConfiguration.getRequestedHeartbeat());
    connectionFactory.setSaslConfig(rabbitMQConfiguration.getSaslConfig());
    connectionFactory.setSharedExecutor(rabbitMQConfiguration.getSharedExecutor());
    connectionFactory.setShutdownExecutor(rabbitMQConfiguration.getShutdownExecutor());
    connectionFactory.setShutdownTimeout(rabbitMQConfiguration.getShutdownTimeout());
    connectionFactory.setSocketConfigurator(rabbitMQConfiguration.getSocketConf());
    connectionFactory.setSocketFactory(rabbitMQConfiguration.getFactory());
    connectionFactory.setThreadFactory(rabbitMQConfiguration.getThreadFactory());
    connectionFactory.setTopologyRecoveryEnabled(rabbitMQConfiguration.isTopologyRecovery());
    try {
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
    }
    catch (Exception e) {
        throw new RuntimeException("Unable to populate URI ",e);
    }
    connectionFactory.setUsername(rabbitMQConfiguration.getUsername());
    connectionFactory.setVirtualHost(rabbitMQConfiguration.getVirtualHost());
    if(rabbitMQConfiguration.getSslContext() != null) {
        connectionFactory.useSslProtocol(rabbitMQConfiguration.getSslContext());
    }
    return connectionFactory;
}
 
Example 10
Source File: AbstractAMQPProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Connection createConnection(ProcessContext context) {
    final ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(context.getProperty(HOST).evaluateAttributeExpressions().getValue());
    cf.setPort(Integer.parseInt(context.getProperty(PORT).evaluateAttributeExpressions().getValue()));
    cf.setUsername(context.getProperty(USER).evaluateAttributeExpressions().getValue());
    cf.setPassword(context.getProperty(PASSWORD).getValue());

    final String vHost = context.getProperty(V_HOST).evaluateAttributeExpressions().getValue();
    if (vHost != null) {
        cf.setVirtualHost(vHost);
    }

    // handles TLS/SSL aspects
    final Boolean useCertAuthentication = context.getProperty(USE_CERT_AUTHENTICATION).asBoolean();
    final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    // if the property to use cert authentication is set but the SSL service hasn't been configured, throw an exception.
    if (useCertAuthentication && sslService == null) {
        throw new IllegalStateException("This processor is configured to use cert authentication, " +
                "but the SSL Context Service hasn't been configured. You need to configure the SSL Context Service.");
    }
    final String rawClientAuth = context.getProperty(CLIENT_AUTH).getValue();

    if (sslService != null) {
        final SslContextFactory.ClientAuth clientAuth;
        if (StringUtils.isBlank(rawClientAuth)) {
            clientAuth = SslContextFactory.ClientAuth.REQUIRED;
        } else {
            try {
                clientAuth = SslContextFactory.ClientAuth.valueOf(rawClientAuth);
            } catch (final IllegalArgumentException iae) {
                throw new IllegalStateException(String.format("Unrecognized client auth '%s'. Possible values are [%s]",
                        rawClientAuth, StringUtils.join(SslContextFactory.ClientAuth.values(), ", ")));
            }
        }
        final SSLContext sslContext = sslService.createSSLContext(clientAuth);
        cf.useSslProtocol(sslContext);

        if (useCertAuthentication) {
            // this tells the factory to use the cert common name for authentication and not user name and password
            // REF: https://github.com/rabbitmq/rabbitmq-auth-mechanism-ssl
            cf.setSaslConfig(DefaultSaslConfig.EXTERNAL);
        }
    }

    try {
        Connection connection = cf.newConnection();
        return connection;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to establish connection with AMQP Broker: " + cf.toString(), e);
    }
}