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.elasticsearch.river.rabbitmq.RabbitMQRiverTest.java

License:Apache License

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

    Node node = NodeBuilder.nodeBuilder()
            .settings(ImmutableSettings.settingsBuilder().put("gateway.type", "none")).node();

    node.client().prepareIndex("_river", "test1", "_meta")
            .setSource(jsonBuilder().startObject().field("type", "rabbitmq").endObject()).execute().actionGet();

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setHost("localhost");
    cfconn.setPort(AMQP.PROTOCOL.PORT);//from  w  w w  .j a va2  s.  c  o  m
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();
    ch.exchangeDeclare("elasticsearch", "direct", true);
    ch.queueDeclare("elasticsearch", true, false, false, null);

    String message = "{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());

    ch.close();
    conn.close();

    Thread.sleep(100000);
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQRiverWithCustomActionsTest.java

License:Apache License

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

    String rabbitHost = "rabbit-qa1";
    Node node = NodeBuilder.nodeBuilder().settings(
            ImmutableSettings.settingsBuilder().put("gateway.type", "none").put("cluster.name", "es-mqtest"))
            .node();//from   ww w. j  a  va2  s .  co m

    node.client().prepareIndex("_river", "mqtest1", "_meta")
            .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("rabbitmq")
                    .field("host", rabbitHost).endObject().startObject("index").field("ordered", "true")
                    .field("warnOnBulkErrors", "false").endObject().endObject())
            .execute().actionGet();

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setHost(rabbitHost);
    cfconn.setPort(AMQP.PROTOCOL.PORT);
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();
    ch.exchangeDeclare("elasticsearch", "direct", true);
    ch.queueDeclare("elasticsearch", true, false, false, null);

    Thread.sleep(5000);
    String message = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    String messageWithWrongIndex = "{ \"index\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }\n"
            + "{ \"delete\" : { \"_index\" : \"This.Is.An.Invalid.Name\", \"_type\" : \"type1\", \"_id\" : \"2\" } }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"2\"} }\n"
            + "{ \"create\" : { \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_id\" : \"1\" , \"_version\" : \"1\"} }\n"
            + "{ \"type1\" : { \"field1\" : \"value1\" } }";

    String mapping = "{ \"type2\" : { \"properties\" : {\"data\" : {\"dynamic\" : true,\"properties\" : {\"myString\" : {\"type\" : \"string\",\"boost\" : 1.0,\"index\" : \"not_analyzed\",\"store\" : \"no\"},\"myText\" : {\"type\" : \"string\",\"include_in_all\" : true,\"index\" : \"analyzed\",\"store\" : \"no\"}}}}}}";
    String mappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}\n" + mapping;
    String partialmappingMessage = "{ \"_index\" : \"mqtest\", \"_type\" : \"type2\"}";
    String deleteByQuery = "{ \"_index\" : \"mqtest\", \"_type\" : \"type1\", \"_queryString\" : \"_id:1\"}\n";

    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());

    HashMap<String, Object> headers = new HashMap<String, Object>();
    headers.put("X-ES-Command", "mapping");
    BasicProperties props = MessageProperties.MINIMAL_BASIC;
    props = props.builder().headers(headers).build();
    ch.basicPublish("elasticsearch", "elasticsearch", props, mappingMessage.getBytes());
    headers.put("X-ES-Command", "deleteByQuery");
    props = props.builder().headers(headers).build();
    ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes());
    Thread.sleep(5000);
    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", null, messageWithWrongIndex.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", null, message.getBytes());
    ch.basicPublish("elasticsearch", "elasticsearch", props, deleteByQuery.getBytes());
    Thread.sleep(5000);
    ch.close();
    conn.close();

    Thread.sleep(5000);
    Boolean exists = node.client().get(new GetRequest("mqtest").id("1")).get().isExists();
    ClusterState state = node.client().admin().cluster()
            .state(new ClusterStateRequest().filteredIndices("mqtest")).get().getState();
    ImmutableOpenMap<String, MappingMetaData> mappings = state.getMetaData().index("mqtest").mappings();
    MappingMetaData typeMap = mappings.get("type2");
    if (null != typeMap) {
        String gotMapping = typeMap.source().toString();
    }
}

From source file:org.elasticsearch.river.rabbitmq.RabbitMQTestRunner.java

License:Apache License

@Test
public void test_all_messages_are_consumed() throws Exception {

    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    try {/*www.j a  va2 s . c  o  m*/
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory cfconn = new ConnectionFactory();
        cfconn.setHost("localhost");
        cfconn.setPort(AMQP.PROTOCOL.PORT);
        Connection conn = cfconn.newConnection();

        Channel ch = conn.createChannel();
        ch.exchangeDeclare("elasticsearch", "direct", true);
        AMQP.Queue.DeclareOk queue = ch.queueDeclare("elasticsearch", true, false, false, null);

        // We purge the queue in case of something is remaining there
        ch.queuePurge("elasticsearch");

        logger.info(" --> sending messages");
        pushMessages(ch);

        logger.info(" --> create river");
        createIndex(INDEX);

        index("_river", "test", "_meta", river());

        // We need at some point to check if we have consumed the river
        int steps = timeout();
        long count = 0;

        while (true) {
            // We wait for one second
            Thread.sleep(1000);

            CountResponse response = client().prepareCount("test").execute().actionGet();
            count = response.getCount();

            steps--;
            if (steps < 0 || count == expectedDocuments()) {
                break;
            }
        }

        ch.close();
        conn.close();

        postInjectionTests();
    } catch (ConnectException e) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", e);
    }
}

From source file:org.geoserver.notification.common.sender.RabbitMQSender.java

License:Open Source License

public void initialize() throws Exception {

    if (uri == null) {
        if (this.username != null && !this.username.isEmpty() && this.password != null
                && !this.password.isEmpty()) {
            this.uri = "amqp://" + this.username + ":" + this.password + "@" + this.host + ":" + this.port;
        } else {// w  w  w.  j a  va2 s . co  m
            this.uri = "amqp://" + this.host + ":" + this.port;
        }

    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(this.uri);
    String vHost = (this.virtualHost != null && !this.virtualHost.isEmpty() ? this.virtualHost : "/");
    factory.setVirtualHost(vHost);
    factory.setSaslConfig(new CustomSaslConfig());
    conn = factory.newConnection();
    channel = conn.createChannel();
}

From source file:org.geoserver.notification.support.Receiver.java

License:Open Source License

public void receive(ReceiverService service) throws Exception {
    // let's setup evrything and start listening
    this.service = service;
    ConnectionFactory factory = createConnectionFactory();
    factory.setSaslConfig(new CustomSaslConfig());
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare("testExchange", "fanout");
    channel.queueDeclare(QUEUE_NAME, false, true, false, null);
    channel.queueBind(QUEUE_NAME, "testExchange", "testRouting");
    channel.basicConsume(QUEUE_NAME, true, newConsumer(channel));
}

From source file:org.graylog2.inputs.amqp.Consumer.java

License:Open Source License

public void connect() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);//  w w w.  j ava2s.c  o m
    factory.setPort(port);

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

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

    if (prefetchCount > 0) {
        channel.basicQos(prefetchCount);

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

    connection.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            while (true) {
                try {
                    LOG.error("AMQP connection lost! Trying reconnect in 1 second.");

                    Thread.sleep(1000);

                    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);
                } catch (InterruptedException ignored) {
                }
            }
        }
    });
}

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);/*from w w  w  .j a  va2 s. 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.graylog2.messagehandlers.amqp.AMQPBroker.java

License:Open Source License

public Connection getConnection() throws IOException {
    if (connection == null || !connection.isOpen()) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(getUsername());
        factory.setPassword(getPassword());
        factory.setVirtualHost(getVirtualHost());
        factory.setHost(getHost());// www.ja v a  2 s.c o m
        factory.setPort(getPort());
        this.connection = factory.newConnection();
    }

    return this.connection;
}

From source file:org.graylog2.radio.Radio.java

License:Open Source License

public Connection getBroker() throws IOException {
    if (brokerConnection == null || !brokerConnection.isOpen()) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(configuration.getAMQPHost());
        factory.setPort(configuration.getAMQPPort());
        factory.setUsername(configuration.getAMQPUser());
        factory.setPassword(configuration.getAMQPPassword());

        brokerConnection = factory.newConnection();
    }// w  w w  .j av  a 2 s.  c o  m

    return brokerConnection;
}

From source file:org.graylog2.radio.transports.amqp.AMQPSender.java

License:Open Source License

public void connect() throws IOException {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);/*w  ww .ja v a  2 s . com*/
    factory.setPort(port);

    factory.setVirtualHost(vHost);

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

    factory.setConnectionTimeout((int) connectTimeout.getMillis());

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

    // It's ok if the queue or exchange already exist.
    channel.queueDeclare(queueName, true, false, false, null);
    channel.exchangeDeclare(exchangeName, queueType, false, false, null);

    channel.queueBind(queueName, exchangeName, routingKey);
}