/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.tests;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;

import javax.management.Attribute;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;



/**
 * Tests the JOnAS - CARGO plug-in. This test is expected to work with JOnAS 4
 * and JOnAS 5 without any issues.
 *
 * @author S. Ali Tokmen
 * @author Florent Benoit junit->TestNG and Connection leaks checks
 */
public class CargoTest {

    private static int TIMEOUT = 10;

    private int port;
    private int rmiPort;


    @BeforeClass
    public void setUp() {
        String webcontainerPort = System.getProperty("webcontainer.port");
        Assert.assertNotNull(webcontainerPort, "webcontainer.port not set!");
        this.port = Integer.parseInt(webcontainerPort);
        String carolPort = System.getProperty("carol.port");
        Assert.assertNotNull(carolPort, "carolPort not set!");
        this.rmiPort = Integer.parseInt(carolPort);
    }

    @Test
    public void testCargo() throws Exception {
        final URL url = new URL("http://localhost:" + port + "/cargocpc/index.html");
        final String expected = "Cargo Ping Component used to verify if the container is started.";

        String content = null;
        final long stopTime = System.currentTimeMillis() + CargoTest.TIMEOUT * 1000;
        while (System.currentTimeMillis() < stopTime) {
            Thread.sleep(1000);
            content = this.getContentAsString(url);
            if (content.contains(expected)) {
                break;
            }
        }

        Assert.assertTrue(content.contains(expected), content + " does not contain " + expected);
    }


    /**
     * Test that the connection leak closing mechanism is working
     * @throws Exception
     */
    @Test
    public void testConnectionLeak() throws Exception {

        // Connect to the JMX server
        MBeanServerConnection mBeanServerConnection = getMBeanServerConnection();

        int CONNECTION_LEAKS_REQUEST= 3;

        ObjectName datasourceON = new ObjectName("jonas:j2eeType=JCAConnectionFactory,name=jdbc_1,JCAResource=jdbc_1,J2EEServer=jonas");
        ObjectName jndiJDBCInterceptorON = new ObjectName("jonas:type=service,name=jndi-interceptors,interceptor=org.ow2.jonas.jndi.interceptors.impl.datasource.DataSourceLeakDetectorContextInterceptor");


        // Check there is no busy connections
        Integer currentBusy = (Integer) mBeanServerConnection.getAttribute(datasourceON, "currentBusy");
        Assert.assertNotNull(currentBusy);
        Assert.assertEquals(currentBusy.intValue(), 0);


        // Do some connection leaks
        for (int i = 0; i < CONNECTION_LEAKS_REQUEST; i++) {
            hitConnectionLeakServlet();
        }

        // Check busy are still to 0 (automatic close of connection leak is working)
        currentBusy = (Integer) mBeanServerConnection.getAttribute(datasourceON, "currentBusy");
        Assert.assertEquals(currentBusy.intValue(), 0);


        // Disable automatic close of connection leaks
        Attribute attribute = new Attribute("forceClose", false);
        mBeanServerConnection.setAttribute(jndiJDBCInterceptorON, attribute);

        // Do some connection leaks
        for (int i = 0; i < CONNECTION_LEAKS_REQUEST; i++) {
            hitConnectionLeakServlet();
        }

        // Check that now we have busy connections
        currentBusy = (Integer) mBeanServerConnection.getAttribute(datasourceON, "currentBusy");
        Assert.assertEquals(currentBusy.intValue(), CONNECTION_LEAKS_REQUEST);

    }

    /**
     * @return MBean Server connection to the remote server
     * @throws IOException
     */
    protected MBeanServerConnection getMBeanServerConnection() throws IOException {
     // The address of the connector server
        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi://localhost/jndi/rmi://localhost:" + rmiPort + "/jrmpconnector_jonas");

        // The environment map, null in this case
        Map<String, ?> environment = null;

        // Connector
        JMXConnector jmxConnector = JMXConnectorFactory.connect(address, environment);

        // Get connection
        return jmxConnector.getMBeanServerConnection();
    }



    /**
     * Make a request and check that the result is OK
     */
    protected void hitConnectionLeakServlet() throws Exception {
        // Connect on the servlet that is making connection leaks
        final URL url = new URL("http://localhost:" + port + "/connection-leaks/");
        final String expected = "Example OK";

        String content = null;
        final long stopTime = System.currentTimeMillis() + CargoTest.TIMEOUT * 1000;
        while (System.currentTimeMillis() < stopTime) {
            Thread.sleep(1000);
            content = this.getContentAsString(url);
            if (content.contains(expected)) {
                break;
            }
        }
        // Check expected value
        Assert.assertTrue(content.contains(expected), content + " does not contain " + expected);

    }


    /**
     * Get the URL content as a String.
     * @param url the url
     * @return the URL content as a String
     * @throws IOException if an I/O exception occurs.
     */
    private String getContentAsString(final URL url) throws IOException {
        final InputStream inStream = url.openStream();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            int c;
            while ((c = inStream.read()) != -1) {
                bos.write(c);
            }
        } finally {
            inStream.close();
            bos.flush();
        }
        final String urlString = bos.toString();
        return urlString;
    }

}
