/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 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 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;

import javax.management.Attribute;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Multitenant Service test suite.<br />
 * <br />
 *
 * @author Mohammed Boukada
 */
public class MultitenantTest extends TestCommons {

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

    /**
     * Multitenant service object name.
     */
    private static ObjectName multitenant;

    /**
     * Was multitenant started at the beginning of the test?
     */
    private static boolean multitenantStarted;

    /**
     * File name of test-multitenant-war.war
     */
    private String tenantWar;

    /**
     * File name of test-multitenant-T1.ear
     */
    private String tenant1File;

    /**
     * File name of test-multitenant-T2.ear
     */
    private String tenant2File;

    /**
     * Project version
     */
    private String projectVersion;

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

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

        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 enableMultitenant() throws Exception {
        final Object[] opParams = {"multitenant"};
        final String[] opSignature = {"java.lang.String"};

        if ("RUNNING".equals(mBeanServerConnection.invoke(j2eeServer, "getServiceState", opParams, opSignature))) {
            multitenantStarted = true;
            mBeanServerConnection.invoke(j2eeServer, "stopService", opParams, opSignature);
        }

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

    @Test(dependsOnMethods = "enableMultitenant")
    public void testDeployTenantWar() throws Exception {
        tenantWar = deployApplication("tenant-war/test-multitenant-war.war");
        String response = getURL("http://localhost:" + webcontainerPort + "/multitenant-war", null, null);
        checkString(response, "Connection error: [404] Not Found");
        response = getURL("http://localhost:" + webcontainerPort + "/T99/multitenant-war", null, null);
        checkString(response, "Hello World! This is a multitenant war application");
    }

    @Test(dependsOnMethods = "testDeployTenantWar")
    public void testUndeployTenantWar() throws Exception {
        undeployApplication(tenantWar);

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

    @Test(dependsOnMethods = "enableMultitenant")
    public void testDeployTenants() throws Exception {
        tenant1File = deployApplication("tenant-ear/test-multitenant-T1.ear");
        // Test context root customization
        String response = getURL("http://localhost:" + webcontainerPort + "/test-multitenant", null, null);
        checkString(response, "Connection error: [404] Not Found");
        response = getURL("http://localhost:" + webcontainerPort + "/T1/test-multitenant", null, null);
        checkString(response, "Hello, World!");
        response = getURL("http://localhost:" + webcontainerPort + "/T1/test-multitenant/test-servlet", null, null);
        checkString(response, "TestServlet : Hey !");
        tenant2File = deployApplication("tenant-ear/test-multitenant-T2.ear");
        response = getURL("http://localhost:" + webcontainerPort + "/test-multitenant", null, null);
        checkString(response, "Connection error: [404] Not Found");
        response = getURL("http://localhost:" + webcontainerPort + "/T2/test-multitenant", null, null);
        checkString(response, "Hello, World!");
        response = getURL("http://localhost:" + webcontainerPort + "/T2/test-multitenant/test-servlet", null, null);
        checkString(response, "TestServlet : Hey !");

        // Test MBeans customization
        Assert.assertFalse(mBeanServerConnection.isRegistered(new ObjectName("Hello:type=HelloObject")),
                "MBean ObjectName must be prefixed by tenant-id");
        Assert.assertTrue(mBeanServerConnection.isRegistered(new ObjectName("Hello:type=HelloObject,tenant-id=T1")),
                "MBean ObjectName must be prefixed by tenant-id");
        Assert.assertTrue(mBeanServerConnection.isRegistered(new ObjectName("Hello:type=HelloObject,tenant-id=T2")),
                "MBean ObjectName must be prefixed by tenant-id");

        List<String> jndiNames = listJNDINames();
        String notBoundName = "javaEEApplicationName/test-multitenant/Hello";
        String nameT1 = "T1/javaEEApplicationName/test-multitenant/Hello";
        String nameT2 = "T2/javaEEApplicationName/test-multitenant/Hello";

        if (jndiNames.contains(notBoundName)) {
            throw new Exception(notBoundName + " must not be bound, it is not prefixed by tenant-id");
        }
        if (!jndiNames.contains(nameT1)) {
            throw new Exception(nameT1 + " must be bound for T1");
        }
        if (!jndiNames.contains(nameT2)) {
            throw new Exception(nameT2 + " must be bound for T2");
        }
    }

    @Test(dependsOnMethods = "testDeployTenants")
    public void testUndeployTenants() throws Exception {
        undeployApplication(tenant1File);
        String response = getURL("http://localhost:" + webcontainerPort + "/T1/test-multitenant", null, null);
        checkString(response, "Connection error: [404] Not Found");

        undeployApplication(tenant2File);
        response = getURL("http://localhost:" + webcontainerPort + "/T2/test-multitenant", null, null);
        checkString(response, "Connection error: [404] Not Found");
    }

    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 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");
        }
    }

    private List<String> listJNDINames() throws Exception {
        List<String> listJNDINames = new ArrayList<String>();
        try {
            ArrayList<ObjectName> ons = listJNDIResources("jonas", "jonas", mBeanServerConnection);
            for (ObjectName on : ons) {
                try {
                    String[] names = (String[]) mBeanServerConnection.getAttribute(on, "Names");
                    for (int i = 0; i < names.length; i++) {
                        listJNDINames.add(names[i]);
                    }
                } catch (MBeanException e) {
                    throw new Exception("Cannot access MBean attributes values (" + on + ").",e);

                }
            }
        } catch (Exception e) {
            throw new Exception("Cannot list bound JNDI names.", e);
        }
        return listJNDINames;
    }

    public static ArrayList<ObjectName> listJNDIResources(final String domain, final String server, final MBeanServerConnection conn) throws Exception {
        ArrayList<ObjectName> res = new ArrayList<ObjectName>();
        // Get JNDIResource MBean
        ObjectName ons = getJ2eeMBean(domain, server, "JNDIResource");
        Set onSet = conn.queryNames(ons, null);
        Iterator<ObjectName> it = onSet.iterator();
        while(it.hasNext()) {
            res.add(it.next());
        }
        return res;
    }

    private static ObjectName getJ2eeMBean(final String domain, final String server, final String type) throws MalformedObjectNameException {
        StringBuilder sb = new StringBuilder(domain);
        sb.append(":");
        sb.append("J2EEServer");
        sb.append("=");
        sb.append(server);
        sb.append(",");
        sb.append("j2eeType");
        sb.append("=");
        sb.append(type);
        sb.append(",*");
        return ObjectName.getInstance(sb.toString());
    }
}
