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:com.frannciscocabral.ufs.rabbitmq.Receiver.java

public static void main(String[] argv)
        throws java.io.IOException, java.lang.InterruptedException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override/* w w w . j ava2s  . c  o  m*/
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        }
    };
    channel.basicConsume(QUEUE_NAME, true, consumer);
}

From source file:com.frannciscocabral.ufs.rabbitmq.Send.java

public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from  w w  w .j a  va2 s  . c om*/
    connection.close();
}

From source file:com.gdp.rabbitmq.bench.SharedConnectionPublisherBench.java

public SharedConnectionPublisherBench() {
    try {/*  www  .j  a  v a 2 s.c  o  m*/
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        connection = factory.newConnection();

    } catch (IOException ex) {
        Logger.getLogger(SharedConnectionBench.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.gdp.rabbitmq.task.consumer.ext.ManualAckConsumer.java

public ManualAckConsumer() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
}

From source file:com.gdp.rabbitmq.task.publsher.ext.HandshakePublisher.java

public HandshakePublisher() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("127.0.0.1");
    connection = factory.newConnection();
    channel = connection.createChannel();
    persistence = true;/*from   w  w w . j  ava2  s .c om*/
}

From source file:com.gdp.rabbitmq.task.publsher.ext.HandshakePublisher.java

@Override
protected void execute() {
    try {//w  w  w.  j  a  v a2s .co  m
        channel.confirmSelect();
        publish(Utility.GenerateRandomTask());
        channel.waitForConfirmsOrDie();
        channel.close();
        connection.close();
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        connection = factory.newConnection();
        channel = connection.createChannel();
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    } catch (InterruptedException ex) {
        Logger.getLogger(HandshakePublisher.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMain.java

public static void main(String[] args) {

    //activate logging level if it is DEBUG, default is INFO so no need for any
    //action if it is otherwise
    Injector propInjector = Guice.createInjector(new GeminiPropertiesModule());
    GeminiProperties properties = propInjector.getInstance(GeminiProperties.class);
    if (properties.getProperties().getProperty("LOGGING_LEVEL").equals("DEBUG")) {
        Configurator.defaultConfig().level(Level.DEBUG).activate();
    }/*  w ww. j  a v  a 2  s .  c o  m*/

    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //the app.yml to deployment.yml converter
    Thread yamlConverterThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("YAML_MAPPER_TOPIC"));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: YAML Mapper - could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Fatal Error: YAML Mapper - could not retrieve message. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            Integer status = 0;
            if (routingKey.equals(properties.getProperties().getProperty("YAML_MAPPER_MAP_APP"))) {
                status = mapApptoDeployment(jsonBody);
            } else {
                continue;
            }

            if (status == 0) {
                try {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                } catch (IOException ex) {
                    Logger.error("Could not ack message. Exception: {}", ex);
                }
            } else {
                //failed so requeue the message
                try {
                    channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
                } catch (IOException ex) {
                    Logger.error("Could not nack message. Exception: {}", ex);
                }
            }
        }
    });
    yamlConverterThread.start();

    //the networking message recevier
    Thread networkingThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("NETWORK_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);

                //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_CREATE"))) {
                createNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_UPDATE"))) {
                updateNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("NETWORK_TASK_DELETE"))) {
                deleteNetwork(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_CREATE"))) {
                createSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_UPDATE"))) {
                updateSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SUBNET_TASK_DELETE"))) {
                deleteSubnet(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_CREATE"))) {
                createRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_UPDATE"))) {
                updateRouter(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("ROUTER_TASK_DELETE"))) {
                deleteRouter(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    networkingThread.start();

    //the load balancer 
    Thread lbThread = new Thread(() -> {
    });

    lbThread.start();

    //the security thread
    Thread securityThread = new Thread(() -> {
        //setup the message receiver
        final Connection connection;
        final Channel channel;
        final QueueingConsumer consumer;

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
        String queueName = null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
            queueName = channel.queueDeclare().getQueue();
            channel.queueBind(queueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                    properties.getProperties().getProperty("SECURITY_TOPIC"));
            //                channel.basicQos(Integer.parseUnsignedInt(properties.getProperties().getProperty("PREFETCH_COUNT")));
            consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | NullPointerException | NumberFormatException ex) {
            Logger.error("Fatal Error: could not connect to messaging system. Exception: {}", ex);
            return;
        }

        QueueingConsumer.Delivery delivery = null;
        while (true) {
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
                Logger.error("Could not get message from queue. Exception: {}", ex);
                continue;
            }

            String routingKey = delivery.getEnvelope().getRoutingKey();
            String jsonBody = new String(delivery.getBody());

            //TODO: NEED TO PUT THE MESSAGE BACK IN THE QUEUE IF THERE IS A FAILURE
            if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_CREATE"))) {
                createSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_UPDATE"))) {
                updateSecurityGroup(jsonBody);
            } else if (routingKey.equals(properties.getProperties().getProperty("SECURITY_TASK_SG_DELETE"))) {
                deleteSecurityGroup(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_CREATE"))) {
                createSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_UPDATE"))) {
                updateSecurityGroupRule(jsonBody);
            } else if (routingKey
                    .equals(properties.getProperties().getProperty("SECURITY_TASK_SG_RULE_DELETE"))) {
                deleteSecurityGroupRule(jsonBody);
            }

            try {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (IOException ex) {
                Logger.error("Could not ack message. Exception: {}", ex);
            }
        }
    });
    securityThread.start();
}

From source file:com.gemini.provision.network.main.GeminiNetworkProvisionMainIT.java

@BeforeClass
public static void setUpClass() {
    //load the properties singleton, will be used throughout the tests.
    properties = Guice.createInjector(new GeminiPropertiesModule()).getInstance(GeminiProperties.class);

    //create the mapper in the main class
    //inject the mapper as it will be used in all the threads
    Injector mapperInjector = Guice.createInjector(new GeminiMapperModule());
    mapper = mapperInjector.getInstance(GeminiMapper.class);

    //create the sender
    ConnectionFactory sendMsgFactory = new ConnectionFactory();
    sendMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    try {/*ww  w .j a  va  2s.  c  o  m*/
        sendMsgConnection = sendMsgFactory.newConnection();
        sendMsgChannel = sendMsgConnection.createChannel();
        sendMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
    } catch (IOException ex) {
        Logger.error("Fatal Error: Sender unable to connect to messaging system. Exception: {}", ex);
        fail("Unable to connect to messaging system");
    }

    //create the network receiver
    ConnectionFactory recvNetMsgFactory = new ConnectionFactory();
    recvNetMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    String netQueueName = null;
    try {
        recvNetMsgConnection = recvNetMsgFactory.newConnection();
        recvNetMsgChannel = recvNetMsgConnection.createChannel();
        recvNetMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
        netQueueName = recvNetMsgChannel.queueDeclare().getQueue();
        recvNetMsgChannel.queueBind(netQueueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                properties.getProperties().getProperty("NETWORK_TOPIC"));
        recvNetMsgconsumer = new QueueingConsumer(recvNetMsgChannel);
        recvNetMsgChannel.basicConsume(netQueueName, true, recvNetMsgconsumer);
    } catch (IOException | NullPointerException | NumberFormatException ex) {
        Logger.error("Fatal Error: Network receiver could not connect to messaging system. Exception: {}", ex);
        fail("Fatal Error: Receiver could not connect to messaging system.");
    }

    //create the network receiver
    ConnectionFactory recvSecMsgFactory = new ConnectionFactory();
    recvSecMsgFactory.setHost(properties.getProperties().getProperty("MESSAGING_HOST"));
    String secQueueName = null;
    try {
        recvSecMsgConnection = recvSecMsgFactory.newConnection();
        recvSecMsgChannel = recvSecMsgConnection.createChannel();
        recvSecMsgChannel.exchangeDeclare(properties.getProperties().getProperty("EXCHANGE_NAME"), "topic");
        secQueueName = recvSecMsgChannel.queueDeclare().getQueue();
        recvSecMsgChannel.queueBind(secQueueName, properties.getProperties().getProperty("EXCHANGE_NAME"),
                properties.getProperties().getProperty("SECURITY_TOPIC"));
        recvSecMsgconsumer = new QueueingConsumer(recvSecMsgChannel);
        recvSecMsgChannel.basicConsume(secQueueName, true, recvNetMsgconsumer);
    } catch (IOException | NullPointerException | NumberFormatException ex) {
        Logger.error("Fatal Error: Security receiver could not connect to messaging system. Exception: {}", ex);
        fail("Fatal Error: Receiver could not connect to messaging system.");
    }
}

From source file:com.github.cc007.lightsaver.message.rabbitmq.RMQMessageSender.java

public RMQMessageSender(String serverAddress) {
    try {//from   w  w  w . j a v a  2  s  .co  m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(serverAddress);
        this.con = factory.newConnection();
        this.ch = con.createChannel();
        this.ch.queueDeclare(RMQMessageReceiver.QUEUE_NAME, false, false, false, null);
        this.send = true;
        this.exit = false;
    } catch (IOException ex) {
        Logger.getLogger(RMQMessageSender.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.github.dann.wspusher.pubsub.publisher.impl.RabbitMQPublisherImpl.java

License:Apache License

public void publish(String exchange, String message) {
    Connection connection = null;
    Channel channel = null;/* w w w  .  ja v a 2 s.c om*/
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(WsConfig.getMQServerHost());
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(exchange, EXCHANGE_TYPE);
        channel.basicPublish(exchange, "", null, message.getBytes(WsConstants.ENCODING_UTF8));

    } catch (Exception e) {
        logger.error("Publishing message faile", e);
        throw new WsRuntimeException("Publishig message failed", e);
    } finally {
        RabbitMQResourceUtils.closeQuietly(channel);
        RabbitMQResourceUtils.closeQuietly(connection);
    }

}