Example usage for com.rabbitmq.client Channel queueDeclare

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare a queue

Usage

From source file:normalizer_two.Normalizer_Two.java

public static void main(String[] args) throws IOException, InterruptedException {
    ConnectionCreator creator = ConnectionCreator.getInstance();
    com.rabbitmq.client.Channel channelIn = creator.createChannel();
    com.rabbitmq.client.Channel channelOut = creator.createChannel();
    channelIn.queueDeclare(IN_QUEUE, false, false, false, null);
    channelOut.queueDeclare(OUT_QUEUE, false, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channelIn);
    channelIn.basicConsume(IN_QUEUE, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        //channelIn.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        System.out.println(new String(delivery.getBody()));
        System.out.println("CorrelationID" + delivery.getProperties().getCorrelationId());
        String message = translateMessage(delivery);
        BasicProperties prop = new BasicProperties().builder()
                .correlationId(delivery.getProperties().getCorrelationId()).build();
        channelOut.basicPublish("", OUT_QUEUE, prop, message.getBytes());
    }/*w w w. j a  va 2s  . c  o m*/
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.SimpleJobFinishConsumer.java

License:Apache License

public void listen() {
    try {/*from   w w w .  j av a 2s .c o  m*/
        String queueName = ServerSettings.getSetting(Constants.GFAC_SERVER_PORT, "8950");
        String uri = "amqp://localhost";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();
        logger.info("--------Created the connection to Rabbitmq server successfully-------");

        final Channel ch = conn.createChannel();

        logger.info("--------Created the channel with Rabbitmq server successfully-------");

        ch.queueDeclare(queueName, false, false, false, null);

        logger.info("--------Declare the queue " + queueName + " in Rabbitmq server successfully-------");

        final QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        (new Thread() {
            public void run() {
                try {
                    while (true) {
                        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                        String message = new String(delivery.getBody());
                        logger.info(
                                "---------------- Job Finish message received:" + message + " --------------");
                        synchronized (completedJobsFromPush) {
                            completedJobsFromPush.add(message);
                        }
                        ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    }
                } catch (Exception ex) {
                    logger.error("--------Cannot connect to a RabbitMQ Server--------", ex);
                }
            }

        }).start();
    } catch (Exception ex) {
        logger.error("Cannot connect to a RabbitMQ Server: ", ex);
        logger.info("------------- Push monitoring for HPC jobs is disabled -------------");
    }
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQMessageSender.java

License:Open Source License

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 *//*from  w w  w .  jav  a  2  s.  co m*/
public void send(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException {

    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (connection != null) {
        Channel channel = null;
        String queueName = properties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String durable = properties.get(RabbitMQConstants.EXCHANGE_DURABLE);
        String replyTo = properties.get(RabbitMQConstants.RABBITMQ_REPLY_TO);

        //if the user defined any replyTo value it will be set
        if (replyTo != null) {
            message.setReplyTo(replyTo);
        }

        try {
            if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
                log.info("rabbitmq.queue.routing.key property not found. Using queue name as "
                        + "the routing key.");
                routeKey = queueName;
            }

            channel = connection.createChannel();
            //Declaring the queue
            if (queueName != null && !queueName.equals("")) {

                Boolean queueAvailable = false;
                try {
                    // check availability of the named queue
                    // if an error is encountered, including if the
                    // queue does not exist and if the queue is
                    // exclusively owned by another connection
                    channel.queueDeclarePassive(queueName);
                    queueAvailable = true;
                } catch (java.io.IOException e) {
                    log.info("Queue :" + queueName + " not found.Declaring queue.");
                }

                if (!queueAvailable) {
                    // Declare the named queue if it does not exists.
                    if (!channel.isOpen()) {
                        channel = connection.createChannel();
                    }
                    try {
                        channel.queueDeclare(queueName, RabbitMQUtils.isDurableQueue(properties),
                                RabbitMQUtils.isExclusiveQueue(properties),
                                RabbitMQUtils.isAutoDeleteQueue(properties), null);

                    } catch (java.io.IOException e) {
                        handleException("Error while creating queue: " + queueName + e);
                        return;
                    }
                }
            }

            //Declaring the exchange
            if (exchangeName != null && !exchangeName.equals("")) {
                Boolean exchangeAvailable = false;
                try {
                    // check availability of the named exchange
                    // Throws:java.io.IOException - the server will raise a
                    // 404 channel exception if the named exchange does not
                    // exists.
                    channel.exchangeDeclarePassive(exchangeName);
                    exchangeAvailable = true;
                } catch (java.io.IOException e) {
                    log.info("Exchange :" + exchangeName + " not found.Declaring exchange.");
                }

                if (!exchangeAvailable) {
                    // Declare the named exchange if it does not exists.
                    if (!channel.isOpen()) {
                        channel = connection.createChannel();
                    }
                    try {
                        if (exchangeType != null && !exchangeType.equals("")) {
                            if (durable != null && !durable.equals("")) {
                                channel.exchangeDeclare(exchangeName, exchangeType,
                                        Boolean.parseBoolean(durable));
                            } else {
                                channel.exchangeDeclare(exchangeName, exchangeType, true);
                            }
                        } else {
                            channel.exchangeDeclare(exchangeName, "direct", true);
                        }
                    } catch (java.io.IOException e) {
                        handleException("Error occurred while declaring exchange.");

                    }

                }

                if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                    // Create bind between the queue &
                    // provided routeKey
                    try {
                        // no need to have configure permission to
                        // perform channel.queueBind
                        channel.queueBind(queueName, exchangeName, routeKey);
                    } catch (java.io.IOException e) {
                        handleException("Error occurred while creating the bind between the queue: " + queueName
                                + " & exchange: " + exchangeName + e);
                    }
                }

            }

            AMQP.BasicProperties.Builder builder = buildBasicProperties(message);

            // set delivery mode (default is Persistent): 1=NonPersistent , 2=Persistent
            String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
            int deliveryMode = 2;
            if (deliveryModeString != null) {
                deliveryMode = Integer.parseInt(deliveryModeString);
            }
            builder.deliveryMode(deliveryMode);

            basicProperties = builder.build();
            OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
            MessageFormatter messageFormatter = null;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
            } catch (AxisFault axisFault) {
                throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
            }

            //server plugging should be enabled before using x-consistent hashing
            //for x-consistent-hashing only exchangeName, exchangeType and routingKey should be
            // given. Queue/exchange creation, bindings should be done at the broker
            try {
                // generate random value as routeKey if the exchangeType is
                // x-consistent-hash type
                if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                    routeKey = UUID.randomUUID().toString();
                }

            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
            }
            try {
                messageFormatter.writeTo(msgContext, format, out, false);
                messageBody = out.toByteArray();
            } catch (IOException e) {
                handleException("IO Error while creating BytesMessage", e);
            } finally {
                if (out != null) {
                    out.close();
                    channel.abort();
                }
            }

        } catch (IOException e) {
            handleException("Error while publishing message to the queue ", e);
        }
        try {
            if (connection != null) {

                try {
                    channel = connection.createChannel();
                    if (exchangeName != null && exchangeName != "")
                        channel.basicPublish(exchangeName, routeKey, basicProperties, messageBody);
                    else
                        channel.basicPublish("", routeKey, basicProperties, messageBody);

                } catch (IOException e) {
                    log.error("Error while publishing the message");
                } finally {
                    if (channel != null) {
                        channel.close();
                    }
                }

            }
        } catch (IOException e) {
            handleException("Error while publishing message to the queue ", e);
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testReadQueue() throws Exception {
    final int maxNumRecords = 10;
    PCollection<RabbitMqMessage> raw = p.apply(RabbitMqIO.read().withUri("amqp://guest:guest@localhost:" + port)
            .withQueue("READ").withMaxNumRecords(maxNumRecords));
    PCollection<String> output = raw.apply(MapElements.into(TypeDescriptors.strings())
            .via((RabbitMqMessage message) -> new String(message.getBody(), StandardCharsets.UTF_8)));

    List<String> records = generateRecords(maxNumRecords).stream()
            .map(record -> new String(record, StandardCharsets.UTF_8)).collect(Collectors.toList());
    PAssert.that(output).containsInAnyOrder(records);

    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {/* w w w  .j  a v a2  s . co  m*/
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("READ", false, false, false, null);
        for (String record : records) {
            channel.basicPublish("", "READ", null, record.getBytes(StandardCharsets.UTF_8));
        }

        p.run();
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.beam.sdk.io.rabbitmq.RabbitMqIOTest.java

License:Apache License

@Test
public void testWriteQueue() throws Exception {
    final int maxNumRecords = 1000;
    List<RabbitMqMessage> data = generateRecords(maxNumRecords).stream()
            .map(bytes -> new RabbitMqMessage(bytes)).collect(Collectors.toList());
    p.apply(Create.of(data))//from w w  w. j  a  v  a 2  s.com
            .apply(RabbitMqIO.write().withUri("amqp://guest:guest@localhost:" + port).withQueue("TEST"));

    final List<String> received = new ArrayList<>();
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
    Connection connection = null;
    Channel channel = null;
    try {
        connection = connectionFactory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare("TEST", true, false, false, null);
        Consumer consumer = new TestConsumer(channel, received);
        channel.basicConsume("TEST", true, consumer);

        p.run();

        while (received.size() < maxNumRecords) {
            Thread.sleep(500);
        }

        assertEquals(maxNumRecords, received.size());
        for (int i = 0; i < maxNumRecords; i++) {
            assertTrue(received.contains("Test " + i));
        }
    } finally {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.camel.component.rabbitmq.RabbitMQProducerIntTest.java

License:Apache License

@Test
public void producedMessageIsReceived() throws InterruptedException, IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5672);/*from ww  w.j  a  v a 2 s .co  m*/
    factory.setUsername("cameltest");
    factory.setPassword("cameltest");
    factory.setVirtualHost("/");
    Connection conn = factory.newConnection();

    final List<Envelope> received = new ArrayList<Envelope>();

    Channel channel = conn.createChannel();
    channel.queueDeclare("sammyq", false, false, true, null);
    channel.queueBind("sammyq", EXCHANGE, "route1");
    channel.basicConsume("sammyq", true, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            received.add(envelope);
        }
    });

    template.sendBodyAndHeader("new message", RabbitMQConstants.EXCHANGE_NAME, "ex1");
    Thread.sleep(500);
    assertEquals(1, received.size());
}

From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java

License:Apache License

/** Call to subscribe to interested set of events
 *
 * @param topic defines category and type of the events being subscribed to
 * @param subscriber subscriber that intends to receive event notification
 * @return UUID that represents the subscription with event bus
 * @throws EventBusException/*from   w ww. j  a va  2  s.  com*/
 */
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {

    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }

    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    UUID queueId = UUID.randomUUID();
    String queueName = queueId.toString();

    try {
        String bindingKey = createBindingKey(topic);

        // store the subscriber details before creating channel
        _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber));

        // create a channel dedicated for this subscription
        Connection connection = getConnection();
        Channel channel = createChannel(connection);

        // create a queue and bind it to the exchange with binding key formed from event topic
        createExchange(channel, amqpExchangeName);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, amqpExchangeName, bindingKey);

        // register a callback handler to receive the events that a subscriber subscribed to
        channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
                if (queueDetails != null) {
                    EventSubscriber subscriber = queueDetails.third();
                    String routingKey = envelope.getRoutingKey();
                    String eventSource = getEventSourceFromRoutingKey(routingKey);
                    String eventCategory = getEventCategoryFromRoutingKey(routingKey);
                    String eventType = getEventTypeFromRoutingKey(routingKey);
                    String resourceType = getResourceTypeFromRoutingKey(routingKey);
                    String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
                    Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
                    event.setDescription(new String(body));

                    // deliver the event to call back object provided by subscriber
                    subscriber.onEvent(event);
                }
            }
        });

        // update the channel details for the subscription
        Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
        queueDetails.second(channel);
        _subscribers.put(queueName, queueDetails);

    } catch (AlreadyClosedException closedException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (ConnectException connectException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (Exception e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
    }

    return queueId;
}

From source file:org.apache.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(final InputRowParser<ByteBuffer> firehoseParser, File temporaryDirectory)
        throws IOException {
    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override//  ww  w.j  av a2s  . co  m
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest row as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private InputRow nextRow;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        private Iterator<InputRow> nextIterator = Collections.emptyIterator();

        @Override
        public boolean hasMore() {
            nextRow = null;
            try {
                if (nextIterator.hasNext()) {
                    nextRow = nextIterator.next();
                    return true;
                }
                // Wait for the next delivery. This will block until something is available.
                final Delivery delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    nextIterator = firehoseParser.parseBatch(ByteBuffer.wrap(delivery.getBody())).iterator();
                    if (nextIterator.hasNext()) {
                        nextRow = nextIterator.next();
                        // If delivery is non-null, we report that there is something more to process.
                        return true;
                    }
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Nullable
        @Override
        public InputRow nextRow() {
            if (nextRow == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return nextRow;
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:org.apache.niolex.rabbit.basic.Send.java

License:Apache License

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

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    for (int i = 0; i < 100; ++i) {
        String message = String.format("%02d %s", i, MockUtil.randString(5));
        ThreadUtil.sleepAtLeast(1000);/*w  w  w  .  j a v  a  2s .c  om*/
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");
    }

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

From source file:org.apache.niolex.rabbit.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {//from  w  ww  . j  a v a 2  s  .c om
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

        System.out.println(" [x] Awaiting RPC requests");

        while (true) {
            String response = null;

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                int n = Integer.parseInt(message);

                System.out.println(" [.] fib(" + message + ")");
                response = "" + fib(n);
            } catch (Exception e) {
                System.out.println(" [.] " + e.toString());
                response = "";
            } finally {
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}