Example usage for com.rabbitmq.client Connection close

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

Introduction

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

Prototype

@Override
void close() throws IOException;

Source Link

Document

Close this connection and all its channels with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

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//w ww . j  a  v a 2s .c  o  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.es.sensorgateway.Publish.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w. java 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.AMQPSupportUtil.java

License:Open Source License

public static int drainQueue(String hostName, String queueName) {
    Connection connection = null;
    Channel channel = null;/*from  w  ww. j  a  v  a 2  s.co  m*/

    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        connection = factory.newConnection();
        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);

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

        int count = 0;
        while (true) {
            final QueueingConsumer.Delivery msg = consumer.nextDelivery(1);
            if (msg == null) {
                return count;
            }
        }
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return -1;
}

From source file:com.eventbook.controller.SpringbootPocController.java

@RequestMapping(value = "/rabbitMQSendTest", method = RequestMethod.GET)
public String rabbitMQSendTest(@RequestParam(value = "message", defaultValue = "Hello World!") String message) {
    try {/*from  www  .  ja  v a2  s . c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("rabbitmq");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();

        return "rabbitMQSendTest Sent: " + message;
    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(SpringbootPocController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "rabbitMQSendTest has been failed!!!";
}

From source file:com.eventbook.controller.SpringbootPocController.java

@RequestMapping(value = "/mySQLTest", method = RequestMethod.GET)
public String mySQLTest() {
    java.sql.Connection conn = null;
    Statement stmt = null;/*from  w  ww. j  a  v a2  s. c om*/
    try {
        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();
        String sql = "SELECT User FROM user";
        ResultSet rs = stmt.executeQuery(sql);
        StringBuilder response = new StringBuilder("");

        while (rs.next()) {
            String user = rs.getString("User");
            response.append("\nUser: " + user);
            System.out.print("\nUser: " + user);
        }

        rs.close();
        stmt.close();
        conn.close();

        return response.toString();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }

    return "mySQLTest has been failed!!";
}

From source file:com.frannciscocabral.ufs.rabbitmq.Send.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from  www  . j a  v a2s.  co m*/
    connection.close();
}

From source file:com.github.dann.wspusher.common.util.RabbitMQResourceUtils.java

License:Apache License

public static void closeQuietly(Connection connection) {
    if (connection != null) {
        try {/*w  ww .j av a2s  .  c  o m*/
            connection.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;/* w  ww. j  a  v  a 2  s .  co  m*/
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        logger.info("send message = {}", message);
        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}

From source file:com.github.hexsmith.rabbitmq.producer.MessageProducer.java

License:Open Source License

public boolean sendMulitMessage(String message) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.7");
    Connection connection = null;
    Channel channel = null;// w  ww  . jav a2  s  .co m
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        int i = 0;
        int loop = 0;
        String originalMessage = message;
        while (loop < 10000) {
            loop++;
            message += i++;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            logger.info("send message = {}", message);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            message = originalMessage;
        }

        channel.close();
        connection.close();
    } catch (IOException | TimeoutException e) {
        logger.error("send message failed!,exception message is {}", e);
        return false;
    }
    return true;
}

From source file:com.github.liyp.rabbitmq.demo2.Producer.java

License:Apache License

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername("liyp");
    factory.setPassword("liyp");
    factory.setVirtualHost("/");
    factory.setHost("127.0.0.1");
    factory.setPort(5672);//from  w w  w .  j ava 2  s  .  co m
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    for (int i = 0; i < 10000; i++) {
        byte[] messageBodyBytes = "Hello, world!".getBytes();
        channel.basicPublish("", "my-queue", null, messageBodyBytes);
        System.out.println(channel.isOpen());
    }

    channel.close();
    conn.close();
}