Example usage for com.rabbitmq.client ConnectionFactory newConnection

List of usage examples for com.rabbitmq.client ConnectionFactory newConnection

Introduction

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

Prototype

public Connection newConnection() throws IOException, TimeoutException 

Source Link

Document

Create a new broker connection.

Usage

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);/*from   www  .j  a  v a2 s .  c o m*/

    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:at.ac.tuwien.dsg.comot.m.core.test.utils.TeAgentAdapter.java

License:Apache License

public TeAgentAdapter(String adapterId, String host) throws IOException {

    this.adapterId = adapterId;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);/* ww w.  j  a va2  s .c  o  m*/
    connection = factory.newConnection();
    channel = connection.createChannel();
    channel.queueDeclare(queueNameLifecycle(), false, false, true, null);

    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_LIFE_CYCLE, "#");
    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_CUSTOM_EVENT, "#");
    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_EXCEPTIONS, "#");

    consumerLifecycle = new QueueingConsumer(channel);

    channel.basicConsume(queueNameLifecycle(), true, consumerLifecycle);

}

From source file:at.ac.tuwien.dsg.comot.m.core.test.utils.TestAgentAdapter.java

License:Apache License

public TestAgentAdapter(String adapterId, String host) throws IOException {

    this.adapterId = adapterId;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);/*from w  w w . j a  v a  2 s .  c o m*/
    connection = factory.newConnection();
    channel = connection.createChannel();

    channel.queueDeclare(queueNameLifecycle(), false, false, true, null);
    // channel.queueDeclare(queueNameCustom(), false, false, true, null);

    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_LIFE_CYCLE, "#");
    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_CUSTOM_EVENT, "#");
    channel.queueBind(queueNameLifecycle(), Constants.EXCHANGE_EXCEPTIONS, "#");

    consumerLifecycle = new QueueingConsumer(channel);
    // consumerCustom = new QueueingConsumer(channel);

    channel.basicConsume(queueNameLifecycle(), true, consumerLifecycle);
    // channel.basicConsume(queueNameCustom(), true, consumerCustom);

}

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   ww w.  ja va  2  s  . c om*/
}

From source file:bank.OurRabbitBank.java

private static void sendToNormalizer(Message msg, AMQP.BasicProperties props) {
    try {//from   ww  w .  j  a v  a2s . c o  m
        Gson g = new Gson();
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("datdb.cphbusiness.dk");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //channel.exchangeDeclare(ExchangeName.OUR_JSON_BANK_RESPONSE, "direct");

        int ssn = Integer.valueOf(msg.getSsn());
        double interestRate = calcRate();
        String bank = "OurRabbitBank";
        String correlationId = props.getCorrelationId();

        LoanResponse response = new LoanResponse(ssn, interestRate, bank, correlationId);

        String res = g.toJson(response);

        channel.basicPublish(ExchangeName.OUR_JSON_BANK_RESPONSE, "", props, res.getBytes());

        System.out.println(" [x] Sent '" + res + "'");

        channel.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Error in OutRabbitBank: " + e.getMessage());
    }
}

From source file:benchmarkio.consumer.rabbitmq.RabbitMQMessageConsumer.java

License:Apache License

public RabbitMQMessageConsumer(final String host, final int port, final String topic, final boolean durable) {
    Preconditions.checkNotNull(host);/*from  ww w.  j a v a  2s .co m*/
    Preconditions.checkNotNull(topic, "topic cannot be null");

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);

    try {
        final Connection connection = factory.newConnection();

        this.channel = connection.createChannel();
        this.channel.exchangeDeclare(topic, "topic", durable);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    this.topic = topic;
    this.histogram = Histograms.create();
}

From source file:benchmarkio.producer.rabbitmq.RabbitMQMessageProducer.java

License:Apache License

public RabbitMQMessageProducer(final String host, final int port, final String topic, final String message,
        final long numberOfMessagesToProduce, final boolean durable) {
    Preconditions.checkNotNull(host);/*www  .  ja v  a  2  s  . c om*/

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(host);
    factory.setPort(port);

    try {
        final Connection connection = factory.newConnection();

        this.channel = connection.createChannel();
        this.channel.exchangeDeclare(topic, "topic", durable);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    // To declare a queue
    //channel.queueDeclare(QUEUE_NAME, false, false, false, null);

    this.histogram = Histograms.create();
    this.topic = Preconditions.checkNotNull(topic);
    this.message = Preconditions.checkNotNull(message);
    this.numberOfMessagesToProduce = Preconditions.checkNotNull(numberOfMessagesToProduce);
}

From source file:biospectra.classify.server.RabbitMQInputClient.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    String hostname = this.conf.getRabbitMQHostnames().get(this.hostId);
    factory.setHost(hostname);/*  www.j  a  va  2s . c  o m*/
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.shutdownListener = new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    };

    this.connection.addShutdownListener(this.shutdownListener);

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("reader connected - " + hostname + ":" + this.conf.getRabbitMQPort());

    this.responseChannel.basicQos(10);
    this.queueName = this.responseChannel.queueDeclare().getQueue();

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

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            LOG.info("> " + message);

            ClassificationResponseMessage res = ClassificationResponseMessage.createInstance(message);
            ClassificationRequest ereq = null;
            synchronized (requestMap) {
                ereq = requestMap.get(res.getReqId());
                if (ereq != null) {
                    requestMap.remove(res.getReqId());
                }
            }

            if (ereq == null) {
                LOG.error("cannot find matching request");
            } else {
                ClassificationResponse eres = new ClassificationResponse(ereq, res);

                boolean responded = false;
                synchronized (ereq) {
                    ClassificationRequest.RequestStatus status = ereq.getStatus();
                    if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                        ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_RESPONDED);
                        responded = true;
                    }

                    requestQueue.remove(ereq);
                }

                if (responded) {
                    LOG.info("res : " + ereq.getReqId());
                    if (handler != null) {
                        handler.onSuccess(eres.getReqId(), eres.getHeader(), eres.getSequence(),
                                eres.getResult(), eres.getType(), eres.getTaxonRank(), eres.getTaxonName());
                    }

                    synchronized (requestQueue) {
                        requestQueue.notifyAll();
                    }
                }
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                responseChannel.basicConsume(queueName, consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
    this.reachable = true;

    this.timeoutThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                boolean cont = false;
                if (requestQueue.size() > 0) {
                    ClassificationRequest ereq = requestQueue.peek();
                    Date cur = new Date();
                    if (ereq != null && cur.getTime() - ereq.getSentTime() >= QUERY_TIMEOUT) {
                        LOG.info("found timeout request");
                        //timeout
                        boolean timeout = false;
                        synchronized (ereq) {
                            ClassificationRequest.RequestStatus status = ereq.getStatus();
                            if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                                ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_TIMEOUT);
                                timeout = true;
                            }

                            requestQueue.remove(ereq);
                        }

                        synchronized (requestMap) {
                            requestMap.remove(ereq.getReqId());
                        }

                        if (timeout) {
                            LOG.info("timeout : " + ereq.getReqId());
                            handler.onTimeout(ereq.getReqId(), ereq.getHeader(), ereq.getSequence());

                            synchronized (requestQueue) {
                                requestQueue.notifyAll();
                            }
                        }
                        cont = true;
                    }
                }

                if (!cont) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        break;
                    }
                }
            }
        }
    });
    this.timeoutThread.start();
}

From source file:biospectra.classify.server.RabbitMQInputServer.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    LOG.info("Connecting to - " + this.conf.getRabbitMQHostname() + ":" + this.conf.getRabbitMQPort());

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.conf.getRabbitMQHostname());
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);//from ww  w.  j  av  a2  s . c om

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.connection.addShutdownListener(new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    });

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("connected.");

    this.requestChannel.basicQos(1);
    this.requestChannel.queueDeclare("request", false, false, true, null);

    this.responseChannel.addReturnListener(new ReturnListener() {

        @Override
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            LOG.info("message not delivered to " + routingKey);
            LOG.info(message);
        }
    });

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

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            if (handler != null) {
                ClassificationRequestMessage req = ClassificationRequestMessage.createInstance(message);
                handler.handleMessage(req, properties.getReplyTo());
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                requestChannel.basicConsume("request", consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
}

From source file:blocker.Blocker.java

/**
 * @param argv/*from  w w w.  j  av a2s .c  o m*/
 */
public static void main(String[] argv) throws Exception {
    seconds = Integer.parseInt(argv[7]);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(argv[0]);
    factory.setUsername(argv[2]);
    factory.setPassword(argv[3]);
    factory.setVirtualHost(argv[1]);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(argv[4], "direct", true);
    String queueName = channel.queueDeclare(argv[5], true, false, false, null).getQueue();

    //                          exchange  key
    channel.queueBind(queueName, argv[4], argv[6]);

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

    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");
            JSONParser parser = new JSONParser();

            Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
                @Override
                public void uncaughtException(Thread th, Throwable ex) {
                    System.out.println("Uncaught exception: " + ex);
                }
            };

            try {
                Object obj = parser.parse(message);
                JSONObject jobj = (JSONObject) obj;
                String IP = (String) jobj.get("clientip");
                Thread t = new Thread(new BlockerThread(IP));
                t.setUncaughtExceptionHandler(h);
                t.start();
            } catch (ParseException ex) {
                Logger.getLogger(Blocker.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    };
    channel.basicConsume(argv[5], true, consumer);
}