1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.settings4j.contentresolver;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.URL;
22
23 import org.apache.commons.io.IOUtils;
24 import org.settings4j.ContentResolver;
25
26
27
28
29
30
31
32
33
34
35
36
37 public class ClasspathContentResolver implements ContentResolver {
38
39
40 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(ClasspathContentResolver.class);
41
42
43 public static final String CLASSPATH_URL_PREFIX = "classpath:";
44
45
46
47 public void addContentResolver(final ContentResolver contentResolver) {
48 throw new UnsupportedOperationException("ClasspathContentResolver cannot add other ContentResolvers");
49 }
50
51
52 public byte[] getContent(final String key) {
53 final String normalizedKey = normalizeKey(key);
54
55 try {
56 final InputStream is = getClassLoader().getResourceAsStream(normalizedKey);
57 if (is != null) {
58 return IOUtils.toByteArray(is);
59 }
60
61 return null;
62 } catch (final IOException e) {
63 LOG.error(e.getMessage(), e);
64 return null;
65 }
66 }
67
68
69
70
71
72
73
74
75 public static URL getResource(final String key) {
76 final String normalizedKey = normalizeKey(key);
77
78 return getClassLoader().getResource(normalizedKey);
79 }
80
81
82
83
84
85
86
87
88
89
90
91
92
93 public static ClassLoader getClassLoader() {
94 ClassLoader cl = null;
95 try {
96 cl = Thread.currentThread().getContextClassLoader();
97 } catch (final Throwable ex) {
98 LOG.debug("Cannot access thread context ClassLoader - falling back to system class loader", ex);
99 }
100 if (cl == null) {
101
102 cl = ClasspathContentResolver.class.getClassLoader();
103 }
104 return cl;
105 }
106
107 private static String normalizeKey(final String key) {
108 String normalizedKey = key;
109 if (normalizedKey.startsWith(CLASSPATH_URL_PREFIX)) {
110 normalizedKey = normalizedKey.substring(CLASSPATH_URL_PREFIX.length());
111 }
112 if (normalizedKey.startsWith("/")) {
113 normalizedKey = normalizedKey.substring(1);
114 }
115 return normalizedKey;
116 }
117 }