Example usage for com.rabbitmq.client Channel close

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

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.amqp.AMQPBasicChannel.java

public static boolean amqpQueueExists(AMQPConnectionFactory conFactory, String queueName) throws Exception {
    // Safety first
    if (conFactory == null)
        throw new Exception("Could not test amqp queue: amqp connection factory is null");
    if (queueName == null)
        throw new Exception("Could not test amqp queue: queue name is null");
    if (!conFactory.isConnectionValid())
        throw new Exception("Could not test amqp queue: factory connection is invalid");

    // Need to create an independent connection & channel to test for a queue -
    // a negative result automatically closes a channel.

    AMQPBasicChannel bc = conFactory.createNewChannel();
    Channel channelImpl = (Channel) bc.getChannelImpl();

    boolean result = false;
    String resultInfo = "AMQP queue ( " + queueName + ") existence result: ";

    if (channelImpl != null && channelImpl.isOpen()) {
        // Try passively declaring the queue to see if it exists
        try {//from  w  w  w  . j  av  a 2s .  co  m
            channelImpl.queueDeclarePassive(queueName);
            result = true;
            resultInfo += "exists";
            channelImpl.close();
        } catch (IOException ex) {
            resultInfo += "does not exist";
            // Channel will be automatically closed in this case
        }

    } else
        resultInfo += " could not test: channel is null or closed";

    LoggerFactory.getLogger(AMQPBasicChannel.class).info(resultInfo);

    return result;
}

From source file:uk.org.openeyes.oink.hl7v2.test.ITHl7v2ToRabbitRouteWithoutProcessors.java

License:Open Source License

@Test
public void testA04MessageDoesNotRouteOntoRabbit() throws Exception {
    // Init Rabbit listener
    Channel c = getChannel(rabbitFactory);
    String queueName = setupRabbitQueue(c, getProperty("rabbit.defaultExchange"),
            getProperty("rabbit.outboundRoutingKey"));

    // Choose a message to send
    Message m = Hl7Helper.loadHl7Message("/hl7v2/A04.txt");

    // Send message
    String host = getProperty("hl7v2.host");
    int port = Integer.parseInt(getProperty("hl7v2.port"));
    Message responseMessage = sendHl7Message(m, host, port);
    ACK acknowledgement = (ACK) responseMessage;
    assertEquals("AR", acknowledgement.getMSA().getAcknowledgementCode().getValue());

    // Consume message from rabbit
    byte[] body = receiveRabbitMessage(c, queueName, 1000);
    assertNull(body);//  w w w  . j  ava2 s  . c  o  m

    // Close rabbit connection
    c.close();

    // Check mocks
    verify(a01Processor, never()).process(any(Message.class), any(Exchange.class));
    verify(a05Processor, never()).process(any(Message.class), any(Exchange.class));
    verify(a28Processor, never()).process(any(Message.class), any(Exchange.class));
    verify(a31Processor, never()).process(any(Message.class), any(Exchange.class));
}

From source file:uk.trainwatch.rabbitmq.RabbitConnection.java

License:Apache License

public void close(Object key, Channel channel) {
    if (channels.remove(key, channel)) {
        try {//from  w ww.  j  av a  2 s.c o m
            channel.close();
        } catch (TimeoutException | ShutdownSignalException ex) {
            // Ignore
        } catch (IOException ex) {
            Logger.getLogger(RabbitConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:uniko.west.test.TwitterLogSender.java

public static void main(String[] args) {
    /*      String strJSONFilePaths = { "/home/ubuntu/data/rawtweet-log-short.log",
    "/home/ubuntu/data/IITNNO-prepare-json-example.json",
    "/home/ubuntu/data/json/IITNNO-raw-JSON-example.json",
    "/home/ubuntu/data/json/ITINNO-aggregated-geoparse-example.json"
    "/home/ubuntu/data/json/CERTH-RSS-example.json" };
    *///  w w w . jav  a  2s .  c  om
    //      String strJSONFilePath = "/home/ubuntu/data/rawtweet-log-short.log"; //short twitter log
    //      String strJSONFilePath = "/home/ubuntu/data/json/IITNNO-prepare-json-example.json";
    //String strJSONFilePath = "/home/ubuntu/data/json/IITNNO-raw-JSON-example.json"; //short itinno
    // example
    //      String strJSONFilePath = "/home/ubuntu/data/json/ITINNO-aggregated-geoparse-example.json"; //another itinno example
    String strJSONFilePath = "/home/ubuntu/data/json/simplified-ITINNO-aggregated-geoparse-example.json";

    String exchangeName = "ukob_test";
    //      for (String strJSONFilePath : strJSONFilePaths) {
    try (BufferedReader br = new BufferedReader(new FileReader(strJSONFilePath))) {

        // send a UTF-8 encoded JSON tweet to the RabbitMQ (for
        // stormspout
        // to pick up and send to bolt)
        // read UTF-8 JSON text from file
        Logger.getLogger(TwitterLogSender.class.getName()).log(Level.INFO, "ExampleRabbitmqClient started");

        // connect to rabbitmq broker
        // first of all create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri("amqp://guest:guest@localhost:5672/%2F");
        // initialise connection and define channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String jsonLine;

        while ((jsonLine = br.readLine()) != null) {
            long timestampSinceEpoch = System.currentTimeMillis() / 1000;

            // initialise amqp basic peoperties object
            BasicProperties.Builder basicProperties = new AMQP.BasicProperties.Builder();
            basicProperties.build();
            basicProperties.timestamp(new Date(timestampSinceEpoch)).build();
            basicProperties.contentType("text/json").build();
            basicProperties.deliveryMode(1).build();

            // publish message
            channel.basicPublish(exchangeName, "test-routing", basicProperties.build(),
                    jsonLine.getBytes("UTF-8"));
        }
        // close connection and channel
        channel.close();
        connection.close();

        Logger.getLogger(TwitterLogSender.class.getName()).log(Level.INFO, "ExampleRabbitmqClient finished");

    } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException | IOException ex) {
        Logger.getLogger(TwitterLogSender.class.getName()).log(Level.SEVERE, null, ex);
        //         }
    }
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

private static boolean exists(Connection connection, Checker checker) throws IOException {
    try {/* w  w w . j  a  v  a  2 s . c o m*/
        Channel ch = connection.createChannel();
        checker.check(ch);
        ch.abort();
        return true;
    } catch (IOException e) {
        ShutdownSignalException sse = (ShutdownSignalException) e.getCause();
        if (!sse.isHardError()) {
            AMQP.Channel.Close closeMethod = (AMQP.Channel.Close) sse.getReason();
            if (closeMethod.getReplyCode() == AMQP.NOT_FOUND) {
                return false;
            }
        }
        throw e;
    }
}

From source file:wiki.messaging.NewTask.java

License:Open Source License

public static void main(String[] args) throws IOException {
    int n = 500;//from www.  j a  v  a 2s. c  o m
    String url = null;
    String rabbitMqUrl = null;
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("ds")) {
            url = args[i + 1];
        } else if (args[i].equals("rq")) {
            rabbitMqUrl = args[i + 1];
        } else if (args[i].equals("n")) {
            n = Integer.valueOf(args[i + 1]);
        }
    }
    DbConnector ds = new DbConnector(url);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqUrl);
    factory.setUsername("wiki");
    factory.setPassword("wiki");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    RandomDocGetter rdg = new RandomDocGetter(ds);
    for (int i = 0; i < n; i++) {
        String message = getMessage(rdg);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
    }

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

From source file:wiki.messaging.ResultConsumer.java

License:Open Source License

public static void main(String[] args) throws IOException, InterruptedException {
    String rabbitMqUrl = null;//w w w. ja  v  a 2 s .c  o m
    String resultUrl = null;
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("rs")) {
            resultUrl = args[i + 1];
        } else if (args[i].equals("rq")) {
            rabbitMqUrl = args[i + 1];
        }
    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqUrl);
    factory.setUsername("wiki");
    factory.setPassword("wiki");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(RESULT_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages.");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(RESULT_QUEUE_NAME, autoAck, consumer);

    DbConnector dbc = new DbConnector(resultUrl);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
        if (delivery == null)
            break;
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
        saveResult(message, dbc);
        System.out.println(" [x] Done");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
    channel.close();
    connection.close();
}

From source file:workqueue.NewTask.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

    String message = getMessage(argv);

    channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN,
            message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();//  w w  w.  j  av a 2  s .  com
}

From source file:wunderrabbit.RabbitConnection.java

License:Apache License

@Override
public void send(Endpoint endpoint, byte[] content, String contentType, Map<SendOption, Object> options)
        throws Exception {
    Options<SendOption> opts = new Options<>(options);

    Channel channel = null;
    try {// ww w  .  ja  v  a 2 s . co  m
        channel = this.connection.createChannel();
        declareQueue(channel, endpoint);
        BasicProperties props = new BasicProperties().builder().contentType(contentType)
                .headers((Map<String, Object>) opts.get(SendOption.HEADERS)).build();

        channel.basicPublish("", (String) endpoint.implementation(), props, content);
    } finally {
        if (channel != null) {
            channel.close();
        }
    }

}

From source file:wunderrabbit.RabbitConnection.java

License:Apache License

@Override
public Message receive(Endpoint endpoint, Map<ReceiveOption, Object> options) throws Exception {
    Options<ReceiveOption> opts = new Options<>(options);

    Channel channel = null;
    RabbitMessage message = null;/*from  w  ww  .  j  a  v a2  s.  co m*/
    try {
        channel = this.connection.createChannel();
        declareQueue(channel, endpoint);
        //TODO: this auto-acks
        //TODO: what about timeouts?
        GetResponse response = channel.basicGet((String) endpoint.implementation(), true);
        if (response != null) {
            message = new RabbitMessage(response.getBody(), response.getProps(), endpoint);
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
    }

    return message;
}