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.jexl2.scripting;
19  
20  import java.io.BufferedReader;
21  import java.io.FileReader;
22  import java.io.InputStreamReader;
23  
24  import javax.script.ScriptEngine;
25  import javax.script.ScriptException;
26  
27  /**
28   * Test application for JexlScriptEngine (JSR-223 implementation).
29   * @since 2.0
30   */
31  public class Main {
32  
33      /**
34       * Test application for JexlScriptEngine (JSR-223 implementation).
35       * 
36       * If a single argument is present, it is treated as a filename of a JEXL
37       * script to be evaluated. Any exceptions terminate the application.
38       * 
39       * Otherwise, lines are read from standard input and evaluated.
40       * ScriptExceptions are logged, and do not cause the application to exit.
41       * This is done so that interactive testing is easier.
42       * 
43       * @param args (optional) filename to evaluate. Stored in the args variable.
44       * 
45       * @throws Exception if parsing or IO fail
46       */
47      public static void main(String[] args) throws Exception {
48          JexlScriptEngineFactory fac = new JexlScriptEngineFactory();
49          ScriptEngine engine = fac.getScriptEngine();
50          engine.put("args", args);
51          if (args.length == 1){
52              Object value = engine.eval(new FileReader(args[0]));
53              System.out.println("Return value: "+value);
54          } else {
55              BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
56              String line;
57              System.out.print("> ");
58              while(null != (line=console.readLine())){
59                  try {
60                      Object value = engine.eval(line);
61                      System.out.println("Return value: "+value);
62                  } catch (ScriptException e) {
63                      System.out.println(e.getLocalizedMessage());
64                  }
65                  System.out.print("> ");
66              }
67          }
68      }
69  }