Example usage for com.rabbitmq.client ConnectionFactory setHost

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

Introduction

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

Prototype

public void setHost(String host) 

Source Link

Usage

From source file:pl.nask.hsn2.DataStoreActiveCleaner.java

License:Open Source License

/**
 * Initialize RabbitMQ connection./*  www  .  j  av  a2s . c  o  m*/
 *
 * @return RabbitMQ consumer.
 * @throws IOException
 *             When there's some connection issues.
 */
private QueueingConsumer initRabbitMqConnection() throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setHost(rbtHostName);
    rbtConnection = connFactory.newConnection();
    Channel channel = rbtConnection.createChannel();
    channel.exchangeDeclare(rbtNotifyExchName, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, rbtNotifyExchName, "");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, AUTO_ACK, consumer);
    return consumer;
}

From source file:pl.nask.hsn2.framework.bus.RbtBusTest.java

License:Open Source License

public ConsumeEndPoint setupStub() throws IOException, BusException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("195.187.238.85");
    Connection connection = factory.newConnection();

    final FireAndForgetEndPoint responseEndPoint = new RbtFireAndForgetEndPoint(connection);
    final MessageSerializer<Operation> serializer = new ProtoBufMessageSerializer();
    return new RbtConsumeEndPoint(connection, new ConsumeEndPointHandler() {
        @Override//from  ww w  . jav a2 s.  c o m
        public void handleMessage(Message message) {
            try {
                LOGGER.info("STUB got message {}.", message.getType());
                if ("ObjectRequest".equals(message.getType())) {
                    ObjectResponse res = new ObjectResponseBuilder(ResponseType.SUCCESS_PUT)
                            .addAllObjects(Arrays.asList(6L)).build();
                    Message respMessage = serializer.serialize(res);
                    respMessage.setDestination(message.getReplyTo());
                    respMessage.setReplyTo(new Destination(""));
                    responseEndPoint.sendNotify(respMessage);
                }
            } catch (Exception ex) {
                LOGGER.error("Error with processing message.");
            }
        }
    }, "osHi", false, 10);
}

From source file:pl.nask.hsn2.os.ConnectorImpl.java

License:Open Source License

public static void initConnection(String connectorAddress) throws BusException {
    if (connection == null) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(connectorAddress);
        try {//w  w  w.j  a  v  a 2 s.co m
            connection = factory.newConnection();
        } catch (IOException e) {
            throw new BusException("Can't create connection.", e);
        }
    } else {
        throw new IllegalStateException("Connection already initialized");
    }
}

From source file:pl.nask.hsn2.unicorn.connector.ConnectorImpl.java

License:Open Source License

private void createConnection() throws ConnectionException {
    ConnectionFactory factory = new ConnectionFactory();
    String[] addressParts = address.split(":");
    factory.setHost(addressParts[0]);
    if (addressParts.length > 1) {
        factory.setPort(Integer.parseInt(addressParts[1]));
    }//from w ww  .j  a v  a 2  s  . co m

    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
    } catch (IOException e) {
        throw new ConnectionException("Creating connection error!", e);
    }
}

From source file:pluginmanager.RequestManager.java

License:Open Source License

@Override
public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");

    // RESPONSE QUEUE STUFF
    try {// w  w w. ja v  a2  s  .  c  o m
        responseConnection = factory.newConnection();
        responseChannel = responseConnection.createChannel();
        responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    } catch (IOException | TimeoutException e2) {
        e2.printStackTrace();
    }

    Consumer consumer = new DefaultConsumer(responseChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            HttpResponse response = (HttpResponse) SerializationUtils.deserialize(body);
            try {
                response.write(sockDrawer.get(response.id).getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    try {
        responseChannel.basicConsume(RESPONSE_QUEUE_NAME, true, consumer);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //REQUEST QUEUE STUFF
    try {
        requestConnection = factory.newConnection();
        requestChannel = requestConnection.createChannel();
        requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null);
    } catch (IOException | TimeoutException e1) {
        e1.printStackTrace();
    }

    System.out.println("Request Manger Running");
    while (true) {
        if (!queue.isEmpty()) {
            System.out.println("Processing");
            PriorityRequest request = queue.poll();
            byte[] data = SerializationUtils.serialize(request);
            try {
                requestChannel.basicPublish("", REQUEST_QUEUE_NAME, null, data);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            //response.write(socket.getOutputStream());
        } else {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.QueryConsumer.java

License:Apache License

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    final Session session = cluster.connect();
    session.execute(String.format("CREATE TABLE IF NOT EXISTS tester.warningsrdd (ssn text, "
            + "batchStartTime bigint, id uuid, amount decimal, rule text, PRIMARY KEY(batchStartTime, id))"));
    final PreparedStatement preparedStatement = session
            .prepare("SELECT * FROM tester.warningsrdd where batchStartTime = ?");
    try {/*from  ww w  . j  a  v a  2 s  . com*/
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        final String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, EXCHANGE_NAME, "");

        final Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                String message = new String(body);
                long batchStartTime = Long.parseLong(message);
                System.out.println("Writing batch with start time of " + new Date(batchStartTime));
                ResultSet warningsResultSet = session.execute(preparedStatement.bind(batchStartTime));
                int count = 0;
                for (Row warning : warningsResultSet) {
                    count += 1;
                    BigDecimal decimal = warning.getDecimal("amount");
                    UUID id = warning.getUUID("id");
                    String ssn = warning.getString("ssn");
                    String rule = warning.getString("rule");
                    Warning warningObj = new Warning();
                    warningObj.setAmount(decimal);
                    warningObj.setId(id);
                    warningObj.setSsn(ssn);
                    warningObj.setRule(rule);
                    notifyUI(warningObj);
                }
                System.out.println("Batch with start time of " + new Date(batchStartTime) + " Complete with "
                        + count + " items.");
            }
        };
        channel.basicConsume(queue, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.ResponseWriter.java

License:Apache License

private Messenger initRabbitMqResponseQueue() {

    ConnectionFactory factory = new ConnectionFactory();
    final Connection connection;
    final Channel channel;
    factory.setHost("localhost");
    try {//from w ww  . j  av a2s . c om
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            ResponseWriter.mainThread.interrupt();
            try {
                channel.close();
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return new MessengerImpl(channel);
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.smartconsumer.DeduplicatingRabbitMQConsumer.java

License:Apache License

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try {/* w w w . j a  v a2s  . co  m*/
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(EXCHANGE_NAME, true, consumer);
        Set<String> messages = new HashSet<>();
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            messages.add(message);

            if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 1000l) {
                System.out.println("it should be safe to submit messages now");
                for (String m : messages) {
                    //notifying user interface
                    System.out.println(m);
                }
                stopwatch.stop();
                stopwatch.reset();
                messages.clear();
            }
            if (messages.size() > 100000000) {
                System.out.println("save off to file system and clear before we lose everything");
                messages.clear();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQEmitWarnings.java

License:Apache License

public static void main(String[] argv) throws java.io.IOException {
    String master = Args.parseMaster(argv);

    mainThread = Thread.currentThread();

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            RabbitMQEmitWarnings.mainThread.interrupt();
            try {
                channel.close();/* w w w. ja va2s  . c  om*/
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    while (true) {
        String message = buildMessage();
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

From source file:pro.foundev.examples.spark_streaming.java.messaging.RabbitMQReceiver.java

License:Apache License

@Override
public void onStart() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(master);
    factory = new ConnectionFactory();
    try {/*  w w w.  java 2  s  .co  m*/
        connection = factory.newConnection();
        channel = connection.createChannel();
        String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, queueName, "");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                store(new String(body, "UTF-8"));

            }
        };
        channel.basicConsume(queue, true, consumer);

    } catch (IOException e) {
        restart("error connecting to message queue", e);
    }
}