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    *      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.collections;
18  
19  import java.util.Collection;
20  import java.util.Map;
21  
22  import org.apache.commons.collections.functors.ChainedTransformer;
23  import org.apache.commons.collections.functors.CloneTransformer;
24  import org.apache.commons.collections.functors.ClosureTransformer;
25  import org.apache.commons.collections.functors.ConstantTransformer;
26  import org.apache.commons.collections.functors.EqualPredicate;
27  import org.apache.commons.collections.functors.ExceptionTransformer;
28  import org.apache.commons.collections.functors.FactoryTransformer;
29  import org.apache.commons.collections.functors.InstantiateTransformer;
30  import org.apache.commons.collections.functors.InvokerTransformer;
31  import org.apache.commons.collections.functors.MapTransformer;
32  import org.apache.commons.collections.functors.NOPTransformer;
33  import org.apache.commons.collections.functors.PredicateTransformer;
34  import org.apache.commons.collections.functors.StringValueTransformer;
35  import org.apache.commons.collections.functors.SwitchTransformer;
36  
37  /**
38   * <code>TransformerUtils</code> provides reference implementations and 
39   * utilities for the Transformer functor interface. The supplied transformers are:
40   * <ul>
41   * <li>Invoker - returns the result of a method call on the input object
42   * <li>Clone - returns a clone of the input object
43   * <li>Constant - always returns the same object
44   * <li>Closure - performs a Closure and returns the input object
45   * <li>Predicate - returns the result of the predicate as a Boolean
46   * <li>Factory - returns a new object from a factory
47   * <li>Chained - chains two or more transformers together
48   * <li>Switch - calls one transformer based on one or more predicates
49   * <li>SwitchMap - calls one transformer looked up from a Map
50   * <li>Instantiate - the Class input object is instantiated
51   * <li>Map - returns an object from a supplied Map
52   * <li>Null - always returns null
53   * <li>NOP - returns the input object, which should be immutable
54   * <li>Exception - always throws an exception
55   * <li>StringValue - returns a <code>java.lang.String</code> representation of the input object
56   * </ul>
57   * All the supplied transformers are Serializable.
58   *
59   * @since 3.0
60   * @version $Id: TransformerUtils.java 1443602 2013-02-07 17:00:23Z tn $
61   */
62  public class TransformerUtils {
63  
64      /**
65       * This class is not normally instantiated.
66       */
67      public TransformerUtils() {
68          super();
69      }
70  
71      /**
72       * Gets a transformer that always throws an exception.
73       * This could be useful during testing as a placeholder.
74       * 
75       * @param <I>  the input type
76       * @param <O>  the output type
77       * @return the transformer
78       * @see org.apache.commons.collections.functors.ExceptionTransformer
79       */
80      public static <I, O> Transformer<I, O> exceptionTransformer() {
81          return ExceptionTransformer.<I, O>exceptionTransformer();
82      }
83  
84      /**
85       * Gets a transformer that always returns null.
86       * 
87       * @param <I>  the input type
88       * @param <O>  the output type
89       * @return the transformer
90       * @see org.apache.commons.collections.functors.ConstantTransformer
91       */
92      public static <I, O> Transformer<I, O> nullTransformer() {
93          return ConstantTransformer.<I, O>nullTransformer();
94      }
95  
96      /**
97       * Gets a transformer that returns the input object.
98       * The input object should be immutable to maintain the
99       * contract of Transformer (although this is not checked).
100      * 
101      * @param <T>  the input/output type
102      * @return the transformer
103      * @see org.apache.commons.collections.functors.NOPTransformer
104      */
105     public static <T> Transformer<T, T> nopTransformer() {
106         return NOPTransformer.<T>nopTransformer();
107     }
108 
109     /**
110      * Gets a transformer that returns a clone of the input
111      * object. The input object will be cloned using one of these
112      * techniques (in order):
113      * <ul>
114      * <li>public clone method
115      * <li>public copy constructor
116      * <li>serialization clone
117      * <ul>
118      * 
119      * @param <T>  the input/output type
120      * @return the transformer
121      * @see org.apache.commons.collections.functors.CloneTransformer
122      */
123     public static <T> Transformer<T, T> cloneTransformer() {
124         return CloneTransformer.<T>cloneTransformer();
125     }
126 
127     /**
128      * Creates a Transformer that will return the same object each time the 
129      * transformer is used.
130      *
131      * @param <I>  the input type
132      * @param <O>  the output type
133      * @param constantToReturn  the constant object to return each time in the transformer
134      * @return the transformer.
135      * @see org.apache.commons.collections.functors.ConstantTransformer
136      */
137     public static <I, O> Transformer<I, O> constantTransformer(final O constantToReturn) {
138         return ConstantTransformer.constantTransformer(constantToReturn);
139     }
140 
141     /**
142      * Creates a Transformer that calls a Closure each time the transformer is used.
143      * The transformer returns the input object.
144      *
145      * @param <T>  the input/output type
146      * @param closure  the closure to run each time in the transformer, not null
147      * @return the transformer
148      * @throws IllegalArgumentException if the closure is null
149      * @see org.apache.commons.collections.functors.ClosureTransformer
150      */
151     public static <T> Transformer<T, T> asTransformer(final Closure<? super T> closure) {
152         return ClosureTransformer.closureTransformer(closure);
153     }
154 
155     /**
156      * Creates a Transformer that calls a Predicate each time the transformer is used.
157      * The transformer will return either Boolean.TRUE or Boolean.FALSE.
158      *
159      * @param <T>  the input type
160      * @param predicate  the predicate to run each time in the transformer, not null
161      * @return the transformer
162      * @throws IllegalArgumentException if the predicate is null
163      * @see org.apache.commons.collections.functors.PredicateTransformer
164      */
165     public static <T> Transformer<T, Boolean> asTransformer(final Predicate<? super T> predicate) {
166         return PredicateTransformer.predicateTransformer(predicate);
167     }
168 
169     /**
170      * Creates a Transformer that calls a Factory each time the transformer is used.
171      * The transformer will return the value returned by the factory.
172      *
173      * @param <I>  the input type
174      * @param <O>  the output type
175      * @param factory  the factory to run each time in the transformer, not null
176      * @return the transformer
177      * @throws IllegalArgumentException if the factory is null
178      * @see org.apache.commons.collections.functors.FactoryTransformer
179      */
180     public static <I, O> Transformer<I, O> asTransformer(final Factory<? extends O> factory) {
181         return FactoryTransformer.factoryTransformer(factory);
182     }
183 
184     /**
185      * Create a new Transformer that calls two transformers, passing the result of
186      * the first into the second.
187      * 
188      * @param <T>  the input/output type
189      * @param transformer1  the first transformer
190      * @param transformer2  the second transformer
191      * @return the transformer
192      * @throws IllegalArgumentException if either transformer is null
193      * @see org.apache.commons.collections.functors.ChainedTransformer
194      */
195     @SuppressWarnings("unchecked")
196     public static <T> Transformer<T, T> chainedTransformer(
197             final Transformer<? super T, ? extends T> transformer1,
198             final Transformer<? super T, ? extends T> transformer2) {
199         return ChainedTransformer.<T> chainedTransformer(transformer1, transformer2);
200     }
201 
202     /**
203      * Create a new Transformer that calls each transformer in turn, passing the 
204      * result into the next transformer.
205      * 
206      * @param <T>  the input/output type
207      * @param transformers  an array of transformers to chain
208      * @return the transformer
209      * @throws IllegalArgumentException if the transformers array or any of the transformers is null
210      * @see org.apache.commons.collections.functors.ChainedTransformer
211      */
212     public static <T> Transformer<T, T> chainedTransformer(final Transformer<? super T, ? extends T>[] transformers) {
213         return ChainedTransformer.chainedTransformer(transformers);
214     }
215 
216     /**
217      * Create a new Transformer that calls each transformer in turn, passing the 
218      * result into the next transformer. The ordering is that of the iterator()
219      * method on the collection.
220      * 
221      * @param <T>  the input/output type
222      * @param transformers  a collection of transformers to chain
223      * @return the transformer
224      * @throws IllegalArgumentException if the transformers collection or any of the transformers is null
225      * @see org.apache.commons.collections.functors.ChainedTransformer
226      */
227     public static <T> Transformer<T, T> chainedTransformer(
228             final Collection<? extends Transformer<T, T>> transformers) {
229         return ChainedTransformer.chainedTransformer(transformers);
230     }
231 
232     /**
233      * Create a new Transformer that calls one of two transformers depending 
234      * on the specified predicate.
235      * 
236      * @param <I>  the input type
237      * @param <O>  the output type
238      * @param predicate  the predicate to switch on
239      * @param trueTransformer  the transformer called if the predicate is true
240      * @param falseTransformer  the transformer called if the predicate is false
241      * @return the transformer
242      * @throws IllegalArgumentException if either the predicate or transformer is null
243      * @see org.apache.commons.collections.functors.SwitchTransformer
244      */
245     @SuppressWarnings("unchecked")
246     public static <I, O> Transformer<I, O> switchTransformer(final Predicate<? super I> predicate,
247             final Transformer<? super I, ? extends O> trueTransformer,
248             final Transformer<? super I, ? extends O> falseTransformer) {
249         return SwitchTransformer.switchTransformer(new Predicate[] { predicate },
250                                                    new Transformer[] { trueTransformer }, falseTransformer);
251     }
252 
253     /**
254      * Create a new Transformer that calls one of the transformers depending 
255      * on the predicates. The transformer at array location 0 is called if the
256      * predicate at array location 0 returned true. Each predicate is evaluated
257      * until one returns true. If no predicates evaluate to true, null is returned.
258      * 
259      * @param <I>  the input type
260      * @param <O>  the output type
261      * @param predicates  an array of predicates to check
262      * @param transformers  an array of transformers to call
263      * @return the transformer
264      * @throws IllegalArgumentException if the either array is null or empty
265      * @throws IllegalArgumentException if any element in the arrays is null
266      * @throws IllegalArgumentException if the arrays are different sizes
267      * @see org.apache.commons.collections.functors.SwitchTransformer
268      */
269     public static <I, O> Transformer<I, O> switchTransformer(final Predicate<? super I>[] predicates,
270             final Transformer<? super I, ? extends O>[] transformers) {
271         return SwitchTransformer.<I, O>switchTransformer(predicates, transformers, null);
272     }
273 
274     /**
275      * Create a new Transformer that calls one of the transformers depending 
276      * on the predicates. The transformer at array location 0 is called if the
277      * predicate at array location 0 returned true. Each predicate is evaluated
278      * until one returns true. If no predicates evaluate to true, the default
279      * transformer is called. If the default transformer is null, null is returned.
280      * 
281      * @param <I>  the input type
282      * @param <O>  the output type
283      * @param predicates  an array of predicates to check
284      * @param transformers  an array of transformers to call
285      * @param defaultTransformer  the default to call if no predicate matches, null means return null
286      * @return the transformer
287      * @throws IllegalArgumentException if the either array is null or empty
288      * @throws IllegalArgumentException if any element in the arrays is null
289      * @throws IllegalArgumentException if the arrays are different sizes
290      * @see org.apache.commons.collections.functors.SwitchTransformer
291      */
292     public static <I, O> Transformer<I, O> switchTransformer(final Predicate<? super I>[] predicates,
293             final Transformer<? super I, ? extends O>[] transformers,
294             final Transformer<? super I, ? extends O> defaultTransformer) {
295         return SwitchTransformer.<I, O>switchTransformer(predicates, transformers, defaultTransformer);
296     }
297 
298     /**
299      * Create a new Transformer that calls one of the transformers depending 
300      * on the predicates. 
301      * <p>
302      * The Map consists of Predicate keys and Transformer values. A transformer 
303      * is called if its matching predicate returns true. Each predicate is evaluated
304      * until one returns true. If no predicates evaluate to true, the default
305      * transformer is called. The default transformer is set in the map with a 
306      * null key. If no default transformer is set, null will be returned in a default
307      * case. The ordering is that of the iterator() method on the entryset collection 
308      * of the map.
309      * 
310      * @param <I>  the input type
311      * @param <O>  the output type
312      * @param predicatesAndTransformers  a map of predicates to transformers
313      * @return the transformer
314      * @throws IllegalArgumentException if the map is null or empty
315      * @throws IllegalArgumentException if any transformer in the map is null
316      * @throws ClassCastException  if the map elements are of the wrong type
317      * @see org.apache.commons.collections.functors.SwitchTransformer
318      */
319     public static <I, O> Transformer<I, O> switchTransformer(
320             final Map<Predicate<I>, Transformer<I, O>> predicatesAndTransformers) {
321         return SwitchTransformer.<I, O>switchTransformer(predicatesAndTransformers);
322     }
323 
324     /**
325      * Create a new Transformer that uses the input object as a key to find the
326      * transformer to call. 
327      * <p>
328      * The Map consists of object keys and Transformer values. A transformer 
329      * is called if the input object equals the key. If there is no match, the
330      * default transformer is called. The default transformer is set in the map
331      * using a null key. If no default is set, null will be returned in a default case.
332      * 
333      * @param <I>  the input type
334      * @param <O>  the output type
335      * @param objectsAndTransformers  a map of objects to transformers
336      * @return the transformer
337      * @throws IllegalArgumentException if the map is null or empty
338      * @throws IllegalArgumentException if any transformer in the map is null
339      * @see org.apache.commons.collections.functors.SwitchTransformer
340      */
341     @SuppressWarnings("unchecked")
342     public static <I, O> Transformer<I, O> switchMapTransformer(
343             final Map<I, Transformer<I, O>> objectsAndTransformers) {
344 
345         if (objectsAndTransformers == null) {
346             throw new IllegalArgumentException("The object and transformer map must not be null");
347         }
348         final Transformer<? super I, ? extends O> def = objectsAndTransformers.remove(null);
349         final int size = objectsAndTransformers.size();
350         final Transformer<? super I, ? extends O>[] trs = new Transformer[size];
351         final Predicate<I>[] preds = new Predicate[size];
352         int i = 0;
353         for (final Map.Entry<I, Transformer<I, O>> entry : objectsAndTransformers.entrySet()) {
354             preds[i] = EqualPredicate.<I>equalPredicate(entry.getKey());
355             trs[i++] = entry.getValue();
356         }
357         return TransformerUtils.<I, O>switchTransformer(preds, trs, def);
358     }
359 
360     /**
361      * Gets a Transformer that expects an input Class object that it will instantiate.
362      * 
363      * @param <T>  the output type
364      * @return the transformer
365      * @see org.apache.commons.collections.functors.InstantiateTransformer
366      */
367     public static <T> Transformer<Class<? extends T>, T> instantiateTransformer() {
368         return InstantiateTransformer.<T>instantiateTransformer();
369     }
370 
371     /** 
372      * Creates a Transformer that expects an input Class object that it will 
373      * instantiate. The constructor used is determined by the arguments specified
374      * to this method.
375      *
376      * @param <T>  the output type
377      * @param paramTypes  parameter types for the constructor, can be null
378      * @param args  the arguments to pass to the constructor, can be null
379      * @return the transformer
380      * @throws IllegalArgumentException if the paramTypes and args don't match
381      * @see org.apache.commons.collections.functors.InstantiateTransformer
382      */
383     public static <T> Transformer<Class<? extends T>, T> instantiateTransformer(
384             final Class<?>[] paramTypes, final Object[] args) {
385         return InstantiateTransformer.<T>instantiateTransformer(paramTypes, args);
386     }
387 
388     /** 
389      * Creates a Transformer that uses the passed in Map to transform the input 
390      * object (as a simple lookup).
391      *
392      * @param <I>  the input type
393      * @param <O>  the output type
394      * @param map  the map to use to transform the objects
395      * @return the transformer, or a {@link ConstantTransformer#NULL_INSTANCE} if the {@code map} is {@code null}
396      * @see org.apache.commons.collections.functors.MapTransformer
397      */
398     public static <I, O> Transformer<I, O> mapTransformer(final Map<? super I, ? extends O> map) {
399         return MapTransformer.mapTransformer(map);
400     }
401 
402     /**
403      * Gets a Transformer that invokes a method on the input object.
404      * The method must have no parameters. If the input object is null, 
405      * null is returned.
406      * <p>
407      * For example, <code>TransformerUtils.invokerTransformer("getName");</code>
408      * will call the <code>getName/code> method on the input object to 
409      * determine the transformer result.
410      * 
411      * @param <I>  the input type
412      * @param <O>  the output type
413      * @param methodName  the method name to call on the input object, may not be null
414      * @return the transformer
415      * @throws IllegalArgumentException if the methodName is null.
416      * @see org.apache.commons.collections.functors.InvokerTransformer
417      */
418     public static <I, O> Transformer<I, O> invokerTransformer(final String methodName) {
419         return InvokerTransformer.<I, O>invokerTransformer(methodName, null, null);
420     }
421 
422     /**
423      * Gets a Transformer that invokes a method on the input object.
424      * The method parameters are specified. If the input object is {@code null}, 
425      * {@code null} is returned.
426      * 
427      * @param <I>  the input type
428      * @param <O>  the output type
429      * @param methodName  the name of the method
430      * @param paramTypes  the parameter types
431      * @param args  the arguments
432      * @return the transformer
433      * @throws IllegalArgumentException if the method name is null or the paramTypes and args don't match
434      * @see org.apache.commons.collections.functors.InvokerTransformer
435      */
436     public static <I, O> Transformer<I, O> invokerTransformer(final String methodName, final Class<?>[] paramTypes,
437                                                               final Object[] args) {
438         return InvokerTransformer.<I, O>invokerTransformer(methodName, paramTypes, args);
439     }
440 
441     /**
442      * Gets a transformer that returns a <code>java.lang.String</code>
443      * representation of the input object. This is achieved via the
444      * <code>toString</code> method, <code>null</code> returns 'null'.
445      * 
446      * @param <T>  the input type
447      * @return the transformer
448      * @see org.apache.commons.collections.functors.StringValueTransformer
449      */
450     public static <T> Transformer<T, String> stringValueTransformer() {
451         return StringValueTransformer.<T>stringValueTransformer();
452     }
453     
454 }