Example usage for com.rabbitmq.client Channel basicPublish

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

Introduction

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

Prototype

void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body) throws IOException;

Source Link

Document

Publish a message.

Usage

From source file:in.cs654.chariot.prashti.PrashtiServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {//from   ww w  .ja  v a2 s.  c  o m
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("Prashti Server started. Waiting for requests...");

        final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers();
        final String ipAddr = CommonUtils.getIPAddress();
        prashtiList.add(new Prashti(ipAddr));
        LOGGER.info("Notifying D2 to set Prashti Server IP Address");
        D2Client.setPrashtiServers(prashtiList);

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = RequestProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:in.cs654.chariot.turagraksa.ZooKeeperServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {/*from ww  w  .  jav  a  2s . com*/
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("ZooKeeper Server started. Waiting for requests...");
        ZooKeeper.startPingEcho();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final AMQP.BasicProperties props = delivery.getProperties();
            final AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = ZooKeeperProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:info.pancancer.arch3.worker.WorkerHeartbeat.java

License:Open Source License

@Override
public void run() {

    Channel reportingChannel = null;
    try {/*w w  w  .j  a va  2s .  c  o  m*/
        try {
            reportingChannel = Utilities.setupExchange(settings, this.queueName);
        } catch (IOException | TimeoutException | AlreadyClosedException e) {
            LOG.error("Exception caught! Queue channel could not be opened, waiting. Exception is: "
                    + e.getMessage(), e);
            // retry after a minute, do not die simply because the launcher is unavailable, it may come back
            Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.info("Caught interrupt signal, heartbeat shutting down.", e);
        return;
    }

    LOG.info("starting heartbeat thread, will send heartbeat message ever " + secondsDelay + " seconds.");
    while (!Thread.interrupted()) {
        // byte[] stdOut = this.getMessageBody().getBytes(StandardCharsets.UTF_8);
        try {
            try {
                Status heartbeatStatus = new Status();
                heartbeatStatus.setJobUuid(this.jobUuid);
                heartbeatStatus.setMessage("job is running; IP address: " + networkID);
                heartbeatStatus.setState(StatusState.RUNNING);
                heartbeatStatus.setType(Utilities.JOB_MESSAGE_TYPE);
                heartbeatStatus.setVmUuid(this.vmUuid);
                heartbeatStatus.setIpAddress(networkID);

                // String stdOut = this.statusSource.getStdOut();
                Lock lock = new ReentrantLock();
                lock.lock();
                String stdOut = this.statusSource.getStdOut(stdoutSnipSize);
                String stdErr = this.statusSource.getStdErr();
                lock.unlock();
                heartbeatStatus.setStdout(stdOut);
                heartbeatStatus.setStderr(stdErr);
                String heartBeatMessage = heartbeatStatus.toJSON();
                LOG.debug("Sending heartbeat message to " + queueName + ", with body: " + heartBeatMessage);
                reportingChannel.basicPublish(queueName, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN,
                        heartBeatMessage.getBytes(StandardCharsets.UTF_8));
                reportingChannel.waitForConfirms();

                Thread.sleep((long) (secondsDelay * MILLISECONDS_PER_SECOND));
            } catch (IOException | AlreadyClosedException e) {
                LOG.error("IOException caught! Message may not have been published. Exception is: "
                        + e.getMessage(), e);
                // retry after a minute, do not die simply because the launcher is unavailable, it may come back
                Thread.sleep(Base.ONE_MINUTE_IN_MILLISECONDS);
            }
        } catch (InterruptedException e) {
            LOG.info("Heartbeat shutting down.");
            if (reportingChannel.getConnection().isOpen()) {
                try {
                    reportingChannel.getConnection().close();
                } catch (IOException e1) {
                    LOG.error("Error closing reportingChannel connection: " + e1.getMessage(), e1);
                }
            }
            if (reportingChannel.isOpen()) {
                try {
                    reportingChannel.close();
                } catch (IOException e1) {
                    LOG.error("Error (IOException) closing reportingChannel: " + e1.getMessage(), e1);
                } catch (TimeoutException e1) {
                    LOG.error("Error (TimeoutException) closing reportingChannel: " + e1.getMessage(), e1);
                }
            }
            LOG.debug("reporting channel open: " + reportingChannel.isOpen());
            LOG.debug("reporting channel connection open: " + reportingChannel.getConnection().isOpen());

            Thread.currentThread().interrupt();
        }
    }
}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

License:Apache License

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from   ww w. j  a  v  a2 s .c o  m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

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

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:io.snappydata.rabbitmq.RabbitMQPublisher.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, true, false, false, null);

    int logCount = 0;
    int totalNumLogs = 1000000;

    while (logCount <= totalNumLogs) {
        AdImpressionLog log = AdImpressionGenerator.nextRandomAdImpression();
        channel.basicPublish("", QUEUE_NAME, null, getLogBytes(log));
        logCount += 1;//from  w  w  w .  ja va2  s .c om
        if (logCount % 100000 == 0) {
            System.out.println("RabbitMQPublisher published total " + logCount + " messages");
        }
    }

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

From source file:it.txt.ens.authorisationService.util.AccessRequestEvaluator.java

License:Apache License

@Override
public void run() {
    Channel channel = null;
    String correlationId = requestProperties.getCorrelationId();
    String replyTo = requestProperties.getReplyTo();
    try {/*from w w w . java 2 s .co  m*/
        byte[] response = evaluate();
        channel = connection.createChannel();
        isClosed = false;
        channel.addShutdownListener(this);
        if (correlationId != null && replyTo != null) {
            AMQP.BasicProperties replyProperties = new AMQP.BasicProperties.Builder()
                    .correlationId(correlationId).build();
            channel.basicPublish("", replyTo, replyProperties, response);
            if (LOGGER.isLoggable(Level.FINER))
                LOGGER.log(Level.FINER, MESSAGES.getString("responsePublished"));
        } else {
            LOGGER.severe(MESSAGES.getString("missingCorrelationIDAndReplyTo"));
        }
        //            channel.basicAck(envelope.getDeliveryTag(), false);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE,
                MessageFormat.format(MESSAGES.getString("responsePublishFailure"), correlationId, replyTo), e);
    } finally {
        if (channel != null)
            try {
                isClosed = true;
                channel.close();
            } catch (IOException e) {
            } catch (ShutdownSignalException e) {
            }
    }
}

From source file:itinno.example.ExampleRabbitmqClient.java

public static void main(String[] args) {
    Logger logger = null;/*from  w ww  .  j  a v  a  2  s .  co m*/
    String patternLayout = "%5p %d{yyyy-MM-dd HH:mm:ss,sss} %file %t %L: %m%n";

    try {
        // Initialise logger context and logger pattern encoder
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();

        // Set logging pattern (UTF-8 log)
        // logging patterns defined at http://logback.qos.ch/manual/layouts.html
        patternLayoutEncoder.setPattern(patternLayout);
        patternLayoutEncoder.setContext(loggerContext);
        patternLayoutEncoder.setCharset(Charset.forName("UTF-8"));
        patternLayoutEncoder.start();

        // log to console
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
        appender.setContext(loggerContext);
        appender.setEncoder(patternLayoutEncoder);
        appender.start();

        // Finally setup the logger itself
        logger = (Logger) LoggerFactory.getLogger(ExampleRabbitmqClient.class.getName());
        logger.addAppender(appender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    /*try {
    VisualIndexer.init("/home/kandreadou/webservice/learning_files/","127.0.0.1",LoggerFactory.getLogger(ExampleRabbitmqClient.class));
    VisualIndexer v = new VisualIndexer("simtest");
    v.index("http://resources0.news.com.au/images/2012/08/16/1226451/587056-120816-obama.jpg","obama1");
    } catch (Exception ex) {
    System.out.println(ex);
    }*/

    logger.info("rabitmq client started");

    // send a UTF-8 encoded JSON tweet to the RabbitMQ (for stormspout to pick up and send to bolt)
    try {
        // check args
        /*if ( args.length < 1 ) {
        logger.error( "Usage: example_rabbitmq_client <JSON_filename>" );
        System.exit( 1 );
        }
        logger.info( "JSON file = " + args[0] );*/
        String strJSONFilePath = "/home/kandreadou/mklab/example-tweet-utf8.json";

        // check if the path to JSON file exists
        File fileJSON = new File(strJSONFilePath);

        System.out.println(fileJSON.getAbsolutePath());

        if (fileJSON.exists() == false) {
            logger.info("JSON file does not exist : " + strJSONFilePath);
            logger.info("Usage: example_rabbitmq_client <JSON_filename>");
            System.exit(1);
        }

        // read UTF-8 JSON text from file
        logger.info("ExampleRabbitmqClient started");

        List<String> lines = Files.readAllLines(Paths.get(strJSONFilePath), Charset.forName("UTF-8"));
        String strJSON = "";
        for (String line : lines) {
            if (line.length() > 0) {
                strJSON = strJSON + "\n";
            }
            strJSON = strJSON + line;
        }
        logger.info("JSON test message = " + strJSON);

        // connect to rabbitmq broker
        // first of all create connection factory
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri("amqp://guest:guest@localhost:5672/%2F");
        long timestampSinceEpoch = System.currentTimeMillis() / 1000;

        // initialise connection and define channel
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // initialise amqp basic peoperties object
        BasicProperties.Builder basicProperties = new BasicProperties.Builder();
        basicProperties.build();
        basicProperties.timestamp(new Date(timestampSinceEpoch)).build();
        basicProperties.contentType("text/json").build();
        basicProperties.deliveryMode(1).build();

        // publish message
        /* Exchange name should be {assessment_id}+ "_exchange" */
        channel.basicPublish("indexing_exchange", "test-routing", basicProperties.build(),
                strJSON.getBytes("UTF-8"));

        // close connection and channel
        channel.close();
        connection.close();

        logger.info("ExampleRabbitmqClient finished");

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        System.exit(1);
    }
}

From source file:javarpc_server.JavaRPC_Server.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from w ww .  j  ava2 s. c  om*/
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    // TODO code application logic here

    ConnectionFactory factory = new ConnectionFactory();
    System.out.println(factory.getUsername() + " " + factory.getPassword());
    factory.setHost("localhost");

    Connection connection = factory.newConnection();
    Channel 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(" [x] Awaiting RPC requests");

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

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

        String message = new String(delivery.getBody());

        System.out.println(" [.] convert(" + message + ")");
        String response = "" + convert(message);

        channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

From source file:jenkins.plugins.logstash.persistence.RabbitMqDao.java

License:Open Source License

@Override
public void push(String data) throws IOException {
    Connection connection = null;
    Channel channel = null;
    try {/*  w  ww  .  j  a v a  2 s.c om*/
        connection = pool.newConnection();
        channel = connection.createChannel();

        // Ensure the queue exists
        try {
            channel.queueDeclarePassive(key);
        } catch (IOException e) {
            // The queue does not exist and the channel has been closed
            finalizeChannel(channel);

            // Create the queue
            channel = connection.createChannel();
            channel.queueDeclare(key, true, false, false, null);
        }

        channel.basicPublish("", key, null, data.getBytes());
    } finally {
        finalizeChannel(channel);
        finalizeConnection(connection);
    }
}

From source file:joram.amqp.PersistenceKillTest.java

License:Open Source License

public void killingTest() throws Exception {
    senderConnection = new LiveServerConnection("sender", "localhost", 5672, null, null);
    receiverConnection = new LiveServerConnection("receiver", "localhost", 5672, null, null);

    senderConnection.startLiveConnection();
    receiverConnection.startLiveConnection();

    Channel senderChannel = senderConnection.getConnection().createChannel();
    senderChannel.txSelect();//from www .j av a  2  s  .  c  om

    DeclareOk declareOk = senderChannel.queueDeclare("testQueue", true, false, false, null);

    new Thread(new Runnable() {

        int received;
        long totalReceived;

        Channel consumerChannel;
        QueueingConsumer consumer;

        // Consumer thread
        public void run() {

            try {
                consumerChannel = receiverConnection.getConnection().createChannel();
                consumerChannel.txSelect();
                consumer = new QueueingConsumer(consumerChannel);
                consumerChannel.basicConsume("testQueue", false, consumer);
            } catch (Exception exc) {
                exc.printStackTrace();
            }

            while (true) {
                QueueingConsumer.Delivery delivery;
                try {
                    delivery = consumer.nextDelivery();
                    long receivedNb = Long.parseLong(new String(delivery.getBody()));
                    consumer.getChannel().basicAck(delivery.getEnvelope().getDeliveryTag(), false);

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException exc1) {
                    }

                    if (receivedNb < totalReceived) {
                        System.out.println("Duplicate received: " + receivedNb);
                        continue;
                    }

                    // We can receive duplicates but can't miss one message
                    // One duplicate if the channel is transacted, multiple if it is not
                    assertEquals(totalReceived, receivedNb);

                    totalReceived++;
                    received++;

                    consumerChannel.txCommit();

                    if (received == nbMsgRound) {
                        received = 0;
                        synchronized (lock) {
                            lock.notify();
                        }
                    }

                    if (totalReceived == nbMsgRound * nbRounds) {
                        consumer.getChannel().close();
                        return;
                    }

                } catch (Exception ie) {
                    if (totalReceived == nbRounds * nbMsgRound) {
                        return;
                    }
                    System.out.println("Consumer connection broken. Reconnect.");
                    while (!receiverConnection.isConnectionOpen()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException exc) {
                            exc.printStackTrace();
                        }
                    }
                    try {
                        consumerChannel = receiverConnection.getConnection().createChannel();
                        consumerChannel.txSelect();
                        consumer = new QueueingConsumer(consumerChannel);
                        consumerChannel.basicConsume("testQueue", false, consumer);
                    } catch (IOException exc) {
                        exc.printStackTrace();
                    }
                    System.out.println("Consumer Reconnected --- totalReceived = " + totalReceived);
                    continue;
                }
            }
        }
    }).start();

    long start = System.nanoTime();

    // Killer thread
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("Kill server");
                killAgentServer((short) 0);

                Thread.sleep(5000);
                startAgentServer((short) 0);
                System.out.println("server restarted.");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }).start();

    // Sender
    for (int i = 0; i < nbRounds; i++) {
        if (i % 20 == 0) {
            long delta = System.nanoTime() - start;
            System.out.println("Round " + i + " " + ((i * nbMsgRound * 1000000000L) / delta) + " msg/s");
        }
        try {
            for (int j = 0; j < nbMsgRound; j++) {
                senderChannel.basicPublish("", declareOk.getQueue(), MessageProperties.PERSISTENT_BASIC,
                        new Long(i * nbMsgRound + j).toString().getBytes());
            }

            synchronized (lock) {
                senderChannel.txCommit();
                lock.wait();
            }
        } catch (Exception exc) {
            i--;
            System.out.println("Sender connection broken. Reconnect.");
            while (!senderConnection.isConnectionOpen()) {
                Thread.sleep(100);
            }
            senderChannel = senderConnection.getConnection().createChannel();
            senderChannel.txSelect();
            System.out.println("Sender Reconnected");
            Thread.sleep(1000);
            System.out.println("Restart Sender");
        }
    }

    long delta = System.nanoTime() - start;
    System.out.println(delta / 1000000L + " ms");
    System.out.println(((nbRounds * nbMsgRound * 1000000000L) / delta) + " msg/s");

    senderChannel.queueDelete(declareOk.getQueue());

    senderChannel.close();

    senderConnection.stopLiveConnection();
    receiverConnection.stopLiveConnection();

}