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:com.buzz.dbhandlers.RMQHandler.java

public RMQHandler(String host, String username, String passwd, String queue) throws IOException {
    Queue = queue;/*from   ww w  .  j  a va  2 s . c  o m*/
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setUsername(username);
    factory.setPassword(passwd);
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(Queue, false, false, false, null);
}

From source file:com.caucho.v5.pipe.rabbit.RabbitPipeImpl.java

License:Open Source License

private void connect() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(_config.uri());//from   www. jav  a 2 s  .  c om

    try {
        _conn = factory.newConnection();
        _channel = _conn.createChannel();

        AMQP.Queue.DeclareOk responseQueue = _channel.queueDeclare(_config.queue(), _config.durable(),
                _config.exclusive(), _config.autoDelete(), null);

        if (!"".equals(_config.exchange())) {
            AMQP.Exchange.DeclareOk responseExchange = _channel.exchangeDeclare(_config.exchange(),
                    _config.exchangeType(), _config.durable(), _config.autoDelete(), false, null);

            _channel.queueBind(responseQueue.getQueue(), _config.exchange(), _config.routingKey());
        }

        _logger.log(Level.INFO, "connect: " + _id + ", actual queue=" + responseQueue.getQueue() + ", "
                + _config + " . " + _self);
    } catch (Exception e) {
        closeChannel();
        closeConnection();

        throw e;
    }
}

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

License:Apache License

private void openConnection() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setVirtualHost(getConnectionConfig().getVhost());
    factory.setUsername(getConnectionConfig().getUser());
    factory.setPassword(getConnectionConfig().getPassword());
    factory.setPort(getConnectionConfig().getPort());
    factory.setHost(getConnectionConfig().getHost());
    factory.setAutomaticRecoveryEnabled(true);
    try {// w  w w . ja v  a 2s. c  om
        connection = factory.newConnection();
    } catch (IOException e) {
        LOG.error("Can not open rmq connection {}", e.getMessage());
    }
}

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

License:Open Source License

public static void main(String[] args) throws Exception {
    Connection connection;/*from  ww w .  j a  v  a2 s. c  o  m*/
    Channel channel;
    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);/*from   ww w.ja  v a2  s.  c  o m*/
    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);/*  w ww.j a v a2 s .co 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.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/*from www  .j  av  a 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 {/*from www  . j  a  v a2s. 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 {//ww  w.  j a v a  2  s.c  o 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);
    }

}

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

public void requestData() throws IOException, TimeoutException, InterruptedException {
    System.out.println("ran");
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare("sensors", "topic");

    JSONObject json = new JSONObject();
    json.put("name", "Temperatura dos Narcisos");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Humidade da Cave");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Luminosidade da Estufa");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());
    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());

    json = new JSONObject();
    json.put("name", "Sensor de Fumo");
    json.put("room", "masterbath");
    json.put("start", System.currentTimeMillis() - 3600000);
    json.put("end", System.currentTimeMillis());

    channel.basicPublish("sensors", "dashboard.request", null, json.toString().getBytes());
    //System.err.println("booting");
}