1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.settings4j.connector;
21
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Map;
25
26 import org.apache.commons.lang3.Validate;
27 import org.settings4j.Connector;
28 import org.settings4j.ContentResolver;
29 import org.settings4j.ObjectResolver;
30
31
32
33
34
35
36
37
38
39 public class CachedConnectorWrapper implements Connector {
40
41 private final Connector targetConnector;
42
43 private final Map<String, String> cachedStrings = Collections.synchronizedMap(new HashMap<String, String>());
44 private final Map<String, byte[]> cachedContents = Collections.synchronizedMap(new HashMap<String, byte[]>());
45 private final Map<String, Object> cachedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
46
47
48
49
50
51 public CachedConnectorWrapper(final Connector targetConnector) {
52 super();
53 Validate.notNull(targetConnector, "CachedConnectorWrapper needs a Connector Object");
54 this.targetConnector = targetConnector;
55 }
56
57 @Override
58 public byte[] getContent(final String key) {
59 if (this.cachedContents.containsKey(key)) {
60 return this.cachedContents.get(key);
61 }
62
63 final byte[] result = this.targetConnector.getContent(key);
64 this.cachedContents.put(key, result);
65 return result;
66 }
67
68 @Override
69 public Object getObject(final String key) {
70 if (this.cachedObjects.containsKey(key)) {
71 return this.cachedObjects.get(key);
72 }
73
74 final Object result = this.targetConnector.getObject(key);
75 this.cachedObjects.put(key, result);
76 return result;
77 }
78
79 @Override
80 public String getString(final String key) {
81 if (this.cachedStrings.containsKey(key)) {
82 return this.cachedStrings.get(key);
83 }
84
85 final String result = this.targetConnector.getString(key);
86 this.cachedStrings.put(key, result);
87 return result;
88 }
89
90
91
92
93 public void clearCachedValue(final String key) {
94 this.cachedStrings.remove(key);
95 this.cachedContents.remove(key);
96 this.cachedObjects.remove(key);
97 }
98
99
100
101
102
103 @Override
104 public void addConnector(final Connector connector) {
105 this.targetConnector.addConnector(connector);
106 }
107
108 @Override
109 public void setContentResolver(final ContentResolver contentResolver) {
110 this.targetConnector.setContentResolver(contentResolver);
111 }
112
113 @Override
114 public void setObjectResolver(final ObjectResolver objectResolver) {
115 this.targetConnector.setObjectResolver(objectResolver);
116 }
117
118 @Override
119 public void init() {
120 this.targetConnector.init();
121 }
122
123 @Override
124 public String getName() {
125 return this.targetConnector.getName();
126 }
127
128 @Override
129 public void setName(final String name) {
130 this.targetConnector.setName(name);
131 }
132
133 }