| 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.shared.scriptinterpreter; |
| 20 |
|
| 21 |
import java.io.File; |
| 22 |
import java.io.PrintStream; |
| 23 |
import java.net.URL; |
| 24 |
import java.util.List; |
| 25 |
import java.util.Map; |
| 26 |
|
| 27 |
import groovy.lang.Binding; |
| 28 |
import groovy.lang.GroovyShell; |
| 29 |
import org.codehaus.groovy.control.CompilerConfiguration; |
| 30 |
import org.codehaus.groovy.tools.RootLoader; |
| 31 |
|
| 32 |
/** |
| 33 |
* Provides a facade to evaluate Groovy scripts. |
| 34 |
* |
| 35 |
* @author Benjamin Bentmann |
| 36 |
*/ |
| 37 |
class GroovyScriptInterpreter implements ScriptInterpreter { |
| 38 |
|
| 39 |
/** {@inheritDoc} */ |
| 40 |
@Override |
| 41 |
public Object evaluateScript( |
| 42 |
String script, |
| 43 |
List<String> classPath, |
| 44 |
Map<String, ? extends Object> globalVariables, |
| 45 |
PrintStream scriptOutput) |
| 46 |
throws ScriptEvaluationException { |
| 47 |
PrintStream origOut = System.out; |
| 48 |
PrintStream origErr = System.err; |
| 49 |
|
| 50 |
try (RootLoader childFirstLoader = |
| 51 |
new RootLoader(new URL[] {}, getClass().getClassLoader())) { |
| 52 |
|
| 53 |
if (scriptOutput != null) { |
| 54 |
System.setErr(scriptOutput); |
| 55 |
System.setOut(scriptOutput); |
| 56 |
} |
| 57 |
|
| 58 |
if (classPath != null && !classPath.isEmpty()) { |
| 59 |
for (String path : classPath) { |
| 60 |
childFirstLoader.addURL(new File(path).toURI().toURL()); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
GroovyShell interpreter = new GroovyShell( |
| 65 |
childFirstLoader, |
| 66 |
new Binding(globalVariables), |
| 67 |
new CompilerConfiguration(CompilerConfiguration.DEFAULT)); |
| 68 |
|
| 69 |
return interpreter.evaluate(script); |
| 70 |
} catch (Throwable e) { |
| 71 |
throw new ScriptEvaluationException(e); |
| 72 |
} finally { |
| 73 |
System.setErr(origErr); |
| 74 |
System.setOut(origOut); |
| 75 |
} |
| 76 |
} |
| 77 |
} |