View Javadoc
1   package uk.org.lidalia.slf4jtest;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.util.Properties;
6   
7   import com.google.common.base.Function;
8   import com.google.common.base.Optional;
9   
10  import static com.google.common.base.Optional.fromNullable;
11  import static uk.org.lidalia.lang.Exceptions.throwUnchecked;
12  
13  class OverridableProperties {
14      private static final Properties EMPTY_PROPERTIES = new Properties();
15      private final String propertySourceName;
16      private final Properties properties;
17  
18      OverridableProperties(final String propertySourceName) throws IOException {
19          this.propertySourceName = propertySourceName;
20          this.properties = getProperties();
21      }
22  
23      private Properties getProperties() throws IOException {
24          final Optional<InputStream> resourceAsStream = fromNullable(Thread.currentThread().getContextClassLoader()
25                  .getResourceAsStream(propertySourceName + ".properties"));
26          return resourceAsStream.transform(loadProperties).or(EMPTY_PROPERTIES);
27      }
28  
29      private static final Function<InputStream, Properties> loadProperties = new Function<InputStream, Properties>() {
30          @Override
31          public Properties apply(final InputStream propertyResource) {
32              try (InputStream closablePropertyResource = propertyResource) {
33                  final Properties loadedProperties = new Properties();
34                  loadedProperties.load(closablePropertyResource);
35                  return loadedProperties;
36              } catch (IOException ioException) {
37                  return throwUnchecked(ioException, null);
38              }
39          }
40      };
41  
42      String getProperty(final String propertyKey, final String defaultValue) {
43          final String propertyFileProperty = properties.getProperty(propertyKey, defaultValue);
44          return System.getProperty(propertySourceName + "." + propertyKey, propertyFileProperty);
45      }
46  }