/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.deployment.archivist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Set;
import java.util.logging.Level;
import javax.enterprise.deploy.shared.ModuleType;
import org.xml.sax.SAXParseException;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.Descriptor;
import com.sun.enterprise.deployment.EjbBundleDescriptor;
import com.sun.enterprise.deployment.RootDeploymentDescriptor;
import com.sun.enterprise.deployment.deploy.shared.AbstractArchive;
import com.sun.enterprise.deployment.io.DeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.DescriptorConstants;
import com.sun.enterprise.deployment.io.EjbDeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.runtime.EjbRuntimeDDFile;
import com.sun.enterprise.deployment.util.DOLUtils;
import com.sun.enterprise.deployment.util.EjbBundleValidator;
import com.sun.enterprise.deployment.util.EjbBundleVisitor;
import com.sun.enterprise.deployment.util.EjbComponentAnnotationDetector;
import com.sun.enterprise.deployment.util.ModuleContentValidator;
import com.sun.enterprise.util.FileUtil;
import com.sun.enterprise.util.LocalStringManagerImpl;

/**
 * This class is responsible for handling J2EE EJB Bundlearchive files.
 *
 * @author  Jerome Dochez
 * @version 
 */
public class EjbArchivist extends Archivist {

    EjbBundleDescriptor descriptor = null;
    
    /** 
     * The DeploymentDescriptorFile handlers we are delegating for XML i/o
     */
    DeploymentDescriptorFile standardDD = new EjbDeploymentDescriptorFile();
    
    // resources...
    private static LocalStringManagerImpl localStrings =
	    new LocalStringManagerImpl(EjbArchivist.class);        
    
    /** Creates new EjbBundleArchvisit */
    public EjbArchivist() {
    }
    
    /**
     * @return the  module type handled by this archivist 
     * as defined in the application DTD
     *
     */
    public ModuleType getModuleType() {
        return ModuleType.EJB;
    }                       
    
    /** 
     * Set the DOL descriptor  for this Archivist, used by super classes 
     */    
    public void setDescriptor(Descriptor descriptor) {
        if (descriptor instanceof EjbBundleDescriptor) {
            this.descriptor = (EjbBundleDescriptor) descriptor;
        } else {
            if (descriptor instanceof Application) {
                // this is acceptable if the application actually represents 
                // a standalone module
                Set ejbBundles = ((Application) descriptor).getEjbBundleDescriptors();
                if (ejbBundles.size()>0) {
                    this.descriptor = (EjbBundleDescriptor) ejbBundles.iterator().next();
                    if (this.descriptor.getModuleDescriptor().isStandalone()) 
                        return;
                    else 
                        this.descriptor=null;
                }      
            }
            DOLUtils.getDefaultLogger().log(Level.SEVERE, "enterprise.deployment.backend.descriptorFailure", new Object[] {this});
            throw new RuntimeException("Error setting descriptor " + descriptor + " in " + this);
        }
    }   

    /**
     * @return the DeploymentDescriptorFile responsible for handling
     * standard deployment descriptor
     */
    public DeploymentDescriptorFile getStandardDDFile() {
        return standardDD;
    }      
    
    /**
     * @return if exists the DeploymentDescriptorFile responsible for
     * handling the configuration deployment descriptors
     */
    public DeploymentDescriptorFile getConfigurationDDFile() {
        return new EjbRuntimeDDFile();
    }  
    
    /** 
     * @return the location of the web services related deployment 
     * descriptor file inside this archive or null if this archive
     * does not support webservices implementation.
     */
    public String getWebServicesDeploymentDescriptorPath() {
        return DescriptorConstants.EJB_WEBSERVICES_JAR_ENTRY;
    } 
    
    /** 
     * @return the Descriptor for this archvist
     */
    public Descriptor getDescriptor() {
        return descriptor;
    } 

    /**
     * @return a default BundleDescriptor for this archivist
     */
    public Descriptor getDefaultBundleDescriptor() {
        EjbBundleDescriptor ejbBundleDesc =
            new EjbBundleDescriptor();
        return ejbBundleDesc;
    }

    /**
     * perform any post deployment descriptor reading action
     *
     * @param descriptor deployment descriptor for the module
     * @param archive the module archive
     */
    protected void postOpen(RootDeploymentDescriptor descriptor, AbstractArchive archive) 
        throws IOException
    {
        super.postOpen(descriptor, archive);
        EjbBundleDescriptor ejbBundle = (EjbBundleDescriptor) descriptor;
        ModuleContentValidator mdv = new ModuleContentValidator(archive);
        ejbBundle.visit((EjbBundleVisitor)mdv);
    }
    
    /**
     * validates the DOL Objects associated with this archivist, usually
     * it requires that a class loader being set on this archivist or passed
     * as a parameter
     */
    public void validate(ClassLoader aClassLoader) {
        ClassLoader cl = aClassLoader;
        if (cl==null) {
            cl = classLoader;
        }
        if (cl==null) {
            return;
        }
        descriptor.setClassLoader(cl);
        descriptor.visit((EjbBundleVisitor) new EjbBundleValidator());        
    }     

    /**
     * prepare an archivist for inclusion in a application archive.
     * 
     * @param out file where this archivist will be saved
     */
    protected void prepareForInclusion(AbstractArchive out) throws IOException {
        
	// store the ejbJar by its hort filename        
        String ejbClientJarUri = descriptor.getEjbClientJarUri();

        // If this ejb-jar has an ejb client jar, the ejb client jar URI
        // is relative to the directory in which the ejb-jar lives.
        if( !ejbClientJarUri.equals("") ) {
            String ejbClientJarPath = 
                ejbClientJarUri.replace(FileUtil.JAR_SEPARATOR_CHAR, File.separatorChar);
                
            File ejbJarFile = new File(path);
            File ejbClientJar = new File(ejbJarFile.getParentFile(), ejbClientJarPath);
            if( ejbClientJar.exists() ) {
                // Pull the ejb-client-jar into the .ear and set the
                // ejb-jar manifest classpath to point to it(relative
                // to the base of the .ear)
                addFileToArchive(out, ejbClientJar.getAbsolutePath(), ejbClientJarUri);
                String classPath = getClassPath();
                if (classPath==null) {
                    classPath=ejbClientJarUri;
                } else {
                    classPath+=" " + ejbClientJarUri;
                }
                setClassPath(classPath);
            } else {
               throw new FileNotFoundException(localStrings.getLocalString("enterprise.deployment.noclientjarentry", "Warning: {0} not found as a client jar entry.", new Object[] {ejbClientJar.toString()}));
            }
        }        
    }    

    protected String getArchiveExtension() {
        return EJB_EXTENSION;
    }

    protected boolean postHandles(AbstractArchive abstractArchive) 
            throws IOException {
        EjbComponentAnnotationDetector detector = 
                    new EjbComponentAnnotationDetector();
        return detector.hasAnnotationInArchive(abstractArchive);
    }

    @Override public void readPersistenceDeploymentDescriptors(
            AbstractArchive archive, Descriptor descriptor)
            throws IOException, SAXParseException {
        if(logger.isLoggable(Level.FINE)) {
            logger.logp(Level.FINE, "EjbArchivist",
                    "readPersistenceDeploymentDescriptors", "archive = {0}",
                    archive.getURI());
        }
        // note we pass "" as the PURootPath because META-INF/persistence.xml
        // can only be present on the top level in an ejb-jar, so the root of
        // persistence unit is always same as the root of an ejb-jar file.
        // hence relative distance between them is empty.
        readPersistenceDeploymentDescriptor(archive, "", descriptor);
    }
}
