Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

From source file:com.digispherecorp.enterprise.rabbitmq.ra.cci.interatn.OutboundMessageInteractionSpec.java

public OutboundMessageInteractionSpec() {
    connectionFactory = new ConnectionFactory();
}

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  w ww .  ja v a 2s  . com*/
        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 {//  ww  w.j a  va 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", "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  .  jav a  2 s . com
        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");
}

From source file:com.es.sensorgateway.Publish.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w.j ava  2 s  .c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, UnknownHostException {

    response.setContentType("text/html;charset=UTF-8");

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        logger.info("Connection with rabbit Mq stablish!");

        byte[] original;
        String message = null;
        try {
            message = request.getParameter("data");
            original = Base64.getUrlDecoder().decode(message);
        } catch (Exception ex) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(HttpServletResponse.SC_BAD_REQUEST);
            logger.debug("Ignoring message: " + message);
            return;
        }

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("systembus"); // RabbitMQ IP
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //POR aqui as cenas de autenticao
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(HttpServletResponse.SC_OK);
        logger.info("Received request from REST gateway!");

        channel.exchangeDeclare("sensors", "topic", false);
        channel.basicPublish("sensors", "realtime.sensordata", null, original);
        logger.info("Message sent to broker: " + message);

        channel.close();
        connection.close();
        logger.info("Connection with rabbit Mq closed!");

    } catch (TimeoutException ex) {
        logger.error(ex);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSink.java

License:Open Source License

public void open(DataFlowOpOpenContext openContext) {
    log.info("Opening AMQP, settings are: " + settings.toString());

    try {// w  ww. ja  va 2 s . c o m
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(settings.getHost());
        if (settings.getPort() > -1) {
            connectionFactory.setPort(settings.getPort());
        }
        if (settings.getUsername() != null) {
            connectionFactory.setUsername(settings.getUsername());
        }
        if (settings.getPassword() != null) {
            connectionFactory.setPassword(settings.getPassword());
        }
        if (settings.getVhost() != null) {
            connectionFactory.setVirtualHost(settings.getVhost());
        }

        connection = connectionFactory.newConnection();
        channel = connection.createChannel();

        if (settings.getExchange() != null) {
            channel.exchangeDeclarePassive(settings.getExchange());
        }

        final AMQP.Queue.DeclareOk queue;
        if (settings.getQueueName() == null || settings.getQueueName().trim().length() == 0) {
            queue = channel.queueDeclare();
        } else {
            // java.lang.String queue,boolean durable,boolean exclusive,boolean autoDelete,java.util.Map<java.lang.String,java.lang.Object> arguments) throws java.io.IOException
            queue = channel.queueDeclare(settings.getQueueName(), settings.isDeclareDurable(),
                    settings.isDeclareExclusive(), settings.isDeclareAutoDelete(),
                    settings.getDeclareAdditionalArgs());
        }
        if (settings.getExchange() != null && settings.getRoutingKey() != null) {
            channel.queueBind(queue.getQueue(), settings.getExchange(), settings.getRoutingKey());
        }

        final String queueName = queue.getQueue();
        log.info("AMQP producing queue is " + queueName + (settings.isLogMessages() ? " with logging" : ""));
    } catch (IOException e) {
        String message = "AMQP setup failed: " + e.getMessage();
        log.error(message, e);
        throw new RuntimeException(message, e);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSource.java

License:Open Source License

public void open(DataFlowOpOpenContext openContext) {
    log.info("Opening AMQP, settings are: " + settings.toString());

    try {// ww  w. ja  va 2 s  .c  o m
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(settings.getHost());
        if (settings.getPort() > -1) {
            connectionFactory.setPort(settings.getPort());
        }
        if (settings.getUsername() != null) {
            connectionFactory.setUsername(settings.getUsername());
        }
        if (settings.getPassword() != null) {
            connectionFactory.setPassword(settings.getPassword());
        }
        if (settings.getVhost() != null) {
            connectionFactory.setVirtualHost(settings.getVhost());
        }

        connection = connectionFactory.newConnection();
        channel = connection.createChannel();

        channel.basicQos(settings.getPrefetchCount());
        if (settings.getExchange() != null) {
            channel.exchangeDeclarePassive(settings.getExchange());
        }

        final AMQP.Queue.DeclareOk queue;
        if (settings.getQueueName() == null || settings.getQueueName().trim().length() == 0) {
            queue = channel.queueDeclare();
        } else {
            // java.lang.String queue,boolean durable,boolean exclusive,boolean autoDelete,java.util.Map<java.lang.String,java.lang.Object> arguments) throws java.io.IOException
            queue = channel.queueDeclare(settings.getQueueName(), settings.isDeclareDurable(),
                    settings.isDeclareExclusive(), settings.isDeclareAutoDelete(),
                    settings.getDeclareAdditionalArgs());
        }
        if (settings.getExchange() != null && settings.getRoutingKey() != null) {
            channel.queueBind(queue.getQueue(), settings.getExchange(), settings.getRoutingKey());
        }

        final String queueName = queue.getQueue();
        log.info("AMQP consuming queue " + queueName + (settings.isLogMessages() ? " with logging" : ""));

        consumer = new QueueingConsumer(channel);
        consumerTag = channel.basicConsume(queueName, settings.isConsumeAutoAck(), consumer);
    } catch (IOException e) {
        String message = "AMQP source setup failed: " + e.getMessage();
        log.error(message, e);
        throw new EPException(message, e);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSupportReceiveRunnable.java

License:Open Source License

public void run() {
    try {//ww w  .j  a va2 s .  com
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

        log.info("Start receiving messages");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        int count = 0;
        while (true) {
            final QueueingConsumer.Delivery msg = consumer.nextDelivery(waitMSecNextMsg);
            if (msg == null) {
                continue;
            }
            final byte[] bytes = msg.getBody();
            callback.handleMessage(bytes);

            if (isShutdown()) {
                break;
            }
        }

        log.info("Completed publishing messages: " + count + " messages");
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSupportSendRunnable.java

License:Open Source License

public void run() {
    try {/*  w  ww . j av a 2 s .  com*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

        log.info("Start publishing messages: " + events.size() + " messages");

        int count = 0;
        while (true) {
            if (events.isEmpty()) {
                break;
            }

            Object next = events.remove(0);
            byte[] bytes = SerializerUtil.objectToByteArr(next);
            channel.basicPublish("", queueName, null, bytes);
            count++;

            log.info("Publishing message #" + count + ": " + next);
            Thread.sleep(msecSleepTime);

            if (isShutdown()) {
                break;
            }
        }

        log.info("Completed publishing messages: " + count + " messages");
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    }
}