package org.theonefx.wcframework.cache;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class CachedDateSupport {
private final Map<String, Entry> cacheMap = new ConcurrentHashMap<String, Entry>();
protected void addDate(String name, Object o) {
Entry entry = cacheMap.get(name);
if (entry == null) {
entry = new Entry(o);
cacheMap.put(name, entry);
} else {
entry.update(o);
}
}
protected void addDate(String name, Object o, long timeOut) {
Entry entry = cacheMap.get(name);
if (entry == null) {
if (timeOut > 0) {
entry = new Entry(o, timeOut);
} else {
entry = new Entry(o);
}
cacheMap.put(name, entry);
} else {
entry.update(o);
}
}
public Object get(String name) {
Entry entry = cacheMap.get(name);
if (entry == null) {
return null;
} else {
boolean timedOut = entry.isTimedOut();
if (timedOut) {
cacheMap.remove(name);
return null;
} else {
return entry.getObject();
}
}
}
protected boolean contain(String name) {
return cacheMap.containsKey(name);
}
protected boolean isTimedOut(String name) {
if (!contain(name)) {
return true;
}
Entry entry = cacheMap.get(name);
boolean timedOut = entry.isTimedOut();
if (timedOut) {
cacheMap.remove(name);
}
return timedOut;
}
protected Object remove(String name) {
Entry entry = cacheMap.remove(name);
if (entry == null) {
return null;
} else {
return entry.getObject();
}
}
private static final class Entry {
private static final long DEFAULTTIMEOUT = 1 * 60 * 1000;
private long addTime;
private long updateTime;
@SuppressWarnings("unused")
private long size;
private long timeOut;
private Object o;
private Entry(Object o, long timeOut) {
this.o = o;
this.timeOut = timeOut;
addTime = System.currentTimeMillis();
updateTime = addTime;
}
private Entry(Object o) {
this(o, DEFAULTTIMEOUT);
}
private Entry() {
this(null, DEFAULTTIMEOUT);
}
public void update(Object o) {
this.o = o;
updateTime = System.currentTimeMillis();
}
public boolean isTimedOut() {
return (System.currentTimeMillis() - updateTime) >= timeOut;
}
public Object getObject() {
return this.o;
}
}
}