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


import java.util.logging.*;
import java.util.Vector;
import java.util.Iterator;

import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.sun.ejb.Container;
import com.sun.ejb.InvocationInfo;
import com.sun.enterprise.deployment.*;

import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
import com.sun.enterprise.server.ApplicationServer;
import com.sun.enterprise.server.ServerContext;
import com.sun.enterprise.config.serverbeans.EjbContainer;
import com.sun.enterprise.config.serverbeans.EjbTimerService;


public class TimerBeanContainer
    extends EntityContainer
{
    
    private EJBTimerService ejbTimerService;
        
    /**
     * This constructor is called when the timer service system application is
     * loaded.
     * @exception Exception on error
     */
    protected TimerBeanContainer(EjbDescriptor desc, ClassLoader loader)
        throws Exception
    {
        super(desc, loader);

        _logger.log(Level.FINE,"[TimerBeanContainer] Created "
                + " TimerBeanContainer: " + logParams[0]);

    }

    public void onShutdown() {
        _logger.log(Level.FINE,"[TimerBeanContainer] onShutdown() called....");

        super.onShutdown();

        if (ejbTimerService != null) {
            ejbTimerService.onShutdown();
        }
    }

    /**
     * Called after all the components in the container's application
     * have deployed successfully.
     */
    public void doAfterApplicationDeploy() {

        super.doAfterApplicationDeploy();    

        try {

            TimerLocalHome timerLocalHome = (TimerLocalHome) ejbLocalHome;

            // Do "health check" on access to persistent timer info.
            EjbBundleDescriptor bundle = 
                ejbDescriptor.getEjbBundleDescriptor();

            // Get timer data source name set in timer service system app's
            // sun-ejb-jar.xml
            ResourceReferenceDescriptor cmpResource = 
                bundle.getCMPResourceReference();

            String cmpResourceJndiName = cmpResource.getJndiName();

            // Get the timer data source name from the domain.xml
            ServerContext sc = ApplicationServer.getServerContext();
            EjbContainer ejbc = ServerBeansFactory.
                getConfigBean(sc.getConfigContext()).getEjbContainer();
            EjbTimerService ejbt = ejbc.getEjbTimerService();
            // EjbTimerService is an optional element
            String ejbtDatasource = (ejbt != null) ?
                ejbt.getTimerDatasource() : null;

            // Override the timer datasource with the one from domain.xml 
            // if necessary.  
            if( (ejbtDatasource != null) && 
                (!ejbtDatasource.equals(cmpResourceJndiName)) ) {

                cmpResourceJndiName = ejbtDatasource;               
                 
                // overwrite datasource jndi name in descriptor
                cmpResource.setJndiName(cmpResourceJndiName);
            }

            // Make sure cmp resource is available in the namespace.
            Context context = new InitialContext();
            context.lookup(cmpResourceJndiName);
            
            // Make an invocation on timer bean to ensure that app is 
            // initialized properly.  Second param determines whether 
            // exhaustive database checks are performed.  These are time 
            // consuming so they will be disabled by default.  
            boolean checkStatus = 
                timerLocalHome.checkStatus(cmpResourceJndiName, false);

            if( checkStatus ) {

                //descriptor object representing this application or module
                Application application = ejbDescriptor.getApplication();
        
                //registration name of the applicaton
                String appID = application.getRegistrationName();

                Vector ejbs = application.getEjbDescriptors();
                TimerMigrationLocalHome timerMigrationLocalHome = null;
                for(Iterator iter = ejbs.iterator(); iter.hasNext();) {
                    EjbDescriptor next = (EjbDescriptor) iter.next();
                    if( next.getLocalHomeClassName().equals
                        (TimerMigrationLocalHome.class.getName()) ) {
                        BaseContainer container = (BaseContainer)
                            containerFactory.getContainer(next.getUniqueId());
                        timerMigrationLocalHome = (TimerMigrationLocalHome)
                            container.getEJBLocalHome();
                        break;
                    }
                }

                // Create EJB Timer service. 
                ejbTimerService = 
                    new EJBTimerService(appID, timerLocalHome,
                                        timerMigrationLocalHome);

                containerFactory.setEJBTimerService(ejbTimerService);

                _logger.log(Level.INFO, "ejb.timer_service_started",
                            new Object[] { cmpResourceJndiName } );

            } else {
                // error logged by timer bean.
            }

        } catch (NamingException nnfe) {

            // This is most likely caused by the timer datasource not being
            // configured for this server instance.
            _logger.log(Level.WARNING, "ejb.timer_service_init_error", 
                        logParams);

        } catch (Exception ex) {
            _logger.log(Level.WARNING, "ejb.timer_service_init_error", 
                        logParams);
            _logger.log(Level.WARNING, "", ex);
        } 
        
    }
    
} //TimerBeanContainer.java
