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.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  
32      /** The Uberspect to discover the setter. */
33      private final JexlUberspect uberspect;
34  
35      /** The property we are trying to discover. */
36      private final Object property;
37  
38      /** The result when we solve it. */
39      private JexlPropertySet delegate;
40  
41      OptionalNullSetter(final JexlUberspect jexlUberspect, final Object key) {
42          uberspect = jexlUberspect;
43          property = key;
44      }
45  
46      @Override
47      public Object invoke(final Object obj, final Object arg) throws Exception {
48          if (obj == null) {
49              return null;
50          }
51          if (delegate == null) {
52              delegate = uberspect.getPropertySet(obj, property, arg);
53              if (delegate == null) {
54                  throw new JexlException.Property(null, Objects.toString(property), false, null);
55              }
56          }
57          return delegate.invoke(obj, arg);
58      }
59  
60      @Override
61      public boolean isCacheable() {
62          return false;
63      }
64  
65      @Override
66      public boolean tryFailed(final Object rval) {
67          return delegate != null ? delegate.tryFailed(rval) : JexlEngine.TRY_FAILED == rval;
68      }
69  
70      @Override
71      public Object tryInvoke(final Object obj, final Object key, final Object arg) throws JexlException.TryFailed {
72          if (obj == null) {
73              return null;
74          }
75          return delegate != null ? delegate.tryInvoke(obj, property, arg) : JexlEngine.TRY_FAILED;
76      }
77  }