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:cs.rsa.ts14dist.appserver.RabbitMQRPCConnector.java

License:Apache License

/** Create the connector using the indicated RabbitMQ
 * instance(s) as messaging queue.//  ww  w  .  j  a  v a 2  s.  co  m
 * 
 * @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:de.dhbw.mannheim.assemblylinesim.AssemblyLineSim.java

License:Open Source License

/**
 *
 * @param hostname of the rabbitMq/*from w  ww .  ja v a 2s. c o  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/* w  ww .  j av  a  2s.  co  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:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java

License:Apache License

/**
 * Creates an instance of {@link AMQPEndpoint} whilst
 * mocking all RabbitMQ-Classes / ifaces involved.
 * /*from  ww  w . j  a  va  2  s.  c o  m*/
 * @throws IOException
 */
@Test
public void testAMQPLifecycle() throws IOException {
    // prepare mocks
    ConnectionFactory fac = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    Channel chan = mock(Channel.class);
    Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class);

    // ConnectionFactory
    when(fac.newConnection()).thenReturn(con);
    // Connection
    when(con.createChannel()).thenReturn(chan);
    // Channel
    when(chan.queueDeclare()).thenReturn(declareOK);
    // DeclareOK result object
    String queueName = "testQueue";
    when(declareOK.getQueue()).thenReturn(queueName);

    AMQPEndpoint ep = new AMQPEndpoint();
    Whitebox.setInternalState(ep, "connectionFactory", fac);

    ep.configure(this.exampleConf);
    ep.start();

    // verify "important" connect methods were called
    verify(fac).newConnection();
    verify(con).createChannel();
    verify(chan).queueDeclare();
    verify(declareOK).getQueue();
    // in the example conf we're bindingn to 3 queues, let's check that
    String exchange = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_EXCHANGE_NAME);
    String routingKey = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_ROUTING_KEY);
    // listens for broadcasts
    verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast"));
    // listens for tasks
    verify(chan, times(1)).queueBind(eq("cit_stream_tasks_queue_" + routingKey), eq(exchange),
            eq("task." + routingKey));
    // listens for broadcasts to broadcast.test
    verify(chan, times(1)).queueBind(eq(queueName), eq(exchange), eq("broadcast." + routingKey));
    String exclusiveQueueName = Whitebox.getInternalState(ep, "exclusiveQueueName");
    assertEquals(queueName, exclusiveQueueName);
}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java

License:Apache License

/**
 * Tests sending a "normal" non-{@link de.tuberlin.cit.livescale.messaging.RequestMessage}
 * //from  w  w  w  .  jav a  2s.  c om
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testAMQPSendNoResponse() throws IOException, URISyntaxException {
    ConnectionFactory fac = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    Channel chan = mock(Channel.class);
    Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class);

    // ConnectionFactory
    when(fac.newConnection()).thenReturn(con);
    // Connection
    when(con.createChannel()).thenReturn(chan);
    // Channel
    when(chan.queueDeclare()).thenReturn(declareOK);
    // DeclareOK result object
    String queueName = "testQueue";
    when(declareOK.getQueue()).thenReturn(queueName);

    AMQPEndpoint ep = new AMQPEndpoint();
    ep.setName("amqpTest");
    Whitebox.setInternalState(ep, "connectionFactory", fac);
    ep.configure(this.exampleConf);

    // configuredRoutingKey
    String routingKey = this.exampleConf.get(AMQPEndpoint.CONFIG_KEY_ROUTING_KEY);
    URI targetURI = new URI("amqp:///test");

    MessageCenter mc = new MessageCenter(false, this.emptyConf);
    mc.addEndpoint(ep);
    mc.startAllEndpoints();
    assertTrue(mc.hasEndpointToURI(targetURI));

    // kickin the jams
    mc.send(new TestMessage(), targetURI);
    // verify(chan, times(1)).basicPublish(eq(""), eq(routingKey), (BasicProperties) isNull(), (byte[]) any());
}

From source file:de.tuberlin.cit.livescale.messaging.endpoints.AMQPEndpointTest.java

License:Apache License

/**
 * Tests message arrival on a {@link AMQPEndpoint} and
 * correctness of the generated responseURI in the
 * {@link MessageManifest} /*from w w w . j av  a 2 s . c  o  m*/
 * 
 * @throws IOException
 * @throws URISyntaxException
 */
@Test
public void testArrival() throws IOException, URISyntaxException {
    ConnectionFactory fac = mock(ConnectionFactory.class);
    Connection con = mock(Connection.class);
    Channel chan = mock(Channel.class);
    Queue.DeclareOk declareOK = mock(Queue.DeclareOk.class);

    // ConnectionFactory
    when(fac.newConnection()).thenReturn(con);
    // Connection
    when(con.createChannel()).thenReturn(chan);
    // Channel
    when(chan.queueDeclare()).thenReturn(declareOK);
    // DeclareOK result object
    String queueName = "testQueue";
    when(declareOK.getQueue()).thenReturn(queueName);

    AMQPEndpoint ep = new AMQPEndpoint();
    String endpointName = "amqpTest";
    ep.setName(endpointName);
    Whitebox.setInternalState(ep, "connectionFactory", fac);
    ep.configure(this.exampleConf);
    // hookup a listener
    MessageEndpointListener listener = mock(MessageEndpointListener.class);
    ep.addMessageEndpointListener(listener);

    // kickin the jams 
    ep.start();
    // hook up the consumer / manually call the callback
    ArgumentCaptor<DefaultConsumer> consumer = ArgumentCaptor.forClass(DefaultConsumer.class);
    // should in total consume the own queue and the tasks queue
    // depends on config settings
    verify(chan, times(2)).basicConsume(anyString(), anyBoolean(), (Consumer) anyObject());
    verify(chan).basicConsume(eq(queueName), anyBoolean(), consumer.capture());
    String replyQueueName = "replyQueue";
    // faux envelope
    Envelope envelope = new Envelope(-1l, false, "daExchange", "daRoutingKey");
    // faux properties
    BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName)
            .appId(UUID.randomUUID().toString()).build();
    // faux message 
    TestRequestMessage message = new TestRequestMessage();
    // faux manifest
    MessageManifest mmIn = new MessageManifest(message, new URI("amqp:///targetQueue"));
    // call the callback function
    consumer.getValue().handleDelivery("leTag", envelope, props, MessageFactory.encode(mmIn));
    ArgumentCaptor<MessageManifest> mm = ArgumentCaptor.forClass(MessageManifest.class);
    verify(listener).handleMessageReceived(mm.capture());
    assertEquals("amqp", mm.getValue().getResponseURI().getScheme());
    assertEquals(endpointName, mm.getValue().getResponseURI().getAuthority());
    assertEquals("/" + replyQueueName, mm.getValue().getResponseURI().getPath());
}

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  w  ww .  j  a v a2s  .  c  o 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);
}

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

License:Open Source License

public RabbitMQObjectStreamClient() 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);
}

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

License:Open Source License

public static void main(String[] argv) {
    Channel channel = null;//from   ww w. j a  v  a2 s. c o  m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        processSendAndRecivePackets(consumer, channel);
        if (argv != null && argv.length > 0 && argv[0].equalsIgnoreCase("infinite")) {
            while (true) {
                System.out.println("Waiting for next client");
                processSendAndRecivePackets(consumer, channel);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}