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:org.objectweb.proactive.extensions.amqp.federation.AMQPFederationRemoteObjectServer.java

License:Open Source License

@Override
protected void createObjectQueue(Channel channel, String queueName) throws IOException {
    boolean autoDelete = true;
    boolean durable = false;
    boolean exclusive = false;
    Map<String, Object> arguments = null;

    channel.queueDeclare(queueName, durable, exclusive, autoDelete, arguments);
    channel.queueBind(queueName, AMQPFederationConfig.PA_AMQP_FEDERATION_DISCOVER_EXCHANGE_NAME.getValue(), "");
    channel.queueBind(queueName, AMQPFederationConfig.PA_AMQP_FEDERATION_RPC_EXCHANGE_NAME.getValue(),
            queueName);// w w w  . ja  va2 s .  com
}

From source file:org.objectweb.proactive.extensions.amqp.federation.FederationFindQueuesRPCClient.java

License:Open Source License

@Override
protected String createReplyQueue(Channel channel) throws IOException {
    String replyQueueName = AMQPFederationUtils.uniqueQueueName("reply_discover");
    channel.queueDeclare(replyQueueName, false, true, true, null);
    channel.queueBind(replyQueueName,
            AMQPFederationConfig.PA_AMQP_FEDERATION_RPC_REPLY_EXCHANGE_NAME.getValue(), replyQueueName);
    return replyQueueName;
}

From source file:org.objectweb.proactive.extensions.amqp.remoteobject.AMQPRemoteObjectServer.java

License:Open Source License

@Override
protected void createObjectQueue(Channel channel, String queueName) throws IOException {
    boolean autoDelete = true;
    boolean durable = false;
    boolean exclusive = false;
    Map<String, Object> arguments = null;

    channel.queueDeclare(queueName, durable, exclusive, autoDelete, arguments);
    channel.queueBind(queueName, AMQPConfig.PA_AMQP_DISCOVER_EXCHANGE_NAME.getValue(), "");
    channel.queueBind(queueName, AMQPConfig.PA_AMQP_RPC_EXCHANGE_NAME.getValue(), queueName);
}

From source file:org.openbaton.plugin.utils.PluginCaller.java

License:Apache License

public Serializable executeRPC(String methodName, Collection<Serializable> args, Type returnType)
        throws IOException, InterruptedException, PluginException {

    Channel channel = connection.createChannel();
    String replyQueueName = channel.queueDeclare().getQueue();
    String exchange = "plugin-exchange";
    channel.queueBind(replyQueueName, exchange, replyQueueName);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    String consumerTag = channel.basicConsume(replyQueueName, true, consumer);

    //Check if plugin is still up
    if (!RabbitManager.getQueues(brokerIp, username, password, managementPort).contains(pluginId))
        throw new PluginException("Plugin with id: " + pluginId + " not existing anymore...");

    String response;/*  ww w  .ja v  a 2  s. co  m*/
    String corrId = UUID.randomUUID().toString();
    PluginMessage pluginMessage = new PluginMessage();
    pluginMessage.setMethodName(methodName);
    pluginMessage.setParameters(args);
    String message = gson.toJson(pluginMessage);

    BasicProperties props = new Builder().correlationId(corrId).replyTo(replyQueueName).build();

    channel.basicPublish(exchange, pluginId, props, message.getBytes());

    if (returnType != null) {

        while (true) {
            Delivery delivery = consumer.nextDelivery();
            if (delivery.getProperties().getCorrelationId().equals(corrId)) {
                response = new String(delivery.getBody());
                log.trace("received: " + response);
                break;
            } else {
                log.error("Received Message with wrong correlation id");
                throw new PluginException(
                        "Received Message with wrong correlation id. This should not happen, if it does please call us.");
            }
        }

        channel.queueDelete(replyQueueName);
        try {
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class);

        JsonElement exceptionJson = jsonObject.get("exception");
        if (exceptionJson == null) {
            JsonElement answerJson = jsonObject.get("answer");

            Serializable ret = null;

            if (answerJson.isJsonPrimitive()) {
                ret = gson.fromJson(answerJson.getAsJsonPrimitive(), returnType);
            } else if (answerJson.isJsonArray()) {
                ret = gson.fromJson(answerJson.getAsJsonArray(), returnType);
            } else
                ret = gson.fromJson(answerJson.getAsJsonObject(), returnType);

            log.trace("answer is: " + ret);
            return ret;
        } else {
            PluginException pluginException;
            try {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), VimDriverException.class));
                log.debug("Got Vim Driver Exception with server: "
                        + ((VimDriverException) pluginException.getCause()).getServer());
            } catch (Exception ignored) {
                pluginException = new PluginException(
                        gson.fromJson(exceptionJson.getAsJsonObject(), Throwable.class));
            }
            throw pluginException;
        }
    } else
        return null;
}

From source file:org.pascani.dsl.lib.infrastructure.rabbitmq.RabbitMQConsumer.java

License:Open Source License

/**
 * Creates a RabbitMQ message consumer consuming from an exchange. To do
 * this, an anonymous non-durable queue is declared and bound to the
 * exchange.//from w  ww .  j av  a2s  . co m
 * 
 * @param endPoint
 *            The RabbitMQ end point
 * @param exchange
 *            The exchange from which messages are consumed
 * @param routingKey
 *            The routing key of interest
 * @param tag
 *            The consumer tag for this consumer
 * @param context
 *            The context in which this consumer is used
 * @throws IOException
 *             If an I/O problem is encountered
 * @throws TimeoutException
 *             If there is a connection time out when connecting to the
 *             RabbitMQ server
 */
public RabbitMQConsumer(final EndPoint endPoint, final String exchange, final String routingKey,
        final String tag, final PascaniRuntime.Context context) throws IOException, TimeoutException {

    this.endPoint = endPoint;
    Channel channel = this.endPoint.channel();

    this.queueName = channel.queueDeclare().getQueue();
    channel.queueBind(this.queueName, exchange, routingKey);

    this.consumerTag = tag;
    this.eventProducer = new LocalEventProducer<Event<?>>(context);
}

From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test//from w w  w . java2  s.  co  m
public void testConnect$shouldCleanUpOnQueueBindingFailure(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final CollectorConfiguration defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.queueBind("actualQueueName", defaultCollector.getExchangeName(),
                    Notifications.ROUTING_KEY_PATTERN);
            this.result = new IOException("Failure");
        }
    };
    final CollectorController sut = collectorController(defaultCollector);
    try {
        sut.connect();
        fail("Should not connect on failure");
    } catch (final ControllerException e) {
        assertThat(e.getMessage(),
                equalTo("Could not bind queue 'actualQueueName' to exchange '"
                        + defaultCollector.getExchangeName() + "' using routing key '"
                        + Notifications.ROUTING_KEY_PATTERN + "'"));
        assertThat(e.getCause(), instanceOf(IOException.class));
        assertThat(e.getCause().getMessage(), equalTo("Failure"));
    }
}

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test// w w  w .j ava  2 s.  c o  m
public void testConnect$shouldCleanUpOnQueueBindingFailure(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final Collector defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.queueBind("actualQueueName", defaultCollector.getExchangeName(),
                    Notifications.ROUTING_KEY_PATTERN);
            this.result = new IOException("Failure");
        }
    };
    final CollectorController sut = collectorController(defaultCollector);
    try {
        sut.connect();
        fail("Should not connect on failure");
    } catch (final ControllerException e) {
        assertThat(e.getMessage(),
                equalTo("Could not bind queue 'actualQueueName' to exchange '"
                        + defaultCollector.getExchangeName() + "' using routing key '"
                        + Notifications.ROUTING_KEY_PATTERN + "'"));
        assertThat(e.getCause(), instanceOf(IOException.class));
        assertThat(e.getCause().getMessage(), equalTo("Failure"));
    }
}

From source file:org.springframework.amqp.rabbit.MulticastMain.java

License:Mozilla Public License

public static void main(String[] args) {
    Options options = getOptions();/*w w w.  ja  va 2 s  .  com*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String hostName = strArg(cmd, 'h', "localhost");
        int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int messageCount = intArg(cmd, 'N', 0);
        int consumerCount = intArg(cmd, 'y', 1);
        int connectionCount = cmd.hasOption('c') ? 1 : consumerCount;
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<String> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);

        // setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        factory.setPort(portNumber);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Connection[] consumerConnections = new Connection[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
        }
        Thread[] consumerThreads = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = consumerConnections[i % connectionCount];
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null)
                    .getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.basicConsume(queueName, autoAck, consumer);
            channel.queueBind(queueName, exchangeName, id);
            Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (producerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount);
            channel.addReturnListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
        }
        for (int i = 0; i < connectionCount; i++) {
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.springframework.integration.amqp.config.EchoSample.java

License:Apache License

@BeforeClass
public static void setup() {
    SingleConnectionFactory connectionFactory = new SingleConnectionFactory();
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.execute(new ChannelCallback<Object>() {
        @Override//from  w w w.j a v  a2 s . co  m
        public Object doInRabbit(Channel channel) throws Exception {
            channel.queueDeclare("si.test.queue", true, false, false, null);
            channel.exchangeDeclare("si.test.exchange", "direct", true);
            channel.queueBind("si.test.queue", "si.test.exchange", "si.test.binding");
            return null;
        }
    });
}

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

License:Apache License

protected void declareQueueing(Connection conn, MessageMiddleware config) throws IOException {

    String routingKey = null;// w w w .java  2  s .co  m
    String exchangeName = null;
    String queueName = null;
    String type = null;
    boolean durable = false;
    boolean autoDelete = false;
    boolean exclusive = false;

    List<MessageMiddleware.Queue> queues = config.getQueues();
    for (Queue queue : queues) {
        queueName = queue.getName();
        routingKey = queue.getKey();
        exchangeName = queue.getExchange();
        type = queue.getType();
        durable = queue.isDurable();
        autoDelete = queue.isAutoDelete();
        exclusive = queue.isExclusive();

        logger.info("Declaring exchange [" + exchangeName + "] and queue [" + queueName + "]");

        Channel channel = conn.createChannel();

        channel.exchangeDeclare(exchangeName, type, durable);
        channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);

        logger.info("Binding queue [" + queueName + "] and exchange [" + exchangeName + "] to routing key ["
                + routingKey + "]");
        channel.queueBind(queueName, exchangeName, routingKey);

    }

}