001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.internal;
014
015import static org.apache.juneau.internal.CollectionUtils.*;
016import java.nio.charset.*;
017import java.util.*;
018import java.util.concurrent.*;
019import java.util.function.*;
020
021import org.apache.juneau.*;
022
023/**
024 * Utility methods for accessing system properties and environment variables.
025 *
026 * <h5 class='section'>See Also:</h5><ul>
027 * </ul>
028 */
029public class SystemEnv {
030
031   /**
032    * Looks up a system property or environment variable.
033    *
034    * <p>
035    * First looks in system properties.  Then converts the name to env-safe and looks in the system environment.
036    * Then returns the default if it can't be found.
037    *
038    * @param <T> The type to convert the value to.
039    * @param name The property name.
040    * @param def The default value if not found.
041    * @return The default value.
042    */
043   public static <T> T env(String name, T def) {
044      return env(name).map(x -> toType(x, def)).orElse(def);
045   }
046
047   /**
048    * Looks up a system property or environment variable.
049    *
050    * <p>
051    * First looks in system properties.  Then converts the name to env-safe and looks in the system environment.
052    * Then returns the default if it can't be found.
053    *
054    * @param name The property name.
055    * @return The value if found.
056    */
057   public static Optional<String> env(String name) {
058      String s = System.getProperty(name);
059      if (s == null)
060         s = System.getenv(envName(name));
061      return optional(s);
062   }
063
064   @SuppressWarnings({ "unchecked", "rawtypes" })
065   private static <T> T toType(String s, T def) {
066      if (s == null || def == null)
067         return null;
068      Class<T> c = (Class<T>)def.getClass();
069      if (c == String.class)
070         return (T)s;
071      if (c.isEnum())
072         return (T)Enum.valueOf((Class<? extends Enum>) c, s);
073      Function<String,T> f = (Function<String,T>)ENV_FUNCTIONS.get(c);
074      if (f == null)
075         throw new BasicRuntimeException("Invalid env type: {0}", c);
076      return f.apply(s);
077   }
078
079   private static final Map<Class<?>,Function<String,?>> ENV_FUNCTIONS = new IdentityHashMap<>();
080   static {
081      ENV_FUNCTIONS.put(Boolean.class, Boolean::valueOf);
082      ENV_FUNCTIONS.put(Charset.class, Charset::forName);
083   }
084
085   private static final ConcurrentHashMap<String,String> PROPERTY_TO_ENV = new ConcurrentHashMap<>();
086   private static String envName(String name) {
087      String name2 = PROPERTY_TO_ENV.get(name);
088      if (name2 == null) {
089         name2 = name.toUpperCase().replace(".", "_");
090         PROPERTY_TO_ENV.put(name, name2);
091      }
092      return name2;
093   }
094}