|
1
|
|
|
package es.webbeta.serializer; |
|
2
|
|
|
|
|
3
|
|
|
import es.webbeta.serializer.base.Cache; |
|
4
|
|
|
import es.webbeta.serializer.base.MetadataAccessor; |
|
5
|
|
|
|
|
6
|
|
|
import java.io.File; |
|
7
|
|
|
|
|
8
|
|
|
public class CacheMetadataAccessor extends FileMetadataAccessor implements MetadataAccessor { |
|
9
|
|
|
|
|
10
|
|
|
private static final String KEY_TPL = "serializer_metadata___%s"; |
|
11
|
|
|
|
|
12
|
|
|
private Cache cache; |
|
13
|
|
|
|
|
14
|
|
|
public CacheMetadataAccessor(Cache cache) { |
|
15
|
|
|
super(); |
|
16
|
|
|
|
|
17
|
|
|
this.cache = cache; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
private String generateKey(Class<?> klass) { |
|
21
|
|
|
return generateKey(klass.getCanonicalName()); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
private String generateKey(String canonical) { |
|
25
|
|
|
return String.format(KEY_TPL, canonical); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
private String getFilenameWithoutExtension(String fileName) { |
|
29
|
|
|
if (fileName.indexOf(".") > 0) { |
|
|
|
|
|
|
30
|
|
|
return fileName.substring(0, fileName.lastIndexOf(".")); |
|
31
|
|
|
} else { |
|
32
|
|
|
return fileName; |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
@Override |
|
37
|
|
|
public Boolean hasMetadata(Class<?> klass) { |
|
38
|
|
|
return super.hasMetadata(klass); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
@Override |
|
42
|
|
|
public String getMetadataContent(Class<?> klass) { |
|
43
|
|
|
String key = generateKey(klass); |
|
44
|
|
|
if (cache.get(key) != null) |
|
45
|
|
|
return cache.get(key); |
|
46
|
|
|
else { |
|
47
|
|
|
if (super.hasMetadata(klass)) { |
|
48
|
|
|
String metadata = super.getMetadataContent(klass); |
|
49
|
|
|
cache.set(key, metadata); |
|
50
|
|
|
return metadata; |
|
51
|
|
|
} else |
|
52
|
|
|
return null; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Removes all cache entries |
|
58
|
|
|
*/ |
|
59
|
|
|
public void clearMetadataCache() { |
|
60
|
|
|
File dir = this.metadataPath.toFile(); |
|
61
|
|
|
if (dir == null) return; |
|
62
|
|
|
File[] files = dir.listFiles(); |
|
63
|
|
|
if (files == null) return; |
|
64
|
|
|
|
|
65
|
|
|
for (final File fileEntry : files) { |
|
66
|
|
|
if (!fileEntry.isFile()) continue; |
|
67
|
|
|
|
|
68
|
|
|
String canonical = getFilenameWithoutExtension(fileEntry.getName()); |
|
69
|
|
|
String cacheKey = generateKey(canonical); |
|
70
|
|
|
|
|
71
|
|
|
if (cache.get(cacheKey) != null) |
|
72
|
|
|
cache.remove(cacheKey); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
} |
|
77
|
|
|
|
If you are just looking for the presence of a string in another string, consider using
contains().Should really want to test if a string is there, but not before a specific position, consider using this overload of
indexOf()