Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

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

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null//w  w  w. j  a  va  2s.  c o m
 */
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//from w  ww.  j a  v  a2s .c om
 * @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//from w  ww  .j a v  a2 s . c om
 */
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:Client.ClientImplAbstract.java

License:Open Source License

public ClientImplAbstract() {

    mLogger = Logger.getLogger("Client");
    PropertyConfigurator.configure("log4j.properties");

    try {// w  w  w .  j a va2 s  .  co m
        mFactory = new ConnectionFactory();
        mFactory.setHost("localhost");
        mConnection = mFactory.newConnection();
        mChannel = mConnection.createChannel();

        /*
         * Defines that messages in this queue are persistent (i.e. to be saved on disk)    
         * so that even if RabbitMQ server quits the messages is not lost.
         * Note that when publishing a message, the msg itself has to be declared persistent.
         */
        boolean durable = false; // for commands we don't want it!

        /*
         * true if the server should consider messages acknowledged once delivered; 
         * false if the server should expect explicit acknowledgements.
         */
        boolean autoAck = true;

        // command queue      
        boolean exclusive = false; // restricted to this connection
        boolean autoDelete = false; // server will delete the queue when no longer in use
        mChannel.queueDeclare(CMD_QUEUE_NAME, durable, exclusive, autoDelete, null);

        // broadcasted commands (don't need to subscribe to a topic)
        mChannel.exchangeDeclare(CMD_EXCHANGE_NAME, "fanout", durable);
        String cmdFanoutQueueName = mChannel.queueDeclare().getQueue();
        mChannel.queueBind(cmdFanoutQueueName, CMD_EXCHANGE_NAME, "");

        // data topics to subscribe
        durable = true; // for data we want persistance!
        mChannel.exchangeDeclare(DATA_EXCHANGE_NAME, "topic", durable);
        String dataPubsubQueueName = mChannel.queueDeclare().getQueue();

        // define which queues to get the messages from 
        mConsumer = new QueueingConsumer(mChannel);
        mChannel.basicConsume(CMD_QUEUE_NAME, autoAck, mConsumer);
        mChannel.basicConsume(cmdFanoutQueueName, autoAck, mConsumer);
        mChannel.basicConsume(dataPubsubQueueName, autoAck, mConsumer);

    } catch (IOException e) {
        mLogger.error("Could not create RMQ channel: " + e.getMessage());
        return;
    }

    try {
        mEngine = new SMEngine(mLogger, SMJavaInvoker.class);
        // The context has to be created before the actions/activities are executed
        mEngine.setContextVar("CHANNEL", mChannel);
        mEngine.setContextVar("CMD_QUEUE_NAME", CMD_QUEUE_NAME);
        mEngine.setContextVar("CMD_EXCHANGE_NAME", CMD_EXCHANGE_NAME);
        mEngine.setContextVar("DATA_EXCHANGE_NAME", DATA_EXCHANGE_NAME);
        mEngine.loadModel("Client.xml");
        mEngine.startExecution();
    } catch (IOException e) {
        mLogger.error("Could not start SM execution: " + e.getMessage());
        return;
    }

    mIsRunning = true;
}

From source file:client.MessengerClient.java

public MessengerClient() throws IOException, TimeoutException {
    isLogin = false;//w w w.ja v  a2s  .  c o m
    factory = new ConnectionFactory();
    System.out.print("input host : ");
    String host = sc.nextLine();
    if (!host.equalsIgnoreCase("localhost")) {
        System.out.print("input port : ");
        int port = Integer.parseInt(sc.nextLine());
        factory.setPort(port);
    }

    factory.setHost(host);

    connection = factory.newConnection();
    channel = connection.createChannel();
    //channel.basicQos(1); // accept only one unack-ed message at a time (see below)
    channel.queueDeclare(serverqueue, true, false, false, null);
    consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            //channel.basicAck(envelope.getDeliveryTag(), false);
            Message m = null;
            try {
                m = Message.toMessage(body);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(MessengerClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            switch (m.getType()) {
            case 0: {
                System.out.println(m.getSender() + " : " + m.getContent());
                break;
            }
            case 1: {
                System.out.println(m.getGroupName() + " , " + m.getSender() + " : " + m.getContent());
                break;
            }
            case 2: {
                switch (m.getContent()) {
                case "joingroup": {
                    listgroup.add(m.getGroupName());
                    System.out.println("join group " + m.getGroupName());
                    break;
                }
                case "leavegroup": {
                    listgroup.remove(m.getGroupName());
                    System.out.println("leave group " + m.getGroupName());
                    break;
                }
                case "addfriend": {
                    listfriend.add(m.getFriendID());
                    System.out.println("addfriend " + m.getFriendID());
                    break;
                }
                default: {
                    System.out.println(m.getContent());
                    break;
                }
                }
                break;
            }
            }
        }
    };
    autoAck = true; // acknowledgment is covered below

}

From source file:client.RabbitMQConsumerClient.java

License:Open Source License

public RabbitMQConsumerClient(String host) {
    factory = new ConnectionFactory();
    factory.setHost(host);
}

From source file:client.RabbitMQProducerClient.java

License:Open Source License

public RabbitMQProducerClient(String host, int port, String username, String password) {
    factory = new ConnectionFactory();
    factory.setHost(host);//from   www.  j  ava  2s.co m
    factory.setPort(port);
    factory.setUsername(username);
    factory.setPassword(password);
}

From source file:Client.SMActivity.java

License:Open Source License

public void openConnection() {
    try {/* ww  w .  j  ava  2 s.c  o m*/
        boolean durable = true; // for data we want persistance
        boolean autoAck = true;

        mFactory = new ConnectionFactory();
        mFactory.setHost("localhost");
        mConnection = mFactory.newConnection();
        mChannel = mConnection.createChannel();

        // data pub/sub
        mChannel.exchangeDeclare(DATA_EXCHANGE_NAME, "topic", durable);
        String pubsubQueueName = mChannel.queueDeclare().getQueue();

        mConsumer = new QueueingConsumer(mChannel);
        mChannel.basicConsume(pubsubQueueName, autoAck, mConsumer);

    } catch (IOException e) {
        getLogger().error("Could not create RMQ channel: " + e.getMessage());
        stopRunning();
    }
}

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

public void procesar() {

    ConnectionFactory factory = new ConnectionFactory();
    try {//  w  w  w .ja va 2s  .  com
        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");
        */

}