Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

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

License:Apache License

@Before
public void setup() throws Exception {
    @SuppressWarnings("deprecation")
    InetAddress containerIp = InetAddresses
            .forString(rabbitMqContainer.getContainerInfo().getNetworkSettings().getIpAddress());
    String amqpUri = "amqp://" + containerIp.getHostAddress();

    MailetContainer mailetContainer = MailetContainer.builder().postmaster("postmaster@" + JAMES_APACHE_ORG)
            .threads(5).addProcessor(CommonProcessors.root()).addProcessor(CommonProcessors.error())
            .addProcessor(ProcessorConfiguration.builder().state("transport").enableJmx(true)
                    .addMailet(MailetConfiguration.builder().match("All").clazz("RemoveMimeHeader")
                            .addProperty("name", "bcc").build())
                    .addMailet(MailetConfiguration.builder().match("All").clazz("StripAttachment")
                            .addProperty("attribute", MAIL_ATTRIBUTE).addProperty("pattern", ".*").build())
                    .addMailet(MailetConfiguration.builder().match("All").clazz("AmqpForwardAttribute")
                            .addProperty("uri", amqpUri).addProperty("exchange", EXCHANGE_NAME)
                            .addProperty("attribute", MAIL_ATTRIBUTE).addProperty("routing_key", ROUTING_KEY)
                            .build())/*from   w w  w . j a  v a  2s.  c om*/
                    .addMailet(MailetConfiguration.builder().match("RecipientIsLocal")
                            .clazz("org.apache.james.jmap.mailet.VacationMailet").build())
                    .addMailet(MailetConfiguration.builder().match("RecipientIsLocal").clazz("LocalDelivery")
                            .build())
                    .build())
            .build();

    jamesServer = new TemporaryJamesServer(temporaryFolder, mailetContainer);
    Duration slowPacedPollInterval = Duration.FIVE_HUNDRED_MILLISECONDS;
    calmlyAwait = Awaitility.with().pollInterval(slowPacedPollInterval).and().with()
            .pollDelay(slowPacedPollInterval).await();

    jamesServer.getServerProbe().addDomain(JAMES_APACHE_ORG);
    jamesServer.getServerProbe().addUser(FROM, PASSWORD);
    jamesServer.getServerProbe().addUser(RECIPIENT, PASSWORD);
    jamesServer.getServerProbe().createMailbox(MailboxConstants.USER_NAMESPACE, RECIPIENT, "INBOX");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(amqpUri);
    waitingForRabbitToBeReady(factory);
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
    queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, ROUTING_KEY);
}

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

License:Apache License

public void init() throws MailetException {
    String uri = getInitParameter(URI_PARAMETER_NAME);
    if (Strings.isNullOrEmpty(uri)) {
        throw new MailetException("No value for " + URI_PARAMETER_NAME + " parameter was provided.");
    }// www .j ava  2s  .c  o m
    exchange = getInitParameter(EXCHANGE_PARAMETER_NAME);
    if (Strings.isNullOrEmpty(exchange)) {
        throw new MailetException("No value for " + EXCHANGE_PARAMETER_NAME + " parameter was provided.");
    }
    routingKey = getInitParameter(ROUTING_KEY_PARAMETER_NAME, ROUTING_KEY_DEFAULT_VALUE);
    attribute = getInitParameter(ATTRIBUTE_PARAMETER_NAME);
    if (Strings.isNullOrEmpty(attribute)) {
        throw new MailetException("No value for " + ATTRIBUTE_PARAMETER_NAME + " parameter was provided.");
    }
    connectionFactory = new ConnectionFactory();
    try {
        connectionFactory.setUri(uri);
    } catch (Exception e) {
        throw new MailetException("Invalid " + URI_PARAMETER_NAME + " parameter was provided: " + uri, e);
    }
}

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

License:Apache License

/**
 * Creates {@link Connection} to AMQP system.
 *///from   ww  w . j  a  v a 2  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 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);//from   w w w  . ja v  a  2s .  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  .ja  v  a  2  s  .  c o m*/

        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 w  w .ja  v  a2  s.co 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 w  w .ja  v a2  s.com
    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) {
            }
        }
    }
}

From source file:org.apache.nutch.fetcher.RabbitmqProxy.java

License:Apache License

private RabbitmqProxy(Configuration configuration) {
    try {//  w  w w .j  a va2s . co m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(configuration.get("rabbitmq.ip"));
        factory.setUsername(configuration.get("rabbitmq.username"));
        factory.setPassword(configuration.get("rabbitmq.password"));
        factory.setVirtualHost(configuration.get("rabbitmq.virtualhost"));
        connection = factory.newConnection();
        channel = connection.createChannel();
        exchange_name = configuration.get("rabbitmq.exchange");
        channel.exchangeDeclare(exchange_name, "fanout");
    } catch (java.io.IOException e) {
        LOG.fatal(e);
    }

}

From source file:org.apache.nutch.indexer.history.HistoryIndexer.java

License:Apache License

private void sendEvent(final String message) {

    ConnectionFactory factory = new ConnectionFactory();
    final String host = conf.get("history.rabbitmq.host", "localhost");
    factory.setHost(host);/*from ww w .  j av  a 2 s.  c o  m*/

    final String user = conf.get("history.rabbitmq.user");
    factory.setUsername(user);

    final String password = conf.get("history.rabbitmq.password");
    factory.setPassword(password);

    Connection connection = null;
    Channel channel = null;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
    } catch (IOException | TimeoutException e) {
        final String errMsg = "failed opening connection or channel";
        LOG.error(errMsg, e);
        closeChannelAndConnection(channel, true);
        throw new RuntimeException(errMsg, e);
    }

    final String queueNamesStr = conf.get("history.rabbitmq.queue.names", "nlp,langdetector");
    final String[] queueNames = queueNamesStr.split(",");
    for (final String singleQueueName : queueNames) {
        try {
            channel.queueDeclare(singleQueueName, true, false, false, null);
            channel.basicPublish("", singleQueueName, null, message.getBytes());
            LOG.debug(" [x] Sent '" + message + "'");
        } catch (IOException e) {
            final String errMsg = String.format("failed sending message [%s] to queue [%s]", message,
                    singleQueueName);
            LOG.error(errMsg, e);
        }
    }

    closeChannelAndConnection(channel, false);
}