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() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Document

Convenience method for configuring TLS using the default set of TLS protocols and a trusting TrustManager.

Usage

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

private ConnectionFactory getOrCreateConnectionFactory() {
    if (connectionFactory == null) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(getUsername());
        factory.setPassword(getPassword());
        factory.setVirtualHost(getVhost());
        factory.setHost(getHostname());/*from   ww  w  .j a va2s  .  c o m*/
        factory.setPort(getPortNumber());
        if (getClientProperties() != null) {
            factory.setClientProperties(getClientProperties());
        }
        factory.setConnectionTimeout(getConnectionTimeout());
        factory.setRequestedChannelMax(getRequestedChannelMax());
        factory.setRequestedFrameMax(getRequestedFrameMax());
        factory.setRequestedHeartbeat(getRequestedHeartbeat());
        if (getSslProtocol() != null) {
            try {
                if (getSslProtocol().equals("true")) {
                    factory.useSslProtocol();
                } else if (getTrustManager() == null) {
                    factory.useSslProtocol(getSslProtocol());
                } else {
                    factory.useSslProtocol(getSslProtocol(), getTrustManager());
                }
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                throw new IllegalArgumentException("Invalid sslProtocol " + sslProtocol, e);
            }
        }
        if (getAutomaticRecoveryEnabled() != null) {
            factory.setAutomaticRecoveryEnabled(getAutomaticRecoveryEnabled());
        }
        if (getNetworkRecoveryInterval() != null) {
            factory.setNetworkRecoveryInterval(getNetworkRecoveryInterval());
        }
        if (getTopologyRecoveryEnabled() != null) {
            factory.setTopologyRecoveryEnabled(getTopologyRecoveryEnabled());
        }
        connectionFactory = factory;
    }
    return connectionFactory;
}

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance./*  ww w  .j a  v a2s .c  om*/
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:coyote.dx.reader.RabbitReader.java

License:Open Source License

/**
 * @see coyote.dx.reader.AbstractFrameReader#open(coyote.dx.context.TransformContext)
 *//*from   w w w.  j  a va 2s. co m*/
@Override
public void open(TransformContext context) {
    super.open(context);

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(prefetchCount);
        channel.queueDeclare(getQueueName(), DURABLE, PUBLIC, KEEP, NO_ARGUMENTS);
    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

From source file:coyote.dx.writer.RabbitWriter.java

License:Open Source License

/**
 * @see coyote.dx.writer.AbstractFrameFileWriter#open(coyote.dx.context.TransformContext)
 *///w  w w . j a  v  a2 s  .c  om
@Override
public void open(TransformContext context) {
    super.open(context);

    String format = getFormat();
    if (StringUtil.isNotBlank(format)) {
        if (format.equalsIgnoreCase(JSON) || format.equalsIgnoreCase(XML)) {
            String encoding = getEncoding();
            try {
                "Testing".getBytes(encoding);
            } catch (final java.io.UnsupportedEncodingException e) {
                Log.error("Unsupported string encoding of '" + encoding + "'");
                getContext().setError("Unsupported string encoding of '" + encoding + "'");
            }
        }
    } else {
        Log.error("Unsupported message format of '" + format
                + "' JSON, XML, and Binary are the currently supported options");
        getContext().setError("Unsupported message format of '" + format + "'");
    }

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(getQueueName(), true, false, false, null);

    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

From source file:coyote.mq.AbstractMessagingTest.java

License:Open Source License

public void sendMessage(String queueName, DataFrame message) {
    if (StringUtil.isNotBlank(queueName) && message != null) {
        byte[] data = message.getBytes();
        try {//from  www . ja  v a  2 s.c  o m
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUri(broker.getBrokerUri());
            factory.useSslProtocol();
            // username:password should be in the URI for our tests
            try (Connection connection = factory.newConnection()) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, false, false, false, null);
                channel.basicPublish("", queueName, null, data);
                Log.debug("Sent " + data.length + " bytes to '" + queueName + "'");
            }
        } catch (Exception e) {
            Log.error("Could not send message: " + e.getClass().getSimpleName() + "-" + e.getMessage());
        }
    }
}

From source file:dk.au.cs.karibu.backend.rabbitmq.RabbitMQPollingConsumer.java

License:Apache License

@Override
public void openChannelAndSetRouting() throws IOException {
    theLogger.info(//  www  . j  a v a  2  s .  c o m
            "openChannelAndSetRouting: Exchange:" + exchangeConfiguration + " Queue: " + queueConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("KeyMgtException: " + trace);
        } catch (NoSuchAlgorithmException e) {
            String trace = ExceptionUtils.getStackTrace(e);
            theLogger.error("NoSuchAlgoritmException: " + trace);
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // 'RabbitMQ in Action' p 102 
    Map<String, Object> moreArguments = new HashMap<String, Object>();
    moreArguments.put("ha-mode", "all");
    moreArguments.put("x-ha-policy", "all");
    // TODO: find out why this does not work! 
    channel.queueDeclare(queueConfiguration.getQueueName(), queueConfiguration.isQueueDurable(),
            queueConfiguration.isQueueExclusive(), queueConfiguration.isQueueAutoDelete(), moreArguments);
    channel.queueBind(queueConfiguration.getQueueName(), exchangeConfiguration.getExchangeName(),
            queueConfiguration.getRoutingKey());

    consumer = new QueueingConsumer(channel);
    // Tell RabbitMQ to await acknowledgement before removing
    // msg from the queue. See http://www.rabbitmq.com/tutorials/tutorial-two-java.html
    boolean autoAck = false;
    channel.basicConsume(queueConfiguration.getQueueName(), autoAck, consumer);
    // Set the prefetch count to limit the amount of msg sent
    // to the daemons before they are acknowledged. Fixes a
    // bug that would induce an out-of-memory error in the
    // daemons during high transfer rates.
    // See http://www.rabbitmq.com/tutorials/tutorial-two-java.html 
    // in the 'fair dispatch' section
    int prefetchCount = 100; // ISSUE: what is the 'right' value here?
    channel.basicQos(prefetchCount);
}

From source file:dk.au.cs.karibu.producer.rabbitmq.RabbitChannelConnector.java

License:Apache License

@Override
public void openConnection() throws IOException {
    theLogger.info("openConnection: " + exchangeConfiguration);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(exchangeConfiguration.getUsername());
    factory.setPassword(exchangeConfiguration.getPassword());
    if (exchangeConfiguration.isSSLConnection()) {
        try {//from w ww  .  java2  s.c  o  m
            factory.useSslProtocol();
        } catch (KeyManagementException e) {
            theLogger.error("KeyManagementException: " + e.getLocalizedMessage());
        } catch (NoSuchAlgorithmException e) {
            theLogger.error("NoSuchAlgorithmException: " + e.getLocalizedMessage());
        }
    }
    connection = factory.newConnection(exchangeConfiguration.getServerAddressList());

    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeConfiguration.getExchangeName(), exchangeConfiguration.getExchangeType(),
            exchangeConfiguration.isExchangeDurable());

    // The queue and the binding between queue and exchange is defined by the server side! 
}

From source file:org.graylog2.inputs.transports.AmqpConsumer.java

License:Open Source License

public void connect() throws IOException {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);//  w w  w .j ava  2s  .  co m
    factory.setPort(port);
    factory.setVirtualHost(virtualHost);

    if (tls) {
        try {
            LOG.info("Enabling TLS for AMQP input [{}/{}].", sourceInput.getName(), sourceInput.getId());
            factory.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new IOException("Couldn't enable TLS for AMQP input.", e);
        }
    }

    // Authenticate?
    if (!isNullOrEmpty(username) && !isNullOrEmpty(password)) {
        factory.setUsername(username);
        factory.setPassword(password);
    }

    connection = factory.newConnection();
    channel = connection.createChannel();

    if (null == channel) {
        LOG.error("No channel descriptor available!");
    }

    if (null != channel && prefetchCount > 0) {
        channel.basicQos(prefetchCount);

        LOG.info("AMQP prefetch count overriden to <{}>.", prefetchCount);
    }

    connection.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            if (cause.isInitiatedByApplication()) {
                LOG.info("Not reconnecting connection, we disconnected explicitly.");
                return;
            }
            while (true) {
                try {
                    LOG.error("AMQP connection lost! Trying reconnect in 1 second.");

                    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);

                    connect();

                    LOG.info("Connected! Re-starting consumer.");

                    run();

                    LOG.info("Consumer running.");
                    break;
                } catch (IOException e) {
                    LOG.error("Could not re-connect to AMQP broker.", e);
                }
            }
        }
    });
}

From source file:org.springframework.xd.dirt.integration.rabbit.RabbitConnectionFactoryBean.java

License:Apache License

private void setUpSSL(ConnectionFactory rabbitConnectionFactory) throws Exception {
    if (this.sslPropertiesLocation == null) {
        rabbitConnectionFactory.useSslProtocol();
    } else {//ww  w . ja  v  a 2  s .  co  m
        Properties sslProperties = new Properties();
        sslProperties.load(this.sslPropertiesLocation.getInputStream());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String keyStoreName = sslProperties.getProperty("keyStore");
        Assert.state(StringUtils.hasText(keyStoreName), "keyStore property required");
        String trustStoreName = sslProperties.getProperty("trustStore");
        Assert.state(StringUtils.hasText(trustStoreName), "trustStore property required");
        String keyStorePassword = sslProperties.getProperty("keyStore.passPhrase");
        Assert.state(StringUtils.hasText(keyStorePassword), "keyStore.passPhrase property required");
        String trustStorePassword = sslProperties.getProperty("trustStore.passPhrase");
        Assert.state(StringUtils.hasText(trustStorePassword), "trustStore.passPhrase property required");
        Resource keyStore = resolver.getResource(keyStoreName);
        Resource trustStore = resolver.getResource(trustStoreName);
        char[] keyPassphrase = keyStorePassword.toCharArray();
        char[] trustPassphrase = trustStorePassword.toCharArray();

        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(keyStore.getInputStream(), keyPassphrase);

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

        KeyStore tks = KeyStore.getInstance("JKS");
        tks.load(trustStore.getInputStream(), trustPassphrase);

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

        SSLContext context = SSLContext.getInstance("SSLv3");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        rabbitConnectionFactory.useSslProtocol(context);
    }
}

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

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/* www . j a v a 2  s .co m*/
 * @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;
}