Example usage for com.rabbitmq.client DefaultConsumer DefaultConsumer

List of usage examples for com.rabbitmq.client DefaultConsumer DefaultConsumer

Introduction

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

Prototype

public DefaultConsumer(Channel channel) 

Source Link

Document

Constructs a new instance and records its association to the passed-in channel.

Usage

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleanerTests.java

License:Apache License

@Test
public void testCleanStream() {
    final RabbitBusCleaner cleaner = new RabbitBusCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;/*w  w  w  .  j  a  v  a 2  s .c om*/
    for (int i = 0; i < 5; i++) {
        String queue1Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.constructPipeName(stream1, i));
        String queue2Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.constructPipeName(stream2, i));
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", MessageBusSupport.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
    }
    CachingConnectionFactory connectionFactory = test.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    final FanoutExchange fanout1 = new FanoutExchange(MessageBusSupport.applyPrefix(XDBUS_PREFIX,
            MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(stream1) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout1));
    final FanoutExchange fanout2 = new FanoutExchange(MessageBusSupport.applyPrefix(XDBUS_PREFIX,
            MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(stream2) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout2));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = MessageBusSupport.applyPrefix(XDBUS_PREFIX,
                    BusUtils.constructPipeName(stream1, 4));
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertEquals("Queue " + queueName + " is in use", e.getMessage());
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e.getMessage(),
                        startsWith("Cannot delete exchange " + fanout1.getName() + "; it has bindings:"));
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertTrue("Consumer state remained at " + state + " after 10 seconds", n < 100);
        }

    });
    rabbitAdmin.deleteExchange(fanout1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(fanout1);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertEquals(2, cleanedMap.size());
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertEquals(10, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(XDBUS_PREFIX + stream1 + "." + i, cleanedQueues.get(i * 2));
        assertEquals(XDBUS_PREFIX + stream1 + "." + i + ".dlq", cleanedQueues.get(i * 2 + 1));
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout1.getName(), cleanedExchanges.get(0));

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertEquals(2, cleanedMap.size());
    cleanedQueues = cleanedMap.get("queues");
    assertEquals(5, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(XDBUS_PREFIX + stream2 + "." + i, cleanedQueues.get(i));
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout2.getName(), cleanedExchanges.get(0));
}

From source file:org.thethingsnetwork.data.amqp.Client.java

License:Open Source License

@Override
public Client start() throws Exception {
    if (connection != null) {
        throw new RuntimeException("Already connected");
    }// ww  w.ja v  a  2  s.  c o  m
    connection = factory.newConnection();
    channel = connection.createChannel();

    String queue = channel.queueDeclare().getQueue();

    channel.basicConsume(queue, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String[] tokens = envelope.getRoutingKey().split("\\.");
            if (tokens.length < 4) {
                return;
            }
            switch (tokens[3]) {
            case "up":
                if (handlers.containsKey(UplinkHandler.class)) {
                    String field;
                    if (tokens.length > 4) {
                        field = concat(4, tokens);
                    } else {
                        field = null;
                    }
                    handlers.get(UplinkHandler.class).stream().forEach((handler) -> {
                        executor.submit(() -> {
                            try {
                                UplinkHandler uh = (UplinkHandler) handler;

                                if (uh.matches(tokens[2], field)) {
                                    if (uh.isField()) {
                                        uh.handle(tokens[2], new RawMessage() {
                                            String str = new String(body);

                                            @Override
                                            public String asString() {
                                                return str;
                                            }
                                        });
                                    } else {
                                        uh.handle(tokens[2], MAPPER.readValue(body, UplinkMessage.class));
                                    }
                                }
                            } catch (Exception ex) {
                                if (handlers.containsKey(ErrorHandler.class)) {
                                    handlers.get(ErrorHandler.class).stream().forEach(
                                            (org.thethingsnetwork.data.common.events.EventHandler handler1) -> {
                                                executor.submit(() -> {
                                                    ((ErrorHandler) handler1).safelyHandle(ex);
                                                });
                                            });
                                }
                            }
                        });
                    });
                }
                break;
            case "events":
                if (tokens.length > 5) {
                    switch (tokens[4]) {
                    case "activations":
                        if (handlers.containsKey(ActivationHandler.class)) {
                            handlers.get(ActivationHandler.class).stream().forEach((handler) -> {
                                executor.submit(() -> {
                                    try {
                                        ActivationHandler ah = (ActivationHandler) handler;
                                        if (ah.matches(tokens[2])) {
                                            ah.handle(tokens[2],
                                                    MAPPER.readValue(body, ActivationMessage.class));
                                        }
                                    } catch (Exception ex) {
                                        if (handlers.containsKey(ErrorHandler.class)) {
                                            handlers.get(ErrorHandler.class).stream().forEach((
                                                    org.thethingsnetwork.data.common.events.EventHandler handler1) -> {
                                                executor.submit(() -> {
                                                    ((ErrorHandler) handler1).safelyHandle(ex);
                                                });
                                            });
                                        }
                                    }
                                });
                            });
                        }
                        break;
                    default:
                        if (handlers.containsKey(AbstractEventHandler.class)) {
                            handlers.get(AbstractEventHandler.class).stream().forEach((handler) -> {
                                executor.submit(() -> {
                                    try {
                                        AbstractEventHandler aeh = (AbstractEventHandler) handler;
                                        String event = concat(4, tokens);
                                        if (aeh.matches(tokens[2], event)) {
                                            aeh.handle(tokens[2], event, new RawMessage() {
                                                String str = new String(body);

                                                @Override
                                                public String asString() {
                                                    return str;
                                                }
                                            });
                                        }
                                    } catch (Exception ex) {
                                        if (handlers.containsKey(ErrorHandler.class)) {
                                            handlers.get(ErrorHandler.class).stream().forEach((
                                                    org.thethingsnetwork.data.common.events.EventHandler handler1) -> {
                                                executor.submit(() -> {
                                                    ((ErrorHandler) handler1).safelyHandle(ex);
                                                });
                                            });
                                        }
                                    }
                                });
                            });
                        }
                    }
                }
                break;
            }
        }
    });

    for (List<EventHandler> ehl : handlers.values()) {
        for (EventHandler eh : ehl) {
            eh.subscribe(new Subscribable() {

                private static final String WILDCARD_WORD = "*";
                private static final String WILDCARD_PATH = "#";

                @Override
                public void subscribe(String[] _key) throws Exception {
                    StringJoiner sj = new StringJoiner(".");
                    for (String key : _key) {
                        sj.add(key);
                    }
                    channel.queueBind(queue, exchange, sj.toString());
                }

                @Override
                public String getWordWildcard() {
                    return WILDCARD_WORD;
                }

                @Override
                public String getPathWildcard() {
                    return WILDCARD_PATH;
                }
            });
        }
    }

    if (handlers.containsKey(ConnectHandler.class)) {
        handlers.get(ConnectHandler.class).stream().forEach((handler) -> {
            executor.submit(() -> {
                try {
                    ((ConnectHandler) handler).handle(() -> channel);
                } catch (Exception ex) {
                    if (handlers.containsKey(ErrorHandler.class)) {
                        handlers.get(ErrorHandler.class).stream()
                                .forEach((org.thethingsnetwork.data.common.events.EventHandler handler1) -> {
                                    executor.submit(() -> {
                                        ((ErrorHandler) handler1).safelyHandle(ex);
                                    });
                                });
                    }
                }
            });
        });
    }
    return this;
}

From source file:org.thingsboard.server.extensions.rabbitmq.DemoClient.java

License:Apache License

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);/*ww  w .ja  v a 2  s  .  co m*/
    factory.setUsername(USERNAME);
    factory.setPassword(PASSWORD);

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

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages.");
    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 + "'");
        }
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);

}

From source file:org.wildfly.connector.rabbitmq.ConnectorTestCase.java

License:Open Source License

@Test
public void testConnectionFactory() throws Exception {
    Assert.assertNotNull(connectionFactory1);
    Assert.assertNotNull(queue);//from  ww w  . j  a v  a  2s.  co  m

    RabbitmqConnection connection = connectionFactory1.getConnection();
    Assert.assertNotNull(connection);
    String queueName = "testing";
    Channel channel = connection.createChannel();
    channel.queueDeclare(queueName, false, false, false, null);
    String message = "Hello World!";

    final CountDownLatch counter = new CountDownLatch(1);
    Consumer consume = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            Assert.assertEquals("Hello World!", new String(body));
            counter.countDown();
        }
    };

    channel.basicConsume(queueName, true, consume);
    channel.basicPublish("", queueName, null, message.getBytes());
    counter.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, counter.getCount());
    channel.close();

}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

private void registerConsumerFor(RabbitQueue queue) throws IOException {
    Channel channel = queue.getChannel();
    channel.basicConsume(queue.getName(), false, new DefaultConsumer(channel) {
        @Override/*  w ww .  j a va2 s  .c  om*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            getChannel().basicAck(envelope.getDeliveryTag(), false);
            DebsBenchmarkSystem.this.handleDelivery(body);
        }
    });
}

From source file:ox.softeng.burst.services.RabbitService.java

License:Open Source License

private Consumer createConsumer(Channel channel) {
    return new DefaultConsumer(channel) {
        @Override/*from   www .java  2 s.  co  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String messageString = new String(body, "UTF-8");
            String tag = properties.getMessageId() != null ? properties.getMessageId() : consumerTag;
            try {
                MessageDTO messageDto = (MessageDTO) unmarshaller.unmarshal(new StringReader(messageString));
                Message m = Message.generateMessage(messageDto);

                logger.debug("{} - Received message DTO: {}", tag, messageDto.toString());

                logger.debug("{} - Saving message to database", tag);
                EntityManager entityManager = entityManagerFactory.createEntityManager();
                entityManager.getTransaction().begin();
                entityManager.merge(m);
                entityManager.getTransaction().commit();
                entityManager.close();
                logger.debug("{} - Message saved", tag);
                logger.info("{} - Received {} message from '{}'", tag, m.getSeverity(), m.getSource());
            } catch (JAXBException e) {
                logger.error(tag + " - Could not unmarshall message\n" + messageString, e);
            } catch (HibernateException he) {
                logger.error(tag + " - Could not save message to database: " + he.getMessage(), he);
            } catch (Exception e) {
                logger.error(tag + " - Unhandled exception trying to process message", e);
            }
        }
    };
}

From source file:pluginmanager.RequestManager.java

License:Open Source License

@Override
public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");

    // RESPONSE QUEUE STUFF
    try {/*from ww  w.  jav a2s.com*/
        responseConnection = factory.newConnection();
        responseChannel = responseConnection.createChannel();
        responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    } catch (IOException | TimeoutException e2) {
        e2.printStackTrace();
    }

    Consumer consumer = new DefaultConsumer(responseChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            HttpResponse response = (HttpResponse) SerializationUtils.deserialize(body);
            try {
                response.write(sockDrawer.get(response.id).getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    try {
        responseChannel.basicConsume(RESPONSE_QUEUE_NAME, true, consumer);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //REQUEST QUEUE STUFF
    try {
        requestConnection = factory.newConnection();
        requestChannel = requestConnection.createChannel();
        requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null);
    } catch (IOException | TimeoutException e1) {
        e1.printStackTrace();
    }

    System.out.println("Request Manger Running");
    while (true) {
        if (!queue.isEmpty()) {
            System.out.println("Processing");
            PriorityRequest request = queue.poll();
            byte[] data = SerializationUtils.serialize(request);
            try {
                requestChannel.basicPublish("", REQUEST_QUEUE_NAME, null, data);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            //response.write(socket.getOutputStream());
        } else {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

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 {/*  w w  w .j  av  a 2 s.co 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:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQReceiver.java

License:Apache License

@Override
public void onStart() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);/*ww  w .  ja va2  s  . c o  m*/
    factory = new ConnectionFactory();
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, queueName, "");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                store(new String(body, "UTF-8"));

            }
        };
        channel.basicConsume(queue, true, consumer);

    } catch (IOException e) {
        restart("error connecting to message queue", e);
    }
}

From source file:pro.foundev.messaging.RabbitMQReceiver.java

License:Apache License

@Override
public void onStart() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);/*  ww  w.j  a v a2  s.  c  o m*/
    factory = new ConnectionFactory();
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                store(new String(body, "UTF-8"));

            }
        };
        channel.basicConsume(queueName, true, consumer);

    } catch (IOException e) {
        restart("error connecting to message queue", e);
    }
}