ConstantStringLookup.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.text.lookup;

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

  20. import org.apache.commons.lang3.ClassUtils;
  21. import org.apache.commons.text.StringSubstitutor;

  22. /**
  23.  * <p>
  24.  * Looks up the value of a fully-qualified static final value.
  25.  * </p>
  26.  * <p>
  27.  * Sometimes it is necessary in a configuration file to refer to a constant defined in a class. This can be done with
  28.  * this lookup implementation. Variable names must be in the format {@code apackage.AClass.AFIELD}. The
  29.  * {@code lookup(String)} method will split the passed in string at the last dot, separating the fully qualified class
  30.  * name and the name of the constant (i.e. <strong>static final</strong>) member field. Then the class is loaded and the field's
  31.  * value is obtained using 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.  * <p>
  38.  * Using a {@link StringLookup} from the {@link StringLookupFactory}:
  39.  * </p>
  40.  *
  41.  * <pre>
  42.  * StringLookupFactory.INSTANCE.constantStringLookup().lookup("java.awt.event.KeyEvent.VK_ESCAPE");
  43.  * </pre>
  44.  * <p>
  45.  * Using a {@link StringSubstitutor}:
  46.  * </p>
  47.  *
  48.  * <pre>
  49.  * StringSubstitutor.createInterpolator().replace("... ${const:java.awt.event.KeyEvent.VK_ESCAPE} ..."));
  50.  * </pre>
  51.  * <p>
  52.  * The above examples convert {@code java.awt.event.KeyEvent.VK_ESCAPE} to {@code "27"}.
  53.  * </p>
  54.  * <p>
  55.  * This class was adapted from Apache Commons Configuration.
  56.  * </p>
  57.  *
  58.  * @since 1.5
  59.  */
  60. class ConstantStringLookup extends AbstractStringLookup {

  61.     /** An internally used cache for already retrieved values. */
  62.     private static final ConcurrentHashMap<String, String> CONSTANT_CACHE = new ConcurrentHashMap<>();

  63.     /** Constant for the field separator. */
  64.     private static final char FIELD_SEPARATOR = '.';

  65.     /**
  66.      * Defines the singleton for this class.
  67.      */
  68.     static final ConstantStringLookup INSTANCE = new ConstantStringLookup();

  69.     /**
  70.      * Clears the shared cache with the so far resolved constants.
  71.      */
  72.     static void clear() {
  73.         CONSTANT_CACHE.clear();
  74.     }

  75.     /**
  76.      * Loads the class with the specified name. If an application has special needs regarding the class loaders to be
  77.      * used, it can hook in here. This implementation delegates to the {@code getClass()} method of Commons Lang's
  78.      * <code><a href="https://commons.apache.org/lang/api-release/org/apache/commons/lang/ClassUtils.html">
  79.      * ClassUtils</a></code>.
  80.      *
  81.      * @param className the name of the class to be loaded
  82.      * @return The corresponding class object
  83.      * @throws ClassNotFoundException if the class cannot be loaded
  84.      */
  85.     protected Class<?> fetchClass(final String className) throws ClassNotFoundException {
  86.         return ClassUtils.getClass(className);
  87.     }

  88.     /**
  89.      * Tries to resolve the specified variable. The passed in variable name is interpreted as the name of a <b>static
  90.      * final</b> member field of a class. If the value has already been obtained, it can be retrieved from an internal
  91.      * cache. Otherwise this method will invoke the {@code resolveField()} method and pass in the name of the class and
  92.      * the field.
  93.      *
  94.      * @param key the name of the variable to be resolved
  95.      * @return The value of this variable or <strong>null</strong> if it cannot be resolved
  96.      */
  97.     @Override
  98.     public synchronized String lookup(final String key) {
  99.         if (key == null) {
  100.             return null;
  101.         }
  102.         String result;
  103.         result = CONSTANT_CACHE.get(key);
  104.         if (result != null) {
  105.             return result;
  106.         }
  107.         final int fieldPos = key.lastIndexOf(FIELD_SEPARATOR);
  108.         if (fieldPos < 0) {
  109.             return null;
  110.         }
  111.         try {
  112.             final Object value = resolveField(key.substring(0, fieldPos), key.substring(fieldPos + 1));
  113.             if (value != null) {
  114.                 final String string = Objects.toString(value, null);
  115.                 CONSTANT_CACHE.put(key, string);
  116.                 result = string;
  117.             }
  118.         } catch (final Exception ex) {
  119.             // TODO it would be nice to log
  120.             return null;
  121.         }
  122.         return result;
  123.     }

  124.     /**
  125.      * Determines the value of the specified constant member field of a class. This implementation will call
  126.      * {@code fetchClass()} to obtain the {@link Class} object for the target class. Then it will use
  127.      * reflection to obtain the field's value. For this to work the field must be accessible.
  128.      *
  129.      * @param className the name of the class
  130.      * @param fieldName the name of the member field of that class to read
  131.      * @return The field's value
  132.      * @throws ReflectiveOperationException if an error occurs
  133.      */
  134.     protected Object resolveField(final String className, final String fieldName) throws ReflectiveOperationException {
  135.         final Class<?> clazz = fetchClass(className);
  136.         if (clazz == null) {
  137.             return null;
  138.         }
  139.         return clazz.getField(fieldName).get(null);
  140.     }
  141. }