/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.fw.service;

// Java classes
import java.util.ArrayList;
import java.util.Iterator;

// Library classes

// Framework classes

// EDB classes

/**
 * Project: Framework
 * 
 * @author DNS   LEV
 * @version 1.0
 */
public class PreloadService extends AbstractComponent implements Runnable {

    private ArrayList services = null;
    
    // A flag to run in background
    private boolean preloaded = false;
    
    /**
     * A default constructor for a preload service
     */
    protected PreloadService() {
        super();
    }

    /**
     * @see gov.va.med.fw.service.PreloadServiceTemp#isDaemon()
     */
    public boolean isPreloaded() {
        return preloaded;
    }

    /**
     * @see gov.va.med.fw.service.PreloadServiceTemp#setDaemon(boolean)
     */
    public void setPreloaded( boolean flag ) {
        this.preloaded = flag;
    }
    
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        if( this.isPreloaded() ) {
            Thread t = new Thread( this );
            t.setDaemon( true );
            t.start();
        }
    }
    
    /**
     * @see gov.va.med.fw.service.PreloadServiceTemp#preload()
     */
    public void run() {

        ArrayList services = getServices();
        if( services != null ) {
            for( Iterator i=services.iterator(); i.hasNext(); ) {
                try {
                    Object service = i.next();
                    if( service instanceof Runnable ) {
                        ((Runnable)service).run();
                    }
                }
                catch( Exception e ) {
                    logger.error( "Exception in a preload service ", e );
                }
            }
        }
    }
    
    /**
     * @return Returns the services.
     */
    public ArrayList getServices() {
        return services;
    }
    
    /**
     * @param services The services to set.
     */
    public void setServices(ArrayList services) {
        this.services = services;
    }
}