/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 Bull S.A.S.
 * Contact: jonas-team@objectweb.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.objectweb.jonas.ant.jonasbase.web;

import org.objectweb.jonas.ant.JOnASBaseTask;
import org.objectweb.jonas.ant.jonasbase.JReplace;
import org.objectweb.jonas.ant.jonasbase.Tasks;

/**
 * Support Tomcat Connector Configuration.
 * Prefered order : http, director, ajp, https, cluster.
 *
 * @author Guillaume Sauthier
 */
public class Tomcat extends Tasks {

    /**
     * Info for the logger
     */
    private static final String INFO = "[Tomcat] ";

    /**
     * Tomcat AJP Connector token
     */
    private static final String AJP_CONNECTOR_TOKEN = "<!-- Define an AJP";

    /**
     * Tomcat HTTPS Connector token
     */
    private static final String HTTPS_CONNECTOR_TOKEN = "<!-- Define a SSL Coyote HTTP/1.1";

    /**
     * Proxied HTTP/1.1 COnnector Token used to insert Director Connector.
     */
    private static final String DIRECTOR_CONNECTOR_TOKEN = "<!-- Define a Proxied HTTP/1.1";

    /**
     * Tomcat HTTPS Connector token
     */
    private static final String JVM_ROUTE_TOKEN = "<Engine name=\"jonas\" defaultHost=\"localhost\">";

    /**
     * Is HTTP Configured ?
     */
    private boolean httpConfigured = false;

    /**
     * Default Constructor.
     */
    public Tomcat() {
        super();
    }

    /**
     * Configure a HTTP Connector.
     * @param http HTTP Configuration.
     */
    public void addConfiguredHttp(Http http) {
        httpConfigured = true;
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(Http.DEFAULT_PORT);
        propertyReplace.setValue(http.getPort());
        propertyReplace.setLogInfo(INFO + "Setting HTTP port number to : " + http.getPort());
        addTask(propertyReplace);
    }

    /**
     * Configure a HTTPS Connector.
     * @param https HTTPS Configuration.
     */
    public void addConfiguredHttps(Https https) {
        // Add the HTTPS Connector
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(HTTPS_CONNECTOR_TOKEN);
        StringBuffer value = new StringBuffer();
        value.append("<!-- Define a SSL Coyote HTTP/1.1 Connector on port " + https.getPort() + " -->\n");
        value.append("    <Connector port=\"" + https.getPort() + "\" maxHttpHeaderSize=\"8192\"\n");
        value.append("               maxThreads=\"150\" minSpareThreads=\"25\" maxSpareThreads=\"75\"\n");
        value.append("               enableLookups=\"false\" disableUploadTimeout=\"true\"\n");
        value.append("               acceptCount=\"100\" scheme=\"https\" secure=\"true\"\n");
        value.append("               clientAuth=\"false\" sslProtocol=\"TLS\"\n");
        if (https.getKeystoreFile() != null) {
            value.append("               keystoreFile=\"" + https.getKeystoreFile() + "\"\n");
        }
        if (https.getKeystorePass() != null) {
            value.append("               keystorePass=\"" + https.getKeystorePass() + "\"\n");
        }
        value.append("               />\n\n");
        value.append("    " + HTTPS_CONNECTOR_TOKEN);
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting HTTPS Connector to : " + https.getPort());
        addTask(propertyReplace);

        // Replace redirect port value in HTTP Connector
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(" redirectPort=\"" + Https.DEFAULT_PORT + "\" ");
        propertyReplace.setValue(" redirectPort=\"" + https.getPort() + "\" ");
        propertyReplace.setLogInfo(INFO + "Fix HTTP redirect port number to : " + https.getPort());
        addTask(propertyReplace);

    }

    /**
     * Configure an AJP Connector.
     * @param ajp AJP Configuration.
     */
    public void addConfiguredAjp(Ajp ajp) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(AJP_CONNECTOR_TOKEN);
        StringBuffer value = new StringBuffer();
        value.append(" <!-- Define an AJP 1.3 Connector on port " + ajp.getPort() + " -->\n");
        value.append("    <Connector port=\"" + ajp.getPort() + "\" enableLookups=\"false\"\n");
        value.append("               redirectPort=\"9043\" protocol=\"AJP/1.3\" />\n\n");
        value.append("    " + AJP_CONNECTOR_TOKEN);
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting AJP Connector to : " + ajp.getPort());
        addTask(propertyReplace);

    }

    /**
     * Configure a jvmRoute
     * @param jvmRoute jvm route name
     */
    public void setJvmRoute(String jvmRoute) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(JVM_ROUTE_TOKEN);
        StringBuffer value = new StringBuffer();
        value.append("<Engine name=\"jonas\" defaultHost=\"localhost\" jvmRoute=\"" + jvmRoute + "\">");
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting the jvmRoute to : " + jvmRoute);
        addTask(propertyReplace);
    }

    /**
     * Configure a Director Connector.
     * @param dir Director Configuration.
     */
    public void addConfiguredDirector(Director dir) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);

        propertyReplace.setToken(DIRECTOR_CONNECTOR_TOKEN);
        StringBuffer value = new StringBuffer();
        value.append("<!--  Define a Director Connector on port " + dir.getPort() + " -->\n");
        value.append("    <Connector protocol=\"org.enhydra.servlet.connectionMethods.EnhydraDirector.DirectorProtocol\"\n");
        value.append("               port=\"" + dir.getPort() + "\"\n");
        value.append("               threadTimeout = \"300\"\n");
        value.append("               clientTimeout = \"30\"\n");
        value.append("               sessionAffinity = \"false\"\n");
        value.append("               queueSize = \"400\"\n");
        value.append("               numThreads = \"200\"\n");
        value.append("               bindAddress = \"(All Interfaces)\"\n");
        value.append("               authKey = \"(Unauthenticated)\"\n");
        value.append("               />\n\n");
        value.append("    " + DIRECTOR_CONNECTOR_TOKEN);

        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting Director Connector to : " + dir.getPort());
        addTask(propertyReplace);

    }

    /**
     * Configure a Cluster HTTP Session.
     * @param cluster Cluster HTTP Session.
     */
    public void addConfiguredCluster(Cluster cluster) {
        // General Cluster configuration
        setCluster();

        // Cluster name
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(Cluster.DEFAULT_CLUSTER_NAME);
        propertyReplace.setValue(cluster.getName());
        propertyReplace.setLogInfo(INFO + "Setting Cluster name : " + cluster.getName());
        addTask(propertyReplace);

        // Cluster listening port
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(Cluster.DEFAULT_LISTEN_PORT);
        propertyReplace.setValue(cluster.getListenPort());
        propertyReplace.setLogInfo(INFO + "Setting Cluster listen port : " + cluster.getListenPort());
        addTask(propertyReplace);

        // Cluster Multicast Address
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(Cluster.DEFAULT_MCAST_ADDR);
        propertyReplace.setValue(cluster.getMcastAddr());
        propertyReplace.setLogInfo(INFO + "Setting Cluster multicast addr : " + cluster.getMcastAddr());
        addTask(propertyReplace);

        // Cluster Multicast Port
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken(Cluster.DEFAULT_MCAST_PORT);
        propertyReplace.setValue(cluster.getMcastPort());
        propertyReplace.setLogInfo(INFO + "Setting Cluster multicast port : " + cluster.getMcastPort());
        addTask(propertyReplace);

    }

    /**
     * Enable the cluster feature.
     */
    private void setCluster() {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(JOnASBaseTask.TOMCAT_CONF_FILE);
        propertyReplace.setToken("</Host>");
        StringBuffer value = new StringBuffer("\n");
        value.append("        <Cluster className=\"org.apache.catalina.cluster.tcp.SimpleTcpCluster\"\n");
        value.append("            clusterName=\"" + Cluster.DEFAULT_CLUSTER_NAME + "\"\n");
        value.append("            managerClassName=\"org.apache.catalina.cluster.session.DeltaManager\"\n");
        value.append("            expireSessionsOnShutdown=\"false\"\n");
        value.append("            useDirtyFlag=\"true\"\n");
        value.append("            notifyListenersOnReplication=\"true\">\n");
        value.append("          <Membership\n");
        value.append("              className=\"org.apache.catalina.cluster.mcast.McastService\"\n");
        value.append("              mcastAddr=\"" + Cluster.DEFAULT_MCAST_ADDR + "\"\n");
        value.append("              mcastPort=\"" + Cluster.DEFAULT_MCAST_PORT + "\"\n");
        value.append("              mcastFrequency=\"500\"\n");
        value.append("              mcastDropTime=\"3000\" />\n");
        value.append("          <Receiver\n");
        value.append("              className=\"org.apache.catalina.cluster.tcp.ReplicationListener\"\n");
        value.append("              tcpListenAddress=\"auto\"\n");
        value.append("              tcpListenPort=\"" + Cluster.DEFAULT_LISTEN_PORT + "\"\n");
        value.append("              tcpSelectorTimeout=\"100\"\n");
        value.append("              tcpThreadCount=\"6\" />\n");
        value.append("          <Sender\n");
        value.append("              className=\"org.apache.catalina.cluster.tcp.ReplicationTransmitter\"\n");
        value.append("              replicationMode=\"pooled\"\n");
        value.append("              ackTimeout=\"15000\" />\n");
        value.append("          <Valve className=\"org.apache.catalina.cluster.tcp.ReplicationValve\"\n");
        value.append("                 filter=\".*\\.gif;.*\\.js;.*\\.jpg;.*\\.png;.*\\.htm;.*\\.html;.*\\.css;.*\\.txt;\" />\n");

                //              "          <Deployer className=\"org.apache.catalina.cluster.deploy.FarmWarDeployer\"" + "\n" +
                //              "                    tempDir=\"/tmp/war-temp/\"" + "\n" +
                //              "                    deployDir=\"/tmp/war-deploy/\"" + "\n" +
                //              "                    watchDir=\"/tmp/war-listen/\"" + "\n" +
                //              "                    watchEnabled=\"false\"/>" +"\n" +
        value.append("        </Cluster>\n");
        value.append("      </Host>");
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting Cluster");
        addTask(propertyReplace);
    }

    /**
     * @return Returns <code>true</code> if HTTP is configured.
     */
    public boolean isHttpConfigured() {
        return httpConfigured;
    }


}
