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:amqp.AmqpConsumer.java

License:Apache License

/**
 * This method declares the exchange, queue and bindings needed by this consumer.
 * The method returns the queue name that will be consumed from by this class.
 *
 * @param channel channel used to issue AMQP commands
 * @return queue that will have messages consumed from
 * @throws IOException thrown if there is any communication exception
 *//*  w w w .  j av  a  2  s .c  om*/
protected String declarationsForChannel(Channel channel) throws IOException {
    // setup exchange, queue and binding
    channel.exchangeDeclare(exchangeName, exchangeType, durableExchange);
    // named queue?
    if (queueName == null) {
        queueName = channel.queueDeclare().getQueue();

    } else {
        channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);
    }

    if (bindings != null) {
        // multiple bindings
        for (String binding : bindings) {
            channel.queueBind(queueName, exchangeName, binding);
        }
    } else {
        // no binding given - this could be the case if it is a fanout exchange
        channel.queueBind(queueName, exchangeName, SERVER_GENERATED_QUEUE_NAME);
    }

    return queueName;
}

From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.channel.ReceivingChannel.java

License:Apache License

private void reconnect() {
    if (shutdown.get()) {
        return;//  w ww  .j a  v a 2s .co  m
    }

    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        return;
    }

    this.queueName = null;
    try {
        Channel channel = this.getChannel();

        this.queueName = channel.queueDeclare().getQueue();
        this.consumer = this.rabbitMqFactory.getQueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        synchronized (types) {
            for (String type : types) {
                this.internalBindType(type);
            }
        }
    } catch (ChannelException | IOException | IllegalStateException ex) {
        this.reconnect();
    }
}

From source file:at.ac.tuwien.dsg.cloud.utilities.messaging.lightweight.rabbitMq.channel.ReceivingChannelTest.java

@Test
public void testLazyBindType() throws Exception {
    Discovery discovery = Mockito.mock(Discovery.class);
    Serializer serializer = Mockito.mock(Serializer.class);
    RabbitMqFactory rabbitMqFactory = Mockito.mock(RabbitMqFactory.class);

    ConnectionFactory factory = Mockito.mock(ConnectionFactory.class);
    Connection connection = Mockito.mock(Connection.class);
    Channel channel = Mockito.mock(Channel.class);
    DeclareOk declareOk = Mockito.mock(DeclareOk.class);
    QueueingConsumer consumer = Mockito.mock(QueueingConsumer.class);
    Delivery delivery = Mockito.mock(Delivery.class);
    RabbitMqMessage msg = Mockito.mock(RabbitMqMessage.class);

    String expectedQueue = "testQueue";

    Mockito.when(discovery.discoverHost()).thenReturn("localhost");
    Mockito.when(rabbitMqFactory.getConnectionFactory()).thenReturn(factory);
    Mockito.when(factory.newConnection()).thenReturn(connection);
    Mockito.when(rabbitMqFactory.getQueueingConsumer(channel)).thenReturn(consumer);
    Mockito.when(connection.createChannel()).thenReturn(channel);
    Mockito.when(channel.queueDeclare()).thenReturn(declareOk);
    Mockito.when(declareOk.getQueue()).thenReturn(expectedQueue);
    Mockito.when(consumer.getChannel()).thenReturn(channel);
    Mockito.when(consumer.nextDelivery()).thenReturn(delivery);
    Mockito.when(delivery.getBody()).thenReturn("test".getBytes());
    Mockito.when(serializer.deserilize("test".getBytes(), RabbitMqMessage.class)).thenReturn(msg);

    ReceivingChannel subject = new ReceivingChannel(discovery, serializer, rabbitMqFactory);

    String expectedRoutingKey1 = "testType1";
    String expectedRoutingKey2 = "testType2";

    subject.bindType(expectedRoutingKey1);
    subject.bindType(expectedRoutingKey2);

    //due to lazy startup binding should not yet have been triggered
    Mockito.verify(channel, Mockito.never()).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey1);// ww w. j ava2 s. c  om

    Mockito.verify(channel, Mockito.never()).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey2);

    //this call should trigger the binding to the queues
    RabbitMqMessage msgActual = subject.getDelivery();

    Mockito.verify(channel, Mockito.times(1)).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey1);

    Mockito.verify(channel, Mockito.times(1)).queueBind(expectedQueue, ARabbitChannel.EXCHANGE_NAME,
            expectedRoutingKey2);

    Assert.assertEquals(msg, msgActual);
}

From source file:bank.OurRabbitBank.java

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

    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.OUR_JSON_BANK);

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        AMQP.BasicProperties properties = delivery.getProperties();
        String message = new String(delivery.getBody());

        Gson g = new Gson();

        Message msg = g.fromJson(message, Message.class);

        System.out.println(" [x] Received '" + message + "'");

        sendToNormalizer(msg, properties);
    }/*from  w  ww.  j a  va  2s  . co  m*/
}

From source file:br.uff.labtempo.omcp.common.utils.RabbitUtil.java

License:Apache License

public static AMQP.Queue.DeclareOk declareTemporaryQueue(Channel channel) throws IOException {
    return channel.queueDeclare();
}

From source file:com.ericsson.research.IoTFrameworkEndpoint.java

License:Open Source License

public void subscribe(String hostName, String StreamId, final DataPointCallback dataPointCallback)
        throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName); // listening on port 5672

    Connection connection = factory.newConnection();

    final Channel channel = connection.createChannel();
    final String EXCHANGE_NAME = "streams." + StreamId;

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

    dataPointCallback.setConnection(connection);

    boolean autoAck = true;
    channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {
        @Override//from   w w w .j a  v a2 s.  c  o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            DataPointNotification notification = gson.fromJson(new String(body), DataPointNotification.class);
            dataPointCallback.handleNotification(notification);
        }
    });
}

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java

public static void main(String[] args) {

    //activate logging level if it is DEBUG, default is INFO so no need for any
    //action if it is otherwise
    Injector propInjector = Guice.createInjector(new GeminiPropertiesModule());
    GeminiProperties properties = propInjector.getInstance(GeminiProperties.class);
    if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) {
        Configurator.defaultConfig().level(Level.DEBUG).activate();
    }/*from w  ww  .ja  va 2  s.  c  o  m*/

    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //the app.yml to deployment.yml converter
    Thread yamlConverterThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("YAML_MAPPER_TOPIC"));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            Integer status = 0;
            if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) {
                status = mapApptoDeployment(jsonBody);
            } else {
                continue;
            }

            if (status == 0) {
                try {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } catch (IOException ex) {
                    Logger.error("Could not ack message. Exception: {}", ex);
                }
            } else {
                //failed so requeue the message
                try {
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                } catch (IOException ex) {
                    Logger.error("Could not nack message. Exception: {}", ex);
                }
            }
        }
    });
    yamlConverterThread.start();

    //the networking message recevier
    Thread networkingThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("NETWORK_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);

                //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) {
                createNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) {
                updateNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) {
                deleteNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) {
                createSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) {
                updateSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) {
                deleteSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) {
                createRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) {
                updateRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) {
                deleteRouter(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    networkingThread.start();

    //the load balancer 
    Thread lbThread = new Thread(() -> {
    });

    lbThread.start();

    //the security thread
    Thread securityThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("SECURITY_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) {
                createSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) {
                updateSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) {
                deleteSecurityGroup(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) {
                createSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) {
                updateSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) {
                deleteSecurityGroupRule(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    securityThread.start();
}

From source file:com.github.dann.wspusher.pubsub.subscriber.impl.RabbitMQSubscriberImpl.java

License:Apache License

@Override
public void subscribe(String exchange, DataPusherWebSocket webSocket) {
    Connection connection = null;
    Channel channel = null;

    try {/*from www .jav  a 2 s  .  co  m*/
        // FIXME Cache connection!
        ConnectionFactory factory = new ConnectionFactory();
        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.exchangeDeclare(exchange, DEFAULT_EXCHANGE_TYPE);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, exchange, "");
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);

        doWork(consumer, webSocket);

    } catch (Exception e) {
        logger.error("Error occured", e);
        throw new WsRuntimeException(e);

    } finally {
        RabbitMQResourceUtils.closeQuietly(channel);
        RabbitMQResourceUtils.closeQuietly(connection);
    }

}

From source file:com.groupx.recipientlist.test.TranslatorMock.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    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 X+ENTER");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//  ww w .  ja va2s.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);
    try {
        Scanner in = new Scanner(System.in);
        String input = in.next();
        if ("x".equals(input)) {
            System.exit(0);
        }
    } catch (Exception e) {

    }
}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static void logGetter() throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    LogHandler logHandler = new LogHandler();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);/*  www  .  j av a  2 s . c  o m*/

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

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

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    count = 0;
    boolean over = false;
    while (!over) {

        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            //System.out.println(" [x] Received '" + message + "'");
            synchronized (count) {
                count++;
            }
            logHandler.add(message);
            System.out.print(Thread.currentThread().getId() + " ");

        } catch (InterruptedException interruptedException) {
            System.out.println("finished");
            System.out.println(logHandler);

            System.out.println(logHandler);
            Thread.currentThread().interrupt();
            System.out.println(Thread.currentThread().getId() + " ");
            break;
            // Thread.currentThread().stop();
            // over = true;
        } catch (ShutdownSignalException shutdownSignalException) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        } catch (ConsumerCancelledException consumerCancelledException) {
            System.out.println("finished");
            //  Thread.currentThread().stop();
            over = true;
        } catch (IllegalMonitorStateException e) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        }

    }
    System.out.println("before close");
    channel.close();
    connection.close();
    System.out.println("finished handling");
    Result res = logHandler.fillInResultForm(logHandler.getTheLog());
    ResultHandler resH = new ResultHandler(res);
    resH.createResultFile("/home/alpha/alphaalpha.xml");
    final OverlaidBarChart demo = new OverlaidBarChart("Response Time Chart", res);
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
    int lost = Integer.parseInt(res.getTotalResult().getLostRequests()) / logHandler.getNbRequests();
    PieChart demo1 = new PieChart("Messages", lost * 100);
    demo1.pack();
    demo1.setVisible(true);
    //System.out.println(logHandler);

}