NextableInputStream: better perfs
[fanfix.git] / src / be / nikiroo / utils / CacheMemory.java
1 package be.nikiroo.utils;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.net.URL;
6 import java.util.HashMap;
7 import java.util.Map;
8
9 /**
10 * A memory only version of {@link Cache}.
11 *
12 * @author niki
13 */
14 public class CacheMemory extends Cache {
15 private Map<String, byte[]> data = new HashMap<String, byte[]>();
16
17 /**
18 * Create a new {@link CacheMemory}.
19 */
20 public CacheMemory() {
21 }
22
23 @Override
24 public boolean check(String uniqueID, boolean allowTooOld, boolean stable) {
25 return data.containsKey(getKey(uniqueID));
26 }
27
28 @Override
29 public boolean check(URL url, boolean allowTooOld, boolean stable) {
30 return data.containsKey(getKey(url));
31 }
32
33 @Override
34 public int clean(boolean onlyOld) {
35 int cleaned = 0;
36 if (!onlyOld) {
37 cleaned = data.size();
38 data.clear();
39 }
40
41 return cleaned;
42 }
43
44 @Override
45 public InputStream load(String uniqueID, boolean allowTooOld, boolean stable) {
46 if (check(uniqueID, allowTooOld, stable)) {
47 return load(uniqueID, allowTooOld, stable);
48 }
49
50 return null;
51 }
52
53 @Override
54 public InputStream load(URL url, boolean allowTooOld, boolean stable) {
55 if (check(url, allowTooOld, stable)) {
56 return load(url, allowTooOld, stable);
57 }
58
59 return null;
60 }
61
62 @Override
63 public boolean remove(String uniqueID) {
64 return data.remove(getKey(uniqueID)) != null;
65 }
66
67 @Override
68 public boolean remove(URL url) {
69 return data.remove(getKey(url)) != null;
70 }
71
72 @Override
73 public void save(InputStream in, String uniqueID) throws IOException {
74 data.put(getKey(uniqueID), IOUtils.toByteArray(in));
75 }
76
77 @Override
78 public void save(InputStream in, URL url) throws IOException {
79 data.put(getKey(url), IOUtils.toByteArray(in));
80 }
81
82 /**
83 * Return a key mapping to the given unique ID.
84 *
85 * @param uniqueID
86 * the unique ID
87 *
88 * @return the key
89 */
90 private String getKey(String uniqueID) {
91 return "_/" + uniqueID;
92 }
93
94 /**
95 * Return a key mapping to the given urm.
96 *
97 * @param url
98 * thr url
99 *
100 * @return the key
101 */
102 private String getKey(URL url) {
103 return url.toString();
104 }
105 }