// Copyright 1997 The Open Group Research Institute.  All rights reserved.
// Copyright 1999 Memesoft.  All rights reserved.

package krb5.lib.rcache;

import krb5.lib.*;
import java.util.*;

/**
 * Replay cache implementation
 */
public class ReplayCacheImpl implements ReplayCache {

	/**
	 * Vector
	 */
    Vector list = new Vector();

	/**
	 * Class constructor
	 */
    public ReplayCacheImpl() {
    }

	/**
	 * Checks whether the given criteria exists in the ReplayCache
	 *
	 * @return boolean is a result
	 * @param sname is of type PrincipalName
	 * @param srealm is of type Realm
	 * @param authenticator is of type Authenticator
	 * @see krb5.lib.PrincipalName
	 * @see krb5.lib.Realm
	 * @see krb5.lib.Authenticator
	 */
    public synchronized boolean found(PrincipalName sname, Realm srealm, Authenticator authenticator) {
        ReplayCacheEntry testEntry = new ReplayCacheEntry(sname, srealm, authenticator);
        Enumeration e = list.elements();
        while (e.hasMoreElements()) {
            ReplayCacheEntry entry = (ReplayCacheEntry)e.nextElement();
            if (entry.equals(testEntry))
                return true;
        }
        return false;
    }

	/**
	 * Saves the given information in ReplayCache
	 *
	 * @param sname is of type PrincipalName
	 * @param srealm is of type Realm
	 * @param authenticator is of type Authenticator
	 * @see krb5.lib.PrincipalName
	 * @see krb5.lib.Realm
	 * @see krb5.lib.Authenticator
	 */
    public synchronized void save(PrincipalName sname, Realm srealm, Authenticator authenticator) {
        list.addElement(new ReplayCacheEntry(sname, srealm, authenticator));
        purgeExpired();
    }

	/**
	 * Deletes expired elements
	 */
    synchronized void purgeExpired() {
        KerberosTime time = new KerberosTime(KerberosTime.NOW);
        Enumeration e = list.elements();
        while (e.hasMoreElements()) {
            ReplayCacheEntry entry = (ReplayCacheEntry)e.nextElement();
            if (entry.expired(time))
                list.removeElement(entry);
        }
    }
}