/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2009 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: AxisService.java 19490 2010-03-22 12:40:39Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ws.axis;

import java.io.File;

import javax.xml.namespace.QName;

import org.apache.axis.AxisProperties;
import org.apache.axis.deployment.wsdd.WSDDConstants;
import org.apache.axis.deployment.wsdd.WSDDProvider;
import org.objectweb.util.monolog.api.BasicLevel;
import org.ow2.jonas.generators.genbase.generator.Config;
import org.ow2.jonas.generators.wsgen.WsGen;
import org.ow2.jonas.lib.bootstrap.LoaderManager;
import org.ow2.jonas.lib.execution.ExecutionResult;
import org.ow2.jonas.lib.execution.IExecution;
import org.ow2.jonas.lib.execution.RunnableHelper;
import org.ow2.jonas.lib.loader.ThreadContextClassLoader;
import org.ow2.jonas.ws.jaxrpc.WSException;
import org.ow2.jonas.ws.jaxrpc.base.JAXRPCService;
import org.ow2.jonas.ws.jaxrpc.factory.JServiceFactory;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.archive.impl.ArchiveManager;
import org.ow2.util.ee.deploy.api.deployable.IDeployable;
import org.ow2.util.ee.deploy.api.deployer.DeployerException;
import org.ow2.util.ee.deploy.impl.helper.DeployableHelper;
import org.ow2.util.ee.deploy.impl.helper.UnpackDeployableHelper;
import org.ow2.util.file.FileUtils;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.ow2.util.url.URLUtils;

/**
 * Implements commons methods declared within the abstract class. It's used AXIS classes for specific deployment aspects.
 * @author Guillaume Sauthier
 * @author Xavier Delplanque
 */
public class AxisService extends JAXRPCService {

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(getClass());

    /**
     * Start the AxisWSService.
     * @throws WSException when start fails.
     */
    @Override
    public void doStart() throws WSException {

        super.doStart();

        // Set our custom provider
        QName javaURI = new QName(WSDDConstants.URI_WSDD_JAVA, WSDDJOnASEJBProvider.PROVIDER_NAME);
        WSDDProvider.registerProvider(javaURI, new WSDDJOnASEJBProvider());

        // This method do nothing, but is required here to init AxisProperties class
        AxisProperties.getProperties();

        // Fix for Bug #300844
        // Use a ClassLoader that will delegate to call-time real context ClassLoader
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(new ThreadContextClassLoader());
        AxisProperties.getNameDiscoverer();
        Thread.currentThread().setContextClassLoader(old);

        getLogger().log(BasicLevel.INFO, "Axis Service Started");
    }

    /**
     * Return JServiceFactory instance
     */
    @Override
    public JServiceFactory createServiceFactory() {
        return new JAxisServiceFactory();
    }

    /**
     * Apply WSGen on the given deployable.
     * @param deployable the deployable to use
     * @return the modified file or the original file if WSGen has not been launched.
     * @throws WSException If WSGen cannot be applied.
     */
    public String applyWSGen(final IDeployable<?> deployable) throws WSException {
        // Execute WSGen in an execution block
        IExecution<String> exec = new IExecution<String>() {
            public String execute() throws Exception {
                String path = URLUtils.urlToFile(deployable.getArchive().getURL()).getPath();
                WsGen wsGen = new WsGen();

                Config config = new Config();
                config.setInputname(path);

                // Create temporary output directory
                config.setOut(new File(getServerProperties().getWorkDirectory(), "wsgen"));
                try {
                    String result = wsGen.execute(config, deployable);
                    if (wsGen.isInputModified()) {
                        if (result.endsWith(".ear")) {
                            // EAR case
                            IArchive archive = ArchiveManager.getInstance().getArchive(new File(result));
                            IDeployable deployable = DeployableHelper.getDeployable(archive);
                            String archiveName = new File(result).getName();
                            File folder = new File(path).getParentFile();
                            deployable = UnpackDeployableHelper.unpack(deployable, folder, archiveName, false);
                            return URLUtils.urlToFile(deployable.getArchive().getURL()).getPath();
                        } else {
                            // EJB-JAR/WAR case
                            FileUtils.copyFile(result, path);
                        }
                    }
                    return path;
                } catch (Exception e) {
                    throw new DeployerException("Cannot execute WSGen on archive '" + path + "'", e);
                } finally {
                    FileUtils.delete(config.getOut());
                }
            }
        };

        // Execute
        ExecutionResult<String> result = null;
        try {
            result = RunnableHelper.execute(LoaderManager.getInstance().getExternalLoader(), exec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Throw a WSException if needed
        if (result.hasException()) {
            throw new WSException(result.getException().getMessage(), result.getException());
        }

        return result.getResult();
    }
}
