Example usage for com.rabbitmq.client Channel close

List of usage examples for com.rabbitmq.client Channel close

Introduction

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

Prototype

@Override
void close() throws IOException, TimeoutException;

Source Link

Document

Close this channel with the com.rabbitmq.client.AMQP#REPLY_SUCCESS close code and message 'OK'.

Usage

From source file:taucalcmanager.TaucalcManager.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//from ww  w. j av a 2 s  .  c  om
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    int calcs = Integer.parseInt(args[0]);
    int triesPerCalc = Integer.parseInt(args[1]);
    int[] results = new int[calcs];
    byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8),
            (byte) (triesPerCalc) };

    System.out.println("Start Publishing");
    for (int i = 0; i < calcs; i++) {
        channel.basicPublish("", WORKQUEUENAME, null, task);
    }
    System.out.println("Done Publishing");
    GetResponse response;
    System.out.println("Start Gathering results");
    for (int i = 0; i < calcs; i++) {
        System.out.println("Waiting for next result: ( " + i + " )");
        do {
            response = channel.basicGet(RESULTQUEUENAME, true);
        } while (response == null);

        results[i] = ByteBuffer.wrap(response.getBody()).getInt();
        System.out.println("Received result: " + results[i]);
    }
    System.out.println("Done gathering results");
    System.out.println("Calculating tau");
    BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc);
    System.out.println("Tau = " + result);
    BigDecimal two = new BigDecimal(2);
    System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP));
    channel.close();
    connection.close();
}

From source file:taucalcworker.TaucalcWorker.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*w  w w . java2s  .  c om*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    byte[] inputbyte = { 0, 0, 0, 0 };
    String input = "";

    do {
        if (System.in.available() > 0) {
            System.in.read(inputbyte);
            input = new String(inputbyte);
        }
        GetResponse response = channel.basicGet(WORKQUEUENAME, false);
        if (response != null) {
            long deliverytag = response.getEnvelope().getDeliveryTag();
            byte[] body = response.getBody();
            int tries = ByteBuffer.wrap(body).getInt();
            System.out.println("Task received: " + tries);
            int success = 0;
            for (int i = 0; i < tries; i++) {
                double x = Math.random();
                double y = Math.random();
                if (x * x + y * y <= 1) {
                    success++;
                }
            }
            System.out.println("success: " + success + " out of " + tries);
            double tau = ((double) success / tries) * 8;
            System.out.println("Tau = " + tau);
            byte[] resultbytes = new byte[8];
            ByteBuffer.wrap(resultbytes).putDouble(tau);
            channel.basicPublish("", RESULTQUEUENAME, null, resultbytes);
            channel.basicAck(deliverytag, false);
        }
    } while (!input.equals("stop"));
    channel.close();
    connection.close();
    System.out.println("You stopped the program.");
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Sends a message to the specified queue
 * @param queue//  w w  w .  j  a  v  a2  s . com
 * @param in
 * @param host
 * @throws IOException
 * @throws InterruptedException 
 * @throws TimeoutException
 */
public void sendMessage(String queue, Object in, String host)
        throws IOException, InterruptedException, TimeoutException {
    String message;
    Builder propBuilder = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder();
    if (in.getClass().equals(String.class)) {
        message = (String) in;
    } else {
        message = Utils.objectToJson(in);
        if (in.getClass().equals(WorkerState.class)) {
            host = ((WorkerState) in).getResource().getHostName();
        }
    }
    if (host != null) {
        Map<String, Object> headers = new HashMap();
        headers.put("host", host);
        propBuilder.headers(headers);
    }
    BasicProperties mProp = propBuilder.build();

    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, message.getBytes());
    channel.waitForConfirmsOrDie(5000);
    logger.info(queue + " sent: " + message);
    channel.close();
    closeRmqConn(connectionSend);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void sendFile(String queue, String host, File f)
        throws IOException, InterruptedException, TimeoutException {
    Map<String, Object> headers = new HashMap();
    headers.put("host", host);
    BasicProperties mProp = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build();
    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();/* www.  java  2  s .  c om*/
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, Files.readAllBytes(f.toPath()));
    channel.waitForConfirmsOrDie(5000);
    logger.info(queue + " file: " + f.getAbsolutePath());
    channel.close();
    closeRmqConn(connectionSend);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void cleanQueue(String queue, String match) throws IOException, InterruptedException {
    logger.trace(queue.concat(": ").concat(match));
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
    Set seen = new HashSet();
    while (delivery != null) {
        String body = new String(delivery.getBody());
        if (seen.contains(body)) {
            break;
        }//www .j a va  2  s.c om
        if (body.contains(match)) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
            seen.add(body);
        }
        delivery = consumer.nextDelivery(1000);
    }
    channel.close();
    closeRmqConn(connectionRcv);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public List<File> getFiles(String queue, Path outFolder, boolean ack) throws IOException, InterruptedException {
    List files = new ArrayList();
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);

    Set seen = new HashSet();

    while (delivery != null) {
        String host = delivery.getProperties().getHeaders().get("host").toString();
        File outTo = Paths.get(outFolder.toString(), host + ".tar.gz").toFile();
        FileUtils.writeByteArrayToFile(outTo, delivery.getBody());
        if (ack) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {/*from   www.j a  va2 s  .com*/
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
        }
        if (seen.contains(delivery.getProperties().getHeaders().get("host"))) {
            break;
        }
        seen.add(delivery.getProperties().getHeaders().get("host"));
        files.add(outTo);
        logger.info(queue + " retrieved: " + outTo.getAbsolutePath());
        delivery = consumer.nextDelivery(1000);
    }
    logger.warn("getFiles done");
    channel.close();
    closeRmqConn(connectionRcv);
    return files;
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public WorkerState getWorkerState(String queue, long wait) throws IOException, InterruptedException {
    WorkerState ws = null;// w  w  w. j  a  v  a 2s .  c o  m
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery;
    if (wait == -1) {
        delivery = consumer.nextDelivery(); // will block until response
    } else {
        delivery = consumer.nextDelivery(wait);
    }
    if (delivery != null) {
        String message = new String(delivery.getBody());
        ws = (WorkerState) Utils.jsonToObject(message, WorkerState.class);
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return ws;
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Gets a single message from a queue, ideal for getting an item of work.
 * @param queue/*  w ww  . j a  v a2 s .  c  o  m*/
 * @param wait
 * @return A JSON string representing an object, you need to know what type of object the queue will return and handle this outside of here
 * @throws IOException
 * @throws InterruptedException 
 */
public String getMessageString(String queue, long wait) throws IOException, InterruptedException {
    String message = null;
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery;
    if (wait == -1) {
        delivery = consumer.nextDelivery(); // will block until response
    } else {
        delivery = consumer.nextDelivery(wait);
    }
    if (delivery != null) {
        message = new String(delivery.getBody());
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        logger.info(queue + " recieved: " + message);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return message;
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void removeFromStateQueue(String queue, String hostToRemove) throws IOException, InterruptedException {
    logger.trace(queue.concat(": ").concat(hostToRemove));
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    int maxTries = channel.queueDeclare(queue, true, false, false, null).getMessageCount();
    logger.trace("Queue : messages\t" + queue + " : " + maxTries);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(200);
    logger.trace(maxTries);//  w w w.j av  a2 s. c  om
    while (delivery != null && maxTries > 0) {
        // the toString in the middle of this is needed as it is wrapped with another type that can hold 4GB
        Map<String, Object> headers = delivery.getProperties().getHeaders();
        if (headers != null && headers.get("host").toString().equals(hostToRemove)) {
            logger.trace(headers.get("host").toString().concat(" remove"));
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
        }
        delivery = consumer.nextDelivery(200);
        maxTries--;
    }
    channel.close();
    closeRmqConn(connectionRcv);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Gets all the messages in a queue, best for queues which receive status updates.
 * @param queue/*  w w w .j  av a 2  s  .  c  o m*/
 * @param wait
 * @return List of JSON strings representing objects, you need to know what type of object the queue will return and handle this outside of here
 * @throws IOException
 * @throws InterruptedException 
 */
public List<String> getMessageStrings(String queue, long wait) throws IOException, InterruptedException {
    List<String> responses = new ArrayList();
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, true, consumer);
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery(wait);
        if (delivery == null) {
            break;
        }
        String message = new String(delivery.getBody());
        logger.info(queue + " recieved: " + message);
        responses.add(message);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return responses;
}