1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.properties.spi.config.cache;
17
18 import static de.smartics.properties.spi.config.cache.CacheConfigurationLoader.JNDI_NAME;
19 import static de.smartics.properties.spi.config.cache.CacheConfigurationLoader.CACHE_ID;
20
21 import java.io.BufferedInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.Serializable;
25 import java.net.URL;
26 import java.util.Collections;
27 import java.util.Enumeration;
28 import java.util.List;
29 import java.util.Properties;
30
31 import org.apache.commons.io.IOUtils;
32 import org.apache.commons.lang.StringUtils;
33
34 import de.smartics.properties.api.core.domain.PropertiesContext;
35
36
37
38
39
40 public class CacheConfigurationPropertiesLoader implements Serializable
41 {
42
43
44
45
46
47
48
49
50
51
52 private static final long serialVersionUID = 1L;
53
54
55
56
57 public static final String CLASSPATH_LOCATION =
58 PropertiesContext.BOOT_PROPERTIES_HOME + "/cache.properties";
59
60
61
62
63
64
65
66
67
68
69 public CacheConfigurationPropertiesLoader()
70 {
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91 public Properties load() throws CacheException, IllegalStateException
92 {
93 try
94 {
95 final Properties properties = loadProperties();
96 check(properties);
97 return properties;
98 }
99 catch (final IOException e)
100 {
101 throw new CacheException(CacheMessageBean.configFailure(e,
102 CLASSPATH_LOCATION));
103 }
104 }
105
106 private void check(final Properties properties) throws CacheException
107 {
108 final String jndiName = properties.getProperty(JNDI_NAME);
109 if (StringUtils.isBlank(jndiName))
110 {
111 throw new CacheException(CacheMessageBean.missingProperty(
112 CLASSPATH_LOCATION, JNDI_NAME));
113 }
114 }
115
116 private Properties loadProperties() throws IOException, IllegalStateException
117 {
118 final Enumeration<URL> urlsEnum =
119 Thread.currentThread().getContextClassLoader()
120 .getResources(CLASSPATH_LOCATION);
121 final List<URL> urls = Collections.list(urlsEnum);
122 final int count = urls.size();
123 if (count == 1)
124 {
125 final URL url = urls.get(0);
126
127 final Properties properties = new Properties();
128 final InputStream in = new BufferedInputStream(url.openStream());
129 try
130 {
131 properties.load(in);
132 }
133 finally
134 {
135 IOUtils.closeQuietly(in);
136 }
137 properties.setProperty(CACHE_ID, url.toString());
138
139 return properties;
140 }
141 else if (count == 0)
142 {
143 throw new IllegalStateException(String.format(
144 "Cannot find '%s' to configure the access to a cache.",
145 CLASSPATH_LOCATION));
146 }
147 else
148 {
149 throw new IllegalStateException(String.format(
150 "Found more than one configuration for '%s' to access a cache: %s",
151 CLASSPATH_LOCATION, urls));
152 }
153 }
154
155
156
157 }