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:org.geoserver.notification.common.sender.RabbitMQSender.java

License:Open Source License

public void initialize() throws Exception {

    if (uri == null) {
        if (this.username != null && !this.username.isEmpty() && this.password != null
                && !this.password.isEmpty()) {
            this.uri = "amqp://" + this.username + ":" + this.password + "@" + this.host + ":" + this.port;
        } else {/*from   w w  w .j  a v a2 s  .c  om*/
            this.uri = "amqp://" + this.host + ":" + this.port;
        }

    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(this.uri);
    String vHost = (this.virtualHost != null && !this.virtualHost.isEmpty() ? this.virtualHost : "/");
    factory.setVirtualHost(vHost);
    factory.setSaslConfig(new CustomSaslConfig());
    conn = factory.newConnection();
    channel = conn.createChannel();
}

From source file:org.geoserver.notification.support.Receiver.java

License:Open Source License

protected ConnectionFactory createConnectionFactory() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(false);
    factory.setUri(BROKER_URI);
    return factory;
}

From source file:org.hp.samples.ProcessMessage.java

License:Open Source License

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setStatus(200);//from  w w w  .  j  a v  a  2  s  .co m
    PrintWriter writer = response.getWriter();
    writer.println("Here's your message:");

    // Pull out the RABBITMQ_URL environment variable
    String uri = System.getenv("RABBITMQ_URL");

    ConnectionFactory factory = new ConnectionFactory();
    try {
        factory.setUri(uri);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

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

    // Create the queue
    channel.queueDeclare("hello", false, false, false, null);

    String routingKey = "thekey";
    String exchangeName = "exchange";

    // Declare an exchange and bind it to the queue
    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueBind("hello", exchangeName, routingKey);

    // Grab the message from the HTML form and publish it to the queue
    String message = request.getParameter("message");
    channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
    writer.println(" Message sent to queue '" + message + "'");

    boolean autoAck = false;

    // Get the response message
    GetResponse responseMsg = channel.basicGet("hello", autoAck);

    if (responseMsg == null) {
        // No message retrieved.
    } else {
        byte[] body = responseMsg.getBody();
        // Since getBody() returns a byte array, convert to a string for
        // the user.
        String bodyString = new String(body);
        long deliveryTag = responseMsg.getEnvelope().getDeliveryTag();

        writer.println("Message received: " + bodyString);

        // Acknowledge that we received the message so that the queue
        // removes the message so that it's not sent to us again.
        channel.basicAck(deliveryTag, false);
    }

    writer.close();
}

From source file:org.hp.samples.RabbitServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setStatus(200);/*from w  w  w .  j av  a  2 s.  com*/

    PrintWriter writer = response.getWriter();

    // Create an HTML form for the user to input a message for the queue
    String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
    writer.println(docType + "<html>" + "<body>" + "<p>RabbitMQ for Java</p>"
            + "<form action='ProcessMessage' method='post'>"
            + "Message to send: <input type='text' name='message'><br>"
            + "<input type='submit' value='Send Message'>" + "</form>" + "</body>" + "</html>");

    String uri = System.getenv("RABBITMQ_URL");

    ConnectionFactory factory = new ConnectionFactory();
    try {
        factory.setUri(uri);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare("hello", false, false, false, null);

    writer.close();
}

From source file:org.onosproject.rabbitmq.impl.MQSender.java

License:Apache License

@Override
public void start() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setNetworkRecoveryInterval(RECOVERY_INTERVAL);
    try {//  ww  w . j  a  v  a  2  s. c  o  m
        factory.setUri(url);
        if (executorService != null) {
            conn = factory.newConnection(executorService);
        } else {
            conn = factory.newConnection();
        }
        channel = conn.createChannel();
        channel.exchangeDeclare(exchangeName, TOPIC, true);
        /*
         * Setting the following parameters to queue
         * durable    - true
         * exclusive  - false
         * autoDelete - false
         * arguments  - null
         */
        channel.queueDeclare(this.queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
}

From source file:org.pascani.dsl.lib.infrastructure.rabbitmq.EndPoint.java

License:Open Source License

/**
 * Creates a RabbitMQ end point; that is, a connection to the RabbitMQ
 * server. This is commonly used by all RabbitMQ consumers and producers.
 * /*from   w w  w .  jav a2 s  .c  om*/
 * @param uri
 *            The RabbitMQ connection URI
 * 
 * @throws Exception
 *             If something bat happens. Check exceptions in
 *             {@link ConnectionFactory#setUri(String)},
 *             {@link ConnectionFactory#newConnection()}, and
 *             {@link Connection#createChannel()}
 */
public EndPoint(final String uri) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setUri(uri);
    this.connection = factory.newConnection();
    this.channel = this.connection.createChannel();
}

From source file:org.sdw.scheduler.QueueProcessor.java

License:Apache License

/**
 * Implementation of the Runnable interface's run method
 * Polls for messages in the shared queue and logs the results on arrival of message
 *//*w w  w  .  ja  v  a2 s.co m*/
@Override
public void run() {
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(System.getenv("CLOUDAMQP_URL"));
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String queueName = "work-queue-1";
        Map<String, Object> params = new HashMap<>();
        params.put("x-ha-policy", "all");
        channel.queueDeclare(queueName, true, false, false, params);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, false, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            if (delivery != null) {
                String msg = new String(delivery.getBody(), "UTF-8");
                LOG.info("Message Received: " + msg);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | KeyManagementException | NoSuchAlgorithmException | URISyntaxException
            | ShutdownSignalException | ConsumerCancelledException | InterruptedException ex) {
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:org.trellisldp.amqp.AmqpPublisher.java

License:Apache License

private static Connection buildConnection(final String uri)
        throws IOException, GeneralSecurityException, URISyntaxException, TimeoutException {
    final ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(uri);
    return factory.newConnection();
}

From source file:rabbitmqapp.EmitLog.java

public static void main(String... args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri(Cons.RABBIT_MQ_URL);
    factory.setConnectionTimeout(3000);/* w w  w  .  j  a  va 2 s  .c o m*/
    factory.setRequestedHeartbeat(30);

    //Create a connection
    Connection connection = factory.newConnection();
    //create a channel from connection
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(Cons.EXCHANGE_NAME, EXCHANGE_TYPE);
    String message = "Hello Dolly";

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

From source file:rabbitmqapp.RabbitMQApp.java

/**
 * @param args the command line arguments
 *///from   w w w.  ja  va  2s. c  om
public static void main(String[] args) throws Exception {
    ProductOrder order = new ProductOrder("Thando Mlauzi", 34.50);
    ConnectionFactory factory = new ConnectionFactory();
    String uri = "amqp://ytsoedex:Qu2LCiBJ5x9fhRUyLYkMhJqsURJ9dkSP@chicken.rmq.cloudamqp.com/ytsoedex";
    factory.setUri(uri);

    //Recommended settings
    factory.setRequestedHeartbeat(30);
    factory.setConnectionTimeout(30000);

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

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

    channel.close();
    connection.close();

}