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