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

fr.ird.observe.toolkit.templates.entity.query.PropertiesParser Maven / Gradle / Ivy

package fr.ird.observe.toolkit.templates.entity.query;

/*-
 * #%L
 * Toolkit :: Templates
 * %%
 * Copyright (C) 2017 - 2024 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import fr.ird.observe.dto.ObserveUtil;

import java.net.URL;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created at 14/12/2023.
 *
 * @author Tony Chemit - [email protected]
 * @since 9.3.0
 */
public class PropertiesParser {

    public static final Pattern PROPERTY_PATTERN = Pattern.compile("^([\\w.^=]+)?=(.*)?");


    public static Map load(URL url) {

        String content = ObserveUtil.loadResourceContent(url);
        Map result = new TreeMap<>();
        String[] lines = content.split("\n");
        String currentKey = null;
        StringBuilder currentContent = new StringBuilder();
        for (String line : lines) {
            if (line.startsWith("#")) {
                continue;
            }
            if (line.trim().isEmpty()) {
                continue;
            }
            String value;
            Matcher matcher = PROPERTY_PATTERN.matcher(line);
            if (matcher.matches()) {
                // new property
                if (currentKey != null) {
                    // flush previous property
                    flush(currentKey, currentContent, result);
                }
                currentKey = matcher.group(1);
                value = matcher.group(2);
            } else {
                value = line;
            }
            if (value.trim().endsWith("\\")) {
                value = value.substring(0, value.lastIndexOf("\\"));
            }
            currentContent.append(value).append("\n");
        }
        if (currentKey != null) {
            // flush previous property
            flush(currentKey, currentContent, result);
        }

        return result;
    }


    private static void flush(String currentKey, StringBuilder currentContent, Map properties) {
        properties.put(currentKey, currentContent.toString().trim());
        currentContent.setLength(0);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy