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:com.codio.collab.core.queue.DocumentRequestPerformer.java

License:Apache License

public DocumentRequestPerformer(final Connection connection, final String name,
        final BackendProcessor backendProcessor) {
    this.backendProcessor = backendProcessor;
    try {//from w  w w .  j  av a 2s .c o  m
        channel = connection.createChannel();
        channel.basicQos(1);
        consumer = new QueueingConsumer(channel);

        channel.basicConsume(name, false, consumer);
    } catch (IOException e) {
        LOG.error("Problem with init document consumer = {}, {}", e.getMessage(), e);
    }
}

From source file:com.codio.collab.core.queue.DocumentResponsePerformer.java

License:Apache License

public DocumentResponsePerformer(final Connection connection, final String name,
        final FrontendProcessor frontendProcessor) {
    this.frontendProcessor = frontendProcessor;
    try {/*w  w w. ja v a2 s  .c om*/
        LOG.debug("DocumentResponsePerformer");
        channel = connection.createChannel();
        channel.basicQos(1);
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(name, false, consumer);
    } catch (IOException e) {
        LOG.error("Problem with init response document consumer = {}, {}", e.getMessage(), e);
    }
}

From source file:com.colm.app.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Connection connection;
    Channel channel;//from w w  w  . jav a 2 s.co m
    String replyQueueName;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.0.13");
    factory.setPassword("admin");
    factory.setUsername("admin");
    factory.setVirtualHost("admin");
    connection = factory.newConnection();
    channel = connection.createChannel();
    String queneNAme = "rabbitmq_test";
    channel.queueDeclare(queneNAme, false, false, false, null);
    String message = "Something Else";
    for (int i = 0; i < 1000; i++) {
        channel.basicPublish("", queneNAme, null, message.getBytes());
    }
    System.out.println("Sent '" + message + "'");
    channel.close();
    connection.close();

}

From source file:com.DeadLetterReceiver.java

License:Open Source License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);// w  w w .  j av  a2  s  .  com
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    //creating reply queue
    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }

    System.out.println(" [*] Waiting for responses. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Response received '" + message + "'");
        System.out.println("Correlation id : " + props.getCorrelationId());
    }
}

From source file:com.DeadLetterSender.java

License:Open Source License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);//from   w  w  w .jav  a 2s  .c  o m
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    // Request Message
    String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "<soapenv:Body>\n" + "  <p:greet xmlns:p=\"http://service.wso2.org\">\n" + "     <in>" + "IBM"
            + "</in>\n" + "  </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>";

    // Adding Message Properties
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("007");
    builder.contentType("text/xml");
    builder.correlationId("1111");
    builder.replyTo(REPLY_QUEUE_NAME);
    builder.contentEncoding("UTF-8");

    // Custom user properties
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("SOAP_ACTION", "getQuote");
    builder.headers(headers);

    // Publish the message to exchange
    channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes());
    channel.close();
    connection.close();
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to check for checking exchange availability, if
 * exchange is not available creates a new exchange based on isCreateExchangeIfNotExisting true boolean property  .
 * @throws RemRemPublishException/*from ww  w  .j a  va 2  s.c  o  m*/
 * @throws TimeoutException
 * @throws IOException
 */
public void checkAndCreateExchangeIfNeeded() throws RemRemPublishException {
    final boolean exchangeAlreadyExist = hasExchange();
    if (!exchangeAlreadyExist) {
        if (isCreateExchangeIfNotExisting()) {
            Connection connection = null;
            try {
                connection = factory.newConnection();
            } catch (final IOException | TimeoutException e) {
                throw new RemRemPublishException("Exception occurred while creating Rabbitmq connection ::"
                        + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            Channel channel = null;
            try {
                channel = connection.createChannel();
            } catch (final IOException e) {
                throw new RemRemPublishException(
                        "Exception occurred while creating Channel with Rabbitmq connection ::"
                                + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            }
            try {
                channel.exchangeDeclare(exchangeName, "topic", true);
            } catch (final IOException e) {
                log.info(exchangeName + "failed to create an exchange");
                throw new RemRemPublishException("Unable to create Exchange with Rabbitmq connection "
                        + exchangeName + factory.getHost() + ":" + factory.getPort() + e.getMessage());
            } finally {
                if (channel == null || channel.isOpen()) {
                    try {
                        channel.close();
                        connection.close();
                    } catch (IOException | TimeoutException e) {
                        log.warn("Exception occurred while closing the channel" + e.getMessage());
                    }
                }
            }
        } else {
            if (!Boolean.getBoolean(PropertiesConfig.CLI_MODE)) {
                throw new RemRemPublishException(
                        exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_SERVICE);
            } else {
                throw new RemRemPublishException(
                        "Exchange " + exchangeName + PropertiesConfig.INVALID_EXCHANGE_MESSAGE_CLI);
            }
        }
    }
}

From source file:com.ericsson.eiffel.remrem.publish.helper.RabbitMqProperties.java

License:Apache License

/**
 * This method is used to check exchange exists or not
 * @return Boolean//from   ww  w. j  a  v  a  2  s.co  m
 * @throws RemRemPublishException
 * @throws TimeoutException
 * @throws IOException
 */
private boolean hasExchange() throws RemRemPublishException {
    log.info("Exchange is: " + exchangeName);
    Connection connection;
    try {
        connection = factory.newConnection();
    } catch (final IOException | TimeoutException e) {
        throw new RemRemPublishException("Exception occurred while creating Rabbitmq connection ::"
                + factory.getHost() + factory.getPort() + e.getMessage());
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (final IOException e) {
        log.info("Exchange " + exchangeName + " does not Exist");
        throw new RemRemPublishException("Exception occurred while creating Channel with Rabbitmq connection ::"
                + factory.getHost() + factory.getPort() + e.getMessage());
    }
    try {
        channel.exchangeDeclarePassive(exchangeName);
        return true;
    } catch (final IOException e) {
        log.info("Exchange " + exchangeName + " does not Exist");
        return false;
    } finally {
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
                connection.close();
            } catch (IOException | TimeoutException e) {
                log.warn("Exception occurred while closing the channel" + e.getMessage());
            }
        }
    }
}

From source file:com.ericsson.research.IoTFrameworkEndpoint.java

License:Open Source License

public void subscribe(String hostName, String StreamId, final DataPointCallback dataPointCallback)
        throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName); // listening on port 5672

    Connection connection = factory.newConnection();

    final Channel channel = connection.createChannel();
    final String EXCHANGE_NAME = "streams." + StreamId;

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

    dataPointCallback.setConnection(connection);

    boolean autoAck = true;
    channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {
        @Override/*w  w w  .  j  a va 2 s .  c o m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            DataPointNotification notification = gson.fromJson(new String(body), DataPointNotification.class);
            dataPointCallback.handleNotification(notification);
        }
    });
}

From source file:com.es.dashboard.ConnectionBroker.java

@PostConstruct
public void init() {

    bigBaite = new LinkedList<>();
    readings = new ArrayList<Reading>();
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = null;
    try {/*  w  w w . j  a  v  a 2 s .  c  om*/
        connection = factory.newConnection();
    } catch (IOException ex) {
        logger.error(ex);
    } catch (TimeoutException ex) {
        logger.error(ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        logger.error(ex);
    }

    try {
        channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange
    } catch (IOException ex) {
        logger.error(ex);
    }
    AMQP.Queue.DeclareOk result = null;
    try {
        result = channel.queueDeclare("", false, true, false, null);
    } catch (IOException ex) {
        logger.error(ex);
    }
    String queuename = result.getQueue();
    try {
        channel.queueBind(queuename, "sensors", "realtime.sensordata"); // Binding key is #, this will consume all messages
        channel.queueBind(queuename, "sensors", "realtime.alarms"); // Binding key is #, this will consume all messages
    } catch (IOException ex) {
        logger.error(ex);
    }

    logger.info(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            EventBus eventBus = EventBusFactory.getDefault().eventBus();
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, String>>() {
            }.getType();
            Map<String, String> myMap = gson.fromJson(message, type);
            if (envelope.getRoutingKey().equals("realtime.alarms")) {
                eventBus.publish("/channel", message);
                return;
            }
            logger.info(envelope.getRoutingKey());

            readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("data"),
                    myMap.get("name"), myMap.get("room")));
            eventBus.publish("/channel", message);

        }
    };
    try {
        //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}"
        //        + "var timeoutdummy = window.setInterval(rpt,2000);");
        channel.basicConsume(queuename, true, consumer);
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:com.es.dashboard.ConnectionBrokerJPA.java

@PostConstruct
public void init() {
    bigBaite = new LinkedList<>();
    readings = new ArrayList<Reading>();
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = null;
    try {//from  www  . j a  v  a 2  s .co  m
        connection = factory.newConnection();
    } catch (IOException ex) {
        logger.error(ex);
    } catch (TimeoutException ex) {
        logger.error(ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        logger.error(ex);
    }

    try {
        channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange
    } catch (IOException ex) {
        logger.error(ex);
    }
    AMQP.Queue.DeclareOk result = null;
    try {
        result = channel.queueDeclare("", false, true, false, null);
    } catch (IOException ex) {
        logger.error(ex);
    }
    String queuename = result.getQueue();
    try {
        channel.queueBind(queuename, "sensors", "dashboard.response"); // Binding key is #, this will consume all messages
    } catch (IOException ex) {
        logger.error(ex);
    }

    logger.info(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            EventBus eventBus = EventBusFactory.getDefault().eventBus();
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, String>>() {
            }.getType();
            Map<String, String> myMap = gson.fromJson(message, type);
            if (envelope.getRoutingKey().equals("realtime.alarms")) {
                eventBus.publish("/jpa", message);
                return;
            }
            System.out.println(envelope.getRoutingKey());
            logger.info(envelope.getRoutingKey());

            //readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("value"), myMap.get("name"), myMap.get("room")));
            //System.out.println("publishing " + msg_to_publish);
            eventBus.publish("/jpa", message);
            //System.out.println("published");

        }
    };
    try {
        //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}"
        //        + "var timeoutdummy = window.setInterval(rpt,2000);");
        channel.basicConsume(queuename, true, consumer);
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}