Example usage for com.rabbitmq.client ConnectionFactory setUri

List of usage examples for com.rabbitmq.client ConnectionFactory setUri

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory setUri.

Prototype

public void setUri(String uriString)
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException 

Source Link

Document

Convenience method for setting the fields in an AMQP URI: host, port, username, password and virtual host.

Usage

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance.//from   w ww .  ja  va 2s .  c  o m
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:coyote.dx.reader.RabbitReader.java

License:Open Source License

/**
 * @see coyote.dx.reader.AbstractFrameReader#open(coyote.dx.context.TransformContext)
 *///from   w  ww .  jav  a2  s .  c o  m
@Override
public void open(TransformContext context) {
    super.open(context);

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(prefetchCount);
        channel.queueDeclare(getQueueName(), DURABLE, PUBLIC, KEEP, NO_ARGUMENTS);
    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

From source file:coyote.dx.writer.RabbitWriter.java

License:Open Source License

/**
 * @see coyote.dx.writer.AbstractFrameFileWriter#open(coyote.dx.context.TransformContext)
 *///  ww w. jav  a2  s.co  m
@Override
public void open(TransformContext context) {
    super.open(context);

    String format = getFormat();
    if (StringUtil.isNotBlank(format)) {
        if (format.equalsIgnoreCase(JSON) || format.equalsIgnoreCase(XML)) {
            String encoding = getEncoding();
            try {
                "Testing".getBytes(encoding);
            } catch (final java.io.UnsupportedEncodingException e) {
                Log.error("Unsupported string encoding of '" + encoding + "'");
                getContext().setError("Unsupported string encoding of '" + encoding + "'");
            }
        }
    } else {
        Log.error("Unsupported message format of '" + format
                + "' JSON, XML, and Binary are the currently supported options");
        getContext().setError("Unsupported message format of '" + format + "'");
    }

    ConnectionFactory factory = new ConnectionFactory();

    try {
        factory.setUri(getBrokerURI());
        if (useSSL()) {
            factory.useSslProtocol();
        }

        String username = getUsername();
        if (StringUtil.isNotBlank(username)) {
            factory.setUsername(username);
            factory.setPassword(getPassword());
        }

        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(getQueueName(), true, false, false, null);

    } catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | IOException
            | TimeoutException | ShutdownSignalException | ConsumerCancelledException e) {
        Log.error(e.getClass().getSimpleName() + ":" + e.getMessage() + "\n" + ExceptionUtil.stackTrace(e));
        getContext().setError("Could not open " + getClass().getSimpleName() + ": " + e.getMessage());
    }

}

From source file:coyote.mq.AbstractMessagingTest.java

License:Open Source License

public void sendMessage(String queueName, DataFrame message) {
    if (StringUtil.isNotBlank(queueName) && message != null) {
        byte[] data = message.getBytes();
        try {/*from   w  w  w  .j  a  v  a 2s .co  m*/
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUri(broker.getBrokerUri());
            factory.useSslProtocol();
            // username:password should be in the URI for our tests
            try (Connection connection = factory.newConnection()) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, false, false, false, null);
                channel.basicPublish("", queueName, null, data);
                Log.debug("Sent " + data.length + " bytes to '" + queueName + "'");
            }
        } catch (Exception e) {
            Log.error("Could not send message: " + e.getClass().getSimpleName() + "-" + e.getMessage());
        }
    }
}

From source file:edu.iu.messaging.service.core.impl.RabbitMQPublisher.java

License:Apache License

private void connect() {
    try {//  www. ja va 2s.  c o m
        logger.info("connect() -> Connecting to server");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });

        channel = connection.createChannel();

        /*
        Not required for work queue implementation
         */
        //channel.basicQos(properties.getPrefetchCount());
        //channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true);

    } catch (Exception e) {
        logger.error("connect() -> Error connecting to server.", e);
    }

}

From source file:edu.iu.messaging.service.core.impl.RabbitMQSubscriber.java

License:Apache License

private void createConnection() {
    try {/*from  w  w w  .ja  va 2s .  co m*/
        logger.info("createConnection() -> Connecting to server");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        addShutdownListener();
        channel = connection.createChannel();

        /*
        Not required for work queue implementation
         */
        //channel.basicQos(Constants.PREFETCH_COUT);
        //channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true);

    } catch (Exception e) {
        logger.error("createConnection() -> Error connecting to server.", e);
    }
}

From source file:flink.streamer.CustomRMQSource.java

License:Apache License

/**
 * Initializes the connection to RMQ.//from www .jav a 2s  .  co m
 */
private void initializeConnection() {
    ConnectionFactory factory = setupConnectionFactory();
    try {
        factory.setUri(uri);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, true, false, false, null);
        consumer = new QueueingConsumer(channel);

        RuntimeContext runtimeContext = getRuntimeContext();
        if (runtimeContext instanceof StreamingRuntimeContext
                && ((StreamingRuntimeContext) runtimeContext).isCheckpointingEnabled()) {
            autoAck = false;
            // enables transaction mode
            channel.txSelect();
        } else {
            autoAck = true;
        }

        LOG.debug("Starting RabbitMQ source with autoAck status: " + autoAck);
        channel.basicConsume(queueName, autoAck, consumer);

    } catch (IOException e) {
        throw new RuntimeException("Cannot create RMQ connection with " + queueName + " at " + uri, e);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:io.bootique.rabbitmq.client.connection.URIConnectionConfig.java

License:Apache License

@Override
protected ConnectionFactory createConnectionFactory() {
    ConnectionFactory factory = new ConnectionFactory();
    try {/*from w  w w.j  a  v a2  s  .c  om*/
        factory.setUri(uri);
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize RabbitMQ URI connection factory", e);
    }
    return factory;
}

From source file:io.github.mattcarrier.metrics.transport.rabbit.RabbitMQRule.java

License:Apache License

@Override
protected void before() throws Throwable {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(connectionUri);
    conn = factory.newConnection();/*from w  ww  . j  a  v  a  2 s . com*/
    channel = conn.createChannel();

    // create the queue and register the consumer
    channel.queueDeclare(QUEUE_NAME, false, false, true, null);
    channel.basicConsume(QUEUE_NAME, true, "metrics-rabbit-consumer", new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            if (!isExpecting || !QUEUE_NAME.equals(envelope.getRoutingKey())) {
                return;
            }

            messages.add(body);
            if (messages.size() == expected) {
                isExpecting = false;
            }
        }
    });
}

From source file:itinno.example.ExampleRabbitmqClient.java

public static void main(String[] args) {
    Logger logger = null;/*from  w ww . j  av  a2s  .c  o  m*/
    String patternLayout = "%5p %d{yyyy-MM-dd HH:mm:ss,sss} %file %t %L: %m%n";

    try {
        // Initialise logger context and logger pattern encoder
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();

        // Set logging pattern (UTF-8 log)
        // logging patterns defined at http://logback.qos.ch/manual/layouts.html
        patternLayoutEncoder.setPattern(patternLayout);
        patternLayoutEncoder.setContext(loggerContext);
        patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
        patternLayoutEncoder.start();

        // log to console
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
        appender.setContext(loggerContext);
        appender.setEncoder(patternLayoutEncoder);
        appender.start();

        // Finally setup the logger itself
        logger = (Logger) LoggerFactory.getLogger(ExampleRabbitmqClient.class.getName());
        logger.addAppender(appender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    /*try {
    VisualIndexer.init("/home/kandreadou/webservice/learning_files/","127.0.0.1",LoggerFactory.getLogger(ExampleRabbitmqClient.class));
    VisualIndexer v = new VisualIndexer("simtest");
    v.index("http://resources0.news.com.au/images/2012/08/16/1226451/587056-120816-obama.jpg","obama1");
    } catch (Exception ex) {
    System.out.println(ex);
    }*/

    logger.info("rabitmq client started");

    // send a UTF-8 encoded JSON tweet to the RabbitMQ (for stormspout to pick up and send to bolt)
    try {
        // check args
        /*if ( args.length < 1 ) {
        logger.error( "Usage: example_rabbitmq_client <JSON_filename>" );
        System.exit( 1 );
        }
        logger.info( "JSON file = " + args[0] );*/
        String strJSONFilePath = "/home/kandreadou/mklab/example-tweet-utf8.json";

        // check if the path to JSON file exists
        File fileJSON = new File(strJSONFilePath);

        System.out.println(fileJSON.getAbsolutePath());

        if (fileJSON.exists() == false) {
            logger.info("JSON file does not exist : " + strJSONFilePath);
            logger.info("Usage: example_rabbitmq_client <JSON_filename>");
            System.exit(1);
        }

        // read UTF-8 JSON text from file
        logger.info("ExampleRabbitmqClient started");

        List<String> lines = Files.readAllLines(Paths.get(strJSONFilePath), Charset.forName("UTF-8"));
        String strJSON = "";
        for (String line : lines) {
            if (line.length() > 0) {
                strJSON = strJSON + "\n";
            }
            strJSON = strJSON + line;
        }
        logger.info("JSON test message = " + strJSON);

        // connect to rabbitmq broker
        // first of all create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri("amqp://guest:guest@localhost:5672/%2F");
        long timestampSinceEpoch = System.currentTimeMillis() / 1000;

        // initialise connection and define channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // initialise amqp basic peoperties object
        BasicProperties.Builder basicProperties = new BasicProperties.Builder();
        basicProperties.build();
        basicProperties.timestamp(new Date(timestampSinceEpoch)).build();
        basicProperties.contentType("text/json").build();
        basicProperties.deliveryMode(1).build();

        // publish message
        /* Exchange name should be {assessment_id}+ "_exchange" */
        channel.basicPublish("indexing_exchange", "test-routing", basicProperties.build(),
                strJSON.getBytes("UTF-8"));

        // close connection and channel
        channel.close();
        connection.close();

        logger.info("ExampleRabbitmqClient finished");

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        System.exit(1);
    }
}