Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:reactor.rabbitmq.SenderBenchmarkUtils.java

License:Open Source License

public static String declareQueue(Connection connection) throws Exception {
    String queueName = UUID.randomUUID().toString();
    Channel channel = connection.createChannel();
    String queue = channel.queueDeclare(queueName, false, false, false, null).getQueue();
    channel.close();//from  w w w  .j a  v  a 2 s .c o  m
    return queue;
}

From source file:reactor.rabbitmq.SenderBenchmarkUtils.java

License:Open Source License

public static void deleteQueue(Connection connection, String queue) throws Exception {
    Channel channel = connection.createChannel();
    channel.queueDelete(queue);//w w w . j ava2 s  .  c  o m
    channel.close();
}

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 w w  . j  a  va 2 s. co  m
 * @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/*from  w w  w.j  av a 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  va2 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);/* w ww  .jav  a2s. co  m*/

    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;
    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  a  v a  2 s. com
        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 ww  w. ja  v  a  2  s  .c  om
    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 w w w .ja v a2 s  .  co  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());
            }
        }
    }
}

From source file:scratchpad.SimpleConsumer.java

License:Mozilla Public License

public static void main(String[] args) {
    try {/* w ww.j ava  2 s  .  c o m*/
        String hostName = (args.length > 0) ? args[0] : "localhost";
        int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT;
        String queueName = (args.length > 2) ? args[2] : "eventName";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setHost(hostName);
        connFactory.setPort(portNumber);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        ch.queueDeclare();

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Envelope envelope = delivery.getEnvelope();
            System.out
                    .println("Routing Key: " + envelope.getRoutingKey() + ":" + new String(delivery.getBody()));
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}