Files
EasyDrop/src/main/java/de/rwu/easydrop/util/Config.java
2023-06-02 19:11:15 +02:00

113 lines
2.7 KiB
Java

package de.rwu.easydrop.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.naming.ConfigurationException;
/**
* Allows access to the config.
*
* @since 0.1.0
*/
public final class Config {
/**
* Config file location.
*/
private String configLocation = "config/config.properties";
/**
* @return the configLocation
*/
public String getConfigLocation() {
return configLocation;
}
/**
* @param newConfigLocation the configLocation to set
*/
public void setConfigLocation(final String newConfigLocation) {
configLocation = newConfigLocation;
}
/**
* Holds the config values.
*/
private Properties properties = null;
/**
* Singleton instance.
*/
private static Config instance = null;
/**
* Private constructor to prevent external instantiation.
*/
private Config() {
// Do Nothing
}
/**
* Returns current config instance.
*
* @return Config instance
* @throws ConfigurationException
*/
public static Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
/**
* Loads config file values into the instance.
*
* @throws ConfigurationException
*/
public void loadConfig() throws ConfigurationException {
Properties newProps = new Properties();
try (FileInputStream input = new FileInputStream(configLocation)) {
newProps.load(input);
properties = newProps;
} catch (IOException e) {
throw new ConfigurationException("Couldn't load required config file");
}
}
/**
* Returns a config property by specified key.
*
* @param key Config Key, like "API_KEY"
* @return Config value
* @throws NoSuchElementException Required key missing
*/
public String getProperty(final String key) throws NoSuchElementException {
String value = null;
try {
value = properties.getProperty(key);
} catch (NullPointerException e) {
throw new NoSuchElementException("Config has not been loaded");
}
if (value == null) {
throw new NoSuchElementException("Requested config value does not exist");
}
return value;
}
/**
* Overrides a config property loaded from file for current instance.
*
* @param key Config Key
* @param value Property Value
*/
public void setProperty(final String key, final String value) {
properties.setProperty(key, value);
}
}