Example usage for com.rabbitmq.client Channel queueBind

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

Introduction

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

Prototype

Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;

Source Link

Document

Bind a queue to an exchange, with no extra arguments.

Usage

From source file:translators.ToXmlSchool.java

public static void main(String[] args) throws IOException {
    //final String replyQueueName = "replyFromBanks";
    final String replyQueueName = "teachersXmlReply";
    final String EXCHANGE_NAME_SCHOOL = "cphbusiness.bankXML";
    final String exchangeName = ExchangeName.GLOBAL;

    RabbitConnection rabbitConnection = new RabbitConnection();

    Channel channel = rabbitConnection.makeConnection();
    channel.exchangeDeclare(exchangeName, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, exchangeName, "keyBankXML");

    //get banks from queue. "Get banks" component
    QueueingConsumer consumer = new QueueingConsumer(channel) {
        @Override// w  w  w  .j av  a2s .  c  o  m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            Message messageFromJson = getFromJson(message);
            sendMsgToBank(messageFromJson, properties.getCorrelationId(), EXCHANGE_NAME_SCHOOL, replyQueueName);
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.faces.AbstractAMQPInterface.java

protected void createQueue() {
    assignBindings();/*  www .  j a  v  a  2 s .  c om*/

    String targetExchange = actingAsProvider ? providerExchangeName : userExchangeName;
    String targetRouteKey = actingAsProvider ? providerRoutingKey : userRoutingKey;

    try {
        Channel channel = (Channel) amqpChannel.getChannelImpl();

        channel.queueDeclare(subListenQueue, false, // Durable
                false, // Exclusive
                true, // Auto-delete
                null); // Args

        channel.queueBind(subListenQueue, targetExchange, targetRouteKey); // Args
    } catch (IOException ioe) {
        amqpIntLogger.error("Could not create AMQP queue: " + ioe.getMessage());
    }

}

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

License:Open Source License

protected static String setupRabbitQueue(Channel channel, String exchange, String routingKey)
        throws IOException {
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, exchange, routingKey);
    return queueName;
}

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 .ja  v a 2  s. c o  m*/
    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/*from  w  ww .j  a v a  2  s .c  om*/
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   w  w w.j  a  v a 2s.  c om
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   ww w.j a  v  a  2  s. com*/
    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 a  v  a 2s  . 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);//  w ww .j  a v a2  s . c om
    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:util.ExampleSocialMediaStormDeclarator.java

/**
 * Main RabbitMQ declaration method. Will use RabbitMQ channel reference.
 *
 * Rabbit MQ Channel API:/*from   w w w .ja v a2s  . c  om*/
 * https://www.rabbitmq.com/releases/rabbitmq-java-client/v3.1.5/rabbitmq-
 * java-client-javadoc-3.1.5/ (search for "Channel")
 *
 * @param channel
 *            rabbitmq channel
 */
@Override
public void execute(Channel channel) {
    try {
        // Storm any possible arguments that could be passed
        Map<String, Object> args = new HashMap<>();

        /*
         * Declare the queue
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#queueDeclare(java.lang.String, boolean, boolean, boolean,
         * boolean, java.util.Map))
         * 
         */
        channel.queueDeclare(this.strQueueName, true, false, false, args);

        /*
         * Declare the exchange
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#exchangeDeclare(java.lang.String, java.lang.String, boolean)
         */
        channel.exchangeDeclare(this.strExchange, this.strExchangeType, this.boolPersistence);

        /*
         * Bind the queue
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#queueBind(java.lang.String, java.lang.String,
         * java.lang.String)
         */
        channel.queueBind(this.strQueueName, this.strExchange, this.strRoutingKey);

        // Handle Exception and allow to continue
    } catch (Exception e) {
        System.err.println("Failed to execute RabbitMQ declarations. Details: " + e.getMessage());
        e.printStackTrace();
    }
}