View Javadoc
1   /*-
2    * #%L
3    * Secured Properties
4    * ===============================================================
5    * Copyright (C) 2016 - 2019 Brabenetz Harald, Austria
6    * ===============================================================
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package net.brabenetz.lib.securedproperties.config;
21  
22  import net.brabenetz.lib.securedproperties.utils.SecuredPropertiesUtils;
23  import org.apache.commons.lang3.Validate;
24  
25  import java.io.File;
26  import java.util.Properties;
27  
28  /**
29   * {@link ConfigInitializer} implementation to read from {@link Properties} Files.
30   * <p>
31   * The property-Prefix is "secured-properties".<br>
32   * The Keys must be kebab-case like 'secured-properties.secret-file'.
33   */
34  public class ConfigByPropertyFile extends AbstractConfigInitializer {
35  
36      private final Properties properties;
37  
38      public ConfigByPropertyFile(final File propertyFile) {
39          this(ConfigKey.DEFAULT_PREFIX_KEBAB_CASE, propertyFile);
40      }
41  
42      /**
43       * @param configKeyPrefix an optional key prefix (default is 'secured-properties').
44       * @param propertyFile    required, but the {@link Properties} File itself is the optional.<br>
45       *                        If the File doesn't exist an empty Properties Object will be used to prevent errors.
46       */
47      public ConfigByPropertyFile(final String configKeyPrefix, final File propertyFile) {
48          super(configKeyPrefix, ConfigKey::getKebabCase, (final ConfigKey key) -> configKeyPrefix + "." + key.getKebabCase());
49          Validate.notNull(propertyFile, "The Propety-File is required");
50          if (propertyFile.exists()) {
51              properties = SecuredPropertiesUtils.readProperties(propertyFile);
52          } else {
53              properties = new Properties();
54          }
55      }
56  
57      @Override
58      protected String getValue(final ConfigKey key) {
59          return properties.getProperty(getKeyFactory().apply(key));
60      }
61  
62  }