/**
 * 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: ApplyCatalinaAccessLoggerAction.java 16123 2009-01-08 12:46:35Z eyindanga $
 * --------------------------------------------------------------------------
 */

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

import java.io.IOException;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.JonasAdminException;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * @author Michel-Ange ANTON
 * @author Adriana Danes
 */
public class ApplyCatalinaAccessLoggerAction extends BaseLoggerAction {

    /**
     * Signature for the <code>createStandardConnector</code> operation.
     */
    private String sa_CreateAccessLogger[] = {
        "java.lang.String"
    };

    private static String sDefaultForward = "ActionEditWebAppCatalina";

// --------------------------------------------------------- Protected Variables

// --------------------------------------------------------- Public Methods
     /**
     * Execute CatalinaAccessLogger action
     * @param pForm The current form
     * @param pMapping The current mapping
     * @param pRequest The current request
     * @param pResponse The response to the current request
     * @return The forward to go to the next page
     * @throws Exception
     */
    public ActionForward executeAction(ActionMapping pMapping, ActionForm pForm
        , HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws IOException, ServletException {

        // Default forward
        ActionForward oForward = null;

        // Form used
        CatalinaAccessLogValveForm oForm = (CatalinaAccessLogValveForm) pForm;

        // Populate
        try {
            if ("create".equals(oForm.getAction())) {
                oForward = createAccessLogger(oForm, pMapping, pRequest);
            } else if ("edit".equals(oForm.getAction())) {
                // Save in memory the new datas
                oForward = populateMbean(oForm
                    , pMapping.findForward("ActionEditCatalinaAccessLogger"), pMapping, pRequest);
            }
        } catch (JonasAdminException e) {
            // Build error
            m_Errors.add("logger.catalina.access", new ActionMessage(e.getId()));
            saveErrors(pRequest, m_Errors);
            // Return to the current page
            oForward = new ActionForward(pMapping.getInput());
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(pRequest, m_Errors);
            oForward = pMapping.findForward("Global Error");
        }

        // Next Forward
        return oForward;
    }

    /**
     * Create a new access logger.
     * @param pForm The current form
     * @param pMapping The current mapping
     * @param pRequest The current request
     * @return The forward to go to the next page
     * @throws Exception
     */
    protected ActionForward createAccessLogger(CatalinaAccessLogValveForm pForm
        , ActionMapping pMapping, HttpServletRequest pRequest)
        throws Exception {
        Object values[] = null;
        // Look up the Catalina MBeanFactory
        ObjectName onFactory = CatalinaObjectName.catalinaFactory();
        // Create a new Access Logger Valve object
        values = new Object[1];
        String domainName = m_WhereAreYou.getCurrentCatalinaDomainName();
        // Determine container type
        String containerType = pForm.getContainerType();
        if (containerType.equals(m_Resources.getMessage("label.loggers.container.engine"))) {
            ObjectName onEngine = CatalinaObjectName.catalinaEngine(domainName);
            values[0] = (onEngine).toString();
        } else if (containerType.equals(m_Resources.getMessage("label.loggers.container.host"))) {
            ObjectName onHost = CatalinaObjectName.catalinaHost(domainName, pForm.getContainerName());
            values[0] = (onHost).toString();
        }
        WhereAreYou oWhere = (WhereAreYou) pRequest.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String jonasServerName = oWhere.getCurrentJonasServerName();
        Object onValve = JonasManagementRepr.invoke(onFactory
                , "createAccessLoggerValve",
                values,
                sa_CreateAccessLogger,
                jonasServerName);
        pForm.setObjectName((String) onValve);
        // Populate
        ActionForward oForward = populateMbean(pForm, pMapping.findForward("ActionListLoggers")
            , pMapping, pRequest);

        // refresh tree
        refreshTree(pRequest);
        // Force the node selected in tree
        m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER) + WhereAreYou.NODE_SEPARATOR
            + "logging" + WhereAreYou.NODE_SEPARATOR + LoggerItem.LOGGER_CATALINA_ACCESS_HOST, true);

        // Return the next forward
        return oForward;
    }

    /**
     * Populate the Mbean Access Logger.
     * @param p_Form The current form
     * @param p_Forward The current forward
     * @param p_Mapping The current mapping
     * @param p_Request The current request
     * @return If 'save' is requested then return the new forward to save
     * else return the current forward
     * @throws Exception Failed to populate Mbean
     */
    protected ActionForward populateMbean(CatalinaAccessLogValveForm p_Form
        , ActionForward p_Forward, ActionMapping p_Mapping, HttpServletRequest p_Request)
        throws Exception {
        ActionForward oForward = p_Forward;
        // Access logger
        ObjectName on = new ObjectName(p_Form.getObjectName());
        setStringAttribute(on, "directory", p_Form.getDirectory());
        setStringAttribute(on, "prefix", p_Form.getPrefix());
        setStringAttribute(on, "suffix", p_Form.getSuffix());
        setBooleanAttribute(on, "resolveHosts", p_Form.isResolveHosts());
        setBooleanAttribute(on, "rotatable", p_Form.isRotatable());
        setStringAttribute(on, "pattern", p_Form.getPattern());
        // Save in configuration file
        if (p_Form.isSave()) {
            //ObjectName onServer = CatalinaObjectName.catalinaServer();
            //JonasManagementRepr.invoke(onServer, "store", null, null);
            p_Form.setSave(false);
            p_Request.setAttribute("forward", p_Forward.getName());
            oForward = p_Mapping.findForward("ActionEditServletServer");
        }
        return oForward;
    }

}
