Example usage for com.rabbitmq.client ConnectionFactory newConnection

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

Introduction

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

Prototype

public Connection newConnection() throws IOException, TimeoutException 

Source Link

Document

Create a new broker connection.

Usage

From source file:org.apache.james.transport.mailets.AmqpForwardAttributeTest.java

License:Apache License

@Test
public void serviceShouldNotUseConnectionWhenNoAttributeInMail() throws Exception {
    mailet.init(mailetConfig);/*from ww w  .ja v  a2  s.  c  o  m*/
    Connection connection = mock(Connection.class);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.newConnection()).thenReturn(connection);
    mailet.setConnectionFactory(connectionFactory);
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(null);

    mailet.service(mail);

    verifyZeroInteractions(connection);
}

From source file:org.apache.james.transport.mailets.AmqpForwardAttributeTest.java

License:Apache License

@Test
public void serviceShouldLogWhenTimeoutException() throws Exception {
    mailet.init(mailetConfig);//  w  ww  .  j  av  a 2  s. c  om
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    TimeoutException expectedLoggedException = new TimeoutException();
    when(connectionFactory.newConnection()).thenThrow(expectedLoggedException);
    mailet.setConnectionFactory(connectionFactory);

    mailet.service(mail);

    verify(logger).error(any(String.class), eq(expectedLoggedException));
}

From source file:org.apache.james.transport.mailets.AmqpForwardAttributeTest.java

License:Apache License

@Test
public void serviceShouldLogWhenIOException() throws Exception {
    mailet.init(mailetConfig);/*from   w  w w . j  av  a2s.  co m*/
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    IOException expectedLoggedException = new IOException();
    when(connectionFactory.newConnection()).thenThrow(expectedLoggedException);
    mailet.setConnectionFactory(connectionFactory);

    mailet.service(mail);

    verify(logger).error(any(String.class), eq(expectedLoggedException));
}

From source file:org.apache.james.transport.mailets.AmqpForwardAttributeTest.java

License:Apache License

@Test
public void serviceShouldPublishAttributeContentWhenAttributeInMail() throws Exception {
    mailet.init(mailetConfig);//ww  w. j  a v a  2 s.  co m
    Channel channel = mock(Channel.class);
    Connection connection = mock(Connection.class);
    when(connection.createChannel()).thenReturn(channel);
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.newConnection()).thenReturn(connection);
    mailet.setConnectionFactory(connectionFactory);
    Mail mail = mock(Mail.class);
    when(mail.getAttribute(MAIL_ATTRIBUTE)).thenReturn(ATTRIBUTE_CONTENT);
    BasicProperties expectedProperties = new AMQP.BasicProperties();

    mailet.service(mail);

    ArgumentCaptor<BasicProperties> basicPropertiesCaptor = ArgumentCaptor.forClass(BasicProperties.class);
    verify(channel).basicPublish(eq(EXCHANGE_NAME), eq(ROUTING_KEY), basicPropertiesCaptor.capture(),
            eq(ATTACHMENT_CONTENT));
    assertThat(basicPropertiesCaptor.getValue()).isEqualToComparingFieldByField(expectedProperties);
}

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

License:Apache License

/**
 * Creates {@link Connection} to AMQP system.
 *//*from   w ww  .  jav  a  2  s  . c o 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.apache.niolex.rabbit.basic.Send.java

License:Apache License

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    for (int i = 0; i < 100; ++i) {
        String message = String.format("%02d %s", i, MockUtil.randString(5));
        ThreadUtil.sleepAtLeast(1000);/*from   w w  w  .  ja  v  a  2 s . c o  m*/
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");
    }

    channel.close();
    connection.close();
}

From source file:org.apache.niolex.rabbit.log.EmitLog.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    for (int i = 0; i < 100; ++i) {
        String message = String.format("%02d %s", i, MockUtil.randString(5));
        ThreadUtil.sleepAtLeast(1000);/*  w  w w . ja  v a  2  s  . c om*/

        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
    }

    channel.close();
    connection.close();
}

From source file:org.apache.niolex.rabbit.log.EmitLogDirect.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    for (int i = 0; i < 100; ++i) {
        String message = String.format("%02d %s", i, MockUtil.randString(5));
        String severity = MockUtil.randInt(3) == 0 ? "error" : "info";
        ThreadUtil.sleepAtLeast(1000);/*  w  ww . j a v a 2 s  . c om*/

        channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
        System.out.println(" [x] Sent '" + severity + "': '" + message + "'");
    }

    channel.close();
    connection.close();
}

From source file:org.apache.niolex.rabbit.log.EmitLogTopic.java

License:Apache License

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic");

    for (int i = 0; i < 100; ++i) {
        String message = String.format("%02d %s", i, MockUtil.randString(5));
        ThreadUtil.sleepAtLeast(1000);/* w  ww.ja va 2s .c o  m*/

        String routingKey = getSeverity() + "." + getFacility();

        channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes());
        System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
    }

    channel.close();
    connection.close();
}

From source file:org.apache.niolex.rabbit.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;/*from   w ww .ja va 2s. c  o  m*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

        System.out.println(" [x] Awaiting RPC requests");

        while (true) {
            String response = null;

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                int n = Integer.parseInt(message);

                System.out.println(" [.] fib(" + message + ")");
                response = "" + fib(n);
            } catch (Exception e) {
                System.out.println(" [.] " + e.toString());
                response = "";
            } finally {
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}