API Reference
Complete API documentation for ConfNG classes, interfaces, and methods.
ConfNG Class
The main entry point for configuration management. Provides static methods for loading sources and accessing configuration values.
Configuration Access Methods
get(ConfNGKey key)
public static String get(ConfNGKey key)
Gets a configuration value as a string.
- Parameters:
key
- the configuration key - Returns: the configuration value, or the default value if not found
- Example:
String browser = ConfNG.get(TestConfig.BROWSER);
getInt(ConfNGKey key)
public static Integer getInt(ConfNGKey key)
Gets a configuration value as an integer.
- Parameters:
key
- the configuration key - Returns: the configuration value as Integer, or null if not found and no default
- Throws:
IllegalArgumentException
if the value cannot be converted to integer - Example:
Integer timeout = ConfNG.getInt(TestConfig.TIMEOUT);
getBoolean(ConfNGKey key)
public static Boolean getBoolean(ConfNGKey key)
Gets a configuration value as a boolean.
- Parameters:
key
- the configuration key - Returns: the configuration value as Boolean, or null if not found and no default
- Throws:
IllegalArgumentException
if the value cannot be converted to boolean - Example:
Boolean headless = ConfNG.getBoolean(TestConfig.HEADLESS);
Source Management Methods
loadProperties(String filePath)
public static void loadProperties(String filePath)
Loads a properties file as a configuration source.
- Parameters:
filePath
- path to the properties file - Behavior: If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.
- Example:
ConfNG.loadProperties("test.properties");
loadJson(String filePath)
public static void loadJson(String filePath)
Loads a JSON file as a configuration source.
- Parameters:
filePath
- path to the JSON file - Behavior: If the file doesn't exist, it's silently skipped. If the file exists but is invalid, throws a runtime exception.
- Example:
ConfNG.loadJson("config.json");
loadSecretSource(ConfigSource source)
public static void loadSecretSource(ConfigSource source)
Loads a custom secret source.
- Parameters:
source
- the custom configuration source to add - Example:
ConfNG.loadSecretSource(new AWSSecretsSource());
registerSource(ConfigSource source)
public static void registerSource(ConfigSource source)
Registers a configuration source at the end of the precedence list.
- Parameters:
source
- the configuration source to add - Example:
ConfNG.registerSource(new DatabaseConfigSource());
registerSourceAt(int precedenceIndex, ConfigSource source)
public static void registerSourceAt(int precedenceIndex, ConfigSource source)
Registers a configuration source at a specific precedence position.
- Parameters:
precedenceIndex
- the position in the precedence list (0 = highest precedence)source
- the configuration source to add
- Throws:
IllegalArgumentException
if the precedence index is invalid - Example:
ConfNG.registerSourceAt(0, new HighPrioritySource());
Resolution Management Methods
resolveAllValues()
public static void resolveAllValues()
Resolves all configuration values from all sources according to precedence. This method is called automatically when needed but can be called manually to force immediate resolution.
resolveAllValues(Set<String> keys)
public static void resolveAllValues(Set<String> keys)
Resolves configuration values for the specified keys from all sources.
- Parameters:
keys
- specific keys to resolve, or null to discover all keys
refresh()
public static void refresh()
Forces re-resolution of all configuration values. Useful when configuration sources might have changed.
Utility Methods
getForDisplay(ConfNGKey key)
public static String getForDisplay(ConfNGKey key)
Gets a configuration value with masking for sensitive data.
- Parameters:
key
- the configuration key - Returns: the configuration value, masked if sensitive
- Example:
String maskedKey = ConfNG.getForDisplay(SecureConfig.API_KEY);
getAllForDisplay(ConfNGKey... keys)
public static String getAllForDisplay(ConfNGKey... keys)
Gets all configuration values for display purposes. Sensitive values are masked.
- Parameters:
keys
- the configuration keys to display - Returns: a formatted string showing all configuration values
- Example:
String allConfigs = ConfNG.getAllForDisplay(TestConfig.values());
getResolvedValueCount()
public static int getResolvedValueCount()
Gets the number of resolved configuration values.
isResolved()
public static boolean isResolved()
Checks if configuration values have been resolved.
getResolvedKeys()
public static Set<String> getResolvedKeys()
Gets all resolved configuration keys.
ConfNGKey Interface
Interface that defines configuration keys. Typically implemented by enums to provide type-safe configuration access.
Methods
getKey()
String getKey()
Returns the string key used to look up the configuration value.
getDefaultValue()
default String getDefaultValue() {
return null;
}
Returns the default value for this configuration key. Override to provide a default.
isSensitive()
default boolean isSensitive() {
return false;
}
Returns true if this configuration key contains sensitive data that should be masked in logs.
Implementation Example
public enum TestConfig implements ConfNGKey {
BROWSER("browser", "chrome"),
API_KEY("api.key", null, true);
private final String key;
private final String defaultValue;
private final boolean sensitive;
TestConfig(String key, String defaultValue) {
this(key, defaultValue, false);
}
TestConfig(String key, String defaultValue, boolean sensitive) {
this.key = key;
this.defaultValue = defaultValue;
this.sensitive = sensitive;
}
@Override
public String getKey() {
return key;
}
@Override
public String getDefaultValue() {
return defaultValue;
}
@Override
public boolean isSensitive() {
return sensitive;
}
}
ConfigSource Interface
Interface for configuration sources. Implement this interface to create custom configuration sources.
Methods
getName()
String getName()
Returns a descriptive name for this configuration source.
get(String key)
Optional<String> get(String key)
Gets a configuration value for the given key.
- Parameters:
key
- the configuration key - Returns: Optional containing the value if found, empty otherwise
Implementation Example
public class DatabaseConfigSource implements ConfigSource {
private final Map<String, String> configCache = new HashMap<>();
public DatabaseConfigSource(DataSource dataSource) {
// Load configuration from database
loadFromDatabase(dataSource);
}
@Override
public String getName() {
return "DatabaseConfig";
}
@Override
public Optional<String> get(String key) {
return Optional.ofNullable(configCache.get(key));
}
private void loadFromDatabase(DataSource dataSource) {
// Implementation details...
}
}
SecretManagerSource Class
Abstract base class for secret manager implementations. Provides common functionality such as caching, key mapping, and error handling.
Constructors
SecretManagerSource(long cacheTimeoutMs)
protected SecretManagerSource(long cacheTimeoutMs)
Creates a new secret manager source with caching enabled.
- Parameters:
cacheTimeoutMs
- cache timeout in milliseconds (0 = no timeout)
SecretManagerSource()
protected SecretManagerSource()
Creates a new secret manager source with caching disabled.
Methods
addKeyMapping(String configKey, String secretId)
public void addKeyMapping(String configKey, String secretId)
Maps a configuration key to a secret identifier.
- Parameters:
configKey
- the configuration keysecretId
- the secret identifier in the secret manager
fetchSecret(String secretId)
protected abstract String fetchSecret(String secretId) throws Exception
Fetches a secret from the secret manager. Must be implemented by subclasses.
- Parameters:
secretId
- the secret identifier - Returns: the secret value, or null if not found
- Throws: Exception if an error occurs while fetching the secret
clearCache()
public void clearCache()
Clears the secret cache.
getCacheSize()
public int getCacheSize()
Gets the number of cached secrets.
Implementation Example
public class AWSSecretsSource extends SecretManagerSource {
private final SecretsManagerClient client;
public AWSSecretsSource() {
super(300000); // 5 minute cache
this.client = SecretsManagerClient.builder()
.region(Region.US_EAST_1)
.build();
}
@Override
public String getName() {
return "AWSSecretsManager";
}
@Override
protected String fetchSecret(String secretId) throws Exception {
GetSecretValueRequest request = GetSecretValueRequest.builder()
.secretId(secretId)
.build();
GetSecretValueResponse response = client.getSecretValue(request);
return response.secretString();
}
}
Built-in Configuration Sources
EnvSource
Reads configuration from environment variables. Automatically registered with highest precedence.
public class EnvSource implements ConfigSource {
@Override
public String getName() {
return "Environment";
}
@Override
public Optional<String> get(String key) {
return Optional.ofNullable(System.getenv(key));
}
}
SystemPropertySource
Reads configuration from Java system properties. Automatically registered with second-highest precedence.
public class SystemPropertySource implements ConfigSource {
@Override
public String getName() {
return "SystemProperties";
}
@Override
public Optional<String> get(String key) {
return Optional.ofNullable(System.getProperty(key));
}
}
PropertiesSource
Reads configuration from Java properties files.
public class PropertiesSource implements ConfigSource {
public PropertiesSource(Path file) {
// Loads properties from file
}
@Override
public String getName() {
return "Properties(" + file.toString() + ")";
}
@Override
public Optional<String> get(String key) {
// Returns property value
}
}
JsonSource
Reads configuration from JSON files using Gson for parsing.
public class JsonSource implements ConfigSource {
public JsonSource(Path file) {
// Loads JSON from file using Gson
}
@Override
public String getName() {
return "Json(" + file.toString() + ")";
}
@Override
public Optional<String> get(String key) {
// Returns JSON value as string
}
}
Exceptions
IllegalArgumentException
Thrown by type conversion methods when values cannot be converted to the requested type.
Common Scenarios
- getInt(): When the configuration value is not a valid integer
- getBoolean(): When the configuration value is not "true" or "false" (case-insensitive)
Example
try {
Integer timeout = ConfNG.getInt(TestConfig.TIMEOUT);
} catch (IllegalArgumentException e) {
// Handle invalid number format
System.err.println("Invalid timeout value: " + e.getMessage());
// Use default or alternative handling
Integer timeout = 30;
}
RuntimeException
Thrown when configuration files exist but cannot be loaded or parsed.
Common Scenarios
- loadProperties(): When properties file exists but has invalid format
- loadJson(): When JSON file exists but has invalid JSON syntax
- registerSourceAt(): When precedence index is invalid
Example
try {
ConfNG.loadJson("config.json");
} catch (RuntimeException e) {
System.err.println("Failed to load JSON config: " + e.getMessage());
// Handle error or use alternative configuration
}