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