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:it.txt.ens.core.util.AMQPFactory.java

License:Apache License

public static ConnectionFactory createConnectionFactory(ENSAuthzServiceConnectionParameters params) {
    //create and configure the RabbitMQ Connection Factory
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(params.getSubjectID());
    factory.setPassword(params.getAccessToken());
    factory.setPort(params.getBrokerPort());
    factory.setHost(params.getBrokerHost());
    factory.setVirtualHost(params.getVirtualHost());
    return factory;
}

From source file:it.txt.ens.core.util.AMQPFactory.java

License:Apache License

public static Connection createConnection(ENSAuthzServiceConnectionParameters params) throws IOException {
    //create and configure the RabbitMQ Connection Factory
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(params.getSubjectID());
    factory.setPassword(params.getAccessToken());
    factory.setPort(params.getBrokerPort());
    factory.setHost(params.getBrokerHost());
    factory.setVirtualHost(params.getVirtualHost());
    return factory.newConnection();
}

From source file:itinno.example.ExampleRabbitmqClient.java

public static void main(String[] args) {
    Logger logger = null;/*from  w  w  w  .j  a v a  2s .c o m*/
    String patternLayout = "%5p %d{yyyy-MM-dd HH:mm:ss,sss} %file %t %L: %m%n";

    try {
        // Initialise logger context and logger pattern encoder
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();

        // Set logging pattern (UTF-8 log)
        // logging patterns defined at http://logback.qos.ch/manual/layouts.html
        patternLayoutEncoder.setPattern(patternLayout);
        patternLayoutEncoder.setContext(loggerContext);
        patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
        patternLayoutEncoder.start();

        // log to console
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
        appender.setContext(loggerContext);
        appender.setEncoder(patternLayoutEncoder);
        appender.start();

        // Finally setup the logger itself
        logger = (Logger) LoggerFactory.getLogger(ExampleRabbitmqClient.class.getName());
        logger.addAppender(appender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    /*try {
    VisualIndexer.init("/home/kandreadou/webservice/learning_files/","127.0.0.1",LoggerFactory.getLogger(ExampleRabbitmqClient.class));
    VisualIndexer v = new VisualIndexer("simtest");
    v.index("http://resources0.news.com.au/images/2012/08/16/1226451/587056-120816-obama.jpg","obama1");
    } catch (Exception ex) {
    System.out.println(ex);
    }*/

    logger.info("rabitmq client started");

    // send a UTF-8 encoded JSON tweet to the RabbitMQ (for stormspout to pick up and send to bolt)
    try {
        // check args
        /*if ( args.length < 1 ) {
        logger.error( "Usage: example_rabbitmq_client <JSON_filename>" );
        System.exit( 1 );
        }
        logger.info( "JSON file = " + args[0] );*/
        String strJSONFilePath = "/home/kandreadou/mklab/example-tweet-utf8.json";

        // check if the path to JSON file exists
        File fileJSON = new File(strJSONFilePath);

        System.out.println(fileJSON.getAbsolutePath());

        if (fileJSON.exists() == false) {
            logger.info("JSON file does not exist : " + strJSONFilePath);
            logger.info("Usage: example_rabbitmq_client <JSON_filename>");
            System.exit(1);
        }

        // read UTF-8 JSON text from file
        logger.info("ExampleRabbitmqClient started");

        List<String> lines = Files.readAllLines(Paths.get(strJSONFilePath), Charset.forName("UTF-8"));
        String strJSON = "";
        for (String line : lines) {
            if (line.length() > 0) {
                strJSON = strJSON + "\n";
            }
            strJSON = strJSON + line;
        }
        logger.info("JSON test message = " + strJSON);

        // connect to rabbitmq broker
        // first of all create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri("amqp://guest:guest@localhost:5672/%2F");
        long timestampSinceEpoch = System.currentTimeMillis() / 1000;

        // initialise connection and define channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // initialise amqp basic peoperties object
        BasicProperties.Builder basicProperties = new BasicProperties.Builder();
        basicProperties.build();
        basicProperties.timestamp(new Date(timestampSinceEpoch)).build();
        basicProperties.contentType("text/json").build();
        basicProperties.deliveryMode(1).build();

        // publish message
        /* Exchange name should be {assessment_id}+ "_exchange" */
        channel.basicPublish("indexing_exchange", "test-routing", basicProperties.build(),
                strJSON.getBytes("UTF-8"));

        // close connection and channel
        channel.close();
        connection.close();

        logger.info("ExampleRabbitmqClient finished");

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        System.exit(1);
    }
}

From source file:javarpc_client.RPCClient.java

public RPCClient() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    connection = (Connection) factory.newConnection();
    channel = connection.createChannel();

    replyQueueName = channel.queueDeclare().getQueue();
    consumer = new QueueingConsumer(channel);
    channel.basicConsume(replyQueueName, true, consumer);
}

From source file:javarpc_server.JavaRPC_Server.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//from   w w w  .j  av  a2  s  .c o m
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    // TODO code application logic here

    ConnectionFactory factory = new ConnectionFactory();
    System.out.println(factory.getUsername() + " " + factory.getPassword());
    factory.setHost("localhost");

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

    channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

    System.out.println(" [x] Awaiting RPC requests");

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

        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                .build();

        String message = new String(delivery.getBody());

        System.out.println(" [.] convert(" + message + ")");
        String response = "" + convert(message);

        channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

From source file:jenkins.plugins.logstash.persistence.RabbitMqDao.java

License:Open Source License

RabbitMqDao(ConnectionFactory factory, String host, int port, String key, String username, String password) {
    super(host, port, key, username, password);

    if (StringUtils.isBlank(key)) {
        throw new IllegalArgumentException("rabbit queue name is required");
    }/*from w  w  w.j  av a 2s.c o m*/

    // The ConnectionFactory must be a singleton
    // We assume this is used as a singleton as well
    // Calling this method means the configuration has changed and the pool must be re-initialized
    pool = factory == null ? new ConnectionFactory() : factory;
    pool.setHost(host);
    pool.setPort(port);

    if (!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {
        pool.setPassword(password);
        pool.setUsername(username);
    }
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover1() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*from   www. ja  va  2 s  .  c om*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

    for (int i = 0; i < 5; i++) {
        GetResponse msg = channel.basicGet("testqueue", true);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    GetResponse msg = channel.basicGet("testqueue", true);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());
}

From source file:joram.amqp.PersistenceSimpleTest.java

License:Open Source License

public void recover2() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    channel.txSelect();/*from   w ww . j  a  va  2 s  .  c om*/
    for (int i = 0; i < 5; i++) {
        channel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                "this is a test message !!!".getBytes());
    }
    channel.txCommit();

    killAgentServer((short) 0);

    startAgentServer((short) 0);
    Thread.sleep(500);

    connection = cnxFactory.newConnection();
    channel = connection.createChannel();
    declareOk = channel.queueDeclarePassive("testqueue");

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

    for (int i = 0; i < 5; i++) {
        Delivery msg = consumer.nextDelivery(1000);
        assertNotNull(msg);
        assertEquals("this is a test message !!!", new String(msg.getBody()));
    }

    Delivery msg = consumer.nextDelivery(1000);
    assertNull(msg);

    channel.queueDelete(declareOk.getQueue());

}

From source file:joram.amqp.QueueTest.java

License:Open Source License

public void queueDeclareName() throws Exception {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    Connection connection = cnxFactory.newConnection();

    Channel channel = connection.createChannel();
    DeclareOk declareOk = channel.queueDeclare("testqueue", true, false, false, null);

    assertEquals("testqueue", declareOk.getQueue());
}

From source file:joram.bridgeamqp.AMQPReceiver.java

License:Open Source License

public static AMQPReceiver createAMQPConsumer(String queue) throws IOException {
    ConnectionFactory cnxFactory = new ConnectionFactory();
    connection = cnxFactory.newConnection();
    Channel channel = connection.createChannel();

    AMQPReceiver consumer = new AMQPReceiver(channel, queue);
    channel.basicConsume(queue, true, consumer);

    return consumer;
}