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:dreamteamjson.DreamTeamJSON.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from w  w  w . j  ava 2s  .  c om*/
 */
public static void main(String[] args) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel listeningChannel = connection.createChannel();
    Channel sendingChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            Message m = gson.fromJson(message, Message.class);
            System.out.println(m.toString());

            double interestRate = 14;

            if (m.creditScore > 600) {
                interestRate -= 4.5;
            } else if (m.creditScore < 601 && m.creditScore > 500) {
                interestRate -= 2.7;
            } else if (m.creditScore < 501 && m.creditScore > 400) {
                interestRate -= 0.9;
            }

            int durationCut = m.loanDuration / 360;

            interestRate -= (durationCut * 0.18);

            double amountCut = m.loanAmount / 100000;

            interestRate -= (amountCut * 0.18);

            // Insert bank logic

            String loanResponse = "{\"interestRate\":" + interestRate + ",\"ssn\":" + m.ssn + "}";

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);
            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, loanResponse.getBytes());
        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:dreamteamxmltranslator.Translator.java

public static void main(String[] args) throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    channel.queueBind(LISTENING_QUEUE_NAME, EXCHANGE_NAME, "DreamTeamBankXML");

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

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//  www . j  a  va  2s . c o m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            try {
                message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");

                String[] arr = message.split(",");
                tester(arr);
            } catch (IOException_Exception ex) {
                Logger.getLogger(Translator.class.getName()).log(Level.SEVERE, null, ex);
            }

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

}

From source file:edu.kit.dama.mdm.audit.servlet.RabbitMQInitializerListener.java

License:Apache License

@Override
public void contextInitialized(ServletContextEvent sce) {
    loadConfiguration();/*w ww .  j  av  a 2 s .c o  m*/

    if (!CONFIGURED) {
        LOGGER.warn("Skipping initialization of RabbitMQ consumer.");
        return;
    }

    try {
        LOGGER.debug("Intitializing RabbitMQ consumer.");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostname);
        connection = factory.newConnection();
        channel = connection.createChannel();
        LOGGER.debug("Declaring topic based exchange with name '{}'", exchange);
        channel.exchangeDeclare(exchange, "topic", true);
        String queueName = channel.queueDeclare().getQueue();
        LOGGER.debug("Using queue with name '{}'. Binding queue to exchange.", queueName);
        channel.queueBind(queueName, exchange, "audit.*");
        LOGGER.debug("Queue bound to exchange with filter 'audit.*'. Starting consumer.");

        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");
                try {
                    LOGGER.debug("Handling new audit event.");
                    AuditEvent event = AuditEvent.fromJson(message);
                    LOGGER.debug("Submitting event to attached consumers.");
                    for (AbstractAuditConsumer consumer : AuditManager.getInstance().getConsumers()) {
                        consumer.consume(event);
                    }
                    LOGGER.debug("Event submitted to all consumers.");
                } catch (FormatException ex) {
                    LOGGER.error("Failed to consume audit event from message '" + message + "'", ex);
                }
            }
        };
        channel.basicConsume(queueName, true, consumer);
        LOGGER.debug("RabbitMQ consumer successfully initialized.");
    } catch (IOException | TimeoutException ex) {
        LOGGER.error("Failed to initialize RabbitMQ audit distributor.", ex);
    }
}

From source file:edu.kit.dama.util.test.RabbitMQReceiver.java

License:Apache License

public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "audit.*");

    //  channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    /*  final Consumer consumer = new DefaultConsumer(channel) {
    @Override/*from  ww  w.  j a v 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 + "'");
    try {
      doWork(message);
    } finally {
      System.out.println(" [x] Done");
      channel.basicAck(envelope.getDeliveryTag(), false);
    }
    }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
    }*/
    /*   QueueingConsumer consumer = new QueueingConsumer(channel);
            
           /*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(queueName, true, consumer);
           QueueingConsumer.Delivery delivery = consumer.nextDelivery(10000);
           if (delivery != null) {
    byte[] message = delivery.getBody();
    System.out.println("MESS " + new String(message));
           }*/
    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(queueName, true, consumer);

    // System.exit(0);
}

From source file:eu.europeana.servicebus.client.rabbitmq.RabbitMQClientAsync.java

/**
 * RabbitMQ implementation of ESBClient/* w w w . j a  va2  s.  c  o  m*/
 *
 * @param host The host to connect to
 * @param incomingQueue The incoming queue
 * @param outgoingQueue The outgoing queue
 * @param username Username
 * @param password Password
 * @param consumer The consumer implementation - It can be null. It allows asynchronous consumers as well as enables
 * custom behaviour handling upon incoming message. The default message handling is and should be agnostic of the
 * method semantics to be implemented
 * @throws IOException
 */
public RabbitMQClientAsync(String host, String incomingQueue, String outgoingQueue, String username,
        String password, Consumer consumer) throws IOException {
    this.host = host;
    this.incomingQueue = incomingQueue;
    this.outgoingQueue = outgoingQueue;
    this.username = username;
    this.password = password;
    if (consumer == null) {
        this.consumer = new DefaultConsumer(receiveChannel);
    } else {
        this.consumer = consumer;
    }
    ConnectionFactory factory = new ConnectionFactory();
    builder = new AMQP.BasicProperties.Builder();
    factory.setHost(host);
    factory.setUsername(username);
    factory.setPassword(password);

    connection = factory.newConnection();
    sendChannel = connection.createChannel();
    receiveChannel = connection.createChannel();
    sendChannel.queueDeclare(outgoingQueue, true, false, false, null);
    receiveChannel.queueDeclare(incomingQueue, true, false, false, null);
    receiveChannel.basicConsume(incomingQueue, true, consumer);

}

From source file:genqa.ExportRabbitMQVerifier.java

License:Open Source License

private Consumer createConsumer(final Channel channel) {
    return new DefaultConsumer(channel) {
        @Override//from w w  w  .  j  av  a 2  s .c  om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            long deliveryTag = envelope.getDeliveryTag();

            String row[] = ExportOnServerVerifier.RoughCSVTokenizer.tokenize(new String(body, Charsets.UTF_8));
            if (row.length != 29) {
                return;
            }
            ExportOnServerVerifier.ValidationErr err = null;
            try {
                err = ExportOnServerVerifier.verifyRow(row);
            } catch (ExportOnServerVerifier.ValidationErr validationErr) {
                validationErr.printStackTrace();
            }
            if (err != null) {
                System.out.println("ERROR in validation: " + err.toString());
            }

            if (++m_verifiedRows % VALIDATION_REPORT_INTERVAL == 0) {
                System.out.println("Verified " + m_verifiedRows + " rows.");
            }

            channel.basicAck(deliveryTag, false);
        }
    };
}

From source file:getbanks2.GetBanks2.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from ww w.  j  av a 2s .c o  m*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");
    Connection connection = factory.newConnection();
    Channel listeningChannel = connection.createChannel();
    Channel sendingChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            String banks = getBanks(arr[0], Integer.parseInt(arr[1]), Double.parseDouble(arr[2]),
                    Integer.parseInt(arr[3]));

            message += "," + banks;

            System.out.println(message);

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);
            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());

        }
    };
    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);

}

From source file:getcreditscore.GetCreditScore.java

public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    factory.setUsername("Dreamteam");
    factory.setPassword("bastian");

    Connection connection = factory.newConnection();
    Channel sendingChannel = connection.createChannel();
    Channel listeningChannel = connection.createChannel();

    listeningChannel.queueDeclare(LISTENING_QUEUE_NAME, false, false, false, null);

    Consumer consumer = new DefaultConsumer(listeningChannel) {
        @Override//from w  w  w. j  a  va2s .c  om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");

            String[] arr = message.split(",");

            sendingChannel.queueDeclare(SENDING_QUEUE_NAME, false, false, false, null);

            String message = arr[0] + "," + creditScore(arr[0]) + "," + arr[1] + "," + arr[2];

            sendingChannel.basicPublish("", SENDING_QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");

        }
    };

    listeningChannel.basicConsume(LISTENING_QUEUE_NAME, true, consumer);
}

From source file:hippo.server.amqp.RpcServer.java

License:Mozilla Public License

/**
 * Registers a consumer on the reply queue.
 * /*from  w  w  w .  ja  v  a2s. c  o  m*/
 * @throws IOException
 *             if an error is encountered
 * @return the newly created and registered consumer
 */
protected DefaultConsumer setupConsumer() throws IOException {
    DefaultConsumer consumer = new DefaultConsumer(_channel) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            if (_mainloopRunning) {
                Delivery request = new Delivery(envelope, properties, body);
                processRequest(request);
            }
        }
    };
    _channel.basicConsume(_queueName, true, consumer);
    return consumer;
}

From source file:io.github.mattcarrier.metrics.transport.rabbit.RabbitClient.java

License:Apache License

/**
 * Registers a {@link TransportableMetric} consumer with RabbitMQ.
 *
 * @param consumerTag//from   w w  w .  j a  v a2s  .  c  o m
 *     the consumer tag
 * @param consumer
 *     the consumer
 * @throws IOException
 *     if there are any issues handling the deliveries
 */
public <T> void consume(String consumerTag, MetricConsumer<T> consumer) throws IOException {
    channel.basicConsume(queueName, true, consumerTag, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            try {
                consumer.consume(serializer.deserialize(body));
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
    });
}