001package org.maxur.perfmodel.backend.service.impl; 002 003import com.typesafe.config.Config; 004import com.typesafe.config.ConfigException; 005import com.typesafe.config.ConfigFactory; 006import org.jvnet.hk2.annotations.Service; 007import org.maxur.perfmodel.backend.service.PropertiesService; 008import org.slf4j.Logger; 009import org.slf4j.LoggerFactory; 010 011import javax.annotation.PostConstruct; 012import java.net.URI; 013import java.util.function.Function; 014 015/** 016 * @author Maxim Yunusov 017 * @version 1.0 018 * @since <pre>9/2/2015</pre> 019 */ 020@Service 021public class PropertiesServiceHoconImpl implements PropertiesService { 022 023 private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesServiceHoconImpl.class); 024 025 private Config defaultConfig; 026 027 private Config userConfig; 028 029 @PostConstruct 030 public void init() { 031 defaultConfig = ConfigFactory.load().getConfig("DEFAULTS"); 032 userConfig = ConfigFactory.load().getConfig("PMC"); 033 } 034 035 @Override 036 public URI asURI(final String key) { 037 return URI.create(asString(key)); 038 } 039 040 @Override 041 public String asString(final String key) { 042 return getValue(key, this::getString); 043 } 044 045 @Override 046 public Integer asInteger(final String key) { 047 return getValue(key, this::getInt); 048 } 049 050 private <T> T getValue(final String key, final Function<String, T> method) { 051 try { 052 final T value = method.apply(key); 053 LOGGER.info("Configuration parameter {} = '{}'", key, value); 054 return value; 055 } catch (ConfigException.Missing e) { 056 LOGGER.error("Configuration parameter '{}' is not found.", key); 057 throw e; 058 } 059 } 060 061 private String getString(final String key) { 062 try { 063 return userConfig.getString(key); 064 } catch (ConfigException.Missing e) { 065 return defaultConfig.getString(key); 066 } 067 } 068 069 private Integer getInt(final String key) { 070 try { 071 return userConfig.getInt(key); 072 } catch (ConfigException.Missing e) { 073 return defaultConfig.getInt(key); 074 } 075 } 076}