/*
 * 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.base.sfsb.initialization;

import java.io.File;

import java.util.logging.Level;
import java.util.logging.Logger;

import java.util.HashMap;
import java.util.Map;

import com.sun.ejb.spi.sfsb.initialization.SFSBContainerInitialization;

import com.sun.ejb.spi.sfsb.store.SFSBStoreManager;
import com.sun.ejb.spi.sfsb.store.SFSBStoreManagerException;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.EjbDescriptor;

import com.sun.ejb.base.sfsb.store.FileStoreManager;
import com.sun.ejb.base.sfsb.store.FileStoreManagerConstants;

import com.sun.enterprise.server.ServerContext;
import com.sun.enterprise.server.ApplicationServer;
import com.sun.enterprise.instance.InstanceEnvironment;

import com.sun.enterprise.config.ConfigException;
import com.sun.enterprise.config.serverbeans.*;
import com.sun.enterprise.instance.*;
import com.sun.enterprise.server.*;
import com.sun.enterprise.server.ServerContext;
import com.sun.enterprise.server.ApplicationServer;
import com.sun.enterprise.util.io.FileUtils;

import com.sun.ejb.base.container.util.CacheProperties;

/**
 * Class to initialize Container with File based persistence
 *
 * @author Mahesh Kannan
 */
public class FileStrategyBuilder
    extends AbstractPersistenceStrategyBuilder
{ 
    /** Creates a new instance of FileStrategyBuilder */
    public FileStrategyBuilder() {
    }

    public void initializePersistenceStrategy(
	SFSBContainerInitialization container, EjbDescriptor descriptor)
    {
	try {
	    super.initializePersistenceStrategy(container, descriptor);

	    SFSBStoreManager storeManager = createStoreManager(
		    container, descriptor);
	    container.setSFSBStoreManager(storeManager);

	} catch (Throwable th) {
	    _logger.log(Level.SEVERE, "Could not initialize container "
		    + "using FilestrategyBuilder", th);
	}
    }

    private SFSBStoreManager createStoreManager(
	SFSBContainerInitialization container, EjbDescriptor descriptor)
    {
	//Step 1. Create the StoreManager
	FileStoreManager manager = new FileStoreManager();

	//Step 2. Create a Map that contains store specific paramteters
	Map map = new HashMap();
	map.put(FileStoreManagerConstants.STORE_MANAGER_NAME,
		descriptor.getName());

	map.put(FileStoreManagerConstants.CONTAINER_ID,
		new Long(descriptor.getUniqueId()));

	CacheProperties cacheProps = new CacheProperties(descriptor);
	map.put(FileStoreManagerConstants.SESSION_TIMEOUT_IN_SECONDS,
		new Integer(cacheProps.getRemovalTimeoutInSeconds()));

	map.put(FileStoreManagerConstants.GRACE_SESSION_TIMEOUT_IN_SECONDS,
		new Integer(super.getRemovalGracePeriodInSeconds()));

	map.put(FileStoreManagerConstants.PASSIVATION_DIRECTORY_NAME,
	    getPassivationDirectoryName(descriptor));

	//Step 3. Initialize the store with the Map
	_logger.log(Level.FINE, "Initialzing FileStoreManager with: " + map);
	manager.initSessionStore(map);

	_logger.log(Level.FINE, "INITIALZED FileStoreManager: " + manager);
	return manager;
    }

    private String getPassivationDirectoryName(EjbDescriptor desc) {
        
        String passivationDirName = null;

        try {
        
            // runtime server context
            ServerContext ctx = ApplicationServer.getServerContext();
         
            // environment object for this server instance
            InstanceEnvironment env = ctx.getInstanceEnvironment();
         
            // application object associated with this ejb
            Application application = desc.getApplication();
            String dirName = null;
            String componentSeparator = "_";
            if (application.isVirtual()) {
                // ejb is part of a stand alone ejb module
		String archURI = desc.getEjbBundleDescriptor().
		    getModuleDescriptor().getArchiveUri();
                passivationDirName = env.getModulePassivatedEjbPath()
		    + File.separator + FileUtils.makeFriendlyFilename(archURI)
		    + componentSeparator + desc.getName();
            } else {
                // ejb is part of an application
                passivationDirName = env.getApplicationPassivatedEjbPath()
		    + File.separator + application.getRegistrationName()
		    + componentSeparator + desc.getName()
		    + componentSeparator + desc.getUniqueId();
            }
         
        } catch (Throwable th) {
            _logger.log(Level.SEVERE,
		    "ejb.sfsb_helper_get_passivation_dir_failed", th);
        }

        return passivationDirName;
    }

}
    
