1 package be
.nikiroo
.utils
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
7 import java
.util
.HashMap
;
11 * A memory only version of {@link Cache}.
15 public class CacheMemory
extends Cache
{
16 private Map
<String
, byte[]> data
;
19 * Create a new {@link CacheMemory}.
21 public CacheMemory() {
22 data
= new HashMap
<String
, byte[]>();
26 public boolean check(String uniqueID
, boolean allowTooOld
, boolean stable
) {
27 return data
.containsKey(getKey(uniqueID
));
31 public boolean check(URL url
, boolean allowTooOld
, boolean stable
) {
32 return data
.containsKey(getKey(url
));
36 public int clean(boolean onlyOld
) {
39 cleaned
= data
.size();
47 public InputStream
load(String uniqueID
, boolean allowTooOld
, boolean stable
) {
48 if (check(uniqueID
, allowTooOld
, stable
)) {
49 return load(getKey(uniqueID
));
56 public InputStream
load(URL url
, boolean allowTooOld
, boolean stable
) {
57 if (check(url
, allowTooOld
, stable
)) {
58 return load(getKey(url
));
65 public boolean remove(String uniqueID
) {
66 return data
.remove(getKey(uniqueID
)) != null;
70 public boolean remove(URL url
) {
71 return data
.remove(getKey(url
)) != null;
75 public long save(InputStream in
, String uniqueID
) throws IOException
{
76 byte[] bytes
= IOUtils
.toByteArray(in
);
77 data
.put(getKey(uniqueID
), bytes
);
82 public long save(InputStream in
, URL url
) throws IOException
{
83 byte[] bytes
= IOUtils
.toByteArray(in
);
84 data
.put(getKey(url
), bytes
);
89 * Return a key mapping to the given unique ID.
91 * @param uniqueID the unique ID
95 private String
getKey(String uniqueID
) {
96 return "UID:" + uniqueID
;
100 * Return a key mapping to the given urm.
106 private String
getKey(URL url
) {
107 return "URL:" + url
.toString();
111 * Load the given key.
113 * @param key the key to load
114 * @return the loaded data
116 private InputStream
load(String key
) {
117 byte[] data
= this.data
.get(key
);
119 return new ByteArrayInputStream(data
);