/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
 package scone.netobjects;


import java.util.Observable;
import java.util.Vector;


// observable that notifies the observers if any new items have been cached 
// since sleeptime
class Cache extends Observable {

    // the newly cached items
    protected Vector items = new Vector(); // ...
	
    // creates an observable that notifies the observers if any new items have been cached 
    // since sleeptime
    public Cache() {
        super();
        (new Notifier()).start();
    }
	
    // adds an item to the newly added items
    protected void addItem(Object o) {
        if (countObservers() > 0) {
            synchronized (items) {
                items.add(o);
                setChanged();
            }
        }
    }
	
    // notifies observers if any items have been added since last call
    // sends an Enumeration of the the items
    public void notifyObservers() {
        synchronized (items) {
            notifyObservers(items.elements());
            items = new Vector();
        }
    }
	
    // this thread looks up the newly added items and notifies the observers if neccessary
    protected class Notifier extends Thread {
		
        protected Notifier() {}
		
        public void run() {
            if (NetNodeCache.getObservePeriod() > 0) {
                while (true) {
                    try {
                        sleep(NetNodeCache.getObservePeriod());
                        notifyObservers();
                    } catch (InterruptedException e) {}
                }
            }
        }		
    }
	
}
