Example usage for com.rabbitmq.client ConnectionFactory setUri

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

Introduction

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

Prototype

public void setUri(String uriString)
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException 

Source Link

Document

Convenience method for setting the fields in an AMQP URI: host, port, username, password and virtual host.

Usage

From source file:org.apache.airavata.messaging.core.impl.RabbitMQTaskLaunchConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/*from   w  w  w.  jav  a2 s. c  om*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + taskLaunchExchangeName);

        channel = connection.createChannel();
        //            channel.exchangeDeclare(taskLaunchExchangeName, "fanout");

    } catch (Exception e) {
        String msg = "could not open channel for exchange " + taskLaunchExchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.monitoring.consumer.StatusReceiver.java

License:Apache License

public void startThread() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException,
        IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setUri(brokerURI);
    connection = factory.newConnection();
    recieverThread = new Thread(this);
    recieverThread.start();//from w w  w  . java  2 s .  com
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testReadQueue() throws Exception {
    final int maxNumRecords = 10;
    PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port)
            .withQueue("READ").withMaxNumRecords(maxNumRecords));
    PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings())
            .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8)));

    List<String> records = generateRecords(maxNumRecords).stream()
            .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList());
    PAssert.that(output).containsInAnyOrder(records);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;//w  w w  . j  a va  2s. co m
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("READ", false, false, false, null);
        for (String record : records) {
            channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8));
        }

        p.run();
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test(timeout = 60 * 1000)
public void testReadExchange() throws Exception {
    final int maxNumRecords = 10;
    PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port)
            .withExchange("READEXCHANGE", "fanout", "test").withMaxNumRecords(maxNumRecords));
    PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings())
            .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8)));

    List<String> records = generateRecords(maxNumRecords).stream()
            .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList());
    PAssert.that(output).containsInAnyOrder(records);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;//from w  ww.  j  a  va 2s . c  om
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare("READEXCHANGE", "fanout");
        Channel finalChannel = channel;
        Thread publisher = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
            for (int i = 0; i < maxNumRecords; i++) {
                try {
                    finalChannel.basicPublish("READEXCHANGE", "test", null,
                            ("Test " + i).getBytes(StandardCharsets.UTF_8));
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        });
        publisher.start();
        p.run();
        publisher.join();
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testWriteQueue() throws Exception {
    final int maxNumRecords = 1000;
    List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream()
            .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList());
    p.apply(Create.of(data))/*from   w ww  . j  av a 2  s . c o  m*/
            .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST"));

    final List<String> received = new ArrayList<>();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("TEST", true, false, false, null);
        Consumer consumer = new TestConsumer(channel, received);
        channel.basicConsume("TEST", true, consumer);

        p.run();

        while (received.size() < maxNumRecords) {
            Thread.sleep(500);
        }

        assertEquals(maxNumRecords, received.size());
        for (int i = 0; i < maxNumRecords; i++) {
            assertTrue(received.contains("Test " + i));
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testWriteExchange() throws Exception {
    final int maxNumRecords = 1000;
    List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream()
            .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList());
    p.apply(Create.of(data)).apply(/*from   w w  w .  jav  a  2 s .  c om*/
            RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withExchange("WRITE", "fanout"));

    final List<String> received = new ArrayList<>();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare("WRITE", "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, "WRITE", "");
        Consumer consumer = new TestConsumer(channel, received);
        channel.basicConsume(queueName, true, consumer);

        p.run();

        while (received.size() < maxNumRecords) {
            Thread.sleep(500);
        }

        assertEquals(maxNumRecords, received.size());
        for (int i = 0; i < maxNumRecords; i++) {
            assertTrue(received.contains("Test " + i));
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java

License:Apache License

/**
 *
 * @return Connection Factory for RMQ// w w w  .j a  v a2  s . c o m
 * @throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException if Malformed URI has been passed
 */
public ConnectionFactory getConnectionFactory()
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
    ConnectionFactory factory = new ConnectionFactory();
    if (this.uri != null && !this.uri.isEmpty()) {
        try {
            factory.setUri(this.uri);
        } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException e) {
            LOG.error("Failed to parse uri", e);
            throw e;
        }
    } else {
        factory.setHost(this.host);
        factory.setPort(this.port);
        factory.setVirtualHost(this.virtualHost);
        factory.setUsername(this.username);
        factory.setPassword(this.password);
    }

    if (this.automaticRecovery != null) {
        factory.setAutomaticRecoveryEnabled(this.automaticRecovery);
    }
    if (this.connectionTimeout != null) {
        factory.setConnectionTimeout(this.connectionTimeout);
    }
    if (this.networkRecoveryInterval != null) {
        factory.setNetworkRecoveryInterval(this.networkRecoveryInterval);
    }
    if (this.requestedHeartbeat != null) {
        factory.setRequestedHeartbeat(this.requestedHeartbeat);
    }
    if (this.topologyRecovery != null) {
        factory.setTopologyRecoveryEnabled(this.topologyRecovery);
    }
    if (this.requestedChannelMax != null) {
        factory.setRequestedChannelMax(this.requestedChannelMax);
    }
    if (this.requestedFrameMax != null) {
        factory.setRequestedFrameMax(this.requestedFrameMax);
    }

    return factory;
}

From source file:org.apache.james.backend.rabbitmq.RabbitMQConnectionFactory.java

License:Apache License

private ConnectionFactory from(RabbitMQConfiguration rabbitMQConfiguration) {
    try {/*from   w w  w .  j  ava  2s  .c o m*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(rabbitMQConfiguration.getUri());
        connectionFactory.useNio();
        return connectionFactory;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.james.transport.mailets.amqp.AmqpRule.java

License:Apache License

@Override
protected void before() throws Throwable {
    amqpUri = "amqp://" + rabbitMqContainer.getIp();
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(amqpUri);
    waitingForRabbitToBeReady(factory);/*  w  w w . j ava 2  s  .com*/
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT);
    queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, exchangeName, routingKey);
}

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 ww  .  ja va2  s  .c  o  m*/
                    .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);
}