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.svl.vars;
018
019import java.nio.file.*;
020
021import org.apache.juneau.commons.settings.*;
022import org.apache.juneau.commons.svl.*;
023
024/**
025 * Environment-file variable resolver.
026 *
027 * <p>
028 * The format for this var is <js>"$EF{key[,default]}"</js>.
029 *
030 * <p>
031 * This variable is functionally identical to {@link DotenvVar}, but provides a
032 * generic env-file naming option for callers that do not want dotenv-specific naming.
033 */
034public class EnvFileVar extends DefaultingVar {
035
036   /** The name of this variable. */
037   public static final String NAME = "EF";
038
039   /**
040    * Creates an {@link EnvFileVar} bound to a specific env file path.
041    *
042    * @param path The env file path.  Can be <jk>null</jk>, in which case no properties are loaded.
043    * @return A new {@link EnvFileVar} instance.
044    */
045   public static EnvFileVar create(Path path) {
046      return new EnvFileVar(path);
047   }
048
049   private final DotenvPropertySource source;
050
051   /**
052    * Constructor.
053    */
054   public EnvFileVar() {
055      super(NAME);
056      this.source = new DotenvPropertySource();
057   }
058
059   private EnvFileVar(Path path) {
060      super(NAME);
061      this.source = new DotenvPropertySource(path);
062   }
063
064   @Override /* Overridden from Var */
065   public String resolve(VarResolverSession session, String key) {
066      var result = source.get(key);
067      return result.isPresent() ? result.value().orElse(null) : null;
068   }
069}