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