feat(config): implement configuration system with TOML parser (#2)

- Add LogLevel enum with case-insensitive parsing
- Add OperatingSystem enum with platform detection
- Create config records: Config, ServiceConfig, JobsConfig, CleanupConfig, StorageConfig
- Add ConfigDefaults for platform-specific paths (Unix/Windows)
- Implement TomlParser supporting sections, strings, integers, floats, booleans, arrays
- Create ConfigLoader with:
  - File loading from search paths (system/user config)
  - Environment variable overrides (BARN_SECTION_KEY pattern)
  - Validation of all config values
  - Defaults for missing values
- Add comprehensive tests (93 new tests, 119 total)

Closes #2

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-21 12:59:15 +00:00
1 parent 05937b1f7e
commit 79f89be47c
16 files changed
+2120

No files matched your search

@@ -0,0 +1,64 @@
package com.samsonmedia.barn.config;
/**
* Configuration for automatic job cleanup.
*
* @param enabled whether automatic cleanup is enabled
* @param maxAgeHours remove jobs older than this
* @param cleanupIntervalMinutes how often the cleanup task runs
* @param keepFailedJobs preserve failed jobs for debugging
* @param keepFailedJobsHours how long to keep failed jobs
*/
public record CleanupConfig(
boolean enabled,
int maxAgeHours,
int cleanupIntervalMinutes,
boolean keepFailedJobs,
int keepFailedJobsHours
) {
/** Default enabled state. */
public static final boolean DEFAULT_ENABLED = true;
/** Default max age in hours (3 days). */
public static final int DEFAULT_MAX_AGE_HOURS = 72;
/** Default cleanup interval in minutes. */
public static final int DEFAULT_CLEANUP_INTERVAL_MINUTES = 60;
/** Default keep failed jobs setting. */
public static final boolean DEFAULT_KEEP_FAILED_JOBS = true;
/** Default keep failed jobs hours (1 week). */
public static final int DEFAULT_KEEP_FAILED_JOBS_HOURS = 168;
/**
* Creates a CleanupConfig with validation.
*/
public CleanupConfig {
if (maxAgeHours < 1) {
throw new IllegalArgumentException("maxAgeHours must be at least 1");
}
if (cleanupIntervalMinutes < 1) {
throw new IllegalArgumentException("cleanupIntervalMinutes must be at least 1");
}
if (keepFailedJobsHours < 1) {
throw new IllegalArgumentException("keepFailedJobsHours must be at least 1");
}
}
/**
* Creates a CleanupConfig with default values.
*
* @return a CleanupConfig with all defaults
*/
public static CleanupConfig withDefaults() {
return new CleanupConfig(
DEFAULT_ENABLED,
DEFAULT_MAX_AGE_HOURS,
DEFAULT_CLEANUP_INTERVAL_MINUTES,
DEFAULT_KEEP_FAILED_JOBS,
DEFAULT_KEEP_FAILED_JOBS_HOURS
);
}
}
@@ -0,0 +1,43 @@
package com.samsonmedia.barn.config;
import java.util.Objects;
/**
* Top-level configuration for the Barn application.
*
* @param service service daemon configuration
* @param jobs job execution configuration
* @param cleanup automatic cleanup configuration
* @param storage storage and filesystem configuration
*/
public record Config(
ServiceConfig service,
JobsConfig jobs,
CleanupConfig cleanup,
StorageConfig storage
) {
/**
* Creates a Config with validation.
*/
public Config {
Objects.requireNonNull(service, "service must not be null");
Objects.requireNonNull(jobs, "jobs must not be null");
Objects.requireNonNull(cleanup, "cleanup must not be null");
Objects.requireNonNull(storage, "storage must not be null");
}
/**
* Creates a Config with all default values.
*
* @return a Config with all defaults
*/
public static Config withDefaults() {
return new Config(
ServiceConfig.withDefaults(),
JobsConfig.withDefaults(),
CleanupConfig.withDefaults(),
StorageConfig.withDefaults()
);
}
}
@@ -0,0 +1,92 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* Provides platform-specific default values for configuration.
*/
public final class ConfigDefaults {
private ConfigDefaults() {
// Utility class - prevent instantiation
}
/**
* Gets the default base directory for Barn data.
*
* @return the default base directory
*/
public static Path getDefaultBaseDir() {
return switch (OperatingSystem.current()) {
case WINDOWS -> Path.of(System.getenv("TEMP"), "barn");
case LINUX, MACOS -> Path.of("/tmp/barn");
};
}
/**
* Gets the default IPC socket path.
*
* @return the default IPC socket path
*/
public static Path getDefaultIpcSocket() {
return switch (OperatingSystem.current()) {
case WINDOWS -> Path.of("\\\\.\\pipe\\barn");
case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock");
};
}
/**
* Gets the system-wide configuration file path.
*
* @return the system config path
*/
public static Path getSystemConfigPath() {
return switch (OperatingSystem.current()) {
case WINDOWS -> {
String programData = System.getenv("PROGRAMDATA");
if (programData == null || programData.isBlank()) {
programData = "C:\\ProgramData";
}
yield Path.of(programData, "barn", "barn.conf");
}
case LINUX, MACOS -> Path.of("/etc/barn/barn.conf");
};
}
/**
* Gets the user-specific configuration file path.
*
* @return the user config path
*/
public static Path getUserConfigPath() {
String userHome = System.getProperty("user.home", "");
return switch (OperatingSystem.current()) {
case WINDOWS -> {
String appData = System.getenv("APPDATA");
if (appData == null || appData.isBlank()) {
appData = Path.of(userHome, "AppData", "Roaming").toString();
}
yield Path.of(appData, "barn", "barn.conf");
}
case MACOS -> Path.of(userHome, "Library", "Application Support", "barn", "barn.conf");
case LINUX -> Path.of(userHome, ".config", "barn", "barn.conf");
};
}
/**
* Gets the list of configuration file paths in priority order.
*
* <p>Paths are returned in order of increasing priority - later paths
* override earlier ones.
*
* @return list of config paths to check
*/
public static List<Path> getConfigSearchPaths() {
List<Path> paths = new ArrayList<>();
paths.add(getSystemConfigPath());
paths.add(getUserConfigPath());
return paths;
}
}
@@ -0,0 +1,319 @@
package com.samsonmedia.barn.config;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Loads and validates Barn configuration from files and environment variables.
*
* <p>Configuration is loaded in the following priority order (later overrides earlier):
* <ol>
* <li>Default values</li>
* <li>System config file (e.g., /etc/barn/barn.conf)</li>
* <li>User config file (e.g., ~/.config/barn/barn.conf)</li>
* <li>Explicit config file (via --config flag)</li>
* <li>Environment variables (BARN_SECTION_KEY format)</li>
* </ol>
*/
public final class ConfigLoader {
private static final Logger LOG = LoggerFactory.getLogger(ConfigLoader.class);
private static final String ENV_PREFIX = "BARN_";
private final Map<String, String> environment;
/**
* Creates a ConfigLoader using the system environment.
*/
public ConfigLoader() {
this(System.getenv());
}
/**
* Creates a ConfigLoader with a custom environment (for testing).
*
* @param environment the environment variables to use
*/
public ConfigLoader(Map<String, String> environment) {
this.environment = Objects.requireNonNull(environment, "environment must not be null");
}
/**
* Loads configuration using default search paths.
*
* @return the loaded configuration
* @throws ConfigException if configuration is invalid
*/
public Config load() {
return load(Optional.empty());
}
/**
* Loads configuration, optionally with an explicit config file.
*
* @param explicitPath optional explicit config file path
* @return the loaded configuration
* @throws ConfigException if configuration is invalid
*/
public Config load(Optional<Path> explicitPath) {
Objects.requireNonNull(explicitPath, "explicitPath must not be null");
Map<String, Map<String, Object>> merged = new HashMap<>();
// Load from search paths
for (Path path : ConfigDefaults.getConfigSearchPaths()) {
loadIfExists(path).ifPresent(data -> mergeInto(merged, data));
}
// Load from explicit path if provided
explicitPath.flatMap(this::loadIfExists).ifPresent(data -> mergeInto(merged, data));
// Apply environment overrides
applyEnvironmentOverrides(merged);
return buildConfig(merged);
}
/**
* Loads configuration from a specific file.
*
* @param path the path to the config file
* @return the loaded configuration
* @throws ConfigException if the file cannot be read or is invalid
*/
public Config loadFromFile(Path path) {
Objects.requireNonNull(path, "path must not be null");
Map<String, Map<String, Object>> data = loadFile(path);
applyEnvironmentOverrides(data);
return buildConfig(data);
}
private Optional<Map<String, Map<String, Object>>> loadIfExists(Path path) {
if (!Files.exists(path)) {
LOG.debug("Config file not found: {}", path);
return Optional.empty();
}
try {
return Optional.of(loadFile(path));
} catch (ConfigException e) {
LOG.warn("Failed to load config file {}: {}", path, e.getMessage());
return Optional.empty();
}
}
private Map<String, Map<String, Object>> loadFile(Path path) {
LOG.debug("Loading config from: {}", path);
try {
String content = Files.readString(path);
return TomlParser.parse(content);
} catch (IOException e) {
throw new ConfigException("Failed to read config file: " + path, e);
} catch (TomlParser.TomlParseException e) {
throw new ConfigException("Failed to parse config file: " + path + " - " + e.getMessage(), e);
}
}
private void mergeInto(Map<String, Map<String, Object>> target,
Map<String, Map<String, Object>> source) {
for (Map.Entry<String, Map<String, Object>> entry : source.entrySet()) {
target.computeIfAbsent(entry.getKey(), k -> new HashMap<>())
.putAll(entry.getValue());
}
}
private void applyEnvironmentOverrides(Map<String, Map<String, Object>> data) {
for (Map.Entry<String, String> entry : environment.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!key.startsWith(ENV_PREFIX) || key.equals(ENV_PREFIX)) {
continue;
}
String remainder = key.substring(ENV_PREFIX.length());
int underscoreIndex = remainder.indexOf('_');
if (underscoreIndex <= 0) {
continue;
}
String section = remainder.substring(0, underscoreIndex).toLowerCase();
String configKey = remainder.substring(underscoreIndex + 1).toLowerCase();
LOG.debug("Applying environment override: {}={}", key, value);
data.computeIfAbsent(section, k -> new HashMap<>())
.put(configKey, parseEnvValue(value));
}
}
private Object parseEnvValue(String value) {
if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
return Boolean.parseBoolean(value);
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
// Not an integer
}
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
// Not a double
}
return value;
}
private Config buildConfig(Map<String, Map<String, Object>> data) {
return new Config(
buildServiceConfig(data.getOrDefault("service", Map.of())),
buildJobsConfig(data.getOrDefault("jobs", Map.of())),
buildCleanupConfig(data.getOrDefault("cleanup", Map.of())),
buildStorageConfig(data.getOrDefault("storage", Map.of()))
);
}
private ServiceConfig buildServiceConfig(Map<String, Object> data) {
return new ServiceConfig(
getOrDefault(data, "log_level", ServiceConfig.DEFAULT_LOG_LEVEL,
v -> LogLevel.fromString(v.toString())),
getOrDefault(data, "max_concurrent_jobs", ServiceConfig.DEFAULT_MAX_CONCURRENT_JOBS,
this::toInt),
getOrDefault(data, "heartbeat_interval_seconds", ServiceConfig.DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
this::toInt),
getOrDefault(data, "ipc_socket", ConfigDefaults.getDefaultIpcSocket(),
v -> Path.of(v.toString())),
getOrDefault(data, "stale_heartbeat_threshold_seconds",
ServiceConfig.DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS, this::toInt)
);
}
private JobsConfig buildJobsConfig(Map<String, Object> data) {
return new JobsConfig(
getOrDefault(data, "default_timeout_seconds", JobsConfig.DEFAULT_TIMEOUT_SECONDS,
this::toInt),
getOrDefault(data, "max_retries", JobsConfig.DEFAULT_MAX_RETRIES,
this::toInt),
getOrDefault(data, "retry_delay_seconds", JobsConfig.DEFAULT_RETRY_DELAY_SECONDS,
this::toInt),
getOrDefault(data, "retry_backoff_multiplier", JobsConfig.DEFAULT_RETRY_BACKOFF_MULTIPLIER,
this::toDouble),
getOrDefault(data, "retry_on_exit_codes", List.of(),
this::toIntList)
);
}
private CleanupConfig buildCleanupConfig(Map<String, Object> data) {
return new CleanupConfig(
getOrDefault(data, "enabled", CleanupConfig.DEFAULT_ENABLED,
this::toBoolean),
getOrDefault(data, "max_age_hours", CleanupConfig.DEFAULT_MAX_AGE_HOURS,
this::toInt),
getOrDefault(data, "cleanup_interval_minutes", CleanupConfig.DEFAULT_CLEANUP_INTERVAL_MINUTES,
this::toInt),
getOrDefault(data, "keep_failed_jobs", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS,
this::toBoolean),
getOrDefault(data, "keep_failed_jobs_hours", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS_HOURS,
this::toInt)
);
}
private StorageConfig buildStorageConfig(Map<String, Object> data) {
return new StorageConfig(
getOrDefault(data, "base_dir", ConfigDefaults.getDefaultBaseDir(),
v -> Path.of(v.toString())),
getOrDefault(data, "max_disk_usage_gb", StorageConfig.DEFAULT_MAX_DISK_USAGE_GB,
this::toInt),
getOrDefault(data, "preserve_work_dir", StorageConfig.DEFAULT_PRESERVE_WORK_DIR,
this::toBoolean)
);
}
@SuppressWarnings("unchecked")
private <T> T getOrDefault(Map<String, Object> data, String key, T defaultValue,
Function<Object, T> converter) {
Object value = data.get(key);
if (value == null) {
return defaultValue;
}
try {
if (defaultValue != null && defaultValue.getClass().isInstance(value)) {
return (T) value;
}
return converter.apply(value);
} catch (Exception e) {
throw new ConfigException("Invalid value for '" + key + "': " + value, e);
}
}
private int toInt(Object value) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
return Integer.parseInt(value.toString());
}
private double toDouble(Object value) {
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
return Double.parseDouble(value.toString());
}
private boolean toBoolean(Object value) {
if (value instanceof Boolean) {
return (Boolean) value;
}
return Boolean.parseBoolean(value.toString());
}
@SuppressWarnings("unchecked")
private List<Integer> toIntList(Object value) {
if (value instanceof List) {
List<?> list = (List<?>) value;
List<Integer> result = new ArrayList<>(list.size());
for (Object item : list) {
result.add(toInt(item));
}
return result;
}
throw new ConfigException("Expected list but got: " + value.getClass().getSimpleName());
}
/**
* Exception thrown when configuration loading or validation fails.
*/
public static class ConfigException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new ConfigException.
*
* @param message the error message
*/
public ConfigException(String message) {
super(message);
}
/**
* Creates a new ConfigException with a cause.
*
* @param message the error message
* @param cause the underlying cause
*/
public ConfigException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,69 @@
package com.samsonmedia.barn.config;
import java.util.List;
import java.util.Objects;
/**
* Configuration for job execution behavior.
*
* @param defaultTimeoutSeconds maximum time a job can run before being killed
* @param maxRetries number of retry attempts for failed jobs
* @param retryDelaySeconds initial delay before first retry
* @param retryBackoffMultiplier multiplier applied to delay after each retry
* @param retryOnExitCodes only retry on these exit codes (empty = retry all failures)
*/
public record JobsConfig(
int defaultTimeoutSeconds,
int maxRetries,
int retryDelaySeconds,
double retryBackoffMultiplier,
List<Integer> retryOnExitCodes
) {
/** Default job timeout in seconds (1 hour). */
public static final int DEFAULT_TIMEOUT_SECONDS = 3600;
/** Default maximum number of retries. */
public static final int DEFAULT_MAX_RETRIES = 3;
/** Default retry delay in seconds. */
public static final int DEFAULT_RETRY_DELAY_SECONDS = 30;
/** Default retry backoff multiplier. */
public static final double DEFAULT_RETRY_BACKOFF_MULTIPLIER = 2.0;
/**
* Creates a JobsConfig with validation.
*/
public JobsConfig {
Objects.requireNonNull(retryOnExitCodes, "retryOnExitCodes must not be null");
if (defaultTimeoutSeconds < 1) {
throw new IllegalArgumentException("defaultTimeoutSeconds must be at least 1");
}
if (maxRetries < 0) {
throw new IllegalArgumentException("maxRetries must be non-negative");
}
if (retryDelaySeconds < 0) {
throw new IllegalArgumentException("retryDelaySeconds must be non-negative");
}
if (retryBackoffMultiplier < 1.0) {
throw new IllegalArgumentException("retryBackoffMultiplier must be at least 1.0");
}
retryOnExitCodes = List.copyOf(retryOnExitCodes);
}
/**
* Creates a JobsConfig with default values.
*
* @return a JobsConfig with all defaults
*/
public static JobsConfig withDefaults() {
return new JobsConfig(
DEFAULT_TIMEOUT_SECONDS,
DEFAULT_MAX_RETRIES,
DEFAULT_RETRY_DELAY_SECONDS,
DEFAULT_RETRY_BACKOFF_MULTIPLIER,
List.of()
);
}
}
@@ -0,0 +1,30 @@
package com.samsonmedia.barn.config;
/**
* Log level for the Barn service.
*/
public enum LogLevel {
DEBUG,
INFO,
WARN,
ERROR;
/**
* Parses a log level from a string (case-insensitive).
*
* @param value the string value to parse
* @return the parsed LogLevel
* @throws IllegalArgumentException if the value is not a valid log level
*/
public static LogLevel fromString(String value) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Log level cannot be null or blank");
}
try {
return valueOf(value.trim().toUpperCase());
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
"Invalid log level: '" + value + "'. Valid values are: debug, info, warn, error");
}
}
}
@@ -0,0 +1,44 @@
package com.samsonmedia.barn.config;
/**
* Represents the operating system Barn is running on.
*/
public enum OperatingSystem {
LINUX,
MACOS,
WINDOWS;
private static OperatingSystem detected;
/**
* Detects the current operating system.
*
* @return the detected operating system
*/
public static OperatingSystem current() {
if (detected == null) {
detected = detect();
}
return detected;
}
private static OperatingSystem detect() {
String osName = System.getProperty("os.name", "").toLowerCase();
if (osName.contains("win")) {
return WINDOWS;
} else if (osName.contains("mac") || osName.contains("darwin")) {
return MACOS;
} else {
return LINUX;
}
}
/**
* Checks if the current OS is Unix-like (Linux or macOS).
*
* @return true if Unix-like, false otherwise
*/
public boolean isUnixLike() {
return this == LINUX || this == MACOS;
}
}
@@ -0,0 +1,66 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.Objects;
/**
* Configuration for the Barn service daemon.
*
* @param logLevel the logging verbosity level
* @param maxConcurrentJobs maximum number of jobs running simultaneously
* @param heartbeatIntervalSeconds how often running jobs update their heartbeat
* @param ipcSocket path to the IPC socket for CLI communication
* @param staleHeartbeatThresholdSeconds heartbeat age before a job is considered orphaned
*/
public record ServiceConfig(
LogLevel logLevel,
int maxConcurrentJobs,
int heartbeatIntervalSeconds,
Path ipcSocket,
int staleHeartbeatThresholdSeconds
) {
/** Default log level. */
public static final LogLevel DEFAULT_LOG_LEVEL = LogLevel.INFO;
/** Default maximum concurrent jobs. */
public static final int DEFAULT_MAX_CONCURRENT_JOBS = 4;
/** Default heartbeat interval in seconds. */
public static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 5;
/** Default stale heartbeat threshold in seconds. */
public static final int DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS = 30;
/**
* Creates a ServiceConfig with validation.
*/
public ServiceConfig {
Objects.requireNonNull(logLevel, "logLevel must not be null");
Objects.requireNonNull(ipcSocket, "ipcSocket must not be null");
if (maxConcurrentJobs < 1) {
throw new IllegalArgumentException("maxConcurrentJobs must be at least 1");
}
if (heartbeatIntervalSeconds < 1) {
throw new IllegalArgumentException("heartbeatIntervalSeconds must be at least 1");
}
if (staleHeartbeatThresholdSeconds < 1) {
throw new IllegalArgumentException("staleHeartbeatThresholdSeconds must be at least 1");
}
}
/**
* Creates a ServiceConfig with default values.
*
* @return a ServiceConfig with all defaults
*/
public static ServiceConfig withDefaults() {
return new ServiceConfig(
DEFAULT_LOG_LEVEL,
DEFAULT_MAX_CONCURRENT_JOBS,
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
ConfigDefaults.getDefaultIpcSocket(),
DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS
);
}
}
@@ -0,0 +1,47 @@
package com.samsonmedia.barn.config;
import java.nio.file.Path;
import java.util.Objects;
/**
* Configuration for storage and filesystem settings.
*
* @param baseDir root directory for all Barn data
* @param maxDiskUsageGb maximum disk space Barn can use
* @param preserveWorkDir keep work/input and work/output after job completion
*/
public record StorageConfig(
Path baseDir,
int maxDiskUsageGb,
boolean preserveWorkDir
) {
/** Default max disk usage in GB. */
public static final int DEFAULT_MAX_DISK_USAGE_GB = 50;
/** Default preserve work dir setting. */
public static final boolean DEFAULT_PRESERVE_WORK_DIR = false;
/**
* Creates a StorageConfig with validation.
*/
public StorageConfig {
Objects.requireNonNull(baseDir, "baseDir must not be null");
if (maxDiskUsageGb < 1) {
throw new IllegalArgumentException("maxDiskUsageGb must be at least 1");
}
}
/**
* Creates a StorageConfig with default values.
*
* @return a StorageConfig with all defaults
*/
public static StorageConfig withDefaults() {
return new StorageConfig(
ConfigDefaults.getDefaultBaseDir(),
DEFAULT_MAX_DISK_USAGE_GB,
DEFAULT_PRESERVE_WORK_DIR
);
}
}
@@ -0,0 +1,239 @@
package com.samsonmedia.barn.config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Simple TOML parser supporting the subset of TOML used by Barn configuration.
*
* <p>Supports:
* <ul>
* <li>Sections: [section_name]</li>
* <li>String values: key = "value"</li>
* <li>Integer values: key = 123</li>
* <li>Float values: key = 1.5</li>
* <li>Boolean values: key = true/false</li>
* <li>Array values: key = [1, 2, 3]</li>
* <li>Comments: # comment</li>
* </ul>
*/
public final class TomlParser {
private static final Pattern SECTION_PATTERN = Pattern.compile("^\\s*\\[([a-zA-Z_][a-zA-Z0-9_]*)\\]\\s*$");
private static final Pattern KEY_VALUE_PATTERN = Pattern.compile(
"^\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*=\\s*(.+)$");
private static final Pattern STRING_PATTERN = Pattern.compile("^\"(.*)\"$");
private static final Pattern INTEGER_PATTERN = Pattern.compile("^-?\\d+$");
private static final Pattern FLOAT_PATTERN = Pattern.compile("^-?\\d+\\.\\d+$");
private static final Pattern BOOLEAN_PATTERN = Pattern.compile("^(true|false)$", Pattern.CASE_INSENSITIVE);
private static final Pattern ARRAY_PATTERN = Pattern.compile("^\\[(.*)\\]$");
private TomlParser() {
// Utility class - prevent instantiation
}
/**
* Parses TOML content from a string.
*
* @param content the TOML content
* @return a map of section names to key-value maps
* @throws TomlParseException if the content cannot be parsed
*/
public static Map<String, Map<String, Object>> parse(String content) {
Objects.requireNonNull(content, "content must not be null");
try {
return parse(new StringReader(content));
} catch (IOException e) {
throw new TomlParseException("Failed to parse TOML content", e);
}
}
/**
* Parses TOML content from a reader.
*
* @param reader the reader to read from
* @return a map of section names to key-value maps
* @throws IOException if reading fails
* @throws TomlParseException if the content cannot be parsed
*/
public static Map<String, Map<String, Object>> parse(Reader reader) throws IOException {
Objects.requireNonNull(reader, "reader must not be null");
Map<String, Map<String, Object>> result = new HashMap<>();
String currentSection = null;
int lineNumber = 0;
try (BufferedReader buffered = new BufferedReader(reader)) {
String line;
while ((line = buffered.readLine()) != null) {
lineNumber++;
line = stripComment(line).trim();
if (line.isEmpty()) {
continue;
}
Matcher sectionMatcher = SECTION_PATTERN.matcher(line);
if (sectionMatcher.matches()) {
currentSection = sectionMatcher.group(1);
result.putIfAbsent(currentSection, new HashMap<>());
continue;
}
Matcher keyValueMatcher = KEY_VALUE_PATTERN.matcher(line);
if (keyValueMatcher.matches()) {
if (currentSection == null) {
throw new TomlParseException(
"Key-value pair outside of section at line " + lineNumber);
}
String key = keyValueMatcher.group(1);
String valueStr = keyValueMatcher.group(2).trim();
Object value = parseValue(valueStr, lineNumber);
result.get(currentSection).put(key, value);
continue;
}
throw new TomlParseException("Invalid syntax at line " + lineNumber + ": " + line);
}
}
return result;
}
private static String stripComment(String line) {
int commentIndex = -1;
boolean inString = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '"' && (i == 0 || line.charAt(i - 1) != '\\')) {
inString = !inString;
} else if (c == '#' && !inString) {
commentIndex = i;
break;
}
}
return commentIndex >= 0 ? line.substring(0, commentIndex) : line;
}
private static Object parseValue(String valueStr, int lineNumber) {
Matcher stringMatcher = STRING_PATTERN.matcher(valueStr);
if (stringMatcher.matches()) {
return unescapeString(stringMatcher.group(1));
}
if (BOOLEAN_PATTERN.matcher(valueStr).matches()) {
return Boolean.parseBoolean(valueStr);
}
if (INTEGER_PATTERN.matcher(valueStr).matches()) {
try {
return Integer.parseInt(valueStr);
} catch (NumberFormatException e) {
try {
return Long.parseLong(valueStr);
} catch (NumberFormatException e2) {
throw new TomlParseException(
"Integer value too large at line " + lineNumber + ": " + valueStr);
}
}
}
if (FLOAT_PATTERN.matcher(valueStr).matches()) {
return Double.parseDouble(valueStr);
}
Matcher arrayMatcher = ARRAY_PATTERN.matcher(valueStr);
if (arrayMatcher.matches()) {
return parseArray(arrayMatcher.group(1), lineNumber);
}
throw new TomlParseException("Cannot parse value at line " + lineNumber + ": " + valueStr);
}
private static List<Object> parseArray(String content, int lineNumber) {
List<Object> result = new ArrayList<>();
if (content.trim().isEmpty()) {
return result;
}
StringBuilder current = new StringBuilder();
int depth = 0;
boolean inString = false;
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
if (c == '"' && (i == 0 || content.charAt(i - 1) != '\\')) {
inString = !inString;
current.append(c);
} else if (c == '[' && !inString) {
depth++;
current.append(c);
} else if (c == ']' && !inString) {
depth--;
current.append(c);
} else if (c == ',' && depth == 0 && !inString) {
String value = current.toString().trim();
if (!value.isEmpty()) {
result.add(parseValue(value, lineNumber));
}
current = new StringBuilder();
} else {
current.append(c);
}
}
String remaining = current.toString().trim();
if (!remaining.isEmpty()) {
result.add(parseValue(remaining, lineNumber));
}
return result;
}
private static String unescapeString(String str) {
return str
.replace("\\\"", "\"")
.replace("\\\\", "\\")
.replace("\\n", "\n")
.replace("\\t", "\t")
.replace("\\r", "\r");
}
/**
* Exception thrown when TOML parsing fails.
*/
public static class TomlParseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Creates a new TomlParseException.
*
* @param message the error message
*/
public TomlParseException(String message) {
super(message);
}
/**
* Creates a new TomlParseException with a cause.
*
* @param message the error message
* @param cause the underlying cause
*/
public TomlParseException(String message, Throwable cause) {
super(message, cause);
}
}
}