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