/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006-2008 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.ant.jonasbase.web;

import org.ow2.jonas.ant.JOnASBaseTask;
import org.ow2.jonas.ant.jonasbase.JReplace;
import org.ow2.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(final 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(final 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(final 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(final 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(final 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(final 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.ha.tcp.SimpleTcpCluster\"\n");
        value.append("            channelSendOptions=\"8\">\n");
        value.append("            <Manager className=\"org.apache.catalina.ha.session.DeltaManager\"\n");
        value.append("                expireSessionsOnShutdown=\"false\"\n");
        value.append("                notifyListenersOnReplication=\"true\"/>\n");
        value.append("            <Channel className=\"org.apache.catalina.tribes.group.GroupChannel\">\n");
        value.append("                <Membership\n");
        value.append("                    className=\"org.apache.catalina.tribes.membership.McastService\"\n");
        value.append("                    addr=\"" + Cluster.DEFAULT_MCAST_ADDR + "\"\n");
        value.append("                    port=\"" + Cluster.DEFAULT_MCAST_PORT + "\"\n");
        value.append("                    frequency=\"500\"\n");
        value.append("                    dropTime=\"3000\" />\n");
        value.append("                <Receiver\n");
        value.append("                    className=\"org.apache.catalina.tribes.transport.nio.NioReceiver\"\n");
        value.append("                    address=\"auto\"\n");
        value.append("                    port=\"" + Cluster.DEFAULT_LISTEN_PORT + "\"\n");
        value.append("                    autoBind=\"100\"\n");
        value.append("                    selectorTimeout=\"100\"\n");
        value.append("                    maxThread=\"6\" />\n");
        value.append("                <Sender\n");
        value.append("                    className=\"org.apache.catalina.tribes.transport.ReplicationTransmitter\">\n");
        value.append("                    <Transport\n");
        value.append("                        className=\"org.apache.catalina.tribes.transport.nio.PooledParallelSender\"/>\n");
        value.append("                </Sender>\n");
        value.append("                <Interceptor className=\"org.apache.catalina.tribes.group.interceptors.TcpFailureDetector\"/>\n");
        value.append("                <Interceptor className=\"org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor\"/>\n");
        value.append("            </Channel>\n");
        value.append("            <Valve className=\"org.apache.catalina.ha.tcp.ReplicationValve\"\n");
        value.append("                 filter=\".*\\.gif;.*\\.js;.*\\.jpg;.*\\.png;.*\\.htm;.*\\.html;.*\\.css;.*\\.txt;\" />\n");
        value.append("            <Valve className=\"org.apache.catalina.ha.session.JvmRouteBinderValve\"/>\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("            <ClusterListener className=\"org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener\"/>\n");
        value.append("            <ClusterListener className=\"org.apache.catalina.ha.session.ClusterSessionListener\"/>\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;
    }


}
