001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2024, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014
015package ch.qos.logback.core.model.util;
016
017import ch.qos.logback.core.Context;
018import ch.qos.logback.core.spi.ContextAwareBase;
019import ch.qos.logback.core.spi.ContextAwarePropertyContainer;
020import ch.qos.logback.core.spi.ScanException;
021import ch.qos.logback.core.util.OptionHelper;
022
023import java.util.HashMap;
024import java.util.Map;
025
026/**
027 * Helper methods to deal with properties.
028 *
029 * @since 1.5.1
030 */
031public class VariableSubstitutionsHelper extends ContextAwareBase implements ContextAwarePropertyContainer {
032
033    protected Map<String, String> propertiesMap;
034
035    public VariableSubstitutionsHelper(Context context) {
036        this.setContext(context);
037        this.propertiesMap = new HashMap<>();
038    }
039
040    public VariableSubstitutionsHelper(Context context, Map<String, String> otherMap) {
041        this.setContext(context);
042        this.propertiesMap = new HashMap<>(otherMap);
043    }
044
045    @Override
046    public String subst(String ref) {
047        if (ref == null) {
048            return null;
049        }
050
051        try {
052            return OptionHelper.substVars(ref, this, context);
053        } catch (ScanException | IllegalArgumentException e) {
054            addError("Problem while parsing [" + ref + "]", e);
055            return ref;
056        }
057
058    }
059
060    /**
061     * Add a property to the properties of this execution context. If the property
062     * exists already, it is overwritten.
063     */
064    @Override
065    public void addSubstitutionProperty(String key, String value) {
066        if (key == null || value == null) {
067            return;
068        }
069        // values with leading or trailing spaces are bad. We remove them now.
070        value = value.trim();
071        propertiesMap.put(key, value);
072    }
073
074    @Override
075    public String getProperty(String key) {
076        return propertiesMap.get(key);
077    }
078
079    @Override
080    public Map<String, String> getCopyOfPropertyMap() {
081        return new HashMap<String, String>(propertiesMap);
082    }
083}