/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2003-2005 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: CatalinaAccessLogValveForm.java 16123 2009-01-08 12:46:35Z eyindanga $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.logging;

import java.util.List;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.servlet.http.HttpServletRequest;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.base.mbean.CatalinaObjectName;
import org.ow2.jonas.webapp.jonasadmin.Jlists;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * @author Michel-Ange ANTON
 * @author Adriana Danes
 */

public final class CatalinaAccessLogValveForm extends CatalinaValveForm {

// ----------------------------------------------------- Properties Variables

    /**
     * directory in which log files will be placed
     */
    private String directory = null;
    /**
     * A formatting layout
     */
    private String pattern = null;
    /**
     * prefix added to the start of each log file's name
     */
    private String prefix = null;
    /**
     * suffix added to the end of each log file's name
     */
    private String suffix = null;
    /**
     * Deafult true. Flag to determine if log rotation should occure.
     */
    private boolean rotatable = true;
    /**
     * Set to true to convert the IP address of the remote host into the corresponding host name via a DNS lookup.
     * Set to false to skip this lookup, and report the remote IP address instead.
     */
    private boolean resolveHosts = false;
    /**
     *
     */
    private List booleanValues = Jlists.getBooleanValues();
    /**
     * Domain name used to construct Catalina MBean ObjectNames (JOnAS server name in general)
     */
    private String catalinaDomainName = null;

// --------------------------------------------------------- Public Methods

    public void reset(ActionMapping mapping, HttpServletRequest request) {
        super.reset(mapping, request);
        directory = "logs";
        prefix = "access_log.";
        suffix = ".txt";
        pattern = "%h %l %u %t \"%r\" %s %b";
        resolveHosts = false;
        rotatable = true;
        String[] containerTypes = {"Engine", "Host"};
        setContainerTypes(containerTypes);
    }

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

        WhereAreYou oWhere = (WhereAreYou) request.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();

        ActionErrors oErrors = new ActionErrors();
        // prefix
        if ((prefix == null) || (prefix.length() < 1)) {
            oErrors.add("pattern", new ActionMessage("error.logger.catalina.access.prefix.required"));
        }
        // default is a 0 length string
        if ((suffix == null) || (suffix.length() < 1)) {
            suffix = "";
        }
        // pattern
        if ((pattern == null) || (pattern.length() < 1)) {
            oErrors.add("pattern", new ActionMessage("error.logger.catalina.access.pattern.required"));
        }
        // Test the provided Engine or Host names only in case we are in a "create" action
        if (getAction().equals("edit")) {
            return oErrors;
        }
        if (getContainerType().equals("Engine")) {
            // Test if no access valve set already on the Engine
            ObjectName onEngine = null;
            try {
                onEngine = CatalinaObjectName.catalinaEngine(catalinaDomainName);
            } catch (MalformedObjectNameException e) {
                oErrors.add("", new ActionMessage(e.toString()));
                return oErrors;
            }
            ObjectName[] valveOns = (ObjectName[]) JonasManagementRepr.getAttribute(onEngine, "valveObjectNames", serverName);
            for (int i = 0; i < valveOns.length; i++) {
                ObjectName valveOn = valveOns[i];
                if (valveOn != null) { // can be null because bug in Tomacat (after a remove)
                    String valveName = valveOn.getKeyProperty("name");
                    if (valveName.equals("AccessLogValve")) {
                        // we already have an AccessLogValve associated to the Engine
                        oErrors.add("", new ActionMessage("error.logger.catalina.access.log.engine.alreadypresent"));
                        break;
                    }
                }
            }
        }
        if (getContainerType().equals("Host")) {
            // Test if no access valve set already on the choosen host
            ObjectName onHost;
            try {
                onHost = CatalinaObjectName.catalinaHost(catalinaDomainName, getContainerName());
            } catch (MalformedObjectNameException e) {
                oErrors.add("", new ActionMessage(e.toString()));
                return oErrors;
            }
            if (!JonasManagementRepr.isRegistered(onHost, serverName)) {
                oErrors.add("", new ActionMessage("error.logger.catalina.access.log.nohost"));
            } else {
                ObjectName[] valveOns = (ObjectName[]) JonasManagementRepr.getAttribute(onHost, "valveObjectNames", serverName);
                for (int i = 0; i < valveOns.length; i++) {
                    ObjectName valveOn = valveOns[i];
                    if (valveOn != null) { // can be null because bug in Tomacat (after a remove)
                        String valveName = valveOn.getKeyProperty("name");
                        if (valveName.equals("AccessLogValve")) {
                        // we already have an AccessLogValve associated to the Host
                        oErrors.add("", new ActionMessage("error.logger.catalina.access.log.host.alreadypresent"));
                        break;
                        }
                    }
                }
            }
        }
        return oErrors;
    }

// ------------------------------------------------------------- Properties Methods

    public List getBooleanValues() {
        return booleanValues;
    }

    public void setBooleanValues(List booleanValues) {
        this.booleanValues = booleanValues;
    }

    public String getDirectory() {
        return this.directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    public String getPattern() {
        return this.pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getPrefix() {
        return this.prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return this.suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public boolean isResolveHosts() {
        return this.resolveHosts;
    }

    public void setResolveHosts(boolean resolveHosts) {
        this.resolveHosts = resolveHosts;
    }

    public boolean isRotatable() {
        return this.rotatable;
    }

    public void setRotatable(boolean rotatable) {
        this.rotatable = rotatable;
    }

    /**
     * @return Returns the catalinaDomainName.
     */
    public String getCatalinaDomainName() {
        return catalinaDomainName;
    }


    /**
     * @param catalinaDomainName The catalinaDomainName to set.
     */
    public void setCatalinaDomainName(String catalinaDomainName) {
        this.catalinaDomainName = catalinaDomainName;
    }

}
