View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2024, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  
15  package ch.qos.logback.core.model.util;
16  
17  import ch.qos.logback.core.Context;
18  import ch.qos.logback.core.spi.ContextAwareBase;
19  import ch.qos.logback.core.spi.ContextAwarePropertyContainer;
20  import ch.qos.logback.core.spi.ScanException;
21  import ch.qos.logback.core.util.OptionHelper;
22  
23  import java.util.HashMap;
24  import java.util.Map;
25  
26  /**
27   * Helper methods to deal with properties.
28   *
29   * @since 1.5.1
30   */
31  public class VariableSubstitutionsHelper extends ContextAwareBase implements ContextAwarePropertyContainer {
32  
33      protected Map<String, String> propertiesMap;
34  
35      public VariableSubstitutionsHelper(Context context) {
36          this.setContext(context);
37          this.propertiesMap = new HashMap<>();
38      }
39  
40      public VariableSubstitutionsHelper(Context context, Map<String, String> otherMap) {
41          this.setContext(context);
42          this.propertiesMap = new HashMap<>(otherMap);
43      }
44  
45      @Override
46      public String subst(String ref) {
47          if (ref == null) {
48              return null;
49          }
50  
51          try {
52              return OptionHelper.substVars(ref, this, context);
53          } catch (ScanException | IllegalArgumentException e) {
54              addError("Problem while parsing [" + ref + "]", e);
55              return ref;
56          }
57  
58      }
59  
60      /**
61       * Add a property to the properties of this execution context. If the property
62       * exists already, it is overwritten.
63       */
64      @Override
65      public void addSubstitutionProperty(String key, String value) {
66          if (key == null || value == null) {
67              return;
68          }
69          // values with leading or trailing spaces are bad. We remove them now.
70          value = value.trim();
71          propertiesMap.put(key, value);
72      }
73  
74      @Override
75      public String getProperty(String key) {
76          return propertiesMap.get(key);
77      }
78  
79      @Override
80      public Map<String, String> getCopyOfPropertyMap() {
81          return new HashMap<String, String>(propertiesMap);
82      }
83  }