ConstantLookup.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.configuration2.interpol;

  18. import java.util.Map;
  19. import java.util.concurrent.ConcurrentHashMap;

  20. import org.apache.commons.lang3.ClassUtils;
  21. import org.apache.commons.logging.Log;
  22. import org.apache.commons.logging.LogFactory;

  23. /**
  24.  * <p>
  25.  * Looks up constant fields in classes.
  26.  * </p>
  27.  * <p>
  28.  * Variable names passed in must be of the form {@code mypackage.MyClass.FIELD}. The {@code lookup()} method will split
  29.  * the passed in string at the last dot, separating the fully qualified class name and the name of the constant (i.e.
  30.  * <strong>static final</strong>) member field. Then the class is loaded and the field's value is obtained using
  31.  * reflection.
  32.  * </p>
  33.  * <p>
  34.  * Once retrieved values are cached for fast access. This class is thread-safe. It can be used as a standard (i.e.
  35.  * global) lookup object and serve multiple clients concurrently.
  36.  * </p>
  37.  *
  38.  * @since 1.4
  39.  */
  40. public class ConstantLookup implements Lookup {

  41.     /** Constant for the field separator. */
  42.     private static final char FIELD_SEPRATOR = '.';

  43.     /** Cache of field values. */
  44.     private static final Map<String, Object> CACHE = new ConcurrentHashMap<>();

  45.     /**
  46.      * Clears the shared cache with the so far resolved constants.
  47.      */
  48.     public static void clear() {
  49.         CACHE.clear();
  50.     }

  51.     /** The logger. */
  52.     private final Log log = LogFactory.getLog(getClass());

  53.     /**
  54.      * Loads the class with the specified name. If an application has special needs regarding the class loaders to be used,
  55.      * it can hook in here. This implementation delegates to the {@code getClass()} method of Commons Lang's
  56.      * <a href="https://commons.apache.org/lang/api-release/org/apache/commons/lang/ClassUtils.html">
  57.      * ClassUtils</a>.
  58.      *
  59.      * @param className the name of the class to be loaded
  60.      * @return the corresponding class object
  61.      * @throws ClassNotFoundException if the class cannot be loaded
  62.      */
  63.     protected Class<?> fetchClass(final String className) throws ClassNotFoundException {
  64.         return ClassUtils.getClass(className);
  65.     }

  66.     /**
  67.      * Looks up a variable. The passed in variable name is interpreted as the name of a <strong>static final</strong> member field of
  68.      * a class. If the value has already been obtained, it can be retrieved from an internal cache. Otherwise this method
  69.      * will invoke the {@code resolveField()} method and pass in the name of the class and the field.
  70.      *
  71.      * @param var the name of the variable to be resolved
  72.      * @return the value of this variable or <strong>null</strong> if it cannot be resolved
  73.      */
  74.     @Override
  75.     public Object lookup(final String var) {
  76.         if (var == null) {
  77.             return null;
  78.         }
  79.         return CACHE.computeIfAbsent(var, k -> {
  80.             final int fieldPos = var.lastIndexOf(FIELD_SEPRATOR);
  81.             if (fieldPos >= 0) {
  82.                 try {
  83.                     return resolveField(var.substring(0, fieldPos), var.substring(fieldPos + 1));
  84.                 } catch (final Exception ex) {
  85.                     log.warn("Could not obtain value for variable " + var, ex);
  86.                 }
  87.             }
  88.             return null;
  89.         });
  90.     }

  91.     /**
  92.      * Determines the value of the specified constant member field of a class. This implementation will call
  93.      * {@code fetchClass()} to obtain the {@link Class} object for the target class. Then it will use reflection
  94.      * to obtain the field's value. For this to work the field must be accessible.
  95.      *
  96.      * @param className the name of the class
  97.      * @param fieldName the name of the member field of that class to read
  98.      * @return the field's value
  99.      * @throws Exception if an error occurs
  100.      */
  101.     protected Object resolveField(final String className, final String fieldName) throws Exception {
  102.         return fetchClass(className).getField(fieldName).get(null);
  103.     }
  104. }