All Downloads are FREE. Search and download functionalities are using the official Maven repository.

me.lachlanap.config.loader.PropertiesParser Maven / Gradle / Ivy

Go to download

Configuration is a Java library to manage application configuration with compiled-in defaults and externally overridable config files, in a Properties-like manner.

The newest version!
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package me.lachlanap.config.loader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import me.lachlanap.config.ConfigurationLoadingException;
import me.lachlanap.config.values.Value;
import me.lachlanap.config.values.ValuesContainer;

/**
 *
 * @author lachlan
 */
public class PropertiesParser {

    private final URL resource;

    public PropertiesParser(URL resource) {
        this.resource = resource;
    }

    public void readInto(ValuesContainer valuesContainer) throws ConfigurationLoadingException {
        processFile(valuesContainer);
    }

    private void processFile(ValuesContainer valuesContainer) throws ConfigurationLoadingException {
        try (BufferedReader br
                = new BufferedReader(new InputStreamReader(resource.openStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (!lineIsComment(line) && !line.isEmpty())
                    processLine(line, valuesContainer);
            }
        } catch (IOException ioe) {
            throw new ConfigurationLoadingException("Error reading configuration", ioe);
        }
    }

    private boolean lineIsComment(String line) {
        return line.startsWith("#") || line.startsWith("//");
    }

    private void processLine(String line, ValuesContainer valuesContainer) {
        String[] keyval = split(line);

        if (keyval[0].isEmpty())
            throw new ConfigurationLoadingException("Key cannot be nothing: " + line);
        if (keyval[1] == null)
            throw new ConfigurationLoadingException("Value cannot be null: " + line);

        Value val = Value.parse(keyval[1]);
        valuesContainer.put(keyval[0], val);
    }

    private String[] split(String line) {
        String[] keyval = new String[2];
        int indexOfEquals = line.indexOf("=");

        if (indexOfEquals < 0)
            throw new ConfigurationLoadingException("Invalid line: '" + line + "' - not a comment.");

        keyval[0] = line.substring(0, indexOfEquals).trim();
        keyval[1] = line.substring(indexOfEquals + 1).trim();

        return keyval;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy