    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.commons.configuration2.interpol;
    018
    019import java.util.Map;
    020import java.util.concurrent.ConcurrentHashMap;
    021
    022import org.apache.commons.lang3.ClassUtils;
    023import org.apache.commons.logging.Log;
    024import org.apache.commons.logging.LogFactory;
    025
    026/**
    027 * <p>
    028 * Looks up constant fields in classes.
    029 * </p>
    030 * <p>
    031 * Variable names passed in must be of the form {@code mypackage.MyClass.FIELD}. The {@code lookup()} method will split
    032 * the passed in string at the last dot, separating the fully qualified class name and the name of the constant (i.e.
    033 * <strong>static final</strong>) member field. Then the class is loaded and the field's value is obtained using
    034 * reflection.
    035 * </p>
    036 * <p>
    037 * Once retrieved values are cached for fast access. This class is thread-safe. It can be used as a standard (i.e.
    038 * global) lookup object and serve multiple clients concurrently.
    039 * </p>
    040 *
    041 * @since 1.4
    042 */
    043public class ConstantLookup implements Lookup {
    044
    045    /** Constant for the field separator. */
    046    private static final char FIELD_SEPRATOR = '.';
    047
    048    /** Cache of field values. */
    049    private static final Map<String, Object> CACHE = new ConcurrentHashMap<>();
    050
    051    /**
    052     * Clears the shared cache with the so far resolved constants.
    053     */
    054    public static void clear() {
    055        CACHE.clear();
    056    }
    057
    058    /** The logger. */
    059    private final Log log = LogFactory.getLog(getClass());
    060
    061    /**
    062     * Loads the class with the specified name. If an application has special needs regarding the class loaders to be used,
    063     * it can hook in here. This implementation delegates to the {@code getClass()} method of Commons Lang's
    064     * <code><a href="https://commons.apache.org/lang/api-release/org/apache/commons/lang/ClassUtils.html">
    065     * ClassUtils</a></code>.
    066     *
    067     * @param className the name of the class to be loaded
    068     * @return the corresponding class object
    069     * @throws ClassNotFoundException if the class cannot be loaded
    070     */
    071    protected Class<?> fetchClass(final String className) throws ClassNotFoundException {
    072        return ClassUtils.getClass(className);
    073    }
    074
    075    /**
    076     * Looks up a variable. The passed in variable name is interpreted as the name of a <b>static final</b> member field of
    077     * a class. If the value has already been obtained, it can be retrieved from an internal cache. Otherwise this method
    078     * will invoke the {@code resolveField()} method and pass in the name of the class and the field.
    079     *
    080     * @param var the name of the variable to be resolved
    081     * @return the value of this variable or <b>null</b> if it cannot be resolved
    082     */
    083    @Override
    084    public Object lookup(final String var) {
    085        if (var == null) {
    086            return null;
    087        }
    088        return CACHE.computeIfAbsent(var, k -> {
    089            final int fieldPos = var.lastIndexOf(FIELD_SEPRATOR);
    090            if (fieldPos >= 0) {
    091                try {
    092                    return resolveField(var.substring(0, fieldPos), var.substring(fieldPos + 1));
    093                } catch (final Exception ex) {
    094                    log.warn("Could not obtain value for variable " + var, ex);
    095                }
    096            }
    097            return null;
    098        });
    099    }
    100
    101    /**
    102     * Determines the value of the specified constant member field of a class. This implementation will call
    103     * {@code fetchClass()} to obtain the {@link Class} object for the target class. Then it will use reflection
    104     * to obtain the field's value. For this to work the field must be accessible.
    105     *
    106     * @param className the name of the class
    107     * @param fieldName the name of the member field of that class to read
    108     * @return the field's value
    109     * @throws Exception if an error occurs
    110     */
    111    protected Object resolveField(final String className, final String fieldName) throws Exception {
    112        return fetchClass(className).getField(fieldName).get(null);
    113    }
    114}