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  
18  package org.apache.commons.jexl3.examples;
19  
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  import org.apache.commons.jexl3.JexlBuilder;
24  import org.apache.commons.jexl3.JexlContext;
25  import org.apache.commons.jexl3.JexlEngine;
26  import org.apache.commons.jexl3.JexlExpression;
27  import org.apache.commons.jexl3.MapContext;
28  import org.junit.jupiter.api.Test;
29  
30  /**
31   *  Simple example to show how to access arrays.
32   */
33  class ArrayTest {
34  
35      /**
36       * An example for array access.
37       */
38      static void example(final AbstractOutput out) throws Exception {
39          /*
40           * First step is to retrieve an instance of a JexlEngine;
41           * it might be already existing and shared or created anew.
42           */
43          final JexlEngine jexl = new JexlBuilder().create();
44          /*
45           *  Second make a jexlContext and put stuff in it
46           */
47          final JexlContext jc = new MapContext();
48  
49          final List<Object> l = new ArrayList<>();
50          l.add("Hello from location 0");
51          final Integer two = 2;
52          l.add(two);
53          jc.set("array", l);
54  
55          JexlExpression e = jexl.createExpression("array[1]");
56          Object o = e.evaluate(jc);
57          out.print("Object @ location 1 = ", o, two);
58  
59          e = jexl.createExpression("array[0].length()");
60          o = e.evaluate(jc);
61  
62          out.print("The length of the string at location 0 is : ", o, 21);
63      }
64  
65      /**
66       * Command line entry point.
67       * @param args command line arguments
68       * @throws Exception cos jexl does.
69       */
70      public static void main(final String[] args) throws Exception {
71          example(AbstractOutput.SYSTEM);
72      }
73  
74      /**
75       * Unit test entry point.
76       * @throws Exception
77       */
78      @Test
79      void testExample() throws Exception {
80          example(AbstractOutput.JUNIT);
81      }
82  }