Example usage for com.rabbitmq.client Connection createChannel

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

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

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

License:Open Source License

@Ignore
@Test//  www.  j a va 2s . c  o  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//from ww  w  .  java2 s  . 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();//from  www  . ja  v  a 2s .co  m
    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 {/*from   w  w  w .  j  av  a2s  .com*/
        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: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" };
    *///from  ww w. j av a 2 s. c  o  m
    //      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:user.Client.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("rabbitmq.akhfa.me");
    factory.setUsername(username);//w  ww .  j a va2  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/*w w w .  j  av  a2  s . c om*/
        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/*  w w w . j  av  a  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 + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:v2.Student.java

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;//from w  w w.java 2s.c om
    try {
        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) {
            }
        }
    }
}

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

License:Open Source License

public Producer createProducer(Connection connection, Stats stats, String id) throws IOException {
    Channel channel = connection.createChannel();
    if (producerTxSize > 0)
        channel.txSelect();/*from ww  w.j  a  v a2s .c om*/
    if (confirm >= 0)
        channel.confirmSelect();
    if (!predeclared || !exchangeExists(connection, exchangeName)) {
        channel.exchangeDeclare(exchangeName, exchangeType);
    }
    final Producer producer = new Producer(channel, exchangeName, id, randomRoutingKey, flags, producerTxSize,
            producerRateLimit, producerMsgCount, minMsgSize, timeLimit, confirm, stats);
    channel.addReturnListener(producer);
    channel.addConfirmListener(producer);
    return producer;
}