Example usage for com.rabbitmq.client ConnectionFactory useSslProtocol

List of usage examples for com.rabbitmq.client ConnectionFactory useSslProtocol

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory useSslProtocol.

Prototype

public void useSslProtocol(SSLContext context) 

Source Link

Document

Sets up TLS with an initialized SSLContext .

Usage

From source file:com.hp.ov.sdk.messaging.core.RabbitMqClientConnectionFactory.java

License:Apache License

public static ConnectionFactory getConnectionFactory(final SSLContext sslContext, final RestParams params) {

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(params.getHostname());
    factory.setPort(params.getAmqpPort());

    // Set Auth mechanism to "EXTERNAL" so that commonName of the client
    // certificate is mapped to AMQP user name. Hence, No need to set
    // userId/Password here.
    factory.setSaslConfig(DefaultSaslConfig.EXTERNAL);
    factory.useSslProtocol(sslContext);
    factory.setAutomaticRecoveryEnabled(true);

    return factory;
}

From source file:com.nifi.processors.amqp.AbstractAMQPProcessor.java

License:Apache License

/**
 * Creates {@link Connection} to AMQP system.
 *//*from  ww w  .  j  av  a2  s.  c om*/
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);
    }
}

From source file:net.es.netshell.rabbitmq.SSLConnection.java

License:Open Source License

public ConnectionFactory createConnection() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);//from   w  w  w. ja  v  a  2s  .  c  o m
    factory.setUsername(user);
    factory.setPassword(password);
    factory.setPort(port);

    if (ssl) {
        char[] keyPassphrase = KEYPASS.toCharArray();
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(KEYCERT), keyPassphrase);

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

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

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

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

        factory.useSslProtocol(c);
    }
    return factory;
}

From source file:net.roboconf.messaging.rabbitmq.internal.utils.RabbitMqUtils.java

License:Apache License

/**
 * Configures the connection factory with the right settings.
 * @param factory the connection factory
 * @param configuration the messaging configuration
 * @throws IOException if something went wrong
 * @see RabbitMqConstants// w  w  w.  j  a v  a  2  s  .c  o m
 */
public static void configureFactory(ConnectionFactory factory, Map<String, String> configuration)
        throws IOException {

    final Logger logger = Logger.getLogger(RabbitMqUtils.class.getName());
    logger.fine("Configuring a connection factory for RabbitMQ.");

    String messageServerIp = configuration.get(RABBITMQ_SERVER_IP);
    if (messageServerIp != null) {
        Map.Entry<String, Integer> entry = Utils.findUrlAndPort(messageServerIp);
        factory.setHost(entry.getKey());
        if (entry.getValue() > 0)
            factory.setPort(entry.getValue());
    }

    factory.setUsername(configuration.get(RABBITMQ_SERVER_USERNAME));
    factory.setPassword(configuration.get(RABBITMQ_SERVER_PASSWORD));

    // Timeout for connection establishment: 5s
    factory.setConnectionTimeout(5000);

    // Configure automatic reconnection
    factory.setAutomaticRecoveryEnabled(true);

    // Recovery interval: 10s
    factory.setNetworkRecoveryInterval(10000);

    // Exchanges and so on should be redeclared if necessary
    factory.setTopologyRecoveryEnabled(true);

    // SSL
    if (Boolean.parseBoolean(configuration.get(RABBITMQ_USE_SSL))) {
        logger.fine("Connection factory for RabbitMQ: SSL is used.");

        InputStream clientIS = null;
        InputStream storeIS = null;
        try {
            clientIS = new FileInputStream(configuration.get(RABBITMQ_SSL_KEY_STORE_PATH));
            storeIS = new FileInputStream(configuration.get(RABBITMQ_SSL_TRUST_STORE_PATH));

            char[] keyStorePassphrase = configuration.get(RABBITMQ_SSL_KEY_STORE_PASSPHRASE).toCharArray();
            KeyStore ks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_KEY_STORE_TYPE, DEFAULT_SSL_KEY_STORE_TYPE));
            ks.load(clientIS, keyStorePassphrase);

            String value = getValue(configuration, RABBITMQ_SSL_KEY_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(value);
            kmf.init(ks, keyStorePassphrase);

            char[] trustStorePassphrase = configuration.get(RABBITMQ_SSL_TRUST_STORE_PASSPHRASE).toCharArray();
            KeyStore tks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_TRUST_STORE_TYPE, DEFAULT_SSL_TRUST_STORE_TYPE));
            tks.load(storeIS, trustStorePassphrase);

            value = getValue(configuration, RABBITMQ_SSL_TRUST_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(value);
            tmf.init(tks);

            SSLContext c = SSLContext
                    .getInstance(getValue(configuration, RABBITMQ_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL));
            c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            factory.useSslProtocol(c);

        } catch (GeneralSecurityException e) {
            throw new IOException("SSL configuration for the RabbitMQ factory failed.", e);

        } finally {
            Utils.closeQuietly(storeIS);
            Utils.closeQuietly(clientIS);
        }
    }
}

From source file:org.apache.airavata.gfac.monitor.util.AMQPConnectionUtil.java

License:Apache License

public static Connection connect(String host, String vhost, String proxyFile) {
    Connection connection;/*from  w w  w .  j a v a 2  s .  co m*/
    try {
        String keyPassPhrase = "test123";
        KeyStore ks = X509Helper.keyStoreFromPEM(proxyFile, keyPassPhrase);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, keyPassPhrase.toCharArray());

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

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

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(5671);
        factory.useSslProtocol(c);
        factory.setVirtualHost(vhost);
        factory.setSaslConfig(DefaultSaslConfig.EXTERNAL);

        connection = factory.newConnection();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return connection;
}

From source file:org.apache.nifi.amqp.processors.AbstractAMQPProcessor.java

License:Apache License

/**
 * Creates {@link Connection} to AMQP system.
 *//*from www . j a  v a  2s  . co  m*/
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 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 ProviderCreationException("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 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(), ", ")));
            }
        }
        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);
    }
}

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.ConnectionBasedRabbitConnectionFactoryFactory.java

License:Open Source License

@Override
public ConnectionFactory createConnectionFactory(final Connection connection,
        final ExceptionHandler exceptionHandler) {
    checkNotNull(connection, "Connection");
    checkNotNull(exceptionHandler, "Exception Handler");

    try {/*from  ww  w  .j a v a2  s.  c  o  m*/
        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);
    }
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result//from w w  w  .j  av  a2 s  .c  o  m
 * @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;
}

From source file:rmq.sender.impl.MQSender.java

License:Apache License

@Override
public void start() {
    SSLContext c = null;// w ww . j  ava2s  .  c om
    try {
        char[] pass = "changeit".toCharArray();
        KeyStore tks = KeyStore.getInstance("JKS");
        tks.load(new FileInputStream(
                "/root/test-project/topology-current/" + "/src/main/resources/client/client_cacerts.jks"),
                pass);

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

        c = SSLContext.getInstance("TLSv1.2");
        c.init(null, tmf.getTrustManagers(), null);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setNetworkRecoveryInterval(RECOVERY_INTERVAL);
    factory.useSslProtocol(c);
    try {
        factory.setUri(url);
        if (executorService != null) {
            conn = factory.newConnection(executorService);
        } else {
            conn = factory.newConnection();
        }
        channel = conn.createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        /*
         * Setting the following parameters to queue
         * durable    - true
         * exclusive  - false
         * autoDelete - false
         * arguments  - null
         */
        channel.queueDeclare(this.queueName, true, false, true, null);
        channel.queueBind(queueName, exchangeName, routingKey);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
    log.info("Connection started");
}

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.amqp.AMQPConnectionFactory.java

public void connectToVerifiedAMQPHost(InputStream keystore, String password) throws Exception {
    // Safety first
    if (amqpHostIP == null)
        throw new Exception("AMQP Host IP not correct");
    if (amqpConnection != null)
        throw new Exception("Already connected to host");
    if (password == null)
        throw new Exception("Password is null");

    char[] trustPassphrase = password.toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    try {//from w  w  w  .  j  av  a 2  s .  c  om
        tks.load(keystore, trustPassphrase);
    } catch (Exception ex) {
        factoryLog.error("Had problems loading keystore: " + ex.getMessage());
        throw ex;
    }

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

    SSLContext sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(null, tmf.getTrustManagers(), null);

    ConnectionFactory amqpFactory = new ConnectionFactory();
    amqpFactory.setHost(amqpHostIP.getHostAddress());
    amqpFactory.setPort(amqpPortNumber);
    amqpFactory.useSslProtocol(sslContext);

    try {
        amqpConnection = amqpFactory.newConnection();
    } catch (IOException ioe) {
        throw new Exception("Could not create secure AMQP host connection", ioe);
    }
}