Example usage for com.rabbitmq.client Channel basicConsume

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

Introduction

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

Prototype

String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;

Source Link

Document

Start a non-nolocal, non-exclusive consumer, with a server-generated consumerTag.

Usage

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

License:Open Source License

public byte[] receiveRabbitMessage(Channel channel, String queueName, int timeout)
        throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {

    // Prepare RabbitQueue

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    // Wait for RabbitQueue delivery
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(timeout);
    if (delivery != null) {
        return delivery.getBody();
    } else {//from   ww w. j  ava2s.  c om
        return null;
    }
}

From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java

License:Open Source License

@Test
public void testPatientSearchWithNull() throws Exception {

    // Build Oink request
    String resourcePath = "/Patient";
    String method = "GET";
    OINKRequestMessage request = new OINKRequestMessage();
    request.setResourcePath(resourcePath);
    request.setMethod(HttpMethod.valueOf(method));

    // Send Oink request over rabbit
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);

    BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build();

    byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request);

    channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"),
            testProperties.getProperty("rabbit.routingKey"), props, requestBody);

    // Wait//  w  w  w  .j a v a 2  s.  c om
    Thread.sleep(1000);

    // Assert response
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(5000);
    assertNotNull(delivery);
    byte[] responseBody = delivery.getBody();

    OinkMessageConverter conv = new OinkMessageConverter();
    OINKResponseMessage message = conv.responseMessageFromByteArray(responseBody);

}

From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java

License:Open Source License

@Ignore
@Test//  ww w .  j av a 2 s. co m
public void testGetRequestGetsProxied() throws Exception {

    // Mock endpoint server
    InputStream is = ITProxyRoute.class.getResourceAsStream("/example-messages/fhir/patient.json");
    StringWriter writer = new StringWriter();
    IOUtils.copy(is, writer);
    String jsonPatient = writer.toString();
    byte[] expectedResponseBody = jsonPatient.getBytes();
    server.setResponse(200, expectedResponseBody, "application/json+fhir");
    server.start();

    // Build Oink request
    String resourcePath = "/Patient/1123";
    String parameters = "foo=bar&foo2=bar2";
    String method = "GET";
    OINKRequestMessage request = new OINKRequestMessage();
    request.setResourcePath(resourcePath);
    request.setParameters(parameters);
    request.setMethod(HttpMethod.valueOf(method));

    // Send Oink request over rabbit
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);

    BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build();

    byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request);

    channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"),
            testProperties.getProperty("rabbit.routingKey"), props, requestBody);

    // Wait
    Thread.sleep(1000);

    // Assert mocked server receives request intact
    assertEquals(method, server.getRequestMethod());
    assertEquals(parameters, server.getRequestParams());
    assertEquals("/oink" + resourcePath, server.getRequestPath());

    // Assert response
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(5000);
    assertNotNull(delivery);
    byte[] responseBody = delivery.getBody();

    OINKResponseMessage response = camelCtx.getTypeConverter().convertTo(OINKResponseMessage.class,
            responseBody);

    String responsePatientJson = camelCtx.getTypeConverter().convertTo(String.class,
            response.getBody().getResource());

    assertEquals(200, response.getStatus());
    assertEquals(jsonPatient, responsePatientJson);
    server.stop();

}

From source file:uk.org.openeyes.oink.proxy.test.ITProxyRoute.java

License:Open Source License

@Ignore
@Test// w  w w  .  j  a  v a  2s  .  c o m
public void testPostRequestGetsProxied() throws Exception {

    // Mock endpoint server
    server.setResponse(201, null, null);
    server.start();

    // Build Oink request
    OINKRequestMessage request = new OINKRequestMessage();
    request.setResourcePath("/Patient");
    request.setMethod(HttpMethod.POST);
    FhirBody body = buildFhirBodyFromResource("/example-messages/fhir/patient.json");
    request.setBody(body);

    // Send Oink request over rabbit
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    channel.queueBind(replyQueueName, testProperties.getProperty("rabbit.defaultExchange"), replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);

    BasicProperties props = new BasicProperties().builder().replyTo(replyQueueName).build();

    byte[] requestBody = camelCtx.getTypeConverter().convertTo(byte[].class, request);

    channel.basicPublish(testProperties.getProperty("rabbit.defaultExchange"),
            testProperties.getProperty("rabbit.routingKey"), props, requestBody);

    // Wait
    Thread.sleep(1000);

    // Assert mocked server receives request intact
    String requestBodyReceivedByServer = server.getRequestBody();
    StringWriter writer = new StringWriter();
    IOUtils.copy(ITProxyRoute.class.getResourceAsStream("/example-messages/fhir/patient.json"), writer);
    String expectedBodyReceivedByServer = writer.toString();
    assertEquals(expectedBodyReceivedByServer, requestBodyReceivedByServer);

    // Assert response
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(10000);
    assertNotNull(delivery);
    byte[] responseBody = delivery.getBody();

    OINKResponseMessage response = camelCtx.getTypeConverter().convertTo(OINKResponseMessage.class,
            responseBody);

    assertEquals(201, response.getStatus());
    server.stop();
}

From source file:uk.org.openeyes.oink.proxy.test.support.RabbitClient.java

License:Open Source License

public byte[] sendAndRecieve(byte[] message, String routingKey, String exchange) throws Exception {
    log.debug("Sending message to direct exchange:" + exchange + " with routing key:" + routingKey);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.exchangeDeclare(exchange, "direct", true, false, null);
    String replyQueueName = channel.queueDeclare().getQueue();
    log.debug("Reply queue name is " + replyQueueName);
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);
    String corrId = java.util.UUID.randomUUID().toString();
    BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, routingKey, props, message);
    log.debug("Waiting for delivery");
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(20000);
    connection.close();// w  w  w. j  a  va  2  s. c  om
    if (delivery == null || !delivery.getProperties().getCorrelationId().equals(corrId)) {
        return null;
    } else {
        byte[] response = delivery.getBody();
        return response;

    }
}

From source file:uk.org.openeyes.oink.proxy.test.support.RabbitServer.java

License:Open Source License

@Override
public void run() {
    try {/*ww w .  j  ava 2 s . c o  m*/
        log.info("RabbitServer started");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(exchange, "direct", true, true, null);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, exchange, routingKey);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        while (!stop) {
            // Wait for RabbitQueue delivery
            QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
            if (delivery != null) {
                log.info("Message received");
                receivedMessage = delivery.getBody();
                stop = true;
            }
        }

        if (receivedMessage == null) {
            log.warn("RabbitServer stopping before any message was received");
        }

    } catch (Exception e) {
        log.error("RabbitServer threw an exception:" + e);
        e.printStackTrace();
    }

}

From source file:user.Client.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("rabbitmq.akhfa.me");
    factory.setUsername(username);//from  w  w w  .j  av  a2  s. c  o m
    factory.setPassword(password);
    factory.setVirtualHost("pat");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    ArrayList<String> daftarNick = getAllQueues();

    String nick = "";

    while (true) {
        Scanner in = new Scanner(System.in);

        System.out.print("Please enter your command: ");
        String command = in.nextLine();

        String[] com = command.split(" ", 2);
        try {
            switch (com[0]) {
            case "/NICK":
                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    if (!daftarNick.contains(com[1])) {
                        channel.queueDeclare(com[1], false, false, true, null);
                        nick = com[1];
                        System.out.println("Your nickname is " + nick);

                        System.out.println(" [*] 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");
                                filterChannel(message);
                            }
                        };
                        channel.basicConsume(nick, true, consumer);
                    } else {
                        System.out.println("Nickname exists.");
                    }
                }
                break;
            case "/JOIN":
                channel.exchangeDeclare(com[1], "fanout", false, false, false, null);
                channel.queueBind(nick, com[1], "");
                System.out.println("You have successfully join " + com[1]);
                break;
            case "/LEAVE":
                channel.queueUnbind(nick, com[1], "");
                System.out.println("Leave " + com[1]);
                break;
            case "/EXIT":
                System.out.println("bye bye...  :D");
                System.exit(0);
            default:
                String message = nick + ' ' + command;
                channel.basicPublish(com[0].substring(1), "", null, message.getBytes("UTF-8"));
                break;
            }
        } catch (Exception e) {
            if (command.compareTo("/NICK") == 0) {
                //random nick
                String random;

                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    do {
                        random = randomNick();
                    } while (daftarNick.contains(random));

                    nick = random;

                    channel.queueDeclare(random, false, false, true, null);
                    System.out.println("Your nickname is " + random);

                    System.out.println(" [*] 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");
                            filterChannel(message);
                        }
                    };
                    channel.basicConsume(nick, true, consumer);
                }

            } else if ((command.compareTo("/JOIN") == 0) || (command.compareTo("/LEAVE") == 0)) {
                //error
                System.out.println("Please enter channel name!");
            } else if (command.charAt(0) == '@') {
                System.out.println("Please enter your command for the channel.");
            } else {
                System.out.println("Invalid command.");
            }
        }
    }
}

From source file:v2.APAdmin.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.exchangeDeclare(EXCHANGE_NAME, "topic");
    String queueName = channel.queueDeclare().getQueue();
    String bindingKey = "AP.*";

    channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//from   w  w  w  . j ava  2 s .  c  o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            //REPLY HERE
            String response = "You are in, breh";
            BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(properties.getCorrelationId()).build();
            channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes());
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:v2.PBAAdmin.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.exchangeDeclare(EXCHANGE_NAME, "topic");
    String queueName = channel.queueDeclare().getQueue();
    String bindingKey = "PBA.*";

    channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override/*from  w  w  w . ja  v  a 2s.  c o  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:v2.Student.java

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {// ww  w  . j av a  2s.c o  m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");

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

        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        String routingKey = "AP.DAT";//getRouting(argv);
        String message = "Plz enroll me, breh";//getMessage(argv);
        String corrId = java.util.UUID.randomUUID().toString();
        String callbackQueueName = channel.queueDeclare().getQueue();
        String response = null;
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(callbackQueueName, true, consumer);

        BasicProperties props = new BasicProperties.Builder().replyTo(callbackQueueName).build();

        channel.basicPublish(EXCHANGE_NAME, routingKey, props, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");

        while (true) {
            System.out.println("blocked?");
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println("unblocked");
            System.out.println(delivery);
            response = new String(delivery.getBody());
            System.out.println(response);
            //        if (delivery.getProperties().getCorrelationId().equals(corrId)) {
            //            response = new String(delivery.getBody());
            //            System.out.println(response);
            //            break;
            //        }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}