001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.commons.settings;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.io.*;
023import java.nio.file.*;
024import java.util.*;
025import java.util.concurrent.atomic.*;
026
027/**
028 * Property source backed by a dotenv file.
029 */
030@SuppressWarnings({
031   "java:S3776" // load() reads the file line by line with nested blank/comment, key=value and quote-stripping checks
032})
033public class DotenvPropertySource implements PropertySource {
034
035   private static final String DEFAULT_PATH = ".env";
036   private static final String DOTENV_PATH_PROP = "juneau.dotenv.path";
037   private static final String DOTENV_PATH_ENV = "JUNEAU_DOTENV_PATH";
038
039   private final AtomicReference<Map<String,String>> map = new AtomicReference<>();
040   private final Path path;
041
042   /**
043    * Constructor with default path discovery.
044    */
045   public DotenvPropertySource() {
046      this(resolvePath());
047   }
048
049   /**
050    * Constructor.
051    *
052    * @param path Dotenv path.  Can be <jk>null</jk>, in which case no properties are loaded.
053    */
054   public DotenvPropertySource(Path path) {
055      this.path = path;
056   }
057
058   private static Path resolvePath() {
059      var configured = System.getProperty(DOTENV_PATH_PROP);
060      if (isEmpty(configured))
061         configured = System.getenv(DOTENV_PATH_ENV);
062      if (isEmpty(configured))
063         configured = DEFAULT_PATH;
064      return Paths.get(configured);
065   }
066
067   @Override
068   public PropertyLookupResult get(String name) {
069      var values = map.updateAndGet(existing -> existing != null ? existing : load(path));
070      var value = values.get(name);
071      return value == null ? PropertyLookupResult.missing() : PropertyLookupResult.present(o(value));
072   }
073
074   private static Map<String,String> load(Path path) {
075      if (path == null || ! Files.exists(path))
076         return Collections.emptyMap();
077      var m = new LinkedHashMap<String,String>();
078      try (var r = Files.newBufferedReader(path)) {
079         String line;
080         while ((line = r.readLine()) != null) {
081            line = line.trim();
082            if (! (line.isEmpty() || line.startsWith("#"))) {
083               var i = line.indexOf('=');
084               if (i > 0) {
085                  var key = line.substring(0, i).trim();
086                  var value = line.substring(i + 1).trim();
087                  if ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'")))
088                     value = value.substring(1, value.length() - 1);
089                  m.put(key, value);
090               }
091            }
092         }
093      } catch (@SuppressWarnings("unused") IOException unused) {
094         return Collections.emptyMap();
095      }
096      return m;
097   }
098}