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() throws IOException;

Source Link

Document

Actively declare a server-named exclusive, autodelete, non-durable queue.

Usage

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;/*from w  ww .  ja v a2 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   ww  w .  j  a v  a2  s.c  o  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.springframework.amqp.rabbit.core.RabbitAdmin.java

License:Apache License

/**
 * Declares a server-named exclusive, autodelete, non-durable queue.
 *///from   ww w .  j  av a  2  s  .co  m
@Override
@ManagedOperation
public Queue declareQueue() {
    DeclareOk declareOk = this.rabbitTemplate.execute(new ChannelCallback<DeclareOk>() {
        @Override
        public DeclareOk doInRabbit(Channel channel) throws Exception {
            return channel.queueDeclare();
        }
    });
    Queue queue = new Queue(declareOk.getQueue(), false, true, true);
    return queue;
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateTests.java

License:Apache License

@SuppressWarnings("unchecked")
@Test // AMQP-249
public void dontHangConsumerThread() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    when(mockChannel.queueDeclare()).thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
    doAnswer(new Answer<Object>() {
        @Override/*from  w  ww.  jav  a 2s .  c om*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            consumer.set((Consumer) invocation.getArguments()[6]);
            return null;
        }
    }).when(mockChannel).basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
            Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap(), Mockito.any(Consumer.class));
    RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setReplyTimeout(1);
    Message input = new Message("Hello, world!".getBytes(), new MessageProperties());
    template.doSendAndReceiveWithTemporary("foo", "bar", input);
    Envelope envelope = new Envelope(1, false, "foo", "bar");
    // used to hang here because of the SynchronousQueue and doSendAndReceive() already exited
    consumer.get().handleDelivery("foo", envelope, new AMQP.BasicProperties(), new byte[0]);
}

From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber.java

License:Open Source License

private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {/*from  w w  w. java  2  s .c  o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

From source file:pl.nask.hsn2.DataStoreActiveCleaner.java

License:Open Source License

/**
 * Initialize RabbitMQ connection.//from ww  w.java2  s. c  om
 *
 * @return RabbitMQ consumer.
 * @throws IOException
 *             When there's some connection issues.
 */
private QueueingConsumer initRabbitMqConnection() throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setHost(rbtHostName);
    rbtConnection = connFactory.newConnection();
    Channel channel = rbtConnection.createChannel();
    channel.exchangeDeclare(rbtNotifyExchName, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, rbtNotifyExchName, "");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, AUTO_ACK, consumer);
    return consumer;
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.QueryConsumer.java

License:Apache License

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    final Session session = cluster.connect();
    session.execute(String.format("CREATE TABLE IF NOT EXISTS tester.warningsrdd (ssn text, "
            + "batchStartTime bigint, id uuid, amount decimal, rule text, PRIMARY KEY(batchStartTime, id))"));
    final PreparedStatement preparedStatement = session
            .prepare("SELECT * FROM tester.warningsrdd where batchStartTime = ?");
    try {//from  w w w  . ja v  a2  s  .  c  o  m
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        final String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, EXCHANGE_NAME, "");

        final 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);
                long batchStartTime = Long.parseLong(message);
                System.out.println("Writing batch with start time of " + new Date(batchStartTime));
                ResultSet warningsResultSet = session.execute(preparedStatement.bind(batchStartTime));
                int count = 0;
                for (Row warning : warningsResultSet) {
                    count += 1;
                    BigDecimal decimal = warning.getDecimal("amount");
                    UUID id = warning.getUUID("id");
                    String ssn = warning.getString("ssn");
                    String rule = warning.getString("rule");
                    Warning warningObj = new Warning();
                    warningObj.setAmount(decimal);
                    warningObj.setId(id);
                    warningObj.setSsn(ssn);
                    warningObj.setRule(rule);
                    notifyUI(warningObj);
                }
                System.out.println("Batch with start time of " + new Date(batchStartTime) + " Complete with "
                        + count + " items.");
            }
        };
        channel.basicConsume(queue, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:pt.ua.ies.ControllerView.java

@PostConstruct
public void init() {
    System.out.println("init");
    recive = "";//from  w ww  .  ja  v  a2  s. c o  m
    reciveBeforeRefresh = recive;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.exchangeDeclare(DisplayMessage.EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, DisplayMessage.EXCHANGE_NAME, "");

        MessageConsumer m = new MessageConsumer(channel, this);

        channel.basicConsume(queueName, true, m);
    } catch (Exception ex) {
        Logger.getLogger(ControllerView.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:pubsub.RecieveLogs.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, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

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

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//w ww  .  ja  v  a  2  s  .  co  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 '" + message + "'");
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:rabbitirc.RabbitIRC.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Random rnd = new Random();
    int indeks = rnd.nextInt(usernamelist.length);
    String Randusername = usernamelist[indeks] + rnd.nextInt(100);

    user = Randusername;//from ww w. j av a  2s.c  o  m
    channellist.add("lounge");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    Scanner sc = new Scanner(System.in);

    channel.queueBind(queueName, EXCHANGE_NAME, "lounge");
    channellist.add("lounge");
    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");
            System.out.println(" [x] Received :'" + message + "'");
        }
    };
    System.out.println(" Welcome " + user + " to Channel lounge");
    System.out.println(" Queries: ");
    System.out.println(" 1. /NICK <Username>            : Change username ");
    System.out.println(" 2. /JOIN <Channel Name>        : Join Channel");
    System.out.println(" 3. @<Channel Name> <Message>   : Send message to Spesific Channel");
    System.out.println(" 4. /LEAVE <Channel Name>       : Leave Channel");
    System.out.println(" 5. <Random text>               : BroadCast");
    System.out.println(" 6. /EXIT                       : Exit App");
    while (true) {
        channel.basicConsume(queueName, true, consumer);
        String input = sc.nextLine();
        String[] query;
        if ((query = CommandRegexes.NICK.match(input)) != null) {
            String Nickname = query[0];
            user = Nickname;
            System.out.println(" [x] Your Nickname '" + Nickname + "'");

        } else if ((query = CommandRegexes.JOIN.match(input)) != null) {
            String channel_name = query[0];
            channel.queueBind(queueName, EXCHANGE_NAME, channel_name);
            channellist.add(channel_name);
            System.out.println(" [x] you had Join '" + channel_name + "'");

        } else if ((query = CommandRegexes.LEAVE.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                channellist.remove(channellist.indexOf(channel_name));
                channel.queueUnbind(queueName, EXCHANGE_NAME, channel_name);
                System.out.println(" [x] you had leave '" + channel_name);
            } else {
                System.out.println(" [x] you're not in the channel " + channel_name);
            }
            System.out.println(" [x] you had leave '" + channel_name + "'");

        } else if (CommandRegexes.EXIT.match(input) != null) {
            channel.close();
            connection.close();
            break;

        } else if ((query = CommandRegexes.MESSAGE_CHANNEL.match(input)) != null) {
            String channel_name = query[0];
            if (channellist.contains(channel_name)) {
                String message = "[" + channel_name + "] (" + user + ") " + query[1];
                channel.basicPublish(EXCHANGE_NAME, channel_name, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                System.out.println(" : to '" + channel_name + "'");
            } else {
                System.out.println(" [x] No Channel " + channel_name + " on your list");
            }
        } else {
            System.out.println(" [x] Broadcasting '" + input + "'");
            for (String channellist1 : channellist) {
                String messages = "[" + channellist1 + "] (" + user + ") " + input;
                channel.basicPublish(EXCHANGE_NAME, channellist1, null, messages.getBytes());
            }
            System.out.println(" [x] OK ;D");
        }
    }

}