/*
 * 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.server;

import com.sun.enterprise.deployment.*;
import com.sun.enterprise.loader.InstrumentableClassLoader;
import com.sun.logging.LogDomains;

import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;

/**
 * {@inheritDoc}
 *
 * @author Sanjeeb.Sahoo@Sun.COM
 */
public class PersistenceUnitLoaderImpl implements PersistenceUnitLoader {

    /**
     * logger to log loader messages
     */
    private static Logger logger = LogDomains.getLogger(
            LogDomains.LOADER_LOGGER);

    private String applicationLocation;

    private InstrumentableClassLoader classLoader;

    private Application application;

    private static Map<String, String> integrationProperties;

    /**
     * {@inheritDoc}
     */
    public void load(ApplicationInfo appInfo) {
        application = appInfo.getApplication();
        applicationLocation = appInfo.getApplicationLocation();
        classLoader = appInfo.getClassLoader();
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("Loading persistence units for application: " +
                    applicationLocation);
        }
        // step #1: load ear level PUs
        for (PersistenceUnitsDescriptor pus :
                application.getPersistenceUnitsDescriptors()) {
            for (PersistenceUnitDescriptor pu : pus.getPersistenceUnitDescriptors()) {
                load(pu);
            }
        }

        // step #2: load ejb-jar level PUs
        for (Object o : application.getEjbBundleDescriptors()) {
            EjbBundleDescriptor bundle = EjbBundleDescriptor.class.cast(o);
            if(logger.isLoggable(Level.FINE)) {
                logger.fine("Loading persistence units for ejb module called " +
                        bundle.getModuleDescriptor().getArchiveUri() +
                        " in application " + applicationLocation);
            }
            for (PersistenceUnitsDescriptor pus : bundle.getPersistenceUnitsDescriptors()) {
                for (PersistenceUnitDescriptor pu : pus.getPersistenceUnitDescriptors()) {
                    load(pu);
                }
            }
        }

        // step #3: load war level PUs
        for (Object o : application.getWebBundleDescriptors()) {
            WebBundleDescriptor bundle = WebBundleDescriptor.class.cast(o);
            if(logger.isLoggable(Level.FINE)) {
                logger.fine("Loading persistence units for web module called " +
                        bundle.getModuleDescriptor().getArchiveUri() +
                        " in application " + applicationLocation);
            }
            for (PersistenceUnitsDescriptor pus : bundle.getPersistenceUnitsDescriptors()) {
                for (PersistenceUnitDescriptor pu : pus.getPersistenceUnitDescriptors()) {
                    load(pu);
                }
            }
        }
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("Finished loading persistence units for application: " +
                    applicationLocation);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void unload(ApplicationInfo appInfo) {
        application = appInfo.getApplication();
        applicationLocation = appInfo.getApplicationLocation();
        classLoader = appInfo.getClassLoader();
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("Unloading persistence units for application: " +
                    applicationLocation);
        }
        // step #1: unload ear level PUs
        closeEMFs(application.getEntityManagerFactories());

        // step #2: unload ejb-jar level PUs
        for (Object o : application.getEjbBundleDescriptors()) {
            EjbBundleDescriptor bundle = EjbBundleDescriptor.class.cast(o);
            if(logger.isLoggable(Level.FINE)) {
                logger.fine("Unloading persistence units for ejb module called " +
                        bundle.getModuleDescriptor().getArchiveUri() +
                        " in application " + applicationLocation);
            }
            closeEMFs(bundle.getEntityManagerFactories());
        }

        // step #3: unload war level PUs
        for (Object o : application.getWebBundleDescriptors()) {
            WebBundleDescriptor bundle = WebBundleDescriptor.class.cast(o);
            if(logger.isLoggable(Level.FINE)) {
                logger.fine("Unloading persistence units for web module called " +
                        bundle.getModuleDescriptor().getArchiveUri() +
                        " in application " + applicationLocation);
            }
            closeEMFs(bundle.getEntityManagerFactories());
        }
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("Finished unloading persistence units for application: " +
                    applicationLocation);
        }
    }

    /**
     * Loads an individual PersistenceUnitDescriptor and registers the
     * EntityManagerFactory in appropriate DOL structure.
     *
     * @param pud PersistenceUnitDescriptor to be loaded.
     */
    private void load(PersistenceUnitDescriptor pud) {
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("loading pud " + pud.getAbsolutePuRoot());
        }
        PersistenceUnitInfo pInfo = new PersistenceUnitInfoImpl(
                pud,
                applicationLocation,
                classLoader);
        if(logger.isLoggable(Level.FINE)) {
            logger.fine("PersistenceInfo for this pud is :\n" + pInfo);
        }
        PersistenceProvider provider;
        try {
            // See we use application CL as opposed to system CL to load
            // provider. This allows user to get hold of provider specific
            // implementation classes in their code. But this also means
            // provider must not use appserver implementation classes directly
            // because once we implement isolation in our class loader hierarchy
            // the only classes available to application class loader would be
            // our appserver interface classes. By Sahoo
            provider =
                    PersistenceProvider.class.cast(
                    ClassLoader.class.cast(classLoader)
                    .loadClass(pInfo.getPersistenceProviderClassName())
                    .newInstance());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        EntityManagerFactory emf = provider.createContainerEntityManagerFactory(
                pInfo, integrationProperties);
        logger.logp(Level.FINE, "PersistenceUnitLoaderImpl", "load",
                    "emf = {0}", emf);

        RootDeploymentDescriptor rootDD = pud.getParent().getParent();
        if (rootDD.isApplication()) {
            Application.class.cast(rootDD).addEntityManagerFactory(
                    pInfo.getPersistenceUnitName(), pud.getPuRoot(), emf);
        } else {
            BundleDescriptor.class.cast(rootDD).addEntityManagerFactory(
                    pInfo.getPersistenceUnitName(), emf);
        }
    }

    private void closeEMFs(
            Collection<EntityManagerFactory> entityManagerFactories) {
        for (EntityManagerFactory emf : entityManagerFactories) {
            try {
                emf.close();
            } catch (Exception e) {
                logger.log(Level.WARNING, e.getMessage(), e);
            }
        }
    }

    static {
        /*
         * We set all the provider specific integration level properties here.
         * It knows about all the integration level properties that
         * are needed to integrate a provider with our container. When we add
         * support for other containers, we should modify this code so that user
         * does not have to specify such properties in their persistence.xml file.
         * These properties can be overriden by persistence.xml as per
         * the spec. Before applying default values for properties, this method
         * first checks if the properties have been set in the system
         * (typically done using -D option in domain.xml).
         *
         */
        Map<String, String> props = new HashMap<String, String>();

        // TopLink specific properties:
        // See https://glassfish.dev.java.net/issues/show_bug.cgi?id=249
        final String TOPLINK_SERVER_PLATFORM_CLASS_NAME_PROPERTY =
                "toplink.server.platform.class.name"; // NOI18N
        props.put(TOPLINK_SERVER_PLATFORM_CLASS_NAME_PROPERTY,
                System.getProperty(TOPLINK_SERVER_PLATFORM_CLASS_NAME_PROPERTY,
                        "oracle.toplink.essentials.platform.server.sunas.SunAS9ServerPlatform")); // NOI18N

        // Hibernate specific properties:
        final String HIBERNATE_TRANSACTION_MANAGER_LOOKUP_CLASS_PROPERTY =
                "hibernate.transaction.manager_lookup_class"; // NOI18N
        props.put(HIBERNATE_TRANSACTION_MANAGER_LOOKUP_CLASS_PROPERTY,
                System.getProperty(HIBERNATE_TRANSACTION_MANAGER_LOOKUP_CLASS_PROPERTY,
                        "org.hibernate.transaction.SunONETransactionManagerLookup")); // NOI18N

        // use an unmodifiable map as we pass this to provider and we don't
        // provider to change this.
        integrationProperties = Collections.unmodifiableMap(props);
    }

}
