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:net.roboconf.messaging.internal.AbstractRabbitMqTest.java

License:Apache License

/**
 * Creates a channel to interact with a RabbitMQ server for tests.
 * @return a non-null channel//from   w  w w. j  a  va  2  s .  c o m
 * @throws IOException if the creation failed
 */
protected Channel createTestChannel() throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(MESSAGE_SERVER_IP);
    Channel channel = factory.newConnection().createChannel();

    return channel;
}

From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMq.java

License:Apache License

@Override
public void openConnection(final IMessageProcessor messageProcessor) throws IOException {

    // Already connected? Do nothing
    if (this.connected)
        return;/*from  w  w w .ja  v a  2s  .c  om*/

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.messageServerIp);
    this.connection = factory.newConnection();
    this.channel = this.connection.createChannel();
    this.connected = true;

    // 1 agent or 1 dm <=> 1 queue
    String exchangeName = getExchangeName();

    // Exchange declaration is idem-potent
    this.channel.exchangeDeclare(exchangeName, TOPIC);

    // Queue declaration is idem-potent
    this.queueName = this.applicationName + "." + this.sourceName;
    this.channel.queueDeclare(this.queueName, true, false, true, null);

    // Start to listen to the queue
    final QueueingConsumer consumer = new QueueingConsumer(this.channel);
    this.consumerTag = this.channel.basicConsume(this.queueName, true, consumer);

    new Thread("Roboconf - Queue listener for " + this.queueName) {
        @Override
        public void run() {

            final Logger logger = Logger.getLogger(MessageServerClientRabbitMq.this.loggerName);
            logger.fine(getName() + " starts listening to new messages.");

            // We listen to messages until the consumer is cancelled
            for (;;) {

                try {
                    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                    Message message = SerializationUtils.deserializeObject(delivery.getBody());

                    StringBuilder sb = new StringBuilder();
                    sb.append(MessageServerClientRabbitMq.this.sourceName);
                    sb.append(" received a message ");
                    sb.append(message.getClass().getSimpleName());
                    sb.append(" on routing key '");
                    sb.append(delivery.getEnvelope().getRoutingKey());
                    sb.append("'.");
                    // FIXME: should be logged in finer
                    logger.info(sb.toString());

                    messageProcessor.processMessage(message);

                } catch (ShutdownSignalException e) {
                    logger.finest(MessageServerClientRabbitMq.this.sourceName
                            + ": the message server is shutting down.");
                    break;

                } catch (ConsumerCancelledException e) {
                    logger.fine(getName() + " stops listening to new messages.");
                    break;

                } catch (InterruptedException e) {
                    logger.finest(Utils.writeException(e));
                    break;

                } catch (ClassNotFoundException e) {
                    logger.severe(MessageServerClientRabbitMq.this.sourceName
                            + ": a message could not be deserialized. Class cast exception.");
                    logger.finest(Utils.writeException(e));

                } catch (IOException e) {
                    logger.severe(MessageServerClientRabbitMq.this.sourceName
                            + ": a message could not be deserialized. I/O exception.");
                    logger.finest(Utils.writeException(e));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

    }.start();
}

From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMq.java

License:Apache License

@Override
public void cleanAllMessagingServerArtifacts() throws IOException {

    if (this.connected)
        throw new IOException("This instance is already connected to the messaging server.");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.messageServerIp);
    Connection connection = factory.newConnection();
    Channel channel = this.connection.createChannel();

    channel.exchangeDelete(getExchangeName(true));
    channel.exchangeDelete(getExchangeName(false));

    channel.close();/*  w  ww  .  java  2 s.co m*/
    connection.close();
}

From source file:net.roboconf.messaging.internal.client.MessageServerClientRabbitMqTest.java

License:Apache License

/**
 * A method to check whether RabbitMQ is running or not.
 * <p>//from  w ww  . jav  a2  s.  c  o m
 * If it is not running, tests in this class will be skipped.
 * </p>
 */
@Before
public void checkRabbitMQIsRunning() throws Exception {

    Assume.assumeTrue(this.running);
    Connection connection = null;
    Channel channel = null;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(MESSAGE_SERVER_IP);
        connection = factory.newConnection();
        channel = connection.createChannel();

    } catch (Exception e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.warning("Tests are skipped because RabbitMQ is not running.");
        logger.finest(Utils.writeException(e));

        this.running = false;
        Assume.assumeNoException(e);

    } finally {
        if (channel != null)
            channel.close();

        if (connection != null)
            connection.close();
    }
}

From source file:net.roboconf.messaging.internal.client.rabbitmq.AgentClient.java

License:Apache License

@Override
public void openConnection(AbstractMessageProcessor messageProcessor) throws IOException {

    // Already connected? Do nothing
    this.logger.fine("Agent " + this.rootInstanceName + " is opening a connection to RabbitMQ.");
    if (this.channel != null) {
        this.logger.info("Agent " + this.rootInstanceName + " has already a connection to RabbitMQ.");
        return;/*from   w  ww .  j  av a2  s  .  c o m*/
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername,
            this.messageServerPassword);
    this.channel = factory.newConnection().createChannel();

    // Store the message processor for later
    this.messageProcessor = messageProcessor;
    this.messageProcessor.start();

    // We start listening the queue here
    // We declare both exchanges.
    // This is for cases where the agent would try to contact the DM
    // before the DM was started. In such cases, the RabbitMQ client
    // will get an error. This error will in turn close the channel and it
    // won't be usable anymore.
    RabbitMqUtils.declareApplicationExchanges(this.applicationName, this.channel);
    // This is really important.

    // Queue declaration is idem-potent
    String queueName = getQueueName();
    this.channel.queueDeclare(queueName, true, false, true, null);

    // Start to listen to the queue
    final QueueingConsumer consumer = new QueueingConsumer(this.channel);
    this.consumerTag = this.channel.basicConsume(queueName, true, consumer);

    new Thread("Roboconf - Queue listener for Agent " + this.rootInstanceName) {
        @Override
        public void run() {
            RabbitMqUtils.listenToRabbitMq(AgentClient.this.rootInstanceName, AgentClient.this.logger, consumer,
                    AgentClient.this.messageProcessor);
        };

    }.start();
}

From source file:net.roboconf.messaging.internal.client.rabbitmq.DmClient.java

License:Apache License

@Override
public void openConnection(AbstractMessageProcessor messageProcessor) throws IOException {

    // Already connected? Do nothing
    this.logger.fine("The DM is opening a connection to RabbitMQ.");
    if (isConnected()) {
        this.logger.info("The DM has already a connection to RabbitMQ.");
        return;//from w w  w .j  a va 2  s  .c  o  m
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.username, this.password);
    this.channel = factory.newConnection().createChannel();

    // Be notified when a message does not arrive in a queue (i.e. nobody is listening)
    this.channel.addReturnListener(new ReturnListener() {
        @Override
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                BasicProperties properties, byte[] body) throws IOException {

            String messageType = "undetermined";
            try {
                Message msg = SerializationUtils.deserializeObject(body);
                messageType = msg.getClass().getName();

            } catch (ClassNotFoundException e) {
                DmClient.this.logger.severe("Failed to deserialize a message object.");
                DmClient.this.logger.finest(Utils.writeException(e));
            }

            StringBuilder sb = new StringBuilder();
            sb.append("A message sent by the DM was not received by any agent queue.");
            sb.append("\nMessage type: " + messageType);
            sb.append("\nRouting key: " + routingKey);
            sb.append("\nReason: " + replyText);

            DmClient.this.logger.warning(sb.toString());
        }
    });

    // Store the message processor for later
    this.messageProcessor = messageProcessor;
    this.messageProcessor.start();
}

From source file:net.roboconf.messaging.internal.client.rabbitmq.RabbitMqClientAgent.java

License:Apache License

@Override
public void openConnection() throws IOException {

    // Already connected? Do nothing
    this.logger.info("Agent '" + getAgentId() + "' is opening a connection to RabbitMQ.");
    if (this.channel != null) {
        this.logger.info("Agent '" + getAgentId() + "' has already a connection to RabbitMQ.");
        return;/*from w  w  w .  ja  va2s  .c  o m*/
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername,
            this.messageServerPassword);
    this.channel = factory.newConnection().createChannel();
    this.logger.info("Agent '" + getAgentId() + "' established a new connection with RabbitMQ. Channel # "
            + this.channel.getChannelNumber());

    // We start listening the queue here
    // We declare both exchanges.
    // This is for cases where the agent would try to contact the DM
    // before the DM was started. In such cases, the RabbitMQ client
    // will get an error. This error will in turn close the channel and it
    // won't be usable anymore.
    RabbitMqUtils.declareApplicationExchanges(this.applicationName, this.channel);
    // This is really important.

    // Queue declaration is idem-potent
    String queueName = getQueueName();
    this.channel.queueDeclare(queueName, true, false, true, null);

    // Start to listen to the queue
    final QueueingConsumer consumer = new QueueingConsumer(this.channel);
    this.consumerTag = this.channel.basicConsume(queueName, true, consumer);

    String threadName = "Roboconf - Queue listener for Agent " + this.rootInstanceName;
    String id = "Agent '" + getAgentId() + "'";
    new ListeningThread(threadName, this.logger, consumer, this.messageQueue, id).start();
}

From source file:net.roboconf.messaging.internal.client.rabbitmq.RabbitMqClientDm.java

License:Apache License

@Override
public void openConnection() throws IOException {

    // Already connected? Do nothing
    this.logger.info("The DM is opening a connection to RabbitMQ.");
    if (isConnected()) {
        this.logger.info("The DM has already a connection to RabbitMQ.");
        return;/*from   ww  w. j  a  v  a 2  s .c o m*/
    }

    // Initialize the connection
    ConnectionFactory factory = new ConnectionFactory();
    RabbitMqUtils.configureFactory(factory, this.messageServerIp, this.messageServerUsername,
            this.messageServerPassword);
    this.channel = factory.newConnection().createChannel();
    this.logger.info(
            "The DM established a new connection with RabbitMQ. Channel # " + this.channel.getChannelNumber());

    // Be notified when a message does not arrive in a queue (i.e. nobody is listening)
    this.channel.addReturnListener(new DmReturnListener());

    // Declare the DM debug-dedicated queue.
    this.channel.queueDeclare(DM_NEUTRAL_QUEUE_NAME, true, false, true, null);

    // Start listening to messages.
    this.consumer = new QueueingConsumer(this.channel);
    String threadName = "Roboconf - Queue listener for the DM";
    String id = "The DM";
    new ListeningThread(threadName, this.logger, this.consumer, this.messageQueue, id).start();
}

From source file:net.roboconf.messaging.internal.RabbitMqTestUtils.java

License:Apache License

/**
 * Creates a channel to interact with a RabbitMQ server for tests.
 * @return a non-null channel/*from w  w w.  j  av  a2 s. c  om*/
 * @throws IOException if the creation failed
 */
public static Channel createTestChannel() throws IOException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(MESSAGE_SERVER_IP);
    Channel channel = factory.newConnection().createChannel();

    return channel;
}

From source file:net.roboconf.messaging.internal.utils.RabbitMqUtilsTest.java

License:Apache License

@Test
public void testConfigureFactory() throws Exception {

    String address = "http://roboconf.net/some/path";
    int port = 18547;
    String username = "toto";
    String password = "123456789";

    ConnectionFactory factory = new ConnectionFactory();
    Assert.assertNotSame(address, factory.getHost());
    Assert.assertNotSame(port, factory.getPort());

    RabbitMqUtils.configureFactory(factory, "http://roboconf.net:" + port + "/some/path", username, password);
    Assert.assertEquals(address, factory.getHost());
    Assert.assertEquals(port, factory.getPort());
    Assert.assertEquals(username, factory.getUsername());
    Assert.assertEquals(password, factory.getPassword());
}