/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006-2007 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.webapp.jonasadmin.resourceadapter;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;
import org.ow2.jonas.webapp.jonasadmin.deploy.BaseDeployAction;
import org.ow2.jonas.webapp.jonasadmin.xml.ArchiveConfigForm;

/**
 * The action used when a Resource Adapter is created.
 * This uses a Velocity template to build up the XML and creates a RAR file.
 *
 * @author Patrick Smith
 */
public class ApplyCreateResourceAdapterAction extends BaseDeployAction {

    /**
     * The location of JOnAS' base directory.
     */
    private String jonasBase = JProp.getJonasBase();

    /**
     * The file separator to use for file access.
     */
    private String fileSeparator = File.separator;

    /**
     * The name of the directory that stores RARs.
     */
    private String rarDir = "rars";

    /**
     * The extention the new files should use.
     */
    private String extention = ".rar";

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

    /**
     * The action to use when the Struts action is executed.
     * Create the appropriate RAR and forward to the RAR configuration tool
     * if no errors exist.
     * @param p_Mapping The ActionMapping for the action.
     * @param p_Form The form used in this action.
     * @param p_Request HTTP Request for the action.
     * @param p_Response The HTTP Response.
     * @throws IOException if the there is a problem with the
     * template files, creation of the RARs.
     * @throws ServletException if the there is a servlet error.
     * @return A forward to the next Struts page.
     */
    @Override
	public ActionForward executeAction(final ActionMapping p_Mapping, final ActionForm p_Form
        , final HttpServletRequest p_Request, final HttpServletResponse p_Response)
        throws IOException, ServletException {

        WhereAreYou oWhere = (WhereAreYou) p_Request.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();
        String domainName = oWhere.getCurrentDomainName();

        // Form used
        CreateResourceAdapterForm oForm = (CreateResourceAdapterForm) p_Form;

        // The path within the new RAR to edit in the xml editor.
        String path;

        // Create a VelocityEngine and set the properties of where to find
        // the templates for the specific rar files.
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(VelocityEngine.VM_LIBRARY, "");
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        try {
            if (oForm.getTemplate().equals("Other")) {
                path = "META-INF/ra.xml";
                createRa(oForm, ve, domainName, serverName);
            } else {
                path = "META-INF/jonas-ra.xml";
                createJonasRa(oForm, ve, domainName, serverName);
            }
        } catch (Exception e) {
            m_Errors.add("error.resourceadapter.load.fail", new ActionMessage(
                    "error.resourceadapter.load.fail", oForm.getRarName()));
            saveErrors(p_Request, m_Errors);
            if (oForm.getTemplate().equals("Other")) {
                return (p_Mapping.findForward("Create Other Resource Adapter"));
            } else {
                return (p_Mapping.findForward("Create JDBC Resource Adapter"));
            }
        }


        m_Session.removeAttribute("createResourceAdapterForm");

        ArchiveConfigForm form = new ArchiveConfigForm();
        form.reset();

        // set the list of deployable files, these are the only files that
        // can be configured
        form.setDeployable(JonasAdminJmx.getRarFilesDeployable(domainName, serverName));
        form.setIsDomain(isDomain());
        form.setJonasBase(getJonasBase());
        form.setArchiveName(oForm.getRarName() + extention);
        form.setPathName(path);
        m_Session.setAttribute("archiveConfigForm", form);
        p_Request.setAttribute("file", path);
        return (p_Mapping.findForward("ActionArchiveConfig"));
    }

// --------------------------------------------------------- Protected Methods

    /**
     * Creates an empty jonas-ra.xml content header.
     * @return The content of an empty jonas-ra XML file.
     */
    protected String createEmptyJonasRa() {
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\"?>\n");
        sb.append("<jonas-connector xmlns=\"http://www.objectweb.org/jonas/ns\" ");
        sb.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
        sb.append("xsi:schemaLocation=\"http://www.objectweb.org/jonas/ns ");
        sb.append("http://www.objectweb.org/jonas/ns/jonas-connector_4_4.xsd\"/>");
        return sb.toString();
    }

    /**
     * Create a ra.xml file (from a Velocity template) and adds it to a RAR file.
     * @param oForm The struts form used in this Struts action.
     * @param ve The Velocity engine that contains the appropriate template.
     * @throws Exception If the invokation of creating the RAR or adding a file to the RAR fails.
     */
    protected void createRa(final CreateResourceAdapterForm oForm, final VelocityEngine ve, final String domainName, final String serverName) throws Exception {
        ve.init();
        VelocityContext context = new VelocityContext();
        context.put("oForm", oForm);
        StringWriter st = new StringWriter();
        String packName = this.getClass().getPackage().getName().replace('/', '.');
        ve.mergeTemplate(packName + "/ra-xml.vm", context, st);
        String raXml = st.toString();

        ObjectName on = JonasAdminJmx.getArchiveConfigObjectName(domainName, serverName);

        String fileName = jonasBase + fileSeparator + rarDir + fileSeparator + oForm.getRarName() + extention;

        Object[] params = new Object[] {fileName,
                                         "META-INF/ra.xml",
                                         raXml};

        String[] sig = new String[] {"java.lang.String",
                                      "java.lang.String",
                                      "java.lang.String" };

        JonasManagementRepr.invoke(on, "createArchiveWithXmlFile", params, sig, serverName);

        params = new Object[] {fileName,
                                "META-INF/jonas-ra.xml",
                                 createEmptyJonasRa()};
        JonasManagementRepr.invoke(on, "addXML", params, sig, serverName);
        }

    /**
     * Create a ra.xml file (from a Velocity template) and adds it to a RAR file.
     * @param oForm The struts form used in this Struts action.
     * @param ve The Velocity engine that contains the appropriate template.
     * @throws Exception If the invokation of creating the RAR or adding a file to the RAR fails.
     */
    protected void createJonasRa(final CreateResourceAdapterForm oForm,
            final VelocityEngine ve, final String domainName, final String serverName) throws Exception {
        ve.init();
        VelocityContext context = new VelocityContext();
        context.put("oForm", oForm);
        StringWriter st = new StringWriter();
        String packName = this.getClass().getPackage().getName().replace('/', '.');
        ve.mergeTemplate(packName + "/jonas-ra-xml.vm", context, st);
        String raXml = st.toString();
        ObjectName on = JonasAdminJmx.getArchiveConfigObjectName(domainName, serverName);

        String fileName = jonasBase + fileSeparator + rarDir + fileSeparator
                + oForm.getRarName() + extention;
        Object[] params = new Object[] {fileName, "META-INF/jonas-ra.xml", raXml };

        String[] sig = new String[] {"java.lang.String", "java.lang.String",
                "java.lang.String" };

        JonasManagementRepr.invoke(on, "createArchiveWithXmlFile", params, sig, serverName);
    }
}
