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:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(Object object) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ObjectOutput objOut = new ObjectOutputStream(os);

    objOut.writeObject(object);//from   www .j  av  a 2 s.c  om
    byte byteForm[] = os.toByteArray();
    objOut.close();
    os.close();

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, byteForm);
    System.out.println(" [x] Sent Message");

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

}

From source file:net.es.netshell.rabbitmq.Publish.java

License:Open Source License

public void Publish(String[] argv) throws Exception {

    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }//  ww  w.jav a  2s  .  c om
    String message = new ParseMessage(argv).getMessage();

    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    token = new CreateToken(info, channel, queueName).getToken();

    message = token + ":" + message;

    channel.queueDeclare(queueName, false, false, true, null);
    channel.basicPublish("", queueName, null, message.getBytes());
    System.out.println(" [x] Sent '" + message + "'");

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

From source file:net.lshift.accent.AccentTestUtils.java

License:Apache License

/**
 * Given the reconnection logic in Accent, a missing AMQP server during testing can cause tests to hang. This method
 * tries a direct AMQP connection first, so we can ensure that an AMQP host is available.
 *///from  w  w  w  .j a  v  a 2 s.c o  m
public static void ensureAMQPServer() throws IOException {
    ConnectionFactory cf = new ConnectionFactory();
    cf.newConnection().close();
}

From source file:net.lshift.accent.ConnectionBehaviourTest.java

License:Apache License

@Test
public void shouldKeepAttemptingToReconnect() throws Exception {
    // Create a connection factory that never returns a valid connection
    ConnectionFactory unconnectableFactory = createMock(ConnectionFactory.class);
    expect(unconnectableFactory.newConnection()).andStubThrow(new ConnectException("Boom"));
    replay(unconnectableFactory);//from w w w  . j  ava2 s .c  om

    // We want to see 4 attempts to connect
    final CountDownLatch attemptLatch = new CountDownLatch(4);
    ConnectionFailureListener eventingListener = new ConnectionFailureListener() {
        @Override
        public void connectionFailure(Exception e) {
            if (e instanceof ConnectException) {
                attemptLatch.countDown();
            } else {
                System.out.println("WARNING: Received unexpected exception - " + e);
            }
        }
    };

    // Create the connection, and wait for the countdown to reach 0
    AccentConnection conn = new AccentConnection(unconnectableFactory, eventingListener);
    assertTrue(attemptLatch.await(5000, TimeUnit.MILLISECONDS));
}

From source file:net.lshift.camcapture.AMQPacketProducer.java

License:Open Source License

public AMQPacketProducer(String host, String exchange, String routingKey) throws IOException {
    this.host = host;
    this.exchange = exchange;
    this.routingKey = routingKey;

    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(host);/*from w  w  w. j a  v a 2  s .co m*/
    this.conn = cf.newConnection();

    this.ch = conn.createChannel();

    ch.exchangeDeclare(exchange, "fanout");
}

From source file:net.lshift.camdisplay.Main.java

License:Open Source License

public Main(String host, String exch, String nickname, final String mixerSpec) throws IOException {
    frame = new JFrame("RabbitCam: " + host + "/" + exch);
    panel = new JPanel();
    componentMap = new HashMap();

    setupWindowDressing(exch, nickname, frame, panel);
    frame.pack();//from   www .j  ava2  s  . c om
    frame.show();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    textInput.requestFocusInWindow();

    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(host);
    cf.setRequestedHeartbeat(0);
    conn = cf.newConnection();

    ch = conn.createChannel();

    ch.exchangeDeclare(exch, "fanout");

    String queueName = ch.queueDeclare().getQueue();
    ch.queueBind(queueName, exch, "");
    ch.basicConsume(queueName, true, new DefaultConsumer(ch) {
        public void handleShutdownSignal(String consumerTag, ShutdownSignalException s) {
            if (s.getReason() instanceof java.io.EOFException) {
                JOptionPane.showMessageDialog(frame, "AMQP server disconnected.", "Connection closed",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                SwingUtil.complain("Connection closed", null, s);
            }
            System.exit(1);
        }

        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String routingKey = envelope.getRoutingKey();
            String contentType = properties.getContentType();

            if (contentType.equals("text/plain")) {
                handleText(routingKey, new String(body));
                return;
            }

            CamstreamComponent comp;
            if (!componentMap.containsKey(routingKey)) {
                comp = new CamstreamComponent(mixerSpec);
                addComponent(routingKey, comp);
                frame.pack();
            } else {
                comp = (CamstreamComponent) componentMap.get(routingKey);
            }
            if (comp.handleDelivery(contentType, body)) {
                frame.pack();
            }
        }
    });
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test
public void prePutHappyCase() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "true", "");
    setupHBase(kvs);/*from w  w  w  .j a  v  a2s. com*/

    //simulate population of secondary index as a result of the above
    Put idxPut = new Put("EFG1".getBytes());
    idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes());
    secondaryIdxTable.put(idxPut);

    // Add a column to the primary table, which should trigger a data ripple to the downstream table
    Put tablePut = new Put("EFG1".getBytes());
    tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes());
    primaryTable.put(tablePut);

    //check that values made it to the queue
    com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
    factory.setUri(amq_default_address);
    com.rabbitmq.client.Connection conn = factory.newConnection();
    com.rabbitmq.client.Channel channel = conn.createChannel();
    System.out.println(String.format("Test: connecting to %s", primaryTableNameString));

    while (true) {
        GetResponse response = channel.basicGet(primaryTableNameString, false);
        if (response == null)//busy-wait until the message has made it through the MQ
        {
            continue;
        }
        String routingKey = response.getEnvelope().getRoutingKey();
        Assert.assertEquals("Routing key should be rowkey", "genome", routingKey);

        String contentType = response.getProps().getContentType();
        Assert.assertEquals("Content type should be preserved", "application/json", contentType);

        Map<String, Object> headers = response.getProps().getHeaders();
        Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString());

        byte[] body = response.getBody();

        JSONObject jo = new JSONObject(new String(body));
        String column_family = (String) jo.get("column_family");
        Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family);

        String column_value = (String) jo.get("column_value");
        Assert.assertEquals("Column value should be preserved in the message body", "some_value", column_value);

        long deliveryTag = response.getEnvelope().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
        break;
    }
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test
public void verifyValueNotSentByDefault() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "false", "");
    setupHBase(kvs);//www  .  j  ava2 s .  com

    //simulate population of secondary index as a result of the above
    Put idxPut = new Put("EFG1".getBytes());
    idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes());
    secondaryIdxTable.put(idxPut);

    // Add a column to the primary table, which should trigger a data ripple to the downstream table
    Put tablePut = new Put("EFG1".getBytes());
    tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes());
    primaryTable.put(tablePut);

    //check that values made it to the queue
    com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
    factory.setUri(amq_default_address);
    com.rabbitmq.client.Connection conn = factory.newConnection();
    com.rabbitmq.client.Channel channel = conn.createChannel();
    System.out.println(String.format("Test: connecting to %s", primaryTableNameString));

    while (true) {
        GetResponse response = channel.basicGet(primaryTableNameString, false);
        if (response == null)//busy-wait until the message has made it through the MQ
        {
            continue;
        }
        String routingKey = response.getEnvelope().getRoutingKey();
        Assert.assertEquals("Routing key should be rowkey", "genome", routingKey);

        String contentType = response.getProps().getContentType();
        Assert.assertEquals("Content type should be preserved", "application/json", contentType);

        Map<String, Object> headers = response.getProps().getHeaders();
        Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString());

        byte[] body = response.getBody();

        JSONObject jo = new JSONObject(new String(body));
        String column_family = (String) jo.get("column_family");
        Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family);

        String column_value = (String) jo.get("column_value");
        Assert.assertEquals("Column value is not sent by default", "", column_value);

        long deliveryTag = response.getEnvelope().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
        break;
    }
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test
public void filterOnQualifiers() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "false", "one_key|some_key");
    setupHBase(kvs);//from   w ww  . j a  va  2 s .  c  o  m

    //simulate population of secondary index as a result of the above
    Put idxPut = new Put("EFG1".getBytes());
    idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes());
    secondaryIdxTable.put(idxPut);

    // Add a column to the primary table, which should trigger a data ripple to the downstream table
    Put tablePut = new Put("EFG1".getBytes());
    tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes());
    primaryTable.put(tablePut);

    //check that values made it to the queue
    com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
    factory.setUri(amq_default_address);
    com.rabbitmq.client.Connection conn = factory.newConnection();
    com.rabbitmq.client.Channel channel = conn.createChannel();
    System.out.println(String.format("Test: connecting to %s", primaryTableNameString));

    while (true) {
        GetResponse response = channel.basicGet(primaryTableNameString, false);
        if (response == null)//busy-wait until the message has made it through the MQ
        {
            continue;
        }
        String routingKey = response.getEnvelope().getRoutingKey();
        Assert.assertEquals("Routing key should be rowkey", "genome", routingKey);

        String contentType = response.getProps().getContentType();
        Assert.assertEquals("Content type should be preserved", "application/json", contentType);

        Map<String, Object> headers = response.getProps().getHeaders();
        Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString());

        byte[] body = response.getBody();

        JSONObject jo = new JSONObject(new String(body));
        String column_family = (String) jo.get("column_family");
        Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family);

        String column_value = (String) jo.get("column_value");
        Assert.assertEquals("Column value is not sent by default", "", column_value);

        long deliveryTag = response.getEnvelope().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
        break;
    }
}

From source file:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test
public void onlyPutWhenInQualifierFilter() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "false", "some_key");
    setupHBase(kvs);/*  w  w w  . j a  v  a  2s . c  om*/

    //simulate population of secondary index as a result of the above
    Put idxPut = new Put("EFG1".getBytes());
    idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes());
    secondaryIdxTable.put(idxPut);

    // Add a column to the primary table, which should trigger a data ripple to the downstream table
    Put tablePut = new Put("EFG1".getBytes());
    tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes());
    tablePut.addColumn("e".getBytes(), "other_key".getBytes(), "some_value".getBytes());
    tablePut.addColumn("e".getBytes(), "third_key".getBytes(), "some_value".getBytes());
    primaryTable.put(tablePut);

    //check that values made it to the queue
    com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
    factory.setUri(amq_default_address);
    com.rabbitmq.client.Connection conn = factory.newConnection();
    com.rabbitmq.client.Channel channel = conn.createChannel();
    System.out.println(String.format("Test: connecting to %s", primaryTableNameString));

    while (true) {
        int numMessages = channel.queueDeclarePassive(primaryTableNameString).getMessageCount();
        GetResponse response = channel.basicGet(primaryTableNameString, false);
        if (response == null || numMessages == 0)//busy-wait until the message has made it through the MQ
        {
            continue;
        }
        Assert.assertEquals("There should be only a single key in the queue", 1, numMessages);
        String routingKey = response.getEnvelope().getRoutingKey();
        Assert.assertEquals("Routing key should be rowkey", "genome", routingKey);

        String contentType = response.getProps().getContentType();
        Assert.assertEquals("Content type should be preserved", "application/json", contentType);

        Map<String, Object> headers = response.getProps().getHeaders();
        Assert.assertEquals("An action should be set on the message", "put", headers.get("action").toString());

        byte[] body = response.getBody();

        JSONObject jo = new JSONObject(new String(body));
        String column_family = (String) jo.get("column_family");
        Assert.assertEquals("Column family should be preserved in the message body", "eg", column_family);

        String column_value = (String) jo.get("column_value");
        Assert.assertEquals("Column value is not sent by default", "", column_value);

        long deliveryTag = response.getEnvelope().getDeliveryTag();
        channel.basicAck(deliveryTag, false);
        break;
    }
}