com.quotemedia.streamer.client.cfg.ConfigJson Maven / Gradle / Ivy
Show all versions of streamerclient-java-core Show documentation
package com.quotemedia.streamer.client.cfg;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quotemedia.streamer.client.auth.cfg.AuthCfg;
import com.quotemedia.streamer.client.auth.cfg.AuthCfgJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* Supports {@link com.quotemedia.streamer.client.StreamFactory} configuration loading form a JSON file.
*/
public final class ConfigJson {
private static final Logger log = LoggerFactory.getLogger(ConfigJson.class);
@JsonIgnore
private String file;
/**
* Sets the configuration file path.
*
* @param value the file path
* @return a reference to this object
*/
public final ConfigJson file(final String value) {
this.file = value;
return this;
}
/**
* Loads configuration from file.
*
* First the filesystem is searched, then the classpath.
* If the file cannot be found in filesystem nor classpath an exception is thrown.
*
* @return the loaded configuration
* @throws IOException if the configuration cannot be loaded from file
*/
public final Config build() throws IOException {
InputStream is = null;
final File f = new File(this.file);
try {
if (f.exists() && f.isFile()) {
is = new FileInputStream(f);
log.debug("Loading config from file '{}'.", f.getAbsolutePath());
} else {
is = ConfigJson.class.getResourceAsStream(this.file);
if (is != null) {
log.debug("Loading config from classpath '{}'.", this.file);
}
}
if (is == null) {
throw new FileNotFoundException(String.format("Config file '%s' not found.", this.file));
}
final ObjectMapper json = new ObjectMapper();
json.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
return json.readValue(is, ConfigImplJson.class);
} finally {
if (is != null) {
is.close();
}
}
}
private static final class ConfigImplJson implements Config {
@JsonProperty
private AuthCfgJson auth;
@Override
public AuthCfg auth() {
return this.auth;
}
}
}