本文整理汇总了Java中groovy.lang.Script类的典型用法代码示例。如果您正苦于以下问题:Java Script类的具体用法?Java Script怎么用?Java Script使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Script类属于groovy.lang包,在下文中一共展示了Script类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import groovy.lang.Script; //导入依赖的package包/类
public GroovyResult execute(GroovyResult result, final Script groovyScript, final Map<String, Object> variables)
{
if (variables != null) {
final Binding binding = groovyScript.getBinding();
for (final Map.Entry<String, Object> entry : variables.entrySet()) {
binding.setVariable(entry.getKey(), entry.getValue());
}
}
if (result == null) {
result = new GroovyResult();
}
Object res = null;
try {
res = groovyScript.run();
} catch (final Exception ex) {
log.info("Groovy-Execution-Exception: " + ex.getMessage(), ex);
return new GroovyResult(ex);
}
result.setResult(res);
return result;
}
示例2: compileToDir
import groovy.lang.Script; //导入依赖的package包/类
@Override
public void compileToDir(ScriptSource source, ClassLoader classLoader, File classesDir, File metadataDir, CompileOperation<?> extractingTransformer,
Class<? extends Script> scriptBaseClass, Action<? super ClassNode> verifier) {
Timer clock = Timers.startTimer();
GFileUtils.deleteDirectory(classesDir);
GFileUtils.mkdirs(classesDir);
CompilerConfiguration configuration = createBaseCompilerConfiguration(scriptBaseClass);
configuration.setTargetDirectory(classesDir);
try {
compileScript(source, classLoader, configuration, metadataDir, extractingTransformer, verifier);
} catch (GradleException e) {
GFileUtils.deleteDirectory(classesDir);
GFileUtils.deleteDirectory(metadataDir);
throw e;
}
logger.debug("Timing: Writing script to cache at {} took: {}", classesDir.getAbsolutePath(), clock.getElapsed());
}
示例3: getScriptedObjectType
import groovy.lang.Script; //导入依赖的package包/类
public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {
synchronized (this.scriptClassMonitor) {
if (this.scriptClass == null || scriptSource.isModified()) {
this.scriptClass = this.groovyClassLoader.parseClass(scriptSource.getScriptAsString());
if (Script.class.isAssignableFrom(this.scriptClass)) {
// A Groovy script, probably creating an instance: let's execute it.
Object result = executeScript(this.scriptClass);
this.scriptResultClass = (result != null ? result.getClass() : null);
} else {
this.scriptResultClass = this.scriptClass;
}
}
return this.scriptResultClass;
}
}
示例4: runScript
import groovy.lang.Script; //导入依赖的package包/类
/**
* Returns the builder object for creating new output variable value.
*/
protected void runScript(String mapperScript, Slurper slurper, Builder builder)
throws ActivityException, TransformerException {
CompilerConfiguration compilerConfig = new CompilerConfiguration();
compilerConfig.setScriptBaseClass(CrossmapScript.class.getName());
Binding binding = new Binding();
binding.setVariable("runtimeContext", getRuntimeContext());
binding.setVariable(slurper.getName(), slurper.getInput());
binding.setVariable(builder.getName(), builder);
GroovyShell shell = new GroovyShell(getPackage().getCloudClassLoader(), binding, compilerConfig);
Script gScript = shell.parse(mapperScript);
// gScript.setProperty("out", getRuntimeContext().get);
gScript.run();
}
示例5: getPool
import groovy.lang.Script; //导入依赖的package包/类
private synchronized GenericKeyedObjectPool<String, Script> getPool() {
if (pool == null) {
GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
poolConfig.setMaxTotalPerKey(-1);
poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle());
pool = new GenericKeyedObjectPool<>(
new BaseKeyedPooledObjectFactory<String, Script>() {
@Override
public Script create(String key) throws Exception {
return createScript(key);
}
@Override
public PooledObject<Script> wrap(Script value) {
return new DefaultPooledObject<>(value);
}
},
poolConfig
);
}
return pool;
}
示例6: loadScript
import groovy.lang.Script; //导入依赖的package包/类
/**
* Loads a precompiled script with the supplied ID. The script class file must
* be stored in the pre-compiled scripts folder (see {@link Configuration#getFolderCompiledScripts()}.
*
* The method will return null if such a folder does not exist or if it does not contain
* the desired script.
* @param id
* @return
*/
public static Script loadScript(final String id) {
String fileName = id+".class";
Script cached = cache.get(fileName);
if (cached != null) {
return cached;
}
try {
URLClassLoader cl = getURLClassLoader();
if (cl != null) {
Script script = InvokerHelper.createScript(cl.loadClass(fileName), new Binding());
cache.put(fileName, script);
return script;
}
} catch (ClassNotFoundException | RuntimeException | MalformedURLException e) {
// do nothing and just build the class from the text
}
return null;
}
示例7: run
import groovy.lang.Script; //导入依赖的package包/类
@Override
public Object run(String dsl, Binding binding) {
CompilerConfiguration compilerConfiguration = prepareCompilerConfiguration();
ClassLoader classLoader = prepareClassLoader(AbstractDSLLauncher.class.getClassLoader());
GroovyCodeSource groovyCodeSource = prepareGroovyCodeSource(dsl);
// Groovy shell
GroovyShell shell = new GroovyShell(
classLoader,
new Binding(),
compilerConfiguration
);
// Groovy script
Script groovyScript = shell.parse(groovyCodeSource);
// Binding
groovyScript.setBinding(binding);
// Runs the script
return run(groovyScript);
}
示例8: runGroovyDslScript
import groovy.lang.Script; //导入依赖的package包/类
/**
* Runs a Groovy DSL script and returns the value returned by the script.
* @param scriptReader For reading the script text
* @param expectedType The expected type of the return value
* @param parameters Parameters used by the script, null or empty if the script doesn't need any
* @param <T> The expected type of the return value
* @return The return value of the script, not null
*/
private static <T> T runGroovyDslScript(Reader scriptReader, Class<T> expectedType, Map<String, Object> parameters) {
Map<String, Object> timeoutArgs = ImmutableMap.<String, Object>of("value", 2);
ASTTransformationCustomizer customizer = new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class);
CompilerConfiguration config = new CompilerConfiguration();
config.addCompilationCustomizers(customizer);
config.setScriptBaseClass(SimulationScript.class.getName());
Map<String, Object> bindingMap = parameters == null ? Collections.<String, Object>emptyMap() : parameters;
//copy map to ensure that binding is mutable (for use in registerAliases)
Binding binding = new Binding(Maps.newHashMap(bindingMap));
registerAliases(binding);
GroovyShell shell = new GroovyShell(binding, config);
Script script = shell.parse(scriptReader);
Object scriptOutput = script.run();
if (scriptOutput == null) {
throw new IllegalArgumentException("Script " + scriptReader + " didn't return an object");
}
if (expectedType.isInstance(scriptOutput)) {
return expectedType.cast(scriptOutput);
} else {
throw new IllegalArgumentException("Script '" + scriptReader + "' didn't create an object of the expected type. " +
"expected type: " + expectedType.getName() + ", " +
"actual type: " + scriptOutput.getClass().getName() + ", " +
"actual value: " + scriptOutput);
}
}
示例9: processScenario
import groovy.lang.Script; //导入依赖的package包/类
/**
* Post process every stored request just before it get saved to disk
*
* @param sampler recorded http-request (sampler)
* @param tree HashTree (XML like data structure) that represents exact recorded sampler
*/
public void processScenario(HTTPSamplerBase sampler, HashTree tree, Arguments userVariables, JMeterRecorder recorder)
{
Binding binding = new Binding();
binding.setVariable(ScriptBindingConstants.LOGGER, LOG);
binding.setVariable(ScriptBindingConstants.SAMPLER, sampler);
binding.setVariable(ScriptBindingConstants.TREE, tree);
binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext());
binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance());
binding.setVariable(ScriptBindingConstants.USER_VARIABLES, userVariables);
binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader);
Script compiledProcessScript = ScriptEngine.getScript(getScenarioProcessorScript());
if (compiledProcessScript == null)
{
return;
}
compiledProcessScript.setBinding(binding);
LOG.info("Run compiled script");
try {
compiledProcessScript.run();
} catch (Throwable throwable) {
LOG.error(throwable.getMessage(), throwable);
}
}
示例10: evaluate
import groovy.lang.Script; //导入依赖的package包/类
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
LOG.debug("Evaluating Groovy expression: {1}", expression);
try {
final ObjectCache<String, Script> scriptCache = threadScriptCache.get();
Script script = scriptCache.get(expression);
if (script == null) {
script = GROOVY_SHELL.parse(expression);
scriptCache.put(expression, script);
}
final Binding binding = new Binding();
for (final Entry<String, ?> entry : values.entrySet()) {
binding.setVariable(entry.getKey(), entry.getValue());
}
script.setBinding(binding);
return script.run();
} catch (final Exception ex) {
throw new ExpressionEvaluationException("Evaluating script with Groovy failed.", ex);
}
}
示例11: getGroovyScript
import groovy.lang.Script; //导入依赖的package包/类
@SuppressWarnings("unchecked")
Script getGroovyScript(String id, String scriptText) /*throws SQLException*/ {
if (shell == null) {
throw new RuntimeException("Groovy Shell is not initialized: null");
}
try {
Class<Script> clazz = scriptCache.get(scriptText);
if (clazz == null) {
String scriptName = id + "_" + Long.toHexString(scriptText.hashCode()) + ".groovy";
clazz = (Class<Script>) shell.parse(scriptText, scriptName).getClass();
scriptCache.put(scriptText, clazz);
}
Script script = (Script) clazz.newInstance();
return script;
} catch (Throwable t) {
throw new RuntimeException("Failed to parse groovy script: " + t, t);
}
}
示例12: eval
import groovy.lang.Script; //导入依赖的package包/类
/**
* Evaluate an expression.
*/
public Object eval(String source, int lineNo, int columnNo, Object script) throws BSFException {
try {
Class scriptClass = evalScripts.get(script);
if (scriptClass == null) {
scriptClass = loader.parseClass(script.toString(), source);
evalScripts.put(script, scriptClass);
} else {
LOG.fine("eval() - Using cached script...");
}
//can't cache the script because the context may be different.
//but don't bother loading parsing the class again
Script s = InvokerHelper.createScript(scriptClass, context);
return s.run();
} catch (Exception e) {
throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception from Groovy: " + e, e);
}
}
示例13: processFiles
import groovy.lang.Script; //导入依赖的package包/类
/**
* Process the input files.
*/
private void processFiles() throws CompilationFailedException, IOException, URISyntaxException {
GroovyShell groovy = new GroovyShell(conf);
setupContextClassLoader(groovy);
Script s = groovy.parse(getScriptSource(isScriptFile, script));
if (args.isEmpty()) {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out)) {
processReader(s, reader, writer);
}
} else {
Iterator i = args.iterator();
while (i.hasNext()) {
String filename = (String) i.next();
//TODO: These are the arguments for -p and -i. Why are we searching using Groovy script extensions?
// Where is this documented?
File file = huntForTheScriptFile(filename);
processFile(s, file);
}
}
}
示例14: run
import groovy.lang.Script; //导入依赖的package包/类
/**
* Runs this server. There is typically no need to call this method, as the object's constructor
* creates a new thread and runs this object automatically.
*/
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(url.getPort());
while (true) {
// Create one script per socket connection.
// This is purposefully not caching the Script
// so that the script source file can be changed on the fly,
// as each connection is made to the server.
//FIXME: Groovy has other mechanisms specifically for watching to see if source code changes.
// We should probably be using that here.
// See also the comment about the fact we recompile a script that can't change.
Script script = groovy.parse(source);
new GroovyClientConnection(script, autoOutput, serverSocket.accept());
}
} catch (Exception e) {
e.printStackTrace();
}
}
示例15: build
import groovy.lang.Script; //导入依赖的package包/类
public Object build(Script script) {
// this used to be synchronized, but we also used to remove the
// metaclass. Since adding the metaclass is now a side effect, we
// don't need to ensure the meta-class won't be observed and don't
// need to hide the side effect.
MetaClass scriptMetaClass = script.getMetaClass();
script.setMetaClass(new FactoryInterceptorMetaClass(scriptMetaClass, this));
script.setBinding(this);
Object oldScriptName = getProxyBuilder().getVariables().get(SCRIPT_CLASS_NAME);
try {
getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, script.getClass().getName());
return script.run();
} finally {
if(oldScriptName != null) {
getProxyBuilder().setVariable(SCRIPT_CLASS_NAME, oldScriptName);
} else {
getProxyBuilder().getVariables().remove(SCRIPT_CLASS_NAME);
}
}
}