1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.maven.plugins.scripting;
20
21 import javax.script.ScriptContext;
22 import javax.script.ScriptEngine;
23 import javax.script.ScriptEngineManager;
24 import javax.script.ScriptException;
25
26 /**
27 * Evaluates a script held in a string
28 * @author Rusi Popov
29 */
30 public class StringScriptEvaluator extends AbstractScriptEvaluator {
31
32 /**
33 * Not null name of the engine to execute the script
34 */
35 private final String engineName;
36
37 /**
38 * The non-null script itself
39 */
40 private final String script;
41
42 /**
43 * @param engineName the engine name
44 * @param script the script
45 * @throws IllegalArgumentException if either engineName or script is null
46 */
47 public StringScriptEvaluator(String engineName, String script) {
48 if (engineName == null || engineName.isEmpty()) {
49 throw new IllegalArgumentException("Expected a non-empty engine name provided");
50 }
51 this.engineName = engineName;
52
53 if (script == null || script.trim().isEmpty()) {
54 throw new IllegalArgumentException("Expected a non-empty script provided");
55 }
56 this.script = script;
57 }
58
59 /**
60 * @param manager the script engine manager.
61 * @throws UnsupportedScriptEngineException if the engineName is not supported
62 * @see org.apache.maven.plugins.scripting.AbstractScriptEvaluator#getEngine(javax.script.ScriptEngineManager)
63 */
64 protected ScriptEngine getEngine(ScriptEngineManager manager) throws UnsupportedScriptEngineException {
65 ScriptEngine result = manager.getEngineByName(engineName);
66
67 if (result == null) {
68 throw new UnsupportedScriptEngineException("Unknown engine specified with name \"" + engineName + "\"");
69 }
70 return result;
71 }
72
73 /**
74 * @param engine the script engine.
75 * @param context the script context.
76 * @throws ScriptException if an error occurs in script.
77 * @see org.apache.maven.plugins.scripting.AbstractScriptEvaluator#eval(javax.script.ScriptEngine, javax.script.ScriptContext)
78 */
79 protected Object eval(ScriptEngine engine, ScriptContext context) throws ScriptException {
80 return engine.eval(script, context);
81 }
82 }