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:org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqTests.java

License:Apache License

@Test
public void shouldConnectUsingRabbitMQClient() throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RABBITMQ_HOST);//from  w w w . ja v  a 2s .  c  o m
    factory.setPort(RABBITMQ_PORT);
    factory.setUsername(username);
    factory.setPassword(password);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

From source file:org.teksme.server.common.messaging.AMQPBrokerManager.java

License:Apache License

public void shutdownCompleted(ShutdownSignalException sse) {

    Connection conn = (Connection) sse.getReference();
    Command closeCommand = (Command) sse.getReason();
    if (sse.isHardError()) {
        if (!sse.isInitiatedByApplication()) {
            AMQP.Connection.Close closeMethod = (AMQP.Connection.Close) closeCommand.getMethod();
            logger.log(Level.SEVERE, "Connection host [" + conn.getHost() + "] closed. Shutdown reason: "
                    + closeMethod.getReplyCode());
        }//from   w w  w  .ja  v  a2s .  c  o m
    } else {
        Channel ch = (Channel) sse.getReference();
        logger.info("Connection host [" + conn.getHost() + "] closed. Shutdown reason: " + ch.getCloseReason());
    }

    logger.info("RabbitMQ AMQP broker shutdown completed!");

}

From source file:org.voltdb.bulkloader.RMQCSVReceive.java

License:Open Source License

public static void receiveMessages(RMQOptions rmqOpts, TestOptions testOpts, String[] args) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqOpts.host);//from  w w w  .ja  v a 2s .  co m
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    if (rmqOpts.exchange != null) {
        if (rmqOpts.extype != null) {
            channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype);
        }
        for (String bindingKey : rmqOpts.bindings) {
            channel.queueBind(rmqOpts.queue, rmqOpts.exchange, bindingKey);
        }
    }

    try {
        channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rmqOpts.queue, false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            // Sleep 1 second for every trailing '.'.
            int dotCount = 0;
            for (int i = message.length() - 1; i >= 0; --i) {
                if (message.charAt(i) == '.') {
                    dotCount++;
                } else {
                    break;
                }
            }
            if (dotCount > 0) {
                message = message.substring(0, message.length() - dotCount);
            }
            System.out.printf(" [x] Received '%s'\n", message);
            Thread.sleep(dotCount * 1000);
        }
    } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        channel.close();
        connection.close();
    }
}

From source file:org.voltdb.bulkloader.RMQCSVSend.java

License:Open Source License

private static void sendMessages(RMQOptions rmqOpts, RandomSleeper.RSOptions sleeperOpts, TestOptions testOpts)
        throws InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqOpts.host);//from w ww .j a  v a  2s . c  o  m

    Connection connection = null;
    Channel channel = null;
    String exchangeName = "";
    // Use the queue name if the routing key is not specified.
    String routingKey = rmqOpts.routing != null ? rmqOpts.routing : rmqOpts.queue;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        if (rmqOpts.exchange != null) {
            exchangeName = rmqOpts.exchange;
            channel.exchangeDeclare(exchangeName, rmqOpts.extype);
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(255);
    }

    try {
        channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null);
        try {
            while (testOpts.lineIter.hasNext()) {
                String message = testOpts.lineIter.next();
                channel.basicPublish(exchangeName, routingKey, MessageProperties.TEXT_PLAIN,
                        message.getBytes());
                System.out.printf(" [x] Sent '%s'\n", message);
                sleeperOpts.sleeper.sleep();
            }
        } finally {
            testOpts.lineIter.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationPublisher.java

License:Open Source License

@Override
public void invalidateCache(int tenantId, String cacheManagerName, String cacheName, Serializable cacheKey) {
    log.debug("Global cache invalidation: initializing the connection");
    if (ConfigurationManager.getProviderUrl() == null) {
        ConfigurationManager.init();//from   w  ww. j a v  a  2 s .c o m
    }
    //Converting data to json string
    GlobalCacheInvalidationEvent event = new GlobalCacheInvalidationEvent();
    event.setTenantId(tenantId);
    event.setCacheManagerName(cacheManagerName);
    event.setCacheName(cacheName);
    event.setCacheKey(cacheKey);
    String uuid = UUIDGenerator.generateUUID();
    event.setUuid(uuid);
    // Setup the pub/sub connection, session
    // Send the msg (byte stream)
    Connection connection = null;
    try {
        log.debug("Global cache invalidation: converting serializable object to byte stream.");
        byte data[] = serialize(event);
        log.debug("Global cache invalidation: converting data to byte stream complete.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        channel.basicPublish(ConfigurationManager.getTopicName(), "invalidate.cache", null, data);
        ConfigurationManager.getSentMsgBuffer().add(uuid.trim());
        log.debug("Global cache invalidation message sent: " + new String(data));
    } catch (Exception e) {
        log.error("Global cache invalidation: Error publishing the message", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                log.error("Global cache invalidation: error close publish connection", e);
            }
        }
    }
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/*from w w w.  ja v  a2  s.co  m*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithoutClientCertValidationTest.java

License:Open Source License

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result// w w  w .  jav  a2s.  c om
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol();

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithoutClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

@Override
public void close() {

    try {//from ww  w. ja  v  a 2 s. com
        super.close();
        Channel channel = inputQueue.getChannel();
        Connection connection = channel.getConnection();
        channel.close();
        connection.close();
        channel = outputQueue.getChannel();
        connection = channel.getConnection();
        channel.close();
        connection.close();
    } catch (Exception e) {
        logger.debug("Exception", e);
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSampleDataPublisher.java

License:Open Source License

public static void start(String[] argv) {

    try {//from  ww w .j a v a 2s. c o m
        if (argv.length > 0) {
            TASK_QUEUE_NAME = argv[0];
        }
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        String data = "";
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

        channel.close();
        connection.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.siddhi.debs2017.input.rabbitmq.RabbitMQSamplePublisher.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, TimeoutException {

    if (argv.length > 0) {
        TASK_QUEUE_NAME = argv[0];//w  ww  . ja v a2s  .c om
    }
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    String data = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader("frmattedData_63.nt"));//molding_machine_100M.nt rdfSample.txt //Machine_59 //frmattedData.txt
        // read file line by line
        String line;
        Scanner scanner;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            scanner = new Scanner(line);
            while (scanner.hasNext()) {
                String dataInLine = scanner.next();
                if (dataInLine.contains("----")) {
                    if (data.length() > 100) {
                        for (int i = 0; i < 5; i++) {
                            count++;
                            System.out.println(count);
                            // System.out.println(data);
                            //Thread.sleep(5000);
                            String data1 = data.replace("Machine_59", "Machine_" + i).replace("_59_",
                                    "_" + i + "_");
                            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
                                    data1.getBytes());
                        }
                    }
                    data = "";
                } else {
                    data += " " + dataInLine;
                    if (dataInLine.contains(".") && !dataInLine.contains("<")) {
                        data += "\n";
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

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