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

import java.util.ArrayList;

import java.io.File;

import java.util.logging.*;
import com.sun.logging.*;

import com.sun.ejb.spi.sfsb.SFSBUUIDUtil;
import com.sun.ejb.spi.container.ContainerService;

import com.sun.ejb.containers.ContainerFactoryImpl;


/**
 * @author     Mahesh Kannan
 */
 
public class PersistentFileStoreManager
    extends AbstractFileStoreManager
{
    private SFSBUUIDUtil uuidGenerator;

    /**
     * No arg constructor
     */
    public PersistentFileStoreManager() {
    }

    protected void onInitialization() {

        try {
	    uuidGenerator = new SimpleKeyGenerator();
    
	    if (baseDir.isDirectory()) {
		String[] fileNames = baseDir.list();
		_logger.log(Level.FINE, storeManagerName
		    + "; removing: " + fileNames.length + " sessions");

		removeExpiredPassivatedSessions(fileNames);     
	    }
	} catch (Exception ex) {
	    _logger.log(Level.WARNING, "ejb.sfsb_persistmgr_oninit_failed",
		    new Object[] {storeManagerName});
	    _logger.log(Level.WARNING, "ejb.sfsb_persistmgr_oninit_failed_exception", ex);
	}
    }

    public SFSBUUIDUtil getUUIDUtil() {
        return uuidGenerator;
    }

    public void shutdown() {
        super.shutdown();
    }

    private void removeExpiredPassivatedSessions(String[] fileNames) {
	if (fileNames.length > 0) {
	    AsyncFileRemovalTask  task = new AsyncFileRemovalTask(
		    this, fileNames);
	    try {
		ContainerService service = ContainerFactoryImpl.getContainerService();

		//scheduleWork performs the task on the same thread
		//  if it cannot schedule the task for async execution
		service.scheduleWork(super.getClassLoader(), task);
	    } catch (Throwable th) {
		//We would be here only if containerService is null

		_logger.log(Level.FINE, storeManagerName
			+ ": Cannot execute file removal aynchronously", th);

		//Execute in the current thread
		task.run(); //Doesn't throw any exception
	    }
	}
    }

    private static class AsyncFileRemovalTask
	implements Runnable
    {
	AbstractFileStoreManager	storeManager;
	String[]			fileNames;

	AsyncFileRemovalTask(AbstractFileStoreManager manager,
		String[] fileNames)
	{
	    this.storeManager = manager;
	    this.fileNames = fileNames;
	}

	public void run() {
	    try {
		int sz = fileNames.length;
		for (int i=0; i<sz; i++) {
		    storeManager.remove(fileNames[i]);
		}
	    } catch (Exception ex) {
		_logger.log(Level.FINE, "Error while removing expired "
			+ "file during startup", ex);
	    }
	}
    }
}
