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.googlesource.gerrit.plugins.rabbitmq.AMQPSession.java

License:Apache License

public void connect() {
    LOGGER.info("Connect to {}...", properties.getString(Keys.AMQP_URI));
    ConnectionFactory factory = new ConnectionFactory();
    try {//from   w ww  .j  a v  a2s . c o  m
        if (StringUtils.isNotEmpty(properties.getString(Keys.AMQP_URI))) {
            factory.setUri(properties.getString(Keys.AMQP_URI));
            if (StringUtils.isNotEmpty(properties.getString(Keys.AMQP_USERNAME))) {
                factory.setUsername(properties.getString(Keys.AMQP_USERNAME));
            }
            if (StringUtils.isNotEmpty(properties.getString(Keys.AMQP_PASSWORD))) {
                factory.setPassword(properties.getString(Keys.AMQP_PASSWORD));
            }
            connection = factory.newConnection();
            connection.addShutdownListener(this);
            LOGGER.info("Connection established.");
        }
        //TODO: Consume review
        // setupConsumer();
    } catch (URISyntaxException ex) {
        LOGGER.error("URI syntax error: {}", properties.getString(Keys.AMQP_URI));
    } catch (IOException ex) {
        LOGGER.error("Connection cannot be opened.");
    } catch (Exception ex) {
        LOGGER.warn("Connection has something error. it will be disposed.", ex);
    }
}

From source file:com.googlesource.gerrit.plugins.rabbitmq.session.type.AMQPSession.java

License:Apache License

@Override
public void connect() {
    if (connection != null && connection.isOpen()) {
        LOGGER.info(MSG("Already connected."));
        return;/*  w w w.ja  v  a 2  s .  c  om*/
    }
    AMQP amqp = properties.getSection(AMQP.class);
    LOGGER.info(MSG("Connect to {}..."), amqp.uri);
    ConnectionFactory factory = new ConnectionFactory();
    try {
        if (StringUtils.isNotEmpty(amqp.uri)) {
            factory.setUri(amqp.uri);
            if (StringUtils.isNotEmpty(amqp.username)) {
                factory.setUsername(amqp.username);
            }
            Gerrit gerrit = properties.getSection(Gerrit.class);
            String securePassword = gerrit.getAMQPUserPassword(amqp.username);
            if (StringUtils.isNotEmpty(securePassword)) {
                factory.setPassword(securePassword);
            } else if (StringUtils.isNotEmpty(amqp.password)) {
                factory.setPassword(amqp.password);
            }
            connection = factory.newConnection();
            connection.addShutdownListener(connectionListener);
            LOGGER.info(MSG("Connection established."));
        }
    } catch (URISyntaxException ex) {
        LOGGER.error(MSG("URI syntax error: {}"), amqp.uri);
    } catch (IOException ex) {
        LOGGER.error(MSG("Connection cannot be opened."), ex);
    } catch (KeyManagementException | NoSuchAlgorithmException ex) {
        LOGGER.error(MSG("Security error when opening connection."), ex);
    }
}

From source file:com.groupx.recipientlist.test.RecipientList.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.exchangeDeclare(EXCHANGE_NAME, "fanout");

    String message = getMessage(argv);

    channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();/*from  www .j  av  a2 s . c  om*/
    connection.close();
}

From source file:com.groupx.recipientlist.test.TranslatorMock.java

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

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    System.out.println(" [*] Waiting for messages. To exit press X+ENTER");

    Consumer consumer = new DefaultConsumer(channel) {
        @Override//www  . j a  va2 s  .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(queueName, true, consumer);
    try {
        Scanner in = new Scanner(System.in);
        String input = in.next();
        if ("x".equals(input)) {
            System.exit(0);
        }
    } catch (Exception e) {

    }
}

From source file:com.hopped.runner.rabbitmq.RPCClient.java

License:Open Source License

/**
 * @param requestQueueName/*from ww  w  . j  a  v a2s.  c om*/
 * @throws Exception
 */
public RPCClient(String requestQueueName) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    this.requestQueueName = requestQueueName;
    connection = factory.newConnection();
    channel = connection.createChannel();

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

From source file:com.hopped.running.demo.RunServer.java

License:Open Source License

/**
 * //  w  ww .java 2s  .  c om
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final String queueName = "runningRabbit";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.basicQos(1);
    channel.queueDeclare(queueName, false, false, false, null);

    ProtobufRPCServer server = new ProtobufRPCServer(channel, queueName).init()
            .setInstance(new RunnerServiceImpl()).setProtocol(IRunnerService.class);
    server.consume();
}

From source file:com.hp.ov.sdk.messaging.msmb.services.MsmbConnectionManager.java

License:Apache License

public void startMsmb(final RestParams params) {
    Connection conn = null;//from   w w  w  .j ava 2s.  com
    Channel channel = null;
    // validate args
    if (null == params) {
        throw new SDKInvalidArgumentException(SDKErrorEnum.invalidArgument, null, null, null,
                SdkConstants.APPLIANCE, null);
    }
    // check if connection object already exists in the map
    // msmbConnection = map.get(params.getHostname());
    if (!map.containsKey(params.getHostname())) {
        // get client cert
        final RabbitMqClientCert mqClientCert = messagingCertificate
                .getRabbitMqClientCertificateKeyPair(params);
        // get CA cert
        CaCert caCert = messagingCertificate.getCACertificate(params);
        // get SSLContext
        SSLContext sslContext = CertificateStoreManager.getSslContext(mqClientCert, caCert);
        ConnectionFactory connectionFactory = RabbitMqClientConnectionFactory.getConnectionFactory(sslContext,
                params);
        connectionFactory.setConnectionTimeout(1000);

        try {
            conn = connectionFactory.newConnection();
            channel = conn.createChannel();
        } catch (final IOException e) {
            throw new SDKResourceNotFoundException(SDKErrorEnum.resourceNotFound, null, null, null,
                    SdkConstants.APPLIANCE, null);
        }
        // put into map
        map.putIfAbsent(params.getHostname(), new MsmbConnection(conn, channel, MsmbState.START));
    }

}

From source file:com.hp.ov.sdk.messaging.scmb.services.ScmbConnectionManager.java

License:Apache License

public void startScmb(final RestParams params) {
    Connection conn = null;/*from   ww w  .jav a2s  .  c o  m*/
    Channel channel = null;
    // validate args
    if (null == params) {
        throw new SDKInvalidArgumentException(SDKErrorEnum.invalidArgument, null, null, null,
                SdkConstants.APPLIANCE, null);
    }
    final String sessionId = params.getSessionId();
    // check if connection object already exists in the map
    // scmbConnection = map.get(params.getHostname());
    if (!map.containsKey(params.getHostname())) {
        // get client cert
        final RabbitMqClientCert mqClientCert = messagingCertificate
                .getRabbitMqClientCertificateKeyPair(params);
        // get CA cert
        CaCert caCert = messagingCertificate.getCACertificate(params);
        // get SSLContext
        SSLContext sslContext = CertificateStoreManager.getSslContext(mqClientCert, caCert);
        ConnectionFactory connectionFactory = RabbitMqClientConnectionFactory.getConnectionFactory(sslContext,
                params);
        connectionFactory.setConnectionTimeout(1000);
        try {
            conn = connectionFactory.newConnection();
            channel = conn.createChannel();

        } catch (final IOException e) {
            LOGGER.error("ScmbConnectionManager : startScmb: IOException");
            throw new SDKScmbConnectionNotFoundException(SDKErrorEnum.scmbConnectionNotFound, null, null, null,
                    SdkConstants.SCMB_CONNECTION, null);
        }

        // put into map
        map.putIfAbsent(params.getHostname(), new ScmbConnection(conn, channel, ScmbState.START));
    }

}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static String sendConfig1(String who, String config) throws Exception {

    /* calling connectionFactory to create a custome connexion with
    * rabbitMQ server information./* w ww  .j a v  a 2s  .c  o m*/
    */
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);
    System.out.println("connection ok");
    // establish the connection with RabbitMQ server using our factory.
    Connection connection = factory.newConnection();
    // System.out.println("connection ok1");
    // We're connected now, to the broker on the cloud machine.
    // If we wanted to connect to a broker on a the local machine we'd simply specify "localhost" as IP adresse.
    // creating a "configuration" direct channel/queue
    Channel channel = connection.createChannel();
    //  System.out.println("connection ok2");
    channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    //  System.out.println("exchangeDeclare");
    // the message and the distination
    String forWho = who;
    String message = config;

    // publish the message
    channel.basicPublish(EXCHANGE_NAME, forWho, null, message.getBytes());
    //  System.out.println("basicPublish");
    // close the queue and the connexion
    channel.close();
    connection.close();
    return " [x] Sent '" + forWho + "':'" + message + "'";
}

From source file:com.insa.tp3g1.esbsimulator.view.MessageHandler.java

public static void logGetter() throws java.io.IOException {
    ConnectionFactory factory = new ConnectionFactory();
    LogHandler logHandler = new LogHandler();
    factory.setHost("146.148.27.98");
    factory.setUsername("admin");
    factory.setPassword("adminadmin");
    factory.setPort(5672);//from  w  w  w  .j a v a  2s .c om

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

    channel.exchangeDeclare(LOG_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, LOG_NAME, "");

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);
    count = 0;
    boolean over = false;
    while (!over) {

        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            //System.out.println(" [x] Received '" + message + "'");
            synchronized (count) {
                count++;
            }
            logHandler.add(message);
            System.out.print(Thread.currentThread().getId() + " ");

        } catch (InterruptedException interruptedException) {
            System.out.println("finished");
            System.out.println(logHandler);

            System.out.println(logHandler);
            Thread.currentThread().interrupt();
            System.out.println(Thread.currentThread().getId() + " ");
            break;
            // Thread.currentThread().stop();
            // over = true;
        } catch (ShutdownSignalException shutdownSignalException) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        } catch (ConsumerCancelledException consumerCancelledException) {
            System.out.println("finished");
            //  Thread.currentThread().stop();
            over = true;
        } catch (IllegalMonitorStateException e) {
            System.out.println("finished");
            // Thread.currentThread().stop();
            over = true;
        }

    }
    System.out.println("before close");
    channel.close();
    connection.close();
    System.out.println("finished handling");
    Result res = logHandler.fillInResultForm(logHandler.getTheLog());
    ResultHandler resH = new ResultHandler(res);
    resH.createResultFile("/home/alpha/alphaalpha.xml");
    final OverlaidBarChart demo = new OverlaidBarChart("Response Time Chart", res);
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
    int lost = Integer.parseInt(res.getTotalResult().getLostRequests()) / logHandler.getNbRequests();
    PieChart demo1 = new PieChart("Messages", lost * 100);
    demo1.pack();
    demo1.setVisible(true);
    //System.out.println(logHandler);

}