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:joram.bridgeamqp.AMQPSender.java

License:Open Source License

public void run() {
    ConnectionFactory cnxFactory = null;
    Connection connection = null;
    Channel channel = null;//from  ww w.  j av a  2  s. com
    try {
        cnxFactory = new ConnectionFactory();
        connection = cnxFactory.newConnection();
        channel = connection.createChannel();
        //      channel.queueDeclare(queue, true, false, false, null);
    } catch (Exception exc) {
        exc.printStackTrace();
        return;
    }

    System.out.println(SenderId + " starts");

    // Convert message properties
    AMQP.BasicProperties props = new AMQP.BasicProperties();
    if (persistent) {
        props.setDeliveryMode(Integer.valueOf(org.objectweb.joram.shared.messages.Message.PERSISTENT));
    } else {
        props.setDeliveryMode(Integer.valueOf(org.objectweb.joram.shared.messages.Message.NON_PERSISTENT));
    }
    props.setCorrelationId(null);
    props.setPriority(4);
    props.setType(String.valueOf(org.objectweb.joram.shared.messages.Message.TEXT));
    props.setExpiration("0");

    try {
        for (int i = 0; i < nbmsgs; i++) {
            props.setTimestamp(new Date());
            props.setMessageId(SenderId + i);
            channel.basicPublish("", queue, props, getBody("Message number " + i));
            if (delay > 0)
                Thread.sleep(delay);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    } finally {
        try {
            System.out.println(SenderId + " stops");
            connection.close();
        } catch (IOException exc) {
            exc.printStackTrace();
        }
    }
}

From source file:jp.glassmoon.flume.sink.rabbitmq.RabbitMQSink.java

License:Apache License

@Override
public void configure(Context context) {
    try {//from w  w  w .  j ava2 s.c o m
        factory = new ConnectionFactory();
        factory.setUri(context.getString(URI, DEFAULT_URI));
        factory.setUsername(context.getString(USERNAME, DEFAULT_USERNAME));
        factory.setPassword(context.getString(PASSWORD, DEFAULT_PASSWORD));
    } catch (Exception ex) {
        LOGGER.warn("Wrong configuration", ex);
        factory = null;
    }

    exchangeName = context.getString(EXCHANGE, DEFAULT_EXCHANGE);
    deliveryMode = context.getInteger(DELIVERYMODE, DEFAULT_DELIVERYMODE);
    priority = context.getInteger(PRIORITY, DEFAULT_PRIORITY);
    routingKey = context.getString(ROUTINGKEY, DEFAULT_ROUTINGKEY);

    appId = context.getString(APPID, DEFAULT_APPID);
    contentEncoding = context.getString(CONTENT_ENCODING, DEFAULT_CONTENT_ENCODING);
    contentType = context.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}

From source file:kieker.analysis.plugin.reader.amqp.AMQPReader.java

License:Apache License

private Connection createConnection() throws IOException, TimeoutException, KeyManagementException,
        NoSuchAlgorithmException, URISyntaxException {
    final ConnectionFactory connectionFactory = new ConnectionFactory();

    connectionFactory.setUri(this.uri);
    connectionFactory.setRequestedHeartbeat(this.heartbeat);

    return connectionFactory.newConnection();
}

From source file:kieker.monitoring.writer.amqp.AmqpWriter.java

License:Apache License

private Connection createConnection() throws KeyManagementException, NoSuchAlgorithmException,
        URISyntaxException, IOException, TimeoutException {
    final ConnectionFactory connectionFactory = new ConnectionFactory();

    connectionFactory.setUri(this.uri);
    connectionFactory.setRequestedHeartbeat(this.heartbeat);
    // Use only daemon threads for connections. Otherwise, all connections would have to be explicitly
    // closed for the JVM to terminate.
    connectionFactory.setThreadFactory(new DaemonThreadFactory());

    return connectionFactory.newConnection();
}

From source file:li.barter.chat.AbstractRabbitMQConnector.java

License:Open Source License

/**
 * Connect to the broker and create the exchange
 * /*from   w w  w  .j  a  v  a2 s.c om*/
 * @return success
 */
protected boolean connectToRabbitMQ(final String userName, final String password) {
    if ((mChannel != null) && mChannel.isOpen()) {
        return true;
    }
    try {
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(mServer);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(mVirtualHost);
        connectionFactory.setPort(mPort);
        connectionFactory.setRequestedHeartbeat(AppConstants.HEART_BEAT_INTERVAL);
        mConnection = connectionFactory.newConnection();
        mChannel = mConnection.createChannel();
        mChannel.exchangeDeclare(mExchange, mExchangeType.key);

        return true;
    } catch (final Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:loanbroker.Aggregator.java

private void send(entity.Message m, String routingKey)
        throws IOException, TimeoutException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);/* ww  w  .j  a v  a2s.c  om*/
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(ExchangeName.GLOBAL, "direct");

    //creating LoanResponse object
    LoanResponse lp = new LoanResponse(parseInt(m.getSsn()), m.getCreditScore(), m.getLoanDuration(), "");

    Gson gson = new GsonBuilder().create();
    String fm = gson.toJson(lp);
    BasicProperties props = new BasicProperties.Builder().build();

    channel.basicPublish(ExchangeName.GLOBAL, routingKey, props, fm.getBytes());

    System.out.println(" [x] Sent '" + ExchangeName.GLOBAL + routingKey + "':'" + fm + "'");

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

}

From source file:loanbroker.Aggregator.java

public void reciveFromNormalizer(Hashtable<String, Message> messageFroumBankList,
        Hashtable<String, Message> messagesFromNormalizer, ArrayList<Message> foundMessages)
        throws IOException, TimeoutException, Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);/*from   ww w. jav a2 s . c  o  m*/
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    // channel.exchangeDeclare(inputEXCHANGE_NAME, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.NormalizerToAggregator);
    System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL
            + RoutingKeys.NormalizerToAggregator + ". 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 m = new String(body, "UTF-8");

            Gson gson = new GsonBuilder().create();
            LoanResponse lp = gson.fromJson(m, LoanResponse.class);
            Message fm = new Message("" + lp.getSsn(), (int) lp.getInterestRate(), 0, lp.getBank());
            messagesFromNormalizer.put(lp.getCorrelationId(), fm);

            System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'");
            try {
                checkLoanMessages(messageFroumBankList, messagesFromNormalizer, foundMessages);
            } catch (InterruptedException ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TimeoutException ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(Aggregator.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:loanbroker.Aggregator.java

public void reciveFromRecieptList(Hashtable<String, Message> messagesFromBankList)
        throws IOException, TimeoutException, Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);// www.ja v a2 s  .  co m
    factory.setPort(5672);
    factory.setUsername("student");
    factory.setPassword("cph");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(ExchangeName.GLOBAL, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, ExchangeName.GLOBAL, RoutingKeys.RecipientListToAggregator);
    System.out.println(" [*] Waiting for messages on " + ExchangeName.GLOBAL
            + RoutingKeys.RecipientListToAggregator + ".. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String m = new String(body, "UTF-8");
            // System.out.println("reciveFromRecieptList" + m);
            String p = properties.getCorrelationId();
            if (p != null) {
                //send to translator
                Gson g = new Gson();
                Message fm = g.fromJson(m, Message.class);
                if (fm.getBanks() != null) {
                    Message k = new Message(fm.getSsn(), fm.getCreditScore(), fm.getLoanAmount(),
                            fm.getLoanDuration());

                    k.setBanks(fm.getBanks());

                    messagesFromBankList.put(p, k);
                }

                System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + fm.toString() + "'");
                //   System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + m + "'");
            } else {
                System.out.println("No correlationId");
            }

        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:loanbroker.GetBanks.java

private static void init() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("datdb.cphbusiness.dk");
    connection = factory.newConnection();
    inputChannel = connection.createChannel();
    outputChannel = connection.createChannel();

    inputChannel.exchangeDeclare(ExchangeName.OUTPUT_GET_CREDITSCORE, "fanout");
    String queueName = inputChannel.queueDeclare().getQueue();
    inputChannel.queueBind(queueName, ExchangeName.OUTPUT_GET_CREDITSCORE, "");

    outputChannel.exchangeDeclare(ExchangeName.OUTPUT_GET_BANKS, "fanout");

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

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

From source file:loanbroker.GetCreditScore.java

void recive() throws IOException, TimeoutException, InterruptedException, Exception {
    //setting the connection to the RabbitMQ server
    ConnectionFactory connfac = new ConnectionFactory();
    connfac.setHost(hostName);/*from w  ww  .jav a 2 s .  c  om*/
    connfac.setUsername("student");
    connfac.setPassword("cph");

    //make the connection
    Connection conn = connfac.newConnection();
    //make the channel for messaging
    Channel chan = conn.createChannel();

    //Declare a queue
    chan.exchangeDeclare(ExchangeName.OUTPUT_LOAN_REQUEST, "fanout");
    String queueName = chan.queueDeclare().getQueue();
    chan.queueBind(queueName, ExchangeName.OUTPUT_LOAN_REQUEST, "");

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

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

    //start polling messages
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String m = new String(delivery.getBody());
        System.out.println(" [x] Received '" + m + "'");
        Gson gson = new GsonBuilder().create();
        Message fm = gson.fromJson(m, Message.class);
        int creditScore = creditScore(fm.getSsn());
        fm.setCreditScore(creditScore);
        fm.setSsn(fm.getSsn().replace("-", ""));
        send(fm);

    }

}