/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activemq;

import java.util.concurrent.CountDownLatch;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class JmsSendWithAsyncCallbackTest extends TestSupport {

    private static final Logger LOG = LoggerFactory.getLogger(JmsSendWithAsyncCallbackTest.class);

    private Connection connection;

    protected void setUp() throws Exception {
        super.setUp();
        connection = createConnection();
    }

    /**
     * @see junit.framework.TestCase#tearDown()
     */
    protected void tearDown() throws Exception {
        if (connection != null) {
            connection.close();
            connection = null;
        }
        super.tearDown();
    }

    public void testAsyncCallbackIsFaster() throws JMSException, InterruptedException {
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(getName());

        // setup a consumer to drain messages..
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
            }
        });

        // warmup...
        for(int i=0; i < 10; i++) {
            benchmarkNonCallbackRate();
            benchmarkCallbackRate();
        }

        double callbackRate = benchmarkCallbackRate();
        double nonCallbackRate = benchmarkNonCallbackRate();

        LOG.info(String.format("AsyncCallback Send rate: %,.2f m/s", callbackRate));
        LOG.info(String.format("NonAsyncCallback Send rate: %,.2f m/s", nonCallbackRate));

        // The async style HAS to be faster than the non-async style..
        assertTrue( callbackRate/nonCallbackRate > 1.5 );
    }

    private double benchmarkNonCallbackRate() throws JMSException {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(getName());
        int count = 1000;
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            producer.send(session.createTextMessage("Hello"));
        }
        return 1000.0 * count / (System.currentTimeMillis() - start);
    }

    private double benchmarkCallbackRate() throws JMSException, InterruptedException {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(getName());
        int count = 1000;
        final CountDownLatch messagesSent = new CountDownLatch(count);
        ActiveMQMessageProducer producer = (ActiveMQMessageProducer) session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            producer.send(session.createTextMessage("Hello"), new AsyncCallback() {
                @Override
                public void onSuccess() {
                    messagesSent.countDown();
                }

                @Override
                public void onException(JMSException exception) {
                    exception.printStackTrace();
                }
            });
        }
        messagesSent.await();
        return 1000.0 * count / (System.currentTimeMillis() - start);
    }
}

@@ -1378,16 +1378,30 @@
 ction;%0A%0A
+    @Override%0A
     prot
@@ -1430,32 +1430,32 @@
 ows Exception %7B%0A
-
         super.se
@@ -1573,16 +1573,30 @@
      */%0A
+    @Override%0A
     prot
@@ -2345,15 +2345,18 @@
  for
+ 
 (int i
-=
+ = 
 0; i
@@ -2845,22 +2845,111 @@
 rue(
- callbackRate/
+%22async rate%5B%22 + callbackRate + %22%5D should beat non-async rate%5B%22 + nonCallbackRate + %22%5D%22, callbackRate / 
 nonC
@@ -2965,17 +2965,16 @@
 te %3E 1.5
- 
 );%0A    %7D

Add an information message to the assert so we can see how much it failed by.