/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * 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.itests.cargo.jrmp;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.management.Attribute;
import javax.management.ObjectName;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

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

/**
 * Versioning Service test suite.<br />
 * <br />
 * Note that this also tests various other Java EE aspects of JOnAS, including
 * EJB3, the <code>@EJB</code> annotation in servlets, login modules, etc.
 * 
 * @author S. Ali Tokmen
 */
public class VersioningTest extends TestCommons {

    /**
     * J2EEServer object name.
     */
    private static ObjectName j2eeServer;

    /**
     * Versioning service object name.
     */
    private static ObjectName versioning;

    /**
     * Was versioning started at the beginning of the test?
     */
    private static boolean versioningStarted;

    /**
     * Old default deployment policy if versioning was started at the beginning
     * of the test.
     */
    private static String defaultDeploymentPolicy;

    /**
     * File name of the version 1.0.0.
     */
    private static String version1File;

    /**
     * File name of the version 2.0.0.
     */
    private static String version2File;

    /**
     * File name of the secured-war.
     */
    private static String securedWarFile;

    /**
     * File name of the non-versioned-war.
     */
    private static String nonVersionedWarFile;

    /**
     * File name of the root-war.
     */
    private static String rootWarFile;

    /**
     * Cookie manager that will be used as soon as version 1.0.0 gets deployed.
     * It is expected to stay on version 1.0.0.
     */
    private static CookieManager client1;

    /**
     * Cookie manager that will be used as soon as version 2.0.0 gets deployed.
     * It is expected to stay on version 1.0.0.
     */
    private static CookieManager client2;

    /**
     * Cookie manager that will be used as soon as version 2.0.0 gets set as
     * default version. It is expected to stay on version 2.0.0.
     */
    private static CookieManager client3;

    private String projectVersion;

    @Override
    @BeforeClass
    public void setUp() throws Exception {
        super.setUp();

        // Create all cookie managers
        client1 = new CookieManager();
        client2 = new CookieManager();
        client3 = new CookieManager();

        // ObjectNames used by these tests
        j2eeServer = ObjectName.getInstance("jonas:j2eeType=J2EEServer,name=jonas");
        versioning = ObjectName.getInstance("jonas:type=service,name=versioning");

        projectVersion = System.getProperty("project.version");
        Assert.assertNotNull(projectVersion, "project.version not set!");
    }

    @Test
    public void deactivateDevelopmentMode() throws Exception {
        ObjectName depmonitor = new ObjectName("jonas:type=service,name=depmonitor");
        this.mBeanServerConnection.setAttribute(depmonitor, new Attribute("development", Boolean.FALSE));
    }

    @SuppressWarnings("unchecked")
    @Test(dependsOnMethods = "deactivateDevelopmentMode")
    public void enableVersioning() throws Exception {
        final Object[] opParams = {"versioning"};
        final String[] opSignature = {"java.lang.String"};

        if ("RUNNING".equals(mBeanServerConnection.invoke(j2eeServer, "getServiceState", opParams, opSignature))) {
            versioningStarted = true;
            defaultDeploymentPolicy = (String) mBeanServerConnection.getAttribute(versioning, "DefaultDeploymentPolicy");
            mBeanServerConnection.invoke(j2eeServer, "stopService", opParams, opSignature);
        }

        mBeanServerConnection.invoke(j2eeServer, "startService", opParams, opSignature);
        while (!"RUNNING".equals(mBeanServerConnection.invoke(j2eeServer, "getServiceState", opParams, opSignature))) {
            System.out.println("versioning service not RUNNING yet...");
            Thread.sleep(1000);
        }

        // Get the Versioning service
        boolean versioningEnabled = ((Boolean) mBeanServerConnection.getAttribute(versioning, "VersioningEnabled")).booleanValue();
        if (!versioningEnabled) {
            Assert.fail("Cannot enable the versioning service");
        }
    }

    @Test(dependsOnMethods = "enableVersioning")
    public void testDeployRootWar() throws Exception {
        rootWarFile = deployApplication("root-war/root-war.war");
    }

    @Test(dependsOnMethods = "testDeployRootWar")
    public void testRootWar() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/test.jsp", null, null);

        checkString(response, "Context URL: \"\"");
        checkString(response, "Test image: <img src=\"/image.jpg\" />");
    }

    @Test(dependsOnMethods = "testDeployRootWar")
    public void testRootWarVersionedURL() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/-1.0.0/test.jsp", null, null);

        checkString(response, "Context URL: \"/-1.0.0\"");
        checkString(response, "Test image: <img src=\"/-1.0.0/image.jpg\" />");
    }

    @Test(dependsOnMethods = "testDeployRootWar")
    public void testRootRedirectWithContext() throws Exception {
        URL redirect = new URL("http://localhost:" + webcontainerPort + "/redirect-servlet-with-context");

        HttpURLConnection connection = (HttpURLConnection) redirect.openConnection();
        try {
            connection.setInstanceFollowRedirects(false);

            Assert.assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_MOVED_TEMP);

            String location = connection.getHeaderField("Location");
            Assert.assertEquals(location, "http://localhost:" + webcontainerPort + "/somewhere");
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    @Test(dependsOnMethods = "testDeployRootWar")
    public void testRootRedirectWithoutContext() throws Exception {
        URL redirect = new URL("http://localhost:" + webcontainerPort + "/redirect-servlet-without-context");

        HttpURLConnection connection = (HttpURLConnection) redirect.openConnection();
        try {
            connection.setInstanceFollowRedirects(false);

            Assert.assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_MOVED_TEMP);

            String location = connection.getHeaderField("Location");
            Assert.assertEquals(location, "http://localhost:" + webcontainerPort + "/somewhere");
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    @Test(dependsOnMethods = {"testRootWar", "testRootWarVersionedURL", "testRootRedirectWithContext",
        "testRootRedirectWithoutContext"})
    public void testDeployVersion1() throws Exception {
        version1File = deployApplication("version1.0.0/test-versioning.ear");

        verifyVersion(client1, "1.0.0");
    }

    @Test(dependsOnMethods = "enableVersioning")
    public void testDeployVersionedWelcomeFiles() throws Exception {
        String deployed = deployApplication("welcome-file/test-versioning-welcome.war");

        // Expect a 302 for virtual context access without trailing '/'
        assertHttpRedirectIsOk("http://localhost:" + webcontainerPort + "/welcome",
                               "http://localhost:" + webcontainerPort + "/welcome/");

        // Expect a normal HTML response
        String content = getURL("http://localhost:" + webcontainerPort + "/welcome/");
        System.out.println(content);
        Assert.assertTrue(content.contains("<title>Welcome</title>"));

        // Expect a 302 for versioned context access without trailing '/'
        assertHttpRedirectIsOk("http://localhost:" + webcontainerPort + "/welcome-1.0.0",
                               "http://localhost:" + webcontainerPort + "/welcome-1.0.0/");

        // Expect a normal HTML response
        String content2 = getURL("http://localhost:" + webcontainerPort + "/welcome-1.0.0/");
        System.out.println(content2);
        Assert.assertTrue(content2.contains("<title>Welcome</title>"));

        undeployApplication(deployed);
    }

    private void assertHttpRedirectIsOk(String in, String expected) throws Exception {

        URL redirect = new URL(in);
        HttpURLConnection connection = (HttpURLConnection) redirect.openConnection();
        try {
            connection.setInstanceFollowRedirects(false);

            Assert.assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_MOVED_TEMP);

            String location = connection.getHeaderField("Location");
            Assert.assertEquals(location, expected);
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }

    }

    @Test(dependsOnMethods = "testDeployVersion1")
    public void testDeployVersion2() throws Exception {
        version2File = deployApplication("version2.0.0/test-versioning.ear");

        verifyVersion(client1, "1.0.0");
        verifyVersion(client2, "1.0.0");
    }

    @Test(dependsOnMethods = "testDeployVersion2")
    public void testSetDefaultVersion2() throws Exception {
        final Object[] opParams = {"/test-versioning-2.0.0", "Default"};
        final String[] opSignature = {"java.lang.String", "java.lang.String"};

        ObjectName webModule = ObjectName.getInstance(
            "jonas:j2eeType=WebModule,name=//localhost/test-versioning,J2EEApplication=none,J2EEServer=jonas,virtualContext=true");
        mBeanServerConnection.invoke(webModule, "rebindContext", opParams, opSignature);

        verifyVersion(client1, "1.0.0");
        verifyVersion(client2, "1.0.0");
        verifyVersion(client3, "2.0.0");
    }

    @Test(dependsOnMethods = "testSetDefaultVersion2")
    public void testRedirectWithContext() throws Exception {
        URL redirect = new URL("http://localhost:" + webcontainerPort + "/test-versioning/redirect-servlet-with-context");

        HttpURLConnection connection = (HttpURLConnection) redirect.openConnection();
        try {
            connection.setInstanceFollowRedirects(false);

            Assert.assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_MOVED_TEMP);

            String location = connection.getHeaderField("Location");
            Assert.assertEquals(location, "http://localhost:" + webcontainerPort + "/test-versioning/somewhere");
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    @Test(dependsOnMethods = "testSetDefaultVersion2")
    public void testRedirectWithoutContext() throws Exception {
        URL redirect = new URL("http://localhost:" + webcontainerPort + "/test-versioning/redirect-servlet-without-context");

        HttpURLConnection connection = (HttpURLConnection) redirect.openConnection();
        try {
            connection.setInstanceFollowRedirects(false);

            Assert.assertEquals(connection.getResponseCode(), HttpURLConnection.HTTP_MOVED_TEMP);

            String location = connection.getHeaderField("Location");
            Assert.assertEquals(location, "http://localhost:" + webcontainerPort + "/test-versioning/somewhere");
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    @Test(dependsOnMethods = "testSetDefaultVersion2")
    public void testUndeployVersion1() throws Exception {
        undeployApplication(version1File);

        verifyVersion(client1, "2.0.0");
        verifyVersion(client2, "2.0.0");
        verifyVersion(client3, "2.0.0");
    }

    @Test(dependsOnMethods = {"testUndeployVersion1", "testRedirectWithContext", "testRedirectWithoutContext"})
    public void testUndeployVersion2() throws Exception {
        undeployApplication(version2File);

        verifyVersion(client1, null);
        verifyVersion(client2, null);
        verifyVersion(client3, null);
    }

    @Test(dependsOnMethods = {"testRootWar", "testRootWarVersionedURL"})
    public void testDeploySecuredWar() throws Exception {
        securedWarFile = deployApplication("secured-war/secured-war.war");
    }

    @Test(dependsOnMethods = "testDeploySecuredWar")
    public void testSecuredWarWithoutCredentials() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/", null, null);
        checkString(response, "Connection error: [401] Unauthorized");
    }

    @Test(dependsOnMethods = "testDeploySecuredWar")
    public void testSecuredWarWithIncorrectCredentials() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/", "jetty", "jetty");
        checkString(response, "Connection error: [403] Forbidden");
    }

    @Test(dependsOnMethods = "testDeploySecuredWar")
    public void testSecuredWarWithCorrectCredentials() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/", "jonas", "jonas");
        checkString(response, "Hello, World");
    }

    @Test(dependsOnMethods = "testDeploySecuredWar")
    public void testDeployNonVersionedWarUnderTheSecuredWarContext() throws Exception {
        nonVersionedWarFile = deployApplication("non-versioned-war/non-versioned-war.war");
    }

    @Test(dependsOnMethods = "testDeployNonVersionedWarUnderTheSecuredWarContext")
    public void testNonVersionedWarUnderTheSecuredWarContext() throws Exception {
        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/non-versioned/", null, null);
        checkString(response, "Hello again, World");
    }

    @Test(dependsOnMethods = {"testSecuredWarWithoutCredentials", "testSecuredWarWithIncorrectCredentials",
        "testSecuredWarWithCorrectCredentials", "testNonVersionedWarUnderTheSecuredWarContext"})
    public void testUndeploySecuredWar() throws Exception {
        undeployApplication(securedWarFile);

        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/", null, null);
        checkString(response, "Connection error: [404] Not Found");
    }

    @Test(dependsOnMethods = {"testUndeploySecuredWar"})
    public void testUndeployNonVersionedWarUnderTheSecuredWarContext() throws Exception {
        undeployApplication(nonVersionedWarFile);

        String response = getURL("http://localhost:" + webcontainerPort + "/secured-war/non-versioned/", null, null);
        checkString(response, "Connection error: [404] Not Found");
    }

    @Test(dependsOnMethods = {"testUndeployVersion2", "testUndeployNonVersionedWarUnderTheSecuredWarContext"})
    public void testUndeployRootWar() throws Exception {
        undeployApplication(rootWarFile);

        String response = getURL("http://localhost:" + webcontainerPort + "/test.jsp", null, null);
        // Might be Bad Request (400) or Not Found (404), see JONAS-121
        // The tomcat7 itests module will check for "Connection error: Not Found"
        checkString(response, "Connection error: [404] Not Found");
    }

    @Test(dependsOnMethods = "enableVersioning")
    public void testJonas239() throws Exception {
        final String JAXWS_SAMPLE = "jonas-itests-applications-jaxws-sample";
        String jaxWsSampleURL = null;
        List<String> deployedEars = (List<String>) mBeanServerConnection.getAttribute(j2eeServer, "deployedEars");
        for (String deployedEar : deployedEars) {
            if (deployedEar.contains(JAXWS_SAMPLE)) {
                jaxWsSampleURL = deployedEar;
                break;
            }
        }
        Assert.assertNotNull(jaxWsSampleURL, "Cannot find " + JAXWS_SAMPLE + " in " + deployedEars);

        // Redeploy to have it versioned
        final Object[] opParams = {jaxWsSampleURL};
        final String[] opSignature = {"java.lang.String"};
        mBeanServerConnection.invoke(j2eeServer, "undeploy", opParams, opSignature);
        mBeanServerConnection.invoke(j2eeServer, "deploy", opParams, opSignature);

        String wsdl;
        final String originalURL = "http://localhost:" + webcontainerPort + "/quote/QuoteReporterService";
        final String versionedURL = "http://localhost:" + webcontainerPort + "/quote-" + projectVersion
            + "/QuoteReporterService";

        wsdl = getURL(originalURL + "?wsdl");
        Assert.assertTrue(wsdl.contains(originalURL), "The WSDL does not contain " + originalURL + ":\n" + wsdl);
        Assert.assertFalse(wsdl.contains(versionedURL), "The WSDL contains " + versionedURL + ":\n" + wsdl);

        wsdl = getURL(versionedURL + "?wsdl");
        Assert.assertTrue(wsdl.contains(versionedURL), "The WSDL does not contain " + versionedURL + ":\n" + wsdl);
        Assert.assertFalse(wsdl.contains(originalURL), "The WSDL contains " + originalURL + ":\n" + wsdl);
    }

    @Test(dependsOnMethods = {"testUndeployRootWar", "testJonas239"})
    public void testDisableVersioning() throws Exception {
        final Object[] opParams = {"versioning"};
        final String[] opSignature = {"java.lang.String"};
        mBeanServerConnection.invoke(j2eeServer, "stopService", opParams, opSignature);
        while ("RUNNING".equals(mBeanServerConnection.invoke(j2eeServer, "getServiceState", opParams, opSignature))) {
            System.out.println("versioning service still RUNNING...");
            Thread.sleep(1000);
        }
        if (versioningStarted) {
            versioningStarted = true;
            mBeanServerConnection.invoke(j2eeServer, "startService", opParams, opSignature);
            mBeanServerConnection.setAttribute(versioning, new Attribute("DefaultDeploymentPolicy", defaultDeploymentPolicy));
        }
    }

    private String deployApplication(final String filename) throws Exception {
        Object[] opParams;
        String[] opSignature;

        System.out.println("Now deploying " + filename);
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filename);
        if (inputStream == null) {
            throw new FileNotFoundException("Cannot find \"" + filename + "\" in the class loader");
        }
        byte[] bytesOfFile = IOUtils.toByteArray(inputStream);

        String deployFilename;
        if (filename.contains("/")) {
            deployFilename = filename.substring(filename.lastIndexOf('/'));
        } else {
            deployFilename = filename;
        }
        opParams = new Object[] {bytesOfFile, deployFilename, false};
        opSignature = new String[] {"[B", "java.lang.String", "boolean"};
        String sendFile = (String) mBeanServerConnection.invoke(j2eeServer, "sendFile", opParams, opSignature);

        opParams = new Object[] {sendFile};
        opSignature = new String[] {"java.lang.String"};
        mBeanServerConnection.invoke(j2eeServer, "deploy", opParams, opSignature);

        return sendFile;
    }

    private void undeployApplication(final String filename) throws Exception {
        System.out.println("Now undeploying " + filename);

        Object[] opParams;
        String[] opSignature;

        opParams = new Object[] {filename};
        opSignature = new String[] {"java.lang.String"};
        mBeanServerConnection.invoke(j2eeServer, "undeploy", opParams, opSignature);
        mBeanServerConnection.invoke(j2eeServer, "removeModuleFile", opParams, opSignature);
    }

    private void verifyVersion(final CookieManager cookies, final String version) throws Exception {
        String staticResponse = getURL("http://localhost:" + webcontainerPort + "/test-versioning",
            version == null, cookies);
        String servletResponse = getURL("http://localhost:" + webcontainerPort + "/test-versioning/test-servlet",
            version == null, cookies);
        if (version != null) {
            checkString(staticResponse, "Hello, World");

            checkString(servletResponse, "WAR version: " + version);
            checkString(servletResponse, "EJB version: " + version);

            checkString(servletResponse, "Context URL: \"/test-versioning\"");
            checkString(servletResponse, "Test image: <img src=\"/test-versioning/image.jpg\" />");

            // Output that looks like split but that actually isn't (JONAS-221)
            if ("2.0.0".equals(version)) {
                checkString(servletResponse, "First part: /te ... and no other parts !");
            }
        }

        String jspResponse = getURL("http://localhost:" + webcontainerPort + "/test-versioning/test.jsp",
            version == null, cookies);
        if (version != null) {
            checkString(jspResponse, "Context URL: \"/test-versioning\"");
            checkString(jspResponse, "Test image: <img src=\"/test-versioning/image.jpg\" />");
        }
    }

    private String getURL(final String url, final boolean expect404, final CookieManager cookies) throws Exception {
        URL urlObject = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
        try {
            System.out.println("Sending cookies: " + cookies);
            cookies.setCookies(connection);
            if (expect404) {
                try {
                    connection.getInputStream();
                } catch (Exception ignored) {
                    // We'll check the response code only
                }

                if (connection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
                    Assert.fail("Did not get an error " + HttpURLConnection.HTTP_NOT_FOUND + " but rather a code "
                        + connection.getResponseCode() + " (" + connection.getResponseMessage()
                        + ") after application undeployment!");
                }

                return null;
            } else {
                InputStream inputStream;
                try {
                    inputStream = connection.getInputStream();
                } catch (Exception e) {
                    Assert.fail("HTTP request failed: " + connection.getResponseCode() + " " + connection.getResponseMessage());
                    return null;
                }
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder builder = new StringBuilder();

                String inputLine;
                while ((inputLine = reader.readLine()) != null) {
                    builder.append(inputLine);
                    builder.append(' ');
                }
                reader.close();

                cookies.storeCookies(connection);
                System.out.println("Received cookies: " + cookies);

                return builder.toString();
            }
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    private String getURL(final String url) throws Exception {
        return getURL(url, null, null);
    }

    private String getURL(final String url, final String username, final String password) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        try {
            connection.setRequestMethod("GET");

            if (username != null) {
                Base64 enc = new Base64();
                String authData = username + ":" + password;
                String base64AuthData = enc.encodeToString(authData.getBytes("UTF-8"));
                if (base64AuthData.contains("=")) {
                    // Cut the string at the first equals sign
                    // For some reason, the Base64 implementation adds characters
                    // afterwards, which get refused by the URL validator
                    base64AuthData = base64AuthData.substring(0, base64AuthData.indexOf('='));
                }
                String basicHeader = "Basic " + base64AuthData + '=';

                System.out.println("Setting Authorization header: " + basicHeader);
                connection.setRequestProperty("Authorization", basicHeader);
            } else {
                // FIXME: this can be removed as soon as
                //        https://issues.apache.org/jira/browse/CXF-2702
                //        gets fixed and CXF 2.2.7 gets released.
                Authenticator.setDefault(null);
            }

            String response = null;
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream is = connection.getInputStream();
                try {
                    response = IOUtils.toString(is);
                } finally {
                    is.close();
                    is = null;
                }
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append("Connection error: ");
                sb.append("[");
                sb.append(connection.getResponseCode());
                sb.append("] ");
                sb.append(connection.getResponseMessage());
                printHeaders(sb, connection.getHeaderFields());
                response = sb.toString();
            }

            return response;
        } finally {
            connection.disconnect();
            connection = null;
            System.gc();
        }
    }

    private void printHeaders(StringBuilder sb, Map<String, List<String>> headers) {
        sb.append("\n");
        sb.append("Headers: ");
        sb.append(headers.keySet());
        sb.append("\n");
        for(Map.Entry< String, List < String >> entry : headers.entrySet()) {
            String header = entry.getKey();
            sb.append(" * ");
            sb.append(header);
            sb.append(" : ");
            sb.append(entry.getValue());
            sb.append("\n");
        }
    }

}
