Example usage for com.rabbitmq.client ConnectionFactory ConnectionFactory

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

Introduction

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

Prototype

ConnectionFactory

Source Link

Usage

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

License:Open Source License

/**
 * @see coyote.dx.writer.AbstractFrameFileWriter#open(coyote.dx.context.TransformContext)
 *///  w  w  w  .j  a  va2 s  .c om
@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. c  om
            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:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;//from  w w  w.  jav a 2 s  .  co m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

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

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

License:Apache License

/** Create the connector using the indicated RabbitMQ
 * instance(s) as messaging queue./* w w w. ja va  2 s  .com*/
 * 
 * @param hostname
 * @throws IOException
 */
public RabbitMQRPCConnector(String hostname) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);
    connection = factory.newConnection();
    channelHighPriority = connection.createChannel();
    channelLowPriority = connection.createChannel();

    replyHighPriorityQueueName = channelHighPriority.queueDeclare().getQueue();
    consumerHighPriority = new QueueingConsumer(channelHighPriority);
    channelHighPriority.basicConsume(replyHighPriorityQueueName, true, consumerHighPriority);

    replyLowPriorityQueueName = channelLowPriority.queueDeclare().getQueue();
    consumerLowPriority = new QueueingConsumer(channelLowPriority);
    channelLowPriority.basicConsume(replyLowPriorityQueueName, true, consumerLowPriority);

    logger.info("Opening connector on MQ at IP= " + hostname);
}

From source file:cu.uci.plagicoj.config.DIConfiguration.java

@Bean
public ConnectionFactory connectionFactory() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(env.getProperty("amqp.server"));
    factory.setPassword("cojrabbit123*-+");
    return factory;
}

From source file:de.bitzeche.logging.gelfamqp4j.GelfAMQP4jAppender.java

License:Apache License

@Override
public void activateOptions() {
    if (StringUtils.isBlank(amqpUserName) || StringUtils.isBlank(amqpPassword)
            || StringUtils.isBlank(amqpVirtualHost) || StringUtils.isBlank(amqpHostName) || amqpPortNumber <= 0
            || StringUtils.isBlank(amqpExchangeName) || StringUtils.isBlank(amqpRoutingKey)) {
        errorHandler.error("AMQP is not configured correctly!", null, ErrorCode.WRITE_FAILURE);
    } else {//from  w  ww.  java2s  .c  o  m
        factory = new ConnectionFactory();
        factory.setUsername(amqpUserName);
        factory.setPassword(amqpPassword);
        factory.setVirtualHost(amqpVirtualHost);
        factory.setHost(amqpHostName);
        factory.setPort(amqpPortNumber);
    }
}

From source file:de.dhbw.mannheim.assemblylinesim.AssemblyLineSim.java

License:Open Source License

/**
 *
 * @param hostname of the rabbitMq/*w w  w . j  a va  2 s  .  co m*/
 * @param speedUpFactor speed up factor to speed up simulation, e.g. 10 --> 10 times faster
 * @throws IOException is thrown if the connection to rabbitmq fails
 */
private AssemblyLineSim(String hostname, double speedUpFactor) throws IOException {
    (new RabbitListener(hostname)).start();
    this.speedUpFactor = speedUpFactor;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostname);
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare(REPORT_EXCHANGE_NAME, "fanout");
}

From source file:de.dhbw.mannheim.erpsim.ErpSimulator.java

License:Open Source License

/**
 *
 *
 * @param args command line parameter//from ww  w. j  a va2 s  .  c o  m
 *             args[0] number of customer orders that should be created
 *             args[1] hostname of rabbitMQ
 * @throws IOException
 */
public static void main(String[] args) throws IOException {

    int numOfCustomerOrder = 10;
    String rabbitMqHostName = "localhost";
    String rabbitMqUserName = null;
    String rabbitMqPassword = null;

    if (args.length >= 1) {
        try {
            numOfCustomerOrder = Integer.parseInt(args[0]);
            System.out.println("Number of customer orders: " + numOfCustomerOrder);
        } catch (Exception e) {
            System.err.println("Could not parse number of customer orders " + args[0]);
        }
    }

    if (args.length >= 2 && args[1] != null) {
        rabbitMqHostName = args[1];
        System.out.println("Host of rabbitMq: " + rabbitMqHostName);
    }
    if (args.length >= 4 && args[2] != null && args[3] != null) {
        rabbitMqUserName = args[2];
        rabbitMqPassword = args[3];
        System.out.println("Username of rabbitMq: " + rabbitMqUserName);
    }

    CustomerOrder[] customerOrders = new CustomerOrder[numOfCustomerOrder];

    for (int i = 0; i < customerOrders.length; i++) {
        customerOrders[i] = CustomerOrderGenerator.getCustomOrder();
    }

    XStream xstream = new XStream();
    xstream.registerConverter(new Converter() {
        @Override
        public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
            MachineOrder mo = (MachineOrder) o;
            writer.startNode("id");
            writer.setValue(mo.getId());
            writer.endNode();
        }

        @Override
        public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader,
                UnmarshallingContext unmarshallingContext) {
            return null;
        }

        @Override
        public boolean canConvert(Class aClass) {
            return aClass == MachineOrder.class;
        }
    });

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqHostName);
    if (rabbitMqPassword != null && rabbitMqUserName != null) {
        factory.setUsername(rabbitMqUserName);
        factory.setPassword(rabbitMqPassword);
    }
    Connection connection = factory.newConnection();
    Channel channelCO = connection.createChannel();
    channelCO.exchangeDeclare(CUSTOMER_ORDER_EXCHANGE_NAME, "fanout");
    for (CustomerOrder co : customerOrders) {
        String message = xstream.toXML(co);

        channelCO.basicPublish(CUSTOMER_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send customer order");
    }
    channelCO.close();

    Channel channelMO = connection.createChannel();
    channelMO.exchangeDeclare(MACHINE_ORDER_EXCHANGE_NAME, "fanout");
    MachineOrder mo = MachineOrderGenerator.getRandomMachineOrder();

    xstream = new XStream(); // reconstruct XStream to parse the full machine order, not just only the id
    while (mo != null) {
        int i = System.in.read();
        String message = xstream.toXML(mo);
        channelMO.basicPublish(MACHINE_ORDER_EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println("Send Machine order");
        mo = MachineOrderGenerator.getRandomMachineOrder();
    }

    channelMO.close();
    connection.close();
}

From source file:deck36.storm.plan9.Plan9RabbitMQPushBolt.java

License:Open Source License

@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {

    // Setup output collector
    _collector = collector;/*from   ww w  . j a  v  a  2  s . co m*/

    // connect to RabbitMQ

    String host = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.host");
    int port = ((Long) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.port")).intValue();
    String user = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.user");
    String pass = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.pass");
    String vhost = (String) JsonPath.read(stormConf, "$.deck36_storm.rabbitmq.vhost");

    ConnectionFactory factory = new ConnectionFactory();

    try {

        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setVirtualHost(vhost);
        factory.setHost(host);
        factory.setPort(port);
        _conn = factory.newConnection();

        _channel = _conn.createChannel();

    } catch (Exception e) {
        log.error(e.toString());
    }

}

From source file:dfki.sb.rabbitmqjava.RabbitMQClient.java

License:Open Source License

public RabbitMQClient() throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    connection = factory.newConnection();
    channel = connection.createChannel();

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