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.jexl3.jexl342;
18  
19  import java.util.Objects;
20  
21  import org.apache.commons.jexl3.JexlEngine;
22  import org.apache.commons.jexl3.JexlException;
23  import org.apache.commons.jexl3.introspection.JexlPropertySet;
24  import org.apache.commons.jexl3.introspection.JexlUberspect;
25  
26  /**
27   * JexlPropertySet on a reference that pointed null.
28   * <p>Performs a late discovery of the actual setter.</p>
29   */
30  public class OptionalNullSetter implements JexlPropertySet {
31      /** The Uberspect to discover the setter. */
32      private final JexlUberspect uberspect;
33      /** The property we are trying to discover. */
34      private final Object property;
35      /** The result when we solve it. */
36      private JexlPropertySet delegate;
37  
38      OptionalNullSetter(final JexlUberspect jexlUberspect, final Object key) {
39          uberspect = jexlUberspect;
40          property = key;
41      }
42  
43      @Override
44      public Object invoke(final Object obj, final Object arg) throws Exception {
45          if (obj == null) {
46              return null;
47          }
48          if (delegate == null) {
49              delegate = uberspect.getPropertySet(obj, property, arg);
50              if (delegate == null) {
51                  throw new JexlException.Property(null, Objects.toString(property), false, null);
52              }
53          }
54          return delegate.invoke(obj, arg);
55      }
56  
57      @Override
58      public boolean isCacheable() {
59          return false;
60      }
61  
62      @Override
63      public boolean tryFailed(final Object rval) {
64          return delegate != null ? delegate.tryFailed(rval) : JexlEngine.TRY_FAILED == rval;
65      }
66  
67      @Override
68      public Object tryInvoke(final Object obj, final Object key, final Object arg) throws JexlException.TryFailed {
69          if (obj == null) {
70              return null;
71          }
72          return delegate != null ? delegate.tryInvoke(obj, property, arg) : JexlEngine.TRY_FAILED;
73      }
74  }