1 package org.maxur.perfmodel.backend.service.impl;
2
3 import com.typesafe.config.Config;
4 import com.typesafe.config.ConfigException;
5 import com.typesafe.config.ConfigFactory;
6 import org.jvnet.hk2.annotations.Service;
7 import org.maxur.perfmodel.backend.service.PropertiesService;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10
11 import javax.annotation.PostConstruct;
12 import java.net.URI;
13 import java.util.function.Function;
14
15
16
17
18
19
20 @Service
21 public class PropertiesServiceHoconImpl implements PropertiesService {
22
23 private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesServiceHoconImpl.class);
24
25 private Config defaultConfig;
26
27 private Config userConfig;
28
29 @PostConstruct
30 public void init() {
31 defaultConfig = ConfigFactory.load().getConfig("DEFAULTS");
32 userConfig = ConfigFactory.load().getConfig("PMC");
33 }
34
35 @Override
36 public URI asURI(final String key) {
37 return URI.create(asString(key));
38 }
39
40 @Override
41 public String asString(final String key) {
42 return getValue(key, this::getString);
43 }
44
45 @Override
46 public Integer asInteger(final String key) {
47 return getValue(key, this::getInt);
48 }
49
50 private <T> T getValue(final String key, final Function<String, T> method) {
51 try {
52 final T value = method.apply(key);
53 LOGGER.info("Configuration parameter {} = '{}'", key, value);
54 return value;
55 } catch (ConfigException.Missing e) {
56 LOGGER.error("Configuration parameter '{}' is not found.", key);
57 throw e;
58 }
59 }
60
61 private String getString(final String key) {
62 try {
63 return userConfig.getString(key);
64 } catch (ConfigException.Missing e) {
65 return defaultConfig.getString(key);
66 }
67 }
68
69 private Integer getInt(final String key) {
70 try {
71 return userConfig.getInt(key);
72 } catch (ConfigException.Missing e) {
73 return defaultConfig.getInt(key);
74 }
75 }
76 }