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:rabbitsend.RabbitSend.java

public void turnOn(String host, int port) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);/*from  www  . ja  v  a2 s. c o  m*/
    connection = factory.newConnection();
    channel = connection.createChannel();

    //deklarasi exchange
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    //deklarasi queue
    messageQueue = channel.queueDeclare().getQueue();

    //channel.queueBind(messageQueue, EXCHANGE_NAME, "");

    //deklarasi listener
    Consumer receiver = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws UnsupportedEncodingException {
            String message = new String(body, "UTF-8");
            System.out.println(message);
        }
    };
    channel.basicConsume(messageQueue, true, receiver);
}

From source file:raspisensormodule.BrokerSubscriber.java

public BrokerSubscriber() {
    this.foo = 1;

    try {//w w  w.  java2 s . co m

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

        sensorChannel.exchangeDeclare(SENSOR_EXCHANGE, "topic");

        String sensChName = sensorChannel.queueDeclare().getQueue();
        sensorChannel.queueBind(sensChName, SENSOR_EXCHANGE, BIND_KEY_ALL_SENSOR);
        sensorChannel.basicConsume(sensChName, true, sensorConsumer);
        System.out.println("Subscriber up");

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:red.yelo.chat.AbstractRabbitMQConnector.java

License:Open Source License

/**
 * Connect to the broker and create the exchange
 *
 * @return success/*from www .j  a  va2 s.co m*/
 */
protected boolean connectToRabbitMQ(final String userName, final String password) {
    if ((mChannel != null) && mChannel.isOpen()) {
        return true;
    }
    try {
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(mServer);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(mVirtualHost);
        connectionFactory.setPort(mPort);
        // if (AbstractYeloActivity.mainActivityIsOpen()) {
        connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT);
        Logger.d(TAG, AppConstants.HEART_BEAT + "");
        //            }
        //            else{
        //                connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT_BACKGROUND);
        //                Logger.d(TAG,AppConstants.HEART_BEAT_BACKGROUND+"");
        //
        //            }
        mConnection = connectionFactory.newConnection();
        mChannel = mConnection.createChannel();
        mChannel.exchangeDeclare(mExchange, mExchangeType.key);

        return true;
    } catch (final Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:Release1.Controllers.AlarmController.java

/**
 * mtodo para recibir mensajes de los sensores de alarmas de ventana
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException/* w  ww  . j a v  a  2 s .  c  om*/
 * @throws TimeoutException 
 */
private synchronized void receiveAlamrWindowSensorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);

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

    channel.exchangeDeclare(ID_CHANNEL_AWINDOW_SENSOR, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ID_CHANNEL_AWINDOW_SENSOR, "");

    Consumer consumer;
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM WINDOW Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {//si el valor obtenido es mayor al permitido para simular las alarmas se activa la alarma
                try {
                    sendMessage(ID_CHANNEL_AWINDOW_CONTROLLER, ID_AWINDOW_ON);//envio de mensaje para encender alarma la alarma de ventnaa
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AWINDOW_CONTROLLER, ID_AWINDOW_OFF);//envio de mensaje apra apagar la alarma de ventana
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release1.Controllers.AlarmController.java

/**
 * mtodo para recibir mensajes de los sensores de alarmas de puerta
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException/* ww  w.  j  a va 2s.c o  m*/
 * @throws TimeoutException 
 */
private void receiveAlarmDoorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(ID_CHANNEL_ADOOR_SENSOR, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ID_CHANNEL_ADOOR_SENSOR, "");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class Alarm DOOR Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {
                try {
                    sendMessage(ID_CHANNEL_ADOOR_CONTROLLER, ID_ADOOR_ON);//envio de mensaje para encender la alarma
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_ADOOR_CONTROLLER, ID_ADOOR_OFF);//envio de mensajes para apagar la alarma
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release1.Controllers.AlarmController.java

/**
 * * mtodo para recibir mensajes de los sensores de alarmas de movimiento
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException/*from  w w w  .j a v  a  2  s .c o m*/
 * @throws TimeoutException 
 */
private void receiveMoveMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);

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

    channel.exchangeDeclare(ID_CHANNEL_AMOVE_SENSOR, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ID_CHANNEL_AMOVE_SENSOR, "");

    Consumer consumer;
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM MOVE Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {
                try {
                    sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_ON);//envio de mensajes para encender la alarma de movimiento
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_OFF);//envio de mensajes para apagar la alarma de movimientos
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release2.Controllers.AlarmFireController.java

private synchronized void receivedAlarmFireSensorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);

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

    channel.exchangeDeclare(ID_CHANNEL_AFIRE_SENSOR, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ID_CHANNEL_AFIRE_SENSOR, "");

    Consumer consumer;//from  w  w  w  . java2s.  co  m
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM FIRE Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {//si el valor obtenido es mayor al permitido para simular las alarmas se activa la alarma
                try {
                    sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_ON);//envio de mensaje para encender alarma la alarma de ventnaa
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_OFF);//envio de mensaje apra apagar la alarma de ventana
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:ru.iris.common.messaging.JsonConnection.java

License:Apache License

public JsonConnection() {
    // Create a ConnectionFactory
    ConnectionFactory connectionFactory = new ConnectionFactory();

    // Create a Connection
    try {/*from  w w  w .j  ava 2s  . co  m*/
        Config config = Config.getInstance();

        // Create a ConnectionFactory
        connectionFactory.setHost(config.get("AMQPhost"));
        connectionFactory.setPort(Integer.valueOf(config.get("AMQPport")));
        connectionFactory.setUsername(config.get("AMQPuser"));
        connectionFactory.setPassword(config.get("AMQPpasswd"));

        /*
          The AMQ connection.
         */
        Connection connection = connectionFactory.newConnection();
        channel = connection.createChannel();

        // Create exchange
        channel.exchangeDeclare("iris", "topic", true);
    } catch (IOException | TimeoutException e) {
        LOGGER.error("Error while connection to AMQP broker: " + e.getMessage());
        System.exit(1);
    }
}

From source file:ru.kinomir.queue.QueueSender.java

public synchronized void sendToQueue(Object data, String queueName, String queueHost, String userName,
        String password, String port, String virtualHost) {
    Channel channel = null;//from  w  w  w .j  a va 2s  . c o m
    Connection connection = null;
    try {
        logger.info("Send message to queue '" + queueName + "'");
        ConnectionFactory factory = new ConnectionFactory();
        if (!StringTools.isEmpty(userName)) {
            factory.setUsername(userName);
        }
        if (!StringTools.isEmpty(password)) {
            factory.setPassword(password);
        }
        if (!StringTools.isEmpty(port)) {
            try {
                factory.setPort(Integer.parseInt(port));
            } catch (NumberFormatException ignore) {

            }
        }
        if (!StringTools.isEmpty(virtualHost)) {
            factory.setVirtualHost(virtualHost);
        }
        factory.setHost(queueHost);

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
        String message = convertToString(data);
        logger.info("Message text: " + message);
        channel.basicPublish("", queueName, MessageProperties.MINIMAL_PERSISTENT_BASIC, message.getBytes());
        logger.info("Message was sent");
    } catch (Exception ex) {
        logger.error("Uneble send message: " + convertToString(data));
        logger.debug(ex.getMessage(), ex);
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ignore) {

        }
    }
}

From source file:samples.userguide.RabbitMQAMQPClient.java

License:Apache License

public static void main(String[] args) {
    String queueName = System.getProperty("queueName");
    String mode = System.getProperty("mode");
    String routingKey = System.getProperty("routingKey");
    String exchangeName = System.getProperty("exchangeName");

    String quote = System.getProperty("payLoad");
    if (quote == null) {
        quote = "IBM";
    }/*from www. j  ava 2 s . c o m*/
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + quote
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

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

        if (mode == null) {
            mode = "producer";
        }

        if ("producer".equals(mode)) {
            if (queueName != null) {
                channel.basicPublish("", queueName, null, msg.getBytes());
            } else {
                if (routingKey != null) {
                    if (exchangeName == null) {
                        exchangeName = "topic-exchange";
                    }
                    channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());

                } else {
                    if (exchangeName == null) {
                        exchangeName = "subscriber-exchange";
                    }
                    channel.basicPublish(exchangeName, "", null, msg.getBytes());
                }
            }
        } else {
            if (queueName == null) {
                queueName = "ConsumerProxy";
            }
            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println("[x] received '" + message + "'");
        }
        channel.close();
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
            } catch (IOException e) {
                System.err.println("Error occurred while closing the channel:" + e.getMessage());
            }
        }
        if (connection != null && connection.isOpen()) {
            try {
                connection.close();
            } catch (IOException e) {
                System.err.println("Error occurred while closing the connection:" + e.getMessage());
            }
        }
    }
}