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:com.nrkei.microservices.rapids_rivers.rabbit_mq.RabbitMqRapids.java

private DefaultConsumer consumer(final Channel channel) {
    final RapidsConnection sendPort = this;
    return new DefaultConsumer(channel) {
        @Override//from   www .  ja  va 2  s  .c o  m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            final String message = new String(body, "UTF-8");
            //                System.out.println(" [x] Received '" + message + "'");
            for (MessageListener listener : listeners)
                listener.message(sendPort, message);
        }
    };
}

From source file:com.paxxis.cornerstone.messaging.common.amqp.AMQPSession.java

License:Apache License

@Override
public MessageConsumer createConsumer(Destination destination, String selector,
        final MessageListener messageListener, Map<String, Object> args) {

    try {//  w ww. j a v  a2 s . com
        AMQPDestination dest = (AMQPDestination) destination;
        String routingKey = dest.getDestination();

        //as a nicety we declare and bind the queues on the consumer side if the queue is not temporary
        if (!dest.isTemporary()) {
            ConcurrentHashMap<String, Object> p = new ConcurrentHashMap<String, Object>(args);
            p.putIfAbsent("durable", durableQueue);
            p.putIfAbsent("exclusive", exclusiveQueue);
            p.putIfAbsent("autoDelete", autoDeleteQueue);

            channel.queueDeclare(routingKey, (Boolean) p.remove("durable"), (Boolean) p.remove("exclusive"),
                    (Boolean) p.remove("autoDelete"), args);
            channel.queueBind(routingKey, exchangeName, routingKey,
                    createBindingArgs(selector + " AND routingKey = " + routingKey));
        }

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                messageListener.onMessage(new AMQPMessage(body, envelope, properties, channel));
            }
        };

        String consumerTag = channel.basicConsume(routingKey, autoAck, consumer);
        return new AMQPMessageConsumer(dest, consumer, consumerTag);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.project.finalproject.finalBean.java

private void initConsumer() throws IOException {
    consumer = new DefaultConsumer(channel) {
        @Override//from w w w.  j a va  2s.  c  om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            setValue(message);
            setCView(message);
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);
}

From source file:com.project.finalproject.Recv.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.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//from   w w  w. jav a 2  s  .c  o 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(QUEUE_NAME, true, consumer);
}

From source file:com.sat.common.CommonStepDef.java

License:Open Source License

@And("^verify messages are being sent to queue and contains (.*) $")
public void verify_the_messages_are_being_sent_to_queue(String expectedMsg1, String expectedMsg2)
        throws IOException, InterruptedException {
    System.out.println("Starting reading messages for:");
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    Consumer consumer = new DefaultConsumer(channel) {
        @Override//  w ww. ja  v  a 2s. co m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
            msgRcvd = message + msgRcvd;
        }
    };
    channel.basicConsume(QUEUE_NAME1, false, consumer);
    Thread.sleep(180000);
    channel.close();
    connection.close();
    assertTrue("Message consumed does  not contain generateAC queue message as expected",
            msgRcvd.contains(expectedMsg1));
}

From source file:com.sitewhere.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

@Override
public void start() throws SiteWhereException {
    executors = Executors.newFixedThreadPool(getNumConsumers());
    try {// w ww  .j a  v  a2  s  .  co m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection(executors);
        this.channel = connection.createChannel();

        LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri());

        channel.queueDeclare(getQueueName(), isDurable(), false, false, null);

        LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName());

        // Add consumer callback for channel.
        Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                EventProcessingLogic.processRawPayload(RabbitMqInboundEventReceiver.this, body, null);
            }
        };
        channel.basicConsume(getQueueName(), true, consumer);
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event receiver.", e);
    }
}

From source file:com.sitewhere.sources.rabbitmq.RabbitMqInboundEventReceiver.java

License:Open Source License

private void connect() {

    try {//from   ww  w  . java2 s .  co  m

        this.connection = factory.newConnection(executors);

        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
                LOGGER.info("shutdown signal received", cause);

                // Do nothing if SiteWhere initiated the connection close
                if (!cause.isInitiatedByApplication()) {
                    connection = null;
                    scheduleReconnect();
                }
            }
        });

        this.channel = connection.createChannel();

        LOGGER.info("RabbitMQ receiver connected to: " + getConnectionUri());

        channel.queueDeclare(getQueueName(), isDurable(), false, false, null);

        LOGGER.info("RabbitMQ receiver using " + (isDurable() ? "durable " : "") + "queue: " + getQueueName());

        // Add consumer callback for channel.
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                onEventPayloadReceived(body, null);
            }
        };

        channel.basicConsume(getQueueName(), true, consumer);

    } catch (Exception e) {
        LOGGER.error("Connection Error", e);
        connection = null;
        scheduleReconnect();
    }

}

From source file:controllerStuff.ControllerPublisher.java

private void attachControllerCallback(Controller controllerObject) {
    try {/*  w w w  . ja va 2 s.c om*/

        Channel controllerCallbackChannel = connection.createChannel();
        controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic");
        String sensChName = controllerCallbackChannel.queueDeclare().getQueue();
        controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD,
                BIND_KEY_BASE + nodeID + '.' + controllerObject.getName());

        System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug

        controllerCallbackChannel.basicConsume(sensChName, true,
                new DefaultConsumer(controllerCallbackChannel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {

                        controllerObject.call(new String(body, "UTF-8"));

                    }
                });

    } catch (IOException ex) {
        Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.maxikg.messenger.queue.AmqpQueue.java

License:Apache License

@Override
public void addListener(final QueueListener listener) {
    try {//from  w  w  w.  ja v  a  2  s .co m
        channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String routingKey = envelope.getRoutingKey();
                int dotIndex = routingKey.indexOf('.');
                String namespace = routingKey.substring(0, dotIndex);
                String target = routingKey.substring(dotIndex + 1);
                String type = extractType(properties.getHeaders());

                listener.onMessage(namespace, target, type, body);
            }
        });
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpoint.java

License:Apache License

/**
 * Sets up a consumer that passes received messages to the
 * {@link MessageEndpointListener}s.//w w w . ja  va 2  s .  c o  m
 */
private void setUpConsumer() throws IOException {
    DefaultConsumer consumer = new DefaultConsumer(this.channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            long deliveryTag = envelope.getDeliveryTag();
            super.getChannel().basicAck(deliveryTag, false);
            if (!properties.getAppId().equals(AMQPEndpoint.this.uuid.toString())) {
                MessageManifest mm = MessageFactory.decode(body);
                try {
                    URI responseURI = new URIBuilder().routingKey(properties.getReplyTo())
                            .instanceName(getName()).build();
                    mm.setResponseURI(responseURI);
                } catch (URISyntaxException e) { // this should never happen!
                    LOG.warn("Unable to create response URI for incoming message", e);
                }
                notifyMessageEndpointListeners(mm);
            }
        }
    };
    if (this.listenForTasks) {
        String queueName = QUEUE_NAME_TASKS + this.routingKey;
        this.channel.basicConsume(queueName, false, consumer);
    }
    this.channel.basicConsume(this.exclusiveQueueName, false, consumer);

    // listening to the remote shutdown
    ShutdownListener shutdownListener = new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            shutdown();
        }
    };
    this.channel.addShutdownListener(shutdownListener);
    //      if (this.channel.isOpen()) {
    //         handler.handleConnectionEvent(true);
    //      }
}