View Javadoc
1   package org.codehaus.plexus.interpolation.fixed;
2   
3   /*
4    * Copyright 2014 The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  
20  import org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor;
21  
22  /**
23   * Wraps an object, providing reflective access to the object graph of which the
24   * supplied object is the root. Expressions like 'child.name' will translate into
25   * 'rootObject.getChild().getName()' for non-boolean properties, and
26   * 'rootObject.getChild().isName()' for boolean properties.
27   */
28  public class ObjectBasedValueSource
29      implements FixedValueSource
30  {
31  
32      private final Object root;
33  
34      /**
35       * Construct a new value source, using the supplied object as the root from
36       * which to start, and using expressions split at the dot ('.') to navigate
37       * the object graph beneath this root.
38       * @param root The root of the graph.
39       */
40      public ObjectBasedValueSource( Object root )
41      {
42          this.root = root;
43      }
44  
45      /**
46       * Split the expression into parts, tokenized on the dot ('.') character. Then,
47       * starting at the root object contained in this value source, apply each part
48       * to the object graph below this root, using either 'getXXX()' or 'isXXX()'
49       * accessor types to resolve the value for each successive expression part.
50       * Finally, return the result of the last expression part's resolution.
51       * <p><b>NOTE:</b> The object-graph nagivation actually takes place via the
52       * {@link org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor} class.</p>
53       */
54      public Object getValue( String expression, InterpolationState interpolationState )
55      {
56          if ( expression == null || expression.trim().length() < 1 )
57          {
58              return null;
59          }
60          
61          try
62          {
63              return ReflectionValueExtractor.evaluate( expression, root, false );
64          }
65          catch ( Exception e )
66          {
67              interpolationState.addFeedback( "Failed to extract \'" + expression + "\' from: " + root, e );
68          }
69  
70          return null;
71      }
72  
73  }