Apache Maven 脚本解释器
该组件提供了一些实用程序来解释/执行各种实现的一些脚本:groovy 或 beanshell。
依赖声明
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-script-interpreter</artifactId>
<version>1.3</version>
</dependency>
maven-script-interpreter仅依赖于核心解释器库,所有特定的扩展都应该添加到您的项目中。
例如,如果你想在Groovy脚本中使用Grape,你必须在你的项目或调用脚本的插件中添加对 Ivy 的依赖:
<dependency>
<groupId>org.apache.ivy</groupId>
<artifactId>ivy</artifactId>
<version>...</version>
</dependency>
使用 ScriptInterpreter
解释 BeanShell 脚本
ScriptInterpreter interpreter = new BeanShellScriptInterpreter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
interpreter.evaluateScript( script content, extra classPath entries,
Map<String, ? extends Object> globalVariables, new PrintStream( out ) );
out.toString()返回脚本输出。
解释 Groovy 脚本
ScriptInterpreter interpreter = new GroovyScriptInterpreter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
interpreter.evaluateScript( script content, extra classPath entries,
Map<String, ? extends Object> globalVariables, new PrintStream( out ) );
out.toString()返回脚本输出。
使用 ScriptRunner
ScriptRunner类将根据支持的扩展名(.bsh, .groovy)检测要运行的脚本文件。
此类将在提供的目录中搜索具有提供的文件名和支持的扩展名的脚本。
有关方法,请参见javadocrun(...)。
ScriptRunner scriptRunner = new ScriptRunner();
scriptRunner.run( "test", new File( "src/test/resources/bsh-test" ), "verify", buildContext(),
new FileLogger( logFile ) );
脚本解释器的镜像输出
为了对脚本输出做更多的事情,例如。通过您的应用程序登录,您必须实现FileLoggerMirrorHandler
class MyMirrorHandler implements FileLoggerMirrorHandler
{
void consumeOutput( String message )
{
// this method is invoked every time when flush occurs on the underlying stream.
}
}
现在使用它:
ScriptRunner scriptRunner = new ScriptRunner();
scriptRunner.run( "test", new File( "src/test/resources/bsh-test" ), "verify", buildContext(),
new FileLogger( logFile, new MyMirrorHandler() ) );
全局变量
默认情况下,您的脚本将具有两个全局变量:
basedir:脚本的基本目录context:构建上下文(见下文)
您可以添加更多全局变量。
ScriptRunner scriptRunner = new ScriptRunner();
scriptRunner.setGlobalVariable( name, value );
构建上下文
您可以使用具有以下类型的执行上下文将一些值传递给脚本Map<String, ? extends Object> context:
private Map<String, Object> buildContext()
{
Map<String, Object> context = new HashMap<String, Object>();
context.put( "foo", "bar" );
return context;
}
然后值在脚本上下文中可用:
// in your bsh script
String value = context.get( "foo" );
值将是“bar”
// in your Groovy script
context.get("foo")
额外的类路径条目
您可以为脚本执行添加一些额外的类路径条目
List<String> classpathEntries = list of jar paths
ScriptRunner scriptRunner = new ScriptRunner();
scriptRunner.setClassPath( classpathEntries );
scriptRunner.run( "test", new File( "src/test/resources/bsh-test" ), "verify", buildContext(),
new FileLogger( logFile ) );



