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:org.adslabs.adsfulltext.Worker.java

License:Open Source License

public boolean connect() {

    ConnectionFactory rabbitMQInstance;

    // This creates a connection object, that allows connections to be open to the same
    // RabbitMQ instance running
    ////from   w  w  w. jav  a  2 s.c  o m
    // There seems to be a lot of catches, but each one should list the reason for it's raise
    //
    // It is not necessary to disconnect the connection, it should be dropped when the program exits
    // See the API guide for more info: https://www.rabbitmq.com/api-guide.html

    try {

        rabbitMQInstance = new ConnectionFactory();
        logger.info("Connecting to RabbitMQ instance: {}", this.config.data.RABBITMQ_URI);
        rabbitMQInstance.setUri(this.config.data.RABBITMQ_URI);
        this.connection = rabbitMQInstance.newConnection();
        this.channel = this.connection.createChannel();

        // This tells RabbitMQ not to give more than one message to a worker at a time.
        // Or, in other words, don't dispatch a new message to a worker until it has processed
        // and acknowledged the previous one.
        this.channel.basicQos(this.prefetchCount);

        return true;

    } catch (java.net.URISyntaxException error) {

        logger.error("URI error: {}", error.getMessage());
        return false;

    } catch (java.io.IOException error) {

        logger.error("IO Error, is RabbitMQ running???: {}", error.getMessage());
        try {
            logger.error("Sleeping before exit");
            TimeUnit.SECONDS.sleep(5);
            logger.error("Finished sleeping.");
        } catch (java.lang.InterruptedException errorTime) {
            logger.error("Interrupt: {}", errorTime.getMessage());
        }
        return false;

    } catch (java.security.NoSuchAlgorithmException error) {

        logger.error("Most likely an SSL related error: ", error.getMessage());
        return false;

    } catch (java.security.KeyManagementException error) {

        logger.error("Most likely an SSL related error: ", error.getMessage());
        return false;

    }
}

From source file:org.apache.airavata.datacat.agent.messageBroker.AiravataUpdateListener.java

License:Apache License

public void startBroker() {
    (new Thread(new Runnable() {
        @Override/*from ww  w .j  a  va 2 s  .  c om*/
        public void run() {
            try {
                ConnectionFactory factory = new ConnectionFactory();
                factory.setHost(RABBITMQ_HOST);

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

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

                channel.basicQos(1);
                channel.queueBind(queueName, EXCHANGE_NAME, BINDING_KEY);

                logger.debug("Waiting for messages. To exit press CTRL+C");

                QueueingConsumer consumer = new QueueingConsumer(channel);
                channel.basicConsume(queueName, true, consumer);

                while (runFileUpdateListener) {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

                    Message message = new Message();
                    ThriftUtils.createThriftFromBytes(delivery.getBody(), message);
                    TBase event = null;

                    if (message.getMessageType().equals(MessageType.EXPERIMENT_OUTPUT)) {

                        ExperimentOutputCreatedEvent experimentOutputCreatedEvent = new ExperimentOutputCreatedEvent();
                        ThriftUtils.createThriftFromBytes(message.getEvent(), experimentOutputCreatedEvent);

                        logger.debug(" Message Received with message id '" + message.getMessageId()
                                + "' and with message type '" + message.getMessageType()
                                + "'  with experiment name "
                                + experimentOutputCreatedEvent.getExperimentName());

                        event = experimentOutputCreatedEvent;

                        logger.debug(" [x] Received FileInfo Message'");
                        process(experimentOutputCreatedEvent, message.getUpdatedTime());
                        logger.debug(" [x] Done Processing FileInfo Message");
                    } else {
                        logger.debug("Recieved message of type ..." + message.getMessageType());
                    }
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }

    })).start();

}

From source file:org.apache.airavata.datacat.agent.messageBroker.RabbitMQProducer.java

License:Apache License

private Connection createConnection() throws IOException {
    try {/*from w w w . j  a v a 2  s.c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(url);
        Connection connection = factory.newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
        return connection;
    } catch (Exception e) {
        log.info("connection failed to rabbitmq: " + connection + " for " + exchangeName);
        return null;
    }
}

From source file:org.apache.airavata.datacat.agent.org.apache.airavata.datacat.agent.messageBroker.RabbitMQConsumerTest.java

License:Apache License

/**
 * Test method to publish dummy data to RabbitMQ
 * @param messageType// w w w .j a v a2  s.c o  m
 * @throws java.io.IOException
 * @throws TException
 */
public void publish(MessageType messageType) throws java.io.IOException, TException {

    //establishing the connection
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(RABBITMQ_HOST);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic");

    String DATA_ROOT = AgentProperties.getInstance().getProperty(Constants.DATA_ROOT, "");

    //creating the output created Event
    ExperimentOutputCreatedEvent event = new ExperimentOutputCreatedEvent();
    event.setExperimentId("test");
    event.setOutputPath(DATA_ROOT + "/2H2OOHNCmin.com.out");

    //serializing the event
    byte[] body = ThriftUtils.serializeThriftObject(event);
    Message message = new Message();
    message.setEvent(body);
    message.setMessageId("sad");
    message.setMessageType(messageType);
    message.setUpdatedTime(993344232);
    String routingKey = "*";

    //serializing the message object
    byte[] messageArray = ThriftUtils.serializeThriftObject(message);
    channel.basicPublish(EXCHANGE_NAME, BINDING_KEY, null, messageArray);

    logger.debug(" [x] Sent '" + message + "'");

    channel.close();
    connection.close();
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.SimpleJobFinishConsumer.java

License:Apache License

public void listen() {
    try {//  w ww  . ja v a2 s  .c  om
        String queueName = ServerSettings.getSetting(Constants.GFAC_SERVER_PORT, "8950");
        String uri = "amqp://localhost";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();
        logger.info("--------Created the connection to Rabbitmq server successfully-------");

        final Channel ch = conn.createChannel();

        logger.info("--------Created the channel with Rabbitmq server successfully-------");

        ch.queueDeclare(queueName, false, false, false, null);

        logger.info("--------Declare the queue " + queueName + " in Rabbitmq server successfully-------");

        final QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        (new Thread() {
            public void run() {
                try {
                    while (true) {
                        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                        String message = new String(delivery.getBody());
                        logger.info(
                                "---------------- Job Finish message received:" + message + " --------------");
                        synchronized (completedJobsFromPush) {
                            completedJobsFromPush.add(message);
                        }
                        ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    }
                } catch (Exception ex) {
                    logger.error("--------Cannot connect to a RabbitMQ Server--------", ex);
                }
            }

        }).start();
    } catch (Exception ex) {
        logger.error("Cannot connect to a RabbitMQ Server: ", ex);
        logger.info("------------- Push monitoring for HPC jobs is disabled -------------");
    }
}

From source file:org.apache.airavata.gfac.monitor.util.AMQPConnectionUtil.java

License:Apache License

public static Connection connect(String host, String vhost, String proxyFile) {
    Connection connection;/* w w w .  j  av  a2  s.  c  om*/
    try {
        String keyPassPhrase = "test123";
        KeyStore ks = X509Helper.keyStoreFromPEM(proxyFile, keyPassPhrase);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, keyPassPhrase.toCharArray());

        KeyStore tks = X509Helper.trustKeyStoreFromCertDir();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(tks);

        SSLContext c = SSLContext.getInstance("SSLv3");
        c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(5671);
        factory.useSslProtocol(c);
        factory.setVirtualHost(vhost);
        factory.setSaslConfig(DefaultSaslConfig.EXTERNAL);

        connection = factory.newConnection();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return connection;
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/*from   w  w  w .  ja v  a 2  s .  c  om*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);

        channel = connection.createChannel();
        channel.exchangeDeclare(exchangeName, "topic", false);

    } catch (Exception e) {
        String msg = "could not open channel for exchange " + exchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQProcessConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {//from  w  w  w . j a v a2  s.  c om
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for default");

        channel = connection.createChannel();
        //            channel.exchangeDeclare(taskLaunchExchangeName, "fanout");

    } catch (Exception e) {
        String msg = "could not open channel for exchange default";
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQProcessLaunchConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/*  w ww .j a va 2  s.  com*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + taskLaunchExchangeName);

        channel = connection.createChannel();
        channel.basicQos(prefetchCount);

        //            channel.exchangeDeclare(taskLaunchExchangeName, "fanout");

    } catch (Exception e) {
        String msg = "could not open channel for exchange " + taskLaunchExchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQProducer.java

License:Apache License

private Connection createConnection() throws IOException {
    try {/*  w  w  w  . j a v  a2  s.  c o m*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        Connection connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
        return connection;
    } catch (Exception e) {
        log.info("connection failed to rabbitmq: " + connection + " for " + exchangeName);
        return null;
    }
}