1 package org.apache.maven.plugins.scripting; 2 3 /* 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 */ 21 22 import javax.script.Bindings; 23 import javax.script.ScriptContext; 24 import javax.script.ScriptEngine; 25 import javax.script.ScriptEngineManager; 26 import javax.script.ScriptException; 27 28 /** 29 * Evaluates a script in the appropriate context and return its possibly null result 30 * @author Rusi Popov 31 */ 32 abstract class AbstractScriptEvaluator 33 { 34 35 /** 36 * @param bindings not null bindings to provide to the script to execute 37 * @return the possibly null result the script produced 38 * @throws UnsupportedScriptEngineException when the engine is not configured correctly 39 * @throws ScriptException if an error occurs in script. 40 */ 41 public final Object eval( Bindings bindings ) throws ScriptException, UnsupportedScriptEngineException 42 { 43 ScriptEngineManager manager = new ScriptEngineManager(); 44 ScriptEngine engine = getEngine( manager ); 45 ScriptContext context = engine.getContext(); 46 47 context.setBindings( bindings, ScriptContext.GLOBAL_SCOPE ); 48 49 return eval( engine, context ); 50 } 51 52 /** 53 * AbstractScriptEvaluator the script 54 * @param engine not null 55 * @param context not null, initialized 56 * @return possibly null result of the script 57 * @throws ScriptException if an error occurs in script. 58 */ 59 protected abstract Object eval( ScriptEngine engine, ScriptContext context ) throws ScriptException; 60 61 /** 62 * @param manager not null 63 * @return non-null engine to execute the script 64 * @throws UnsupportedScriptEngineException when no engine could be identified 65 */ 66 protected abstract ScriptEngine getEngine( ScriptEngineManager manager ) 67 throws UnsupportedScriptEngineException; 68 }