org.mentalog.config.ConfigParam Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of menta-log Show documentation
Show all versions of menta-log Show documentation
A log library that embraces the kiss principle.
package org.mentalog.config;
import org.mentalog.Log;
public class ConfigParam {
private static boolean forceMode = false;
private E value = null;
private boolean wasForced = false;
private boolean wasSet = false;
private final String name;
private final E defValue;
public ConfigParam(String name, E defValue) {
this.name = name;
this.defValue = defValue;
init(name);
}
protected void init(String name) {
String s = getString(name, null);
if (s != null) {
set(parseString(s), true);
}
}
@SuppressWarnings("unchecked")
protected E parseString(String s) {
try {
Class> klass = Class.forName(s);
return (E) klass.newInstance();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public E getDefault() {
return defValue;
}
public static void setForceMode(boolean flag) {
forceMode = flag;
}
protected void force() {
wasForced = true;
}
public static void checkAndLog(String name, Object attemptedValue, Object currentValue) {
if (Log.isShowBypassedConfig() && !isSame(attemptedValue, currentValue)) {
Log level = Log.getShowBypassedConfigLevel();
level.log("Bypassing configuration!", "config =", name, "attemptedValue =", attemptedValue, "currentValue =", currentValue);
}
}
private static boolean isSame(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 != null && o2 == null) return false;
if (o1 == null && o2 != null) return false;
return o1.equals(o2);
}
public void set(E value, boolean force) {
if (wasForced && !force) {
checkAndLog(name, value, this.value);
return;
}
this.wasSet = true;
this.wasForced = force;
this.value = value;
}
public final void set(E value) {
set(value, forceMode);
}
public final boolean isSet() {
return wasSet;
}
public final boolean isForced() {
return wasForced;
}
protected final boolean isForceMode() {
return forceMode;
}
public final String getName() {
return name;
}
public final E value() {
if (!isSet() && defValue != null) {
return defValue;
}
return value;
}
protected static String getString(String name, String def) {
String[] temp = name.split(",");
String s = null;
for(String x : temp) {
s = System.getenv(x);
if (s == null) {
s = System.getProperty(x);
}
if (s != null) {
break;
}
}
if (s == null) {
return def;
}
return s;
}
}