View Javadoc
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    *     https://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.builder;
18  
19  import java.util.Collection;
20  import java.util.concurrent.CopyOnWriteArrayList;
21  
22  /**
23   * <p>
24   * A class for managing a set of {@link DefaultParametersHandler} objects.
25   * </p>
26   * <p>
27   * This class provides functionality for registering and removing {@code DefaultParametersHandler} objects for arbitrary
28   * parameters classes. The handlers registered at an instance can then be applied on a passed in parameters object, so
29   * that it gets initialized with the provided default values.
30   * </p>
31   * <p>
32   * Usage of this class is as follows: First the {@code DefaultParametersHandler} objects to be supported must be
33   * registered using one of the {@code registerDefaultHandler()} methods. After that arbitrary parameters objects can be
34   * passed to the {@code initializeParameters()} method. This causes all {@code DefaultParametersHandler} objects
35   * supporting this parameters class to be invoked on this object.
36   * </p>
37   * <p>
38   * Implementation note: This class is thread-safe.
39   * </p>
40   *
41   * @since 2.0
42   */
43  public class DefaultParametersManager {
44  
45      /**
46       * A data class storing information about {@code DefaultParametersHandler} objects added to a {@code Parameters} object.
47       * Using this class it is possible to find out which default handlers apply for a given parameters object and to invoke
48       * them.
49       */
50      private static final class DefaultHandlerData {
51  
52          /** The handler object. */
53          private final DefaultParametersHandler<?> handler;
54  
55          /** The class supported by this handler. */
56          private final Class<?> parameterClass;
57  
58          /** The start class for applying this handler. */
59          private final Class<?> startClass;
60  
61          /**
62           * Creates a new instance of {@code DefaultHandlerData}.
63           *
64           * @param h the {@code DefaultParametersHandler}
65           * @param cls the handler's data class
66           * @param startCls the start class
67           */
68          public DefaultHandlerData(final DefaultParametersHandler<?> h, final Class<?> cls, final Class<?> startCls) {
69              handler = h;
70              parameterClass = cls;
71              startClass = startCls;
72          }
73  
74          /**
75           * Checks whether the managed {@code DefaultParametersHandler} can be applied to the given parameters object. If this is
76           * the case, it is executed on this object and can initialize it with default values.
77           *
78           * @param obj the parameters object to be initialized
79           */
80          @SuppressWarnings("unchecked")
81          // There are explicit isInstance() checks, so there won't be
82          // ClassCastExceptions
83          public void applyHandlerIfMatching(final BuilderParameters obj) {
84              if (parameterClass.isInstance(obj) && (startClass == null || startClass.isInstance(obj))) {
85                  @SuppressWarnings("rawtypes")
86                  final DefaultParametersHandler handlerUntyped = handler;
87                  handlerUntyped.initializeDefaults(obj);
88              }
89          }
90  
91          /**
92           * Tests whether this instance refers to the specified occurrence of a {@code DefaultParametersHandler}.
93           *
94           * @param h the handler to be checked
95           * @param startCls the start class
96           * @return <strong>true</strong> if this instance refers to this occurrence, <strong>false</strong> otherwise
97           */
98          public boolean isOccurrence(final DefaultParametersHandler<?> h, final Class<?> startCls) {
99              return h == handler && (startCls == null || startCls.equals(startClass));
100         }
101     }
102 
103     /** A collection with the registered default handlers. */
104     private final Collection<DefaultHandlerData> defaultHandlers;
105 
106     /**
107      * Creates a new instance of {@code DefaultParametersManager}.
108      */
109     public DefaultParametersManager() {
110         defaultHandlers = new CopyOnWriteArrayList<>();
111     }
112 
113     /**
114      * Initializes the passed in {@code BuilderParameters} object by applying all matching {@link DefaultParametersHandler}
115      * objects registered at this instance. Using this method the passed in parameters object can be populated with default
116      * values.
117      *
118      * @param params the parameters object to be initialized (may be <strong>null</strong>, then this method has no effect)
119      */
120     public void initializeParameters(final BuilderParameters params) {
121         if (params != null) {
122             defaultHandlers.forEach(dhd -> dhd.applyHandlerIfMatching(params));
123         }
124     }
125 
126     /**
127      * Registers the specified {@code DefaultParametersHandler} object for the given parameters class. This means that this
128      * handler object is invoked every time a parameters object of the specified class or one of its subclasses is
129      * initialized. The handler can set arbitrary default values for the properties supported by this parameters object. If
130      * there are multiple handlers registered supporting a specific parameters class, they are invoked in the order in which
131      * they were registered. So handlers registered later may override the values set by handlers registered earlier.
132      *
133      * @param <T> the type of the parameters supported by this handler
134      * @param paramsClass the parameters class supported by this handler (must not be <strong>null</strong>)
135      * @param handler the {@code DefaultParametersHandler} to be registered (must not be <strong>null</strong>)
136      * @throws IllegalArgumentException if a required parameter is missing
137      */
138     public <T> void registerDefaultsHandler(final Class<T> paramsClass, final DefaultParametersHandler<? super T> handler) {
139         registerDefaultsHandler(paramsClass, handler, null);
140     }
141 
142     /**
143      * Registers the specified {@code DefaultParametersHandler} object for the given parameters class and start class in the
144      * inheritance hierarchy. This method works like {@link #registerDefaultsHandler(Class, DefaultParametersHandler)}, but
145      * the defaults handler is only executed on parameter objects that are instances of the specified start class. Parameter
146      * classes do not stand in a real inheritance hierarchy; however, there is a logic hierarchy defined by the methods
147      * supported by the different parameter objects. A properties parameter object for instance supports all methods defined
148      * for a file-based parameter object. So one can argue that
149      * {@link org.apache.commons.configuration2.builder.fluent.FileBasedBuilderParameters FileBasedBuilderParameters} is a
150      * base interface of {@link org.apache.commons.configuration2.builder.fluent.PropertiesBuilderParameters
151      * PropertiesBuilderParameters} (although, for technical reasons, this relation is not reflected in the Java classes). A
152      * {@link DefaultParametersHandler} object defined for a base interface can also deal with parameter objects "derived"
153      * from this base interface (i.e. supporting a super set of the methods defined by the base interface). Now there may be
154      * the use case that there is an implementation of {@code DefaultParametersHandler} for a base interface (for example
155      * {@code FileBasedBuilderParameters}), but it should only process specific derived interfaces (say
156      * {@code PropertiesBuilderParameters}, but not
157      * {@link org.apache.commons.configuration2.builder.fluent.XMLBuilderParameters XMLBuilderParameters}). This can be
158      * achieved by passing in {@code PropertiesBuilderParameters} as start class. In this case,
159      * {@code DefaultParametersManager} ensures that the handler is only called on parameter objects having both the start
160      * class and the actual type supported by the handler as base interfaces. The passed in start class can be <strong>null</strong>;
161      * then the parameter class supported by the handler is used (which is the default behavior of the
162      * {@link #registerDefaultsHandler(Class, DefaultParametersHandler)} method).
163      *
164      * @param <T> the type of the parameters supported by this handler
165      * @param paramsClass the parameters class supported by this handler (must not be <strong>null</strong>)
166      * @param handler the {@code DefaultParametersHandler} to be registered (must not be <strong>null</strong>)
167      * @param startClass an optional start class in the hierarchy of parameter objects for which this handler should be
168      *        applied
169      * @throws IllegalArgumentException if a required parameter is missing
170      */
171     public <T> void registerDefaultsHandler(final Class<T> paramsClass, final DefaultParametersHandler<? super T> handler, final Class<?> startClass) {
172         if (paramsClass == null) {
173             throw new IllegalArgumentException("Parameters class must not be null.");
174         }
175         if (handler == null) {
176             throw new IllegalArgumentException("DefaultParametersHandler must not be null.");
177         }
178         defaultHandlers.add(new DefaultHandlerData(handler, paramsClass, startClass));
179     }
180 
181     /**
182      * Removes the specified {@code DefaultParametersHandler} from this instance. If this handler has been registered
183      * multiple times for different start classes, all occurrences are removed.
184      *
185      * @param handler the {@code DefaultParametersHandler} to be removed
186      */
187     public void unregisterDefaultsHandler(final DefaultParametersHandler<?> handler) {
188         unregisterDefaultsHandler(handler, null);
189     }
190 
191     /**
192      * Removes the specified {@code DefaultParametersHandler} from this instance if it is in combination with the given
193      * start class. If this handler has been registered multiple times for different start classes, only occurrences for the
194      * given start class are removed. The {@code startClass} parameter can be <strong>null</strong>, then all occurrences of the
195      * handler are removed.
196      *
197      * @param handler the {@code DefaultParametersHandler} to be removed
198      * @param startClass the start class for which this handler is to be removed
199      */
200     public void unregisterDefaultsHandler(final DefaultParametersHandler<?> handler, final Class<?> startClass) {
201         defaultHandlers.removeIf(dhd -> dhd.isOccurrence(handler, startClass));
202     }
203 }