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 import org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor;
20
21 /**
22 * Wraps an object, providing reflective access to the object graph of which the
23 * supplied object is the root. Expressions like 'child.name' will translate into
24 * 'rootObject.getChild().getName()' for non-boolean properties, and
25 * 'rootObject.getChild().isName()' for boolean properties.
26 */
27 public class ObjectBasedValueSource implements FixedValueSource {
28
29 private final Object root;
30
31 /**
32 * Construct a new value source, using the supplied object as the root from
33 * which to start, and using expressions split at the dot ('.') to navigate
34 * the object graph beneath this root.
35 * @param root The root of the graph.
36 */
37 public ObjectBasedValueSource(Object root) {
38 this.root = root;
39 }
40
41 /**
42 * Split the expression into parts, tokenized on the dot ('.') character. Then,
43 * starting at the root object contained in this value source, apply each part
44 * to the object graph below this root, using either 'getXXX()' or 'isXXX()'
45 * accessor types to resolve the value for each successive expression part.
46 * Finally, return the result of the last expression part's resolution.
47 * <p><b>NOTE:</b> The object-graph nagivation actually takes place via the
48 * {@link org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor} class.</p>
49 */
50 public Object getValue(String expression, InterpolationState interpolationState) {
51 if (expression == null || expression.trim().length() < 1) {
52 return null;
53 }
54
55 try {
56 return ReflectionValueExtractor.evaluate(expression, root, false);
57 } catch (Exception e) {
58 interpolationState.addFeedback("Failed to extract \'" + expression + "\' from: " + root, e);
59 }
60
61 return null;
62 }
63 }