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:bog.processing.rabbit.RabbitListener.java

License:Open Source License

public void Listen(String exchange, String host, Map<String, Object> params, String like) {
    try {/*from   w  w w.jav  a2  s  .c o m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, true, params);
        if (exchange != "") {
            channel.queueBind(QUEUE_NAME, exchange, ROUTING_KEY, params);
        }
        System.out.println(" [*] Waiting for messages...");
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(QUEUE_NAME, true, consumer);
        (new Thread(new ListenerThread(consumer, messages, like))).start();

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:br.uff.labtempo.omcp.common.utils.RabbitComm.java

License:Apache License

public void connect() throws ConnectionException {
    if (connection == null || !connection.isOpen()) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(this.host);

        if (this.user != null && this.pass != null) {
            factory.setUsername(this.user);
            factory.setPassword(this.pass);
        }//  w  w  w. j a  va  2 s.co m

        try {
            connection = factory.newConnection();

        } catch (Exception ex) {//IOException
            close();
            this.checkHostOrDie(host);
            throw new ConnectionException("Could not connect to RabbitMQ", ex);
        }
    } else {
        throw new ConnectionException("Already connected to RabbitMQ");
    }
}

From source file:brooklyn.entity.messaging.rabbit.RabbitEc2LiveTest.java

License:Apache License

private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception {
    String uri = rabbit.getAttribute(MessageBroker.BROKER_URL);
    LOG.warn("connecting to rabbit {}", uri);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(uri);//  w  ww  .j  a v a2s  . c om
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    return channel;
}

From source file:brooklyn.entity.messaging.rabbit.RabbitIntegrationTest.java

License:Apache License

private Channel getAmqpChannel(RabbitBroker rabbit) throws Exception {
    String uri = rabbit.getAttribute(MessageBroker.BROKER_URL);
    log.warn("connecting to rabbit {}", uri);
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(uri);//from   w  ww  .  ja  v a 2s .c  o  m
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    return channel;
}

From source file:cc.gospy.core.remote.rabbitmq.RemoteScheduler.java

License:Apache License

private void init(ConnectionFactory factory) throws IOException, TimeoutException {
    connection = factory.newConnection();
    channel = connection.createChannel();
}

From source file:ch.icclab.cyclops.consume.RabbitMQListener.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null//from  w w  w  .ja  v a  2  s .com
 */
private Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(credentials.getConsumerUsername());
    factory.setPassword(credentials.getConsumerPassword());
    factory.setHost(credentials.getConsumerHost());
    factory.setPort(credentials.getConsumerPort());
    factory.setVirtualHost(credentials.getConsumerVirtualHost());
    factory.setAutomaticRecoveryEnabled(true);

    Channel chan;

    try {
        // create new connection
        connection = factory.newConnection();

        // create/connect to the channel
        chan = connection.createChannel();

        logger.trace(String.format("RabbitMQ Consumer connected to %s:%d", credentials.getConsumerHost(),
                credentials.getConsumerPort()));

    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Consumer couldn't be created: %s", e.getMessage()));
        connection = null;
        chan = null;
    }

    // return channel reference, or null
    return chan;
}

From source file:ch.icclab.cyclops.publish.RabbitMQPublisher.java

License:Open Source License

/**
 * Initialise connection to RabbitMQ// w  ww .java 2 s.c  o m
 * @return status
 */
private Boolean initialiseConnection() {
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(credentials.getPublisherUsername());
        factory.setPassword(credentials.getPublisherPassword());
        factory.setHost(credentials.getPublisherHost());
        factory.setPort(credentials.getPublisherPort());
        factory.setVirtualHost(credentials.getPublisherVirtualHost());
        factory.setAutomaticRecoveryEnabled(true);

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

        // declare exchange to be used (we want it to be durable and based on routing key)
        channel.exchangeDeclare(credentials.getPublisherDispatchExchange(), "direct", true);
        channel.exchangeDeclare(credentials.getPublisherBroadcastExchange(), "fanout", true);

        logger.trace(String.format("RabbitMQ Publisher connected to %s:%d", credentials.getPublisherHost(),
                credentials.getPublisherPort()));
        logger.trace(String.format(
                "RabbitMQ Publisher will dispatch to \"%s\" and broadcast to \"%s\" exchanges",
                credentials.getPublisherDispatchExchange(), credentials.getPublisherBroadcastExchange()));

        return true;
    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Publisher couldn't be created: %s", e.getMessage()));
        return false;
    }
}

From source file:ch.icclab.cyclops.rabbitmq.RabbitMQAbstract.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null/*from ww w .  j  a v  a 2 s.c  o m*/
 */
protected Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(credentials.getRabbitMQUsername());
    factory.setPassword(credentials.getRabbitMQPassword());
    factory.setHost(credentials.getRabbitMQHost());
    factory.setPort(credentials.getRabbitMQPort());
    factory.setVirtualHost(credentials.getRabbitMQVirtualHost());

    Channel chan;

    try {

        logger.trace("Creating connection to RabbitMQ for host: " + credentials.getRabbitMQHost()
                + " and port: " + credentials.getRabbitMQPort());

        // create new connection
        connection = factory.newConnection();

        logger.trace("Creating and connecting to RabbitMQ channel");

        // create/connect to the channel
        chan = connection.createChannel();

    } catch (Exception ex) {
        logger.error("Couldn't start Rabbit MQ: " + ex.getMessage());
        connection = null;
        chan = null;
    }

    // return channel reference, or null
    return chan;
}

From source file:ch.icclab.cyclops.usecases.mcn.rabbitMQClient.McnRabbitMQClient.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 *
 * @return channel reference or null/*ww w.  j  av  a2  s .com*/
 */
private Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(rabbitMQSettings.getRabbitMQUsername());
    factory.setPassword(rabbitMQSettings.getRabbitMQPassword());
    factory.setVirtualHost(rabbitMQSettings.getRabbitMQVirtualHost());
    factory.setHost(rabbitMQSettings.getRabbitMQHost());
    factory.setPort(rabbitMQSettings.getRabbitMQPort());
    try {
        // create new connection
        connection = factory.newConnection();

        // create/connect to the channel
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
    } catch (Exception ex) {
        logger.error("Couldn't start Rabbit MQ: " + ex.getMessage());
        ex.printStackTrace();
    }

    // return channel reference, or null
    return channel;
}

From source file:co.edu.uniandes.cloud.simuladorcredito.negocio.Process.java

public void procesar() {

    ConnectionFactory factory = new ConnectionFactory();
    try {//w  w w .  j av a  2s. co  m
        factory.setUri(uri);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("hello", true, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String mensaje = new String(delivery.getBody());
            System.out.println(" [x] Received '" + mensaje + "'");
            System.out.println("Procesando..." + mensaje + "-" + Calendar.getInstance());
            PlanPago pp = dao.leer(new Long(mensaje));
            if (pp.getLinea() != null) {
                //generar cuota
                List<Cuota> cuotas = aa.generarCuotas(pp.getValor(), pp.getLinea().getTasa(), pp.getPlazo());
                pp.setCuotas(cuotas);
                //calcular nivel de riesgo
                pp.setNivelRiesgo(calcularNivelRiesgo());
                pp.setEstado("Generado");
                //guardar cuota
                dao.actualizar(pp);
                for (Cuota c : pp.getCuotas()) {
                    c.setIdPlan(pp.getId());
                }
                dao2.insertar(pp.getCuotas());
            }
            System.out.println("Finalizo " + mensaje + "-" + Calendar.getInstance());

        }

    } catch (URISyntaxException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
    }

    //listenerContainer.setConnectionFactory(rabbitConnectionFactory);
    //listenerContainer.setQueueNames(rabbitQueue.getName());

    // set the callback for message handling
    /*listenerContainer.setMessageListener(new MessageListener() {
    public void onMessage(Message message) {
        final String mensaje = (String) messageConverter.fromMessage(message);
                
        // simply printing out the operation, but expensive computation could happen here
        System.out.println("Received from RabbitMQ: " + mensaje);
                
    }
    });
            
    // set a simple error handler
    /*listenerContainer.setErrorHandler(new ErrorHandler() {
    public void handleError(Throwable t) {
        t.printStackTrace();
    }
    });
            
    // register a shutdown hook with the JVM
    Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
        System.out.println("Shutting down BigOperationWorker");
        listenerContainer.shutdown();
    }
    });
            
    // start up the listener. this will block until JVM is killed.
    listenerContainer.start();
    System.out.println("BigOperationWorker started");
        */

}