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:mx.bigdata.utils.amqp.AMQPClientHelperImpl.java

License:Apache License

public String createQueue(Channel channel, String key, boolean durable, boolean exclusive, boolean autoDelete)
        throws Exception {
    String queueName = getQueueName(key);
    channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);
    channel.queueBind(queueName, getExchangeName(key), getRoutingKey(key));
    return queueName;
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.ServiceFactory.java

License:Open Source License

/**
 * (internal usage)/*from   ww  w.  j a  v a  2  s. co m*/
 * Create a new MomConsumer to consume message from RabbitMQ source and forward them to the request actor.
 *
 * @param source request source queue
 * @param channel RabbitMQ channel
 * @param requestActor request actor ref to treat the message
 * @param isMsgDebugOnTimeout debug on timeout if true
 * @return the new MomConsumer
 */
private static MomConsumer createConsumer(final String source, final Channel channel,
        final ActorRef requestActor, final boolean isMsgDebugOnTimeout) {
    return new MomConsumer() {
        private boolean isRunning = false;

        @Override
        public void run() {
            try {
                Map<String, Object> finalMessage;
                channel.queueDeclare(source, false, false, true, null);

                QueueingConsumer consumer = new QueueingConsumer(channel);
                channel.basicConsume(source, false, consumer);
                isRunning = true;

                while (isRunning) {
                    try {
                        QueueingConsumer.Delivery delivery = consumer.nextDelivery(10);
                        if (delivery != null && isRunning) {
                            finalMessage = translator.decode(new Message().setEnvelope(delivery.getEnvelope())
                                    .setProperties(delivery.getProperties()).setBody(delivery.getBody()));
                            if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE)
                                    && isMsgDebugOnTimeout)
                                ((MomLogger) log).setMsgTraceLevel(true);
                            ((MomLogger) log).traceMessage("MomConsumer(" + source + ").run", finalMessage);
                            requestActor.tell(delivery, null);
                            if (((HashMap) finalMessage).containsKey(MomMsgTranslator.MSG_TRACE)
                                    && isMsgDebugOnTimeout)
                                ((MomLogger) log).setMsgTraceLevel(false);
                        }
                    } catch (InterruptedException e) {
                        // no message
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (channel.getConnection() != null && channel.getConnection().isOpen()) {
                        channel.queueDelete(source);
                        //channel.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean isRunning() {
            return isRunning;
        }

        @Override
        public void start() {
            new Thread(this).start();
        }

        @Override
        public void stop() {
            isRunning = false;
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.ServiceFactory.java

License:Open Source License

/**
 * Create a new subscriber service./*from  w w  w.  j a  v a 2  s.  c  om*/
 *
 * @param baseSource the feed base source
 * @param selector the selector on the feed source (can be null)
 * @param feedWorker the feed message worker
 * @return the new subscriber service
 */
@Override
public MomAkkaService subscriberService(final String baseSource, String selector, AppMsgWorker feedWorker) {
    MomAkkaService ret = null;
    ActorRef subsActor;
    MomConsumer consumer;
    final Connection connection = ((Client) super.getMomClient()).getConnection();

    if (selector == null || selector.equals(""))
        selector = "#";

    if (connection != null && connection.isOpen()) {
        subsActor = super.getMomClient().getActorSystem().actorOf(MsgSubsActor.props(feedWorker),
                baseSource + "." + ((selector.equals("#")) ? "all" : selector) + "_msgWorker");
        final ActorRef runnableSubsActor = subsActor;
        final String select = selector;
        final Client cli = ((Client) super.getMomClient());

        consumer = new MomConsumer() {
            private boolean isRunning = false;

            @Override
            public void run() {
                Channel channel = null;
                try {
                    channel = connection.createChannel();
                    channel.exchangeDeclare(baseSource, "topic");

                    String queueName = cli.getClientID() + "_SUBS_2_" + baseSource + "." + select;
                    channel.queueDeclare(queueName, false, true, false, null);
                    channel.queueBind(queueName, baseSource, select);

                    QueueingConsumer consumer = new QueueingConsumer(channel);
                    channel.basicConsume(queueName, true, consumer);

                    isRunning = true;

                    while (isRunning) {
                        try {
                            QueueingConsumer.Delivery delivery = consumer.nextDelivery(10);
                            if (delivery != null && isRunning)
                                runnableSubsActor.tell(delivery, null);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    if (channel.getConnection().isOpen())
                        channel.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (channel.getConnection().isOpen())
                            channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public boolean isRunning() {
                return isRunning;
            }

            @Override
            public void start() {
                new Thread(this).start();
            }

            @Override
            public void stop() {
                isRunning = false;
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        consumer.start();
        ret = new MomAkkaService().setMsgWorker(subsActor).setConsumer(consumer)
                .setClient(super.getMomClient());
        super.getServices().add(ret);
    }
    return ret;
}

From source file:net.es.netshell.rabbitmq.Box.java

License:Open Source License

public Queue createQueue(String symLink, Channel channel) throws Exception {
    String queueName = UUID.randomUUID().toString();
    channel.queueDeclare(queueName, false, false, true, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, symLink, false, false, null, consumer);

    return new Queue(queueName, symLink);
}

From source file:net.es.netshell.rabbitmq.Box.java

License:Open Source License

public String queryQueue(String sendQueue, String token, Channel channel, String symLink) throws Exception {

    // Create random UUID for producer's temporary queue
    String uuid = UUID.randomUUID().toString();
    // Declare this temporary queue and start listening (exclusive queue).
    channel.queueDeclare(uuid, false, true, true, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);

    // Send TOKEN_REQUEST with curent username.
    String message = token + ":QUEUE_QUERY" + ":" + uuid + ":"
            + KernelThread.currentKernelThread().getUser().getName() + ":" + symLink;

    channel.basicPublish("", sendQueue, null, message.getBytes());
    // Start consuming to receive token.
    channel.basicConsume(uuid, true, "tokenRequest", false, true, null, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

    // When token is received, store in "token."
    String queueName = new String(delivery.getBody());
    // Delete temporary queue
    channel.queueDelete(uuid);//  w w w  .ja  v a2s  . c om

    return queueName;

}

From source file:net.es.netshell.rabbitmq.Consume.java

License:Open Source License

public void consumeMessage() throws Exception {
    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }/*from  w  w  w .ja va2 s.  c  o  m*/
    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(queueName, false, false, true, null);
    System.out.println(" [*] Waiting for messages.");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, "consumer", false, false, null, consumer);

    //while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    ByteArrayInputStream bais = new ByteArrayInputStream(delivery.getBody());
    ObjectInputStream in = new ObjectInputStream(bais);
    DefaultListenableGraph g = (DefaultListenableGraph) in.readObject();
    System.out.println(" [x] Received Message");

    // GraphViewer view = new GraphViewer(g);
    // view.init();

    //         if (message.substring(0,13).equals("TOKEN_REQUEST")) {
    //            String[] token = new ProcessTokenRequest(message, channel).sendToken();
    //            permissions.put(token[0], token[1]);
    //            //String[] messageSplit = message.split(":");
    //            //sendToken(messageSplit[1], messageSplit[2], channel);
    //         } else {
    //            String[] messageSplit = message.split(":", 2);
    //            if (permissions.containsKey(messageSplit[0])) {
    //               System.out.println(" [x] Received '" + messageSplit[1] + "' from: " + permissions.get(messageSplit[0]));
    //            } else {
    //               System.out.println(" ERROR: INVALID TOKEN PROVIDED IN MESSAGE");
    //            }
    //         }
    //}

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

From source file:net.es.netshell.rabbitmq.CreateToken.java

License:Open Source License

public CreateToken(BrokerInfo info, Channel tokenChannel, String listenerID) throws Exception {
    // Info on data needed to create a connection
    this.info = info;

    // Create random UUID for producer's temporary queue
    String uuid = UUID.randomUUID().toString();
    // Declare this temporary queue and start listening (exclusive queue).
    tokenChannel.queueDeclare(uuid, false, true, true, null);
    QueueingConsumer consumer = new QueueingConsumer(tokenChannel);

    // Send TOKEN_REQUEST with current username.
    String message = "TOKEN_REQUEST" + ":" + uuid + ":"
            + KernelThread.currentKernelThread().getUser().getName();

    tokenChannel.basicPublish("", listenerID, null, message.getBytes());
    // Start consuming to receive token.
    tokenChannel.basicConsume(uuid, true, "tokenRequest", false, false, null, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

    // When token is received, store in "token."
    token = new String(delivery.getBody());
    // Delete temporary queue
    tokenChannel.queueDelete(uuid);/*from w  w w.  jav  a  2  s.c om*/
}

From source file:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(Object object) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ObjectOutput objOut = new ObjectOutputStream(os);

    objOut.writeObject(object);//from  w ww  . ja va 2  s  .  c om
    byte byteForm[] = os.toByteArray();
    objOut.close();
    os.close();

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, byteForm);
    System.out.println(" [x] Sent Message");

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

}

From source file:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(String[] argv) throws Exception {

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }/* w  w  w . j  a  v a  2  s .c  o  m*/
    String message = new ParseMessage(argv).getMessage();

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    token = new CreateToken(info, channel, queueName).getToken();

    message = token + ":" + message;

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

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

From source file:net.lshift.accent.ConnectionSmokeTest.java

License:Apache License

@Test
public void shouldConnectPublishAndConsume() throws IOException, InterruptedException {
    AccentConnection conn = new AccentConnection(directFactory(), AccentTestUtils.printingFailureLogger());
    try {/* w  w w  .j a  v a  2  s. c  om*/
        AccentChannel ch = conn.createChannel();

        // Add a setup listener to create the queue
        ch.addChannelSetupListener(new ChannelListenerAdapter() {
            @Override
            public void channelCreated(Channel c) throws IOException {
                c.queueDeclare("accent.testq", false, false, true, null);
            }
        });

        QueueingConsumer consumer = new QueueingConsumer(null);
        AccentConsumer aConsumer = new AccentConsumer(ch, "accent.testq", consumer);

        AccentConfirmPublisher publisher = new AccentConfirmPublisher(ch);
        publisher.reliablePublish("", "accent.testq", new AMQP.BasicProperties(), new byte[0]);

        QueueingConsumer.Delivery d = consumer.nextDelivery(10000);

        assertNotNull(d);
        assertEquals(0, d.getBody().length);

        aConsumer.reliableAck(d.getEnvelope().getDeliveryTag(), false);

        ch.close();
    } finally {
        closeQuietly(conn);
    }
}