package org.sc.epresolver;
import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.NoSuchElementException;
import org.sc.meta.EndpointMetadata;
/**
* One possible implementation of an endpoint cache
* It uses SoftReferences
* TODO: add a size limit
*/
public class EndpointCache
{
/**
* The actual cache
*/
protected Map<String,SoftReference<EndpointMetadata>> cache=new HashMap<String,SoftReference<EndpointMetadata>>();
public EndpointMetadata get(String serviceName)
{
EndpointMetadata ep=null;
SoftReference<EndpointMetadata> epr=cache.get(serviceName);
if (epr==null)
ep=null;
else
{
ep=epr.get();
if (ep==null)
cache.remove(serviceName);
}
return ep;
}
public void put(String serviceName,EndpointMetadata ep)
{
cache.put(serviceName,new SoftReference<EndpointMetadata>(ep));
}
public Iterator<EndpointMetadata> listCache()
{
return new CacheIterator(cache.entrySet().iterator());
}
class CacheIterator implements Iterator<EndpointMetadata>
{
protected Iterator<Map.Entry<String,SoftReference<EndpointMetadata>>> i;
protected EndpointMetadata next;
protected boolean eof;
CacheIterator (Iterator<Map.Entry<String,SoftReference<EndpointMetadata>>> i)
{
this.i=i;
fetchNext();
}
protected void fetchNext()
{
if (!eof)
{
next=null;
while (next==null && i.hasNext())
{
Map.Entry<String,SoftReference<EndpointMetadata>> nx=i.next();
SoftReference<EndpointMetadata> ref=nx.getValue();
next=ref.get();
}
if (next==null)
eof=true;
}
}
public boolean hasNext()
{
return next!=null;
}
public EndpointMetadata next()
{
if (next==null)
throw new NoSuchElementException();
return next;
}
public void remove()
{
throw new UnsupportedOperationException("remove() is not available");
}
} // class CacheIterator
public void flushCache()
{
cache.clear();
}
}