Example usage for com.rabbitmq.client ConnectionFactory setHost

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

Introduction

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

Prototype

public void setHost(String host) 

Source Link

Usage

From source file:org.apache.nutch.publisher.rabbitmq.RabbitMQPublisherImpl.java

License:Apache License

@Override
public boolean setConfig(Configuration conf) {
    try {//  ww  w  .  j  a va 2  s  . c  o m
        EXCHANGE_SERVER = conf.get("rabbitmq.exchange.server", "fetcher_log");
        EXCHANGE_TYPE = conf.get("rabbitmq.exchange.type", "fanout");

        HOST = conf.get("rabbitmq.host", "localhost");
        PORT = conf.getInt("rabbitmq.port", 5672);
        VIRTUAL_HOST = conf.get("rabbitmq.virtualhost", null);
        USERNAME = conf.get("rabbitmq.username", null);
        PASSWORD = conf.get("rabbitmq.password", null);

        QUEUE_NAME = conf.get("rabbitmq.queue.name", "fanout.queue");
        QUEUE_DURABLE = conf.getBoolean("rabbitmq.queue.durable", true);
        QUEUE_ROUTING_KEY = conf.get("rabbitmq.queue.routingkey", "fanout.key");

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST);
        factory.setPort(PORT);

        if (VIRTUAL_HOST != null) {
            factory.setVirtualHost(VIRTUAL_HOST);
        }

        if (USERNAME != null) {
            factory.setUsername(USERNAME);
            factory.setPassword(PASSWORD);
        }

        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_SERVER, EXCHANGE_TYPE);
        channel.queueDeclare(QUEUE_NAME, QUEUE_DURABLE, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_SERVER, QUEUE_ROUTING_KEY);

        LOG.info("Configured RabbitMQ publisher");
        return true;
    } catch (Exception e) {
        LOG.error("Could not initialize RabbitMQ publisher - {}", StringUtils.stringifyException(e));
        return false;
    }

}

From source file:org.apache.nutch.rabbitmq.RabbitMQClient.java

License:Apache License

/**
 * Builds a new instance of {@link RabbitMQClient}
 *
 * @param serverHost        The server host.
 * @param serverPort        The server port.
 * @param serverVirtualHost The virtual host into the RabbitMQ server.
 * @param serverUsername    The username to access the server.
 * @param serverPassword    The password to access the server.
 * @throws IOException It is thrown if there is some issue during the connection creation.
 *///from   w  ww  .java  2 s .  c  o  m
public RabbitMQClient(String serverHost, int serverPort, String serverVirtualHost, String serverUsername,
        String serverPassword) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(getValue(serverHost, "localhost"));
    factory.setPort(getValue(serverPort, 5672));

    factory.setVirtualHost(getValue(serverVirtualHost, "/"));

    factory.setUsername(getValue(serverUsername, "guest"));
    factory.setPassword(getValue(serverPassword, "guest"));

    try {
        connection = factory.newConnection();
    } catch (TimeoutException e) {
        throw makeIOException(e);
    }
}

From source file:org.apache.synapse.tranport.amqp.AMQPTwoWayProducerClient.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {

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

    Channel channel = connection.createChannel();

    AMQPTwoWayProducerClient.produceAndConsume(MESSAGE2, channel, "consumer", "consumerReply");

    channel.close();//from   w w w . j  a  va 2  s  . c om
    connection.close();

}

From source file:org.ballerinalang.messaging.rabbitmq.util.ConnectionUtils.java

License:Open Source License

/**
 * Creates a RabbitMQ Connection using the given connection parameters.
 *
 * @param connectionConfig Parameters used to initialize the connection.
 * @return RabbitMQ Connection object./*from   w w w .ja v a 2 s . co m*/
 */
public static Connection createConnection(BMap<String, BValue> connectionConfig) {
    try {
        ConnectionFactory connectionFactory = new ConnectionFactory();

        String host = RabbitMQUtils.getStringFromBValue(connectionConfig,
                RabbitMQConstants.RABBITMQ_CONNECTION_HOST);
        connectionFactory.setHost(host);

        int port = RabbitMQUtils.getIntFromBValue(connectionConfig, RabbitMQConstants.RABBITMQ_CONNECTION_PORT,
                LOGGER);
        connectionFactory.setPort(port);

        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_USER) != null) {
            connectionFactory.setUsername(RabbitMQUtils.getStringFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_USER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_PASS) != null) {
            connectionFactory.setPassword(RabbitMQUtils.getStringFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_PASS));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_TIMEOUT) != null) {
            connectionFactory.setConnectionTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_HANDSHAKE_TIMEOUT) != null) {
            connectionFactory.setHandshakeTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_HANDSHAKE_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_SHUTDOWN_TIMEOUT) != null) {
            connectionFactory.setShutdownTimeout(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_SHUTDOWN_TIMEOUT, LOGGER));
        }
        if (connectionConfig.get(RabbitMQConstants.RABBITMQ_CONNECTION_HEARTBEAT) != null) {
            connectionFactory.setRequestedHeartbeat(RabbitMQUtils.getIntFromBValue(connectionConfig,
                    RabbitMQConstants.RABBITMQ_CONNECTION_HEARTBEAT, LOGGER));
        }
        return connectionFactory.newConnection();
    } catch (IOException | TimeoutException exception) {
        LOGGER.error(RabbitMQConstants.CREATE_CONNECTION_ERROR, exception);
        throw new RabbitMQConnectorException(RabbitMQConstants.CREATE_CONNECTION_ERROR + exception.getMessage(),
                exception);
    }
}

From source file:org.belio.mq.RabbitConsumer.java

@Override
public void open() throws IOException {

    try {/* ww  w.jav a  2s . co  m*/
        com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
        factory.setHost(mqproperties.getProperty("host"));
        factory.setVirtualHost(mqproperties.getProperty("vhost"));
        factory.setUsername(mqproperties.getProperty("username"));
        factory.setPassword(mqproperties.getProperty("password"));
        factory.setPort(Integer.parseInt(mqproperties.getProperty("port")));
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(1);
        // Create a new connection to MQ
        connection = factory.newConnection();
        // Create a new channel and declare it's type and exhange as well
        //Create a new rabbit publisher           
        executor = Executors.newScheduledThreadPool(
                Integer.parseInt(threadproperties.getProperty(queueType.name().toLowerCase()).split(",")[0]));

    } catch (IOException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ShutdownSignalException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ConsumerCancelledException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.belio.mq.RabbitConsumer.java

private void openPublisher() {
    try {/*from  ww w  . j a v a  2s .c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(mqproperties.getProperty("host"));
        factory.setVirtualHost(mqproperties.getProperty("vhost"));
        factory.setUsername(mqproperties.getProperty("username"));
        factory.setPassword(mqproperties.getProperty("password"));
        factory.setPort(Integer.parseInt(mqproperties.getProperty("port")));
        // Create a new connection to MQ
        publishingConnection = factory.newConnection();
        // Create a new channel and declare it's type and exhange as well
        publishingChannel = connection.createChannel();
        publishingChannel.queueDeclare(queueType.name().concat(QUEUE_SUFFIX), true, false, false, null);
        publishingChannel.exchangeDeclare(queueType.name().concat(EXCHANGE_SUFFIX),
                mqproperties.getProperty("type"));
        publishingChannel.queueBind(queueType.name().concat(QUEUE_SUFFIX),
                queueType.name().concat(EXCHANGE_SUFFIX), "");
    } catch (IOException exception) {
        Launcher.LOG.error(exception.getLocalizedMessage(), exception);
    }
}

From source file:org.belio.mq.RabbitPublisher.java

@Override
public void open() throws IOException {
    synchronized (RabbitPublisher.class) {
        try {// w ww  .j av a  2 s  . c om
            // Create a connection factory and 
            hosts = mqproperties.getProperty("host").split(",");

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(mqproperties.getProperty("host"));
            factory.setVirtualHost(mqproperties.getProperty("vhost"));
            factory.setUsername(mqproperties.getProperty("username"));
            factory.setPassword(mqproperties.getProperty("password"));
            factory.setPort(Integer.parseInt(mqproperties.getProperty("port")));
            // Create a new connection to MQ
            connection = factory.newConnection();
            // Create a new channel and declare it's type and exhange as well
            channel = connection.createChannel();
            channel.queueDeclare(queueType.name().concat(QUEUE_SUFFIX), true, false, false, null);
            channel.exchangeDeclare(queueType.name().concat(EXCHANGE_SUFFIX), mqproperties.getProperty("type"));
            channel.queueBind(queueType.name().concat(QUEUE_SUFFIX), queueType.name().concat(EXCHANGE_SUFFIX),
                    "");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.eclipse.flux.client.config.RabbitMQFluxConfig.java

License:Open Source License

/**
 * Configure the AMQP ConnectionFactory with information from this RabbitMQFluxConfig
 *///from w  w  w .j a  v  a  2 s. c o m
public void applyTo(ConnectionFactory f) throws Exception {
    if (uri != null) {
        f.setUri(uri);
    } else {
        f.setHost("localhost");
    }
}

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

License:Apache License

private void launchTest(XContentBuilder river, final int numMessages, final int numDocsPerMessage,
        InjectorHook injectorHook, boolean delete, boolean update) throws Exception {

    final String dbName = getDbName();
    logger.info(" --> create index [{}]", dbName);
    try {//from  w  ww . j  a va2 s .c  om
        client().admin().indices().prepareDelete(dbName).get();
    } catch (IndexMissingException e) {
        // No worries.
    }
    try {
        createIndex(dbName);
    } catch (IndexMissingException e) {
        // No worries.
    }
    ensureGreen(dbName);

    logger.info("  -> Checking rabbitmq running");
    // We try to connect to RabbitMQ.
    // If it's not launched, we don't fail the test but only log it
    Channel channel = null;
    Connection connection = null;
    try {
        logger.info(" --> connecting to rabbitmq");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(AMQP.PROTOCOL.PORT);
        connection = factory.newConnection();
    } catch (ConnectException ce) {
        throw new Exception("RabbitMQ service is not launched on localhost:" + AMQP.PROTOCOL.PORT
                + ". Can not start Integration test. " + "Launch `rabbitmq-server`.", ce);
    }

    try {
        logger.info("  -> Creating [{}] channel", dbName);
        channel = connection.createChannel();

        logger.info("  -> Creating queue [{}]", dbName);
        channel.queueDeclare(getDbName(), true, false, false, null);

        // We purge the queue in case of something is remaining there
        logger.info("  -> Purging [{}] channel", dbName);
        channel.queuePurge(getDbName());

        logger.info("  -> Put [{}] messages with [{}] documents each = [{}] docs", numMessages,
                numDocsPerMessage, numMessages * numDocsPerMessage);
        final Set<String> removed = new HashSet<String>();
        int nbUpdated = 0;
        for (int i = 0; i < numMessages; i++) {
            StringBuffer message = new StringBuffer();

            for (int j = 0; j < numDocsPerMessage; j++) {
                if (logger.isTraceEnabled()) {
                    logger.trace("  -> Indexing document [{}] - [{}][{}]", i + "_" + j, i, j);
                }
                message.append("{ \"index\" : { \"_index\" : \"" + dbName
                        + "\", \"_type\" : \"typex\", \"_id\" : \"" + i + "_" + j + "\" } }\n");
                message.append("{ \"field\" : \"" + i + "_" + j + "\",\"numeric\" : " + i * j + " }\n");

                // Sometime we update a document
                if (update && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    // We can only update if it has not been removed :)
                    if (!removed.contains(id)) {
                        logger.debug("  -> Updating document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"update\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        message.append(
                                "{ \"doc\": { \"foo\" : \"bar\", \"field2\" : \"" + i + "_" + j + "\" }}\n");
                        nbUpdated++;
                    }
                }

                // Sometime we delete a document
                if (delete && rarely()) {
                    String id = between(0, i) + "_" + between(0, j);
                    if (!removed.contains(id)) {
                        logger.debug("  -> Removing document [{}] - [{}][{}]", id, i, j);
                        message.append("{ \"delete\" : { \"_index\" : \"" + dbName
                                + "\", \"_type\" : \"typex\", \"_id\" : \"" + id + "\" } }\n");
                        removed.add(id);
                    }
                }
            }

            channel.basicPublish("", dbName, null, message.toString().getBytes());
        }

        logger.info("  -> We removed [{}] docs and updated [{}] docs", removed.size(), nbUpdated);

        if (injectorHook != null) {
            logger.info("  -> Injecting extra data");
            injectorHook.inject();
        }

        logger.info(" --> create river");
        IndexResponse indexResponse = index("_river", dbName, "_meta", river);
        assertTrue(indexResponse.isCreated());

        logger.info("-->  checking that river [{}] was created", dbName);
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(true));

        // Check that docs are still processed by the river
        logger.info(" --> waiting for expected number of docs: [{}]",
                numDocsPerMessage * numMessages - removed.size());
        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                try {
                    refresh();
                    int expected = numDocsPerMessage * numMessages - removed.size();
                    CountResponse response = client().prepareCount(dbName).get();
                    logger.debug("  -> got {} docs, expected {}", response.getCount(), expected);
                    return response.getCount() == expected;
                } catch (IndexMissingException e) {
                    return false;
                }
            }
        }, 20, TimeUnit.SECONDS), equalTo(true));
    } finally {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
        if (connection != null && connection.isOpen()) {
            connection.close();
        }

        // Deletes the river
        GetResponse response = client().prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status")
                .get();
        if (response.isExists()) {
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_meta").get();
            client().prepareDelete(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
        }

        assertThat(awaitBusy(new Predicate<Object>() {
            public boolean apply(Object obj) {
                GetResponse response = client()
                        .prepareGet(RiverIndexName.Conf.DEFAULT_INDEX_NAME, dbName, "_status").get();
                return response.isExists();
            }
        }, 5, TimeUnit.SECONDS), equalTo(false));
    }
}

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

License:Apache License

public static void main(String[] args) throws Exception {
    Settings settings = ImmutableSettings.settingsBuilder().put("gateway.type", "none")
            .put("index.number_of_shards", 1).put("index.number_of_replicas", 0)
            .put("script.native.mock_script.type", MockScriptFactory.class).build();
    Node node = NodeBuilder.nodeBuilder().settings(settings).node();

    node.client().prepareIndex("_river", "test1", "_meta")
            .setSource(jsonBuilder().startObject().field("type", "rabbitmq").startObject("script_filter")
                    .field("script", "ctx.type1.field1 += param1").field("script_lang", "mvel")
                    .startObject("script_params").field("param1", 1).endObject().endObject()
                    .startObject("bulk_script_filter").field("script", "mock_script")
                    .field("script_lang", "native").endObject().endObject())
            .execute().actionGet();//from w w  w.jav  a  2  s.c om

    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);
    ch.queueDeclare("elasticsearch", true, false, false, null);

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

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

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

    Thread.sleep(10000);
}