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