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