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.sitewhere.rabbitmq.RabbitMqOutboundEventProcessor.java

License:Open Source License

@Override
public void start() throws SiteWhereException {
    super.start();
    try {/*ww  w.j a va2 s.co m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(getConnectionUri());
        this.connection = factory.newConnection();
        this.channel = connection.createChannel();
        this.exchange = getTenant().getId() + DEFAULT_EXCHANGE_SUFFIX;
        channel.exchangeDeclare(exchange, "topic");
        LOGGER.info("RabbitMQ outbound processor connected to: " + getConnectionUri());
    } catch (Exception e) {
        throw new SiteWhereException("Unable to start RabbitMQ event processor.", e);
    }
}

From source file:com.sitewhere.sources.ActiveMQTests.java

License:Open Source License

@Test
public void doRabbitMQTest() throws Exception {
    String exchangeName = "sitewhere";
    String queueName = "sitewhere.input";
    String routingKey = "sitewhere";

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://localhost:5672");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = EventsHelper.generateEncodedMeasurementsMessage(HARDWARE_ID);
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

    channel.close();/*ww w.j av a 2  s.c om*/
    connection.close();
}

From source file:com.siva.rabbitmq.AmqpMsgPublisher.java

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setUsername("admin");
    factory.setPassword("welcome01");
    factory.setPort(5672);//w  w w  . j a va2 s. c o m
    factory.setVirtualHost("/admin_vhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "topic", true);

    String routingKey = "mqtt_topic.iot.admin_vhost";
    String message = "Test Message from IoT";

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

    connection.close();
}

From source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

License:Open Source License

/**
 * Tests connection to the server URI.//  w w w .  ja  v  a2  s  .  c  o  m
 *
 * @param uri the URI.
 * @param name the user name.
 * @param pw the user password.
 * @return FormValidation object that indicates ok or error.
 * @throws javax.servlet.ServletException Exception for servlet.
 */
public FormValidation doTestConnection(@QueryParameter(SERVER_URI) final String uri,
        @QueryParameter(USERNAME) final String name, @QueryParameter(PASSWORD) final Secret pw)
        throws ServletException {
    UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
    FormValidation result = FormValidation.ok();
    if (urlValidator.isValid(uri)) {
        try {
            ConnectionFactory conn = new ConnectionFactory();
            conn.setUri(uri);
            if (StringUtils.isNotEmpty(name)) {
                conn.setUsername(name);
                if (StringUtils.isNotEmpty(Secret.toString(pw))) {
                    conn.setPassword(Secret.toString(pw));
                }
            }
            conn.newConnection();
        } catch (URISyntaxException e) {
            result = FormValidation.error("Invalid Uri");
        } catch (PossibleAuthenticationFailureException e) {
            result = FormValidation.error("Authentication Failure");
        } catch (Exception e) {
            result = FormValidation.error(e.getMessage());
        }
    } else {
        result = FormValidation.error("Invalid Uri");

    }
    return result;
}

From source file:com.streamsets.pipeline.lib.rabbitmq.common.RabbitCxnManager.java

License:Apache License

public void init(BaseRabbitConfigBean conf) throws IOException, TimeoutException {
    ConnectionFactory connectionFactory = RabbitUtil.createConnectionFactory(conf);
    this.connection = connectionFactory.newConnection();
    this.channel = this.connection.createChannel();
}

From source file:com.surgeplay.visage.master.VisageMaster.java

License:Open Source License

@Override
public void run() {
    try {//from   www . j a v  a2s. c om
        Log.setLog(new LogShim(Visage.log));
        long total = Runtime.getRuntime().totalMemory();
        long max = Runtime.getRuntime().maxMemory();
        if (Visage.debug)
            Visage.log.finer("Current heap size: " + humanReadableByteCount(total, false));
        if (Visage.debug)
            Visage.log.finer("Max heap size: " + humanReadableByteCount(max, false));
        if (total < max) {
            Visage.log.warning(
                    "You have set your minimum heap size (Xms) lower than the maximum heap size (Xmx) - this can cause GC thrashing. It is strongly recommended to set them both to the same value.");
        }
        if (max < (1000 * 1000 * 1000)) {
            Visage.log.warning(
                    "The heap size (Xmx) is less than one gigabyte; it is recommended to run Visage with a gigabyte or more. Use -Xms1G and -Xmx1G to do this.");
        }
        Visage.log.info("Setting up Jetty");
        Server server = new Server(
                new InetSocketAddress(config.getString("http.bind"), config.getInt("http.port")));

        List<String> expose = config.getStringList("expose");
        String poweredBy;
        if (expose.contains("server")) {
            if (expose.contains("version")) {
                poweredBy = "Visage v" + Visage.VERSION;
            } else {
                poweredBy = "Visage";
            }
        } else {
            poweredBy = null;
        }

        ResourceHandler resource = new ResourceHandler();
        resource.setResourceBase(config.getString("http.static"));
        resource.setDirectoriesListed(false);
        resource.setWelcomeFiles(new String[] { "index.html" });
        resource.setHandler(new VisageHandler(this));

        if (!"/dev/null".equals(config.getString("log"))) {
            new File(config.getString("log")).getParentFile().mkdirs();
            server.setRequestLog(new AsyncNCSARequestLog(config.getString("log")));
        }
        GzipHandler gzip = new GzipHandler();
        gzip.setHandler(new HeaderHandler("X-Powered-By", poweredBy, resource));
        server.setHandler(gzip);

        String redisHost = config.getString("redis.host");
        int redisPort = config.getInt("redis.port");
        Visage.log.info("Connecting to Redis at " + redisHost + ":" + redisPort);
        resolverNum = config.getInt("redis.resolver-db");
        skinNum = config.getInt("redis.skin-db");
        JedisPoolConfig jpc = new JedisPoolConfig();
        jpc.setMaxIdle(config.getInt("redis.max-idle-connections"));
        jpc.setMaxTotal(config.getInt("redis.max-total-connections"));
        jpc.setMinIdle(config.getInt("redis.min-idle-connections"));
        if (config.hasPath("redis.password")) {
            password = config.getString("redis.password");
        }
        pool = new JedisPool(jpc, redisHost, redisPort);

        Visage.log.info("Connecting to RabbitMQ at " + config.getString("rabbitmq.host") + ":"
                + config.getInt("rabbitmq.port"));
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(config.getString("rabbitmq.host"));
        factory.setPort(config.getInt("rabbitmq.port"));
        factory.setRequestedHeartbeat(10);
        if (config.hasPath("rabbitmq.user")) {
            factory.setUsername(config.getString("rabbitmq.user"));
            factory.setPassword(config.getString("rabbitmq.password"));
        }
        String queue = config.getString("rabbitmq.queue");

        Closer closer = Closer.create();
        steve = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("steve.png")));
        alex = ByteStreams.toByteArray(closer.register(ClassLoader.getSystemResourceAsStream("alex.png")));
        closer.close();

        conn = factory.newConnection();
        channel = conn.createChannel();
        if (Visage.debug)
            Visage.log.finer("Setting up queue '" + queue + "'");
        channel.queueDeclare(queue, false, false, true, null);
        channel.basicQos(1);

        if (Visage.debug)
            Visage.log.finer("Setting up reply queue");
        replyQueue = channel.queueDeclare().getQueue();
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(replyQueue, consumer);

        if (config.getBoolean("slave.enable")) {
            Visage.log.info("Starting fallback slave");
            fallback = new VisageSlave(
                    config.getConfig("slave").withValue("rabbitmq", config.getValue("rabbitmq")));
            fallback.start();
        }
        Visage.log.info("Starting Jetty");
        server.start();
        Visage.log.info("Listening for finished jobs");
        try {
            while (run) {
                Delivery delivery = consumer.nextDelivery();
                if (Visage.trace)
                    Visage.log.finest("Got delivery");
                try {
                    String corrId = delivery.getProperties().getCorrelationId();
                    if (queuedJobs.containsKey(corrId)) {
                        if (Visage.trace)
                            Visage.log.finest("Valid");
                        responses.put(corrId, delivery.getBody());
                        Runnable run = queuedJobs.get(corrId);
                        queuedJobs.remove(corrId);
                        if (Visage.trace)
                            Visage.log.finest("Removed from queue");
                        run.run();
                        if (Visage.trace)
                            Visage.log.finest("Ran runnable");
                        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                        if (Visage.trace)
                            Visage.log.finest("Ack'd");
                    } else {
                        Visage.log.warning("Unknown correlation ID?");
                        channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
                    }
                } catch (Exception e) {
                    Visage.log.log(Level.WARNING,
                            "An unexpected error occured while attempting to process a response.", e);
                }
            }
        } catch (InterruptedException e) {
        } catch (Exception e) {
            Visage.log.log(Level.SEVERE, "An unexpected error occured in the master run loop.", e);
            System.exit(2);
        }
        try {
            Visage.log.info("Shutting down master");
            server.stop();
            pool.destroy();
            conn.close(5000);
        } catch (Exception e) {
            Visage.log.log(Level.SEVERE, "A fatal error has occurred while shutting down the master.", e);
        }
    } catch (Exception e) {
        Visage.log.log(Level.SEVERE, "An unexpected error occured while initializing the master.", e);
        System.exit(1);
    }
}

From source file:com.trivago.mail.pigeon.queue.ConnectionPool.java

License:Apache License

public static Connection getConnection() {
    if (connection == null) {
        ConnectionFactory factory = new ConnectionFactory();
        Configuration configuration = settings.getConfiguration();

        factory.setUsername(configuration.getString("rabbit.username"));
        factory.setPassword(configuration.getString("rabbit.password"));
        factory.setVirtualHost(configuration.getString("rabbit.vhost"));
        factory.setHost(configuration.getString("rabbit.hostname"));
        factory.setPort(configuration.getInt("rabbit.port"));

        try {/*ww w  .  ja  v  a  2  s  .c o m*/
            connection = factory.newConnection();
        } catch (IOException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
    }
    return connection;
}

From source file:com.UseCaseSimpleConsumer.java

License:Open Source License

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

    try {/*w ww.  j  a  v  a 2s .  c om*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }
    try {
        channel.queueDeclarePassive(ROUTE_KEY);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(ROUTE_KEY, false, false, false, null);
    }

    channel.queueBind(ROUTE_KEY, EXCHANGE_NAME, ROUTE_KEY);

    String param = "IBM";
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + param
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

    channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY,
            new AMQP.BasicProperties.Builder().contentType("text/plain").build(), msg.getBytes());
    System.out.println(" [x] Sent '" + msg + "'");
    channel.close();
    connection.close();
}

From source file:com.UseCaseSimpleProducer.java

License:Open Source License

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

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

    try {/*from   w w  w . j  av  a2  s. c o  m*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
    }
}

From source file:com.vmware.bdd.manager.RuntimeConnectionManager.java

License:Open Source License

/**
 * Setup rabbitMQ exchange and channel to notify VHMs
 * @throws IOException //from  w w w.  j a v  a2s.c om
 */
public void init() throws IOException {
    String serverHost = ConfigInfo.getMqServerHost();
    int serverPort = ConfigInfo.getMqServerPort();
    String serverUsername = ConfigInfo.getMqServerUsername();
    String serverPassword = ConfigInfo.getMqServerPassword();

    logger.info("init runtime exchange");

    ConnectionFactory factory = new ConnectionFactory();
    if (serverUsername != null && !serverUsername.equals("")) {
        factory.setUsername(serverUsername);
        factory.setPassword(serverPassword);
    }
    factory.setVirtualHost("/");
    factory.setHost(serverHost);
    factory.setPort(serverPort);
    try {
        conn = factory.newConnection();
        runtimeChannel = conn.createChannel();

        logger.info("creating exchange: " + exchangeName);
        runtimeChannel.exchangeDeclare(exchangeName, "direct", true, // durable
                false, // auto-delete
                null); // arguments map
    } catch (IOException e) {
        logger.error(e.getMessage());
        destroy();
        throw e;
    }
}