use of javax.script.CompiledScript in project es6draft by anba.
the class CompilableTest method compileStringWithContextAndSimpleBindings.
@Test
public void compileStringWithContextAndSimpleBindings() throws ScriptException {
CompiledScript script = compilable.compile("numberVal * 2");
ScriptContext context = new SimpleScriptContext();
Bindings bindings = new SimpleBindings();
bindings.put("numberVal", 9);
context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
assertThat(script.eval(context), instanceOfWith(Number.class, is(numberCloseTo(18))));
}
use of javax.script.CompiledScript in project gremlin by tinkerpop.
the class GremlinGroovyScriptEngineTest method testEngineVsCompiledCosts.
public void testEngineVsCompiledCosts() throws Exception {
final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
Bindings bindings = engine.createBindings();
bindings.put("g", TinkerGraphFactory.createTinkerGraph());
int runs = 1000;
long totalTime = 0l;
for (int i = 0; i < runs; i++) {
long time = System.currentTimeMillis();
CompiledScript script = engine.compile("g.v(1).out().count()");
script.eval(bindings);
totalTime += System.currentTimeMillis() - time;
}
System.out.println("Multi-compiled script runtime for " + runs + " runs: " + totalTime);
totalTime = 0l;
for (int i = 0; i < runs; i++) {
long time = System.currentTimeMillis();
engine.eval("g.v(1).out().count()", bindings);
totalTime += System.currentTimeMillis() - time;
}
System.out.println("Evaluated script runtime for " + runs + " runs: " + totalTime);
totalTime = 0l;
CompiledScript script = engine.compile("g.v(1).out().count()");
for (int i = 0; i < runs; i++) {
long time = System.currentTimeMillis();
script.eval(bindings);
totalTime += System.currentTimeMillis() - time;
}
System.out.println("Compiled script runtime for " + runs + " runs: " + totalTime);
}
use of javax.script.CompiledScript in project midpoint by Evolveum.
the class Jsr223ScriptEvaluator method evaluate.
@Override
public <T, V extends PrismValue> List<V> evaluate(ScriptExpressionEvaluatorType expressionType, ExpressionVariables variables, ItemDefinition outputDefinition, Function<Object, Object> additionalConvertor, ScriptExpressionReturnTypeType suggestedReturnType, ObjectResolver objectResolver, Collection<FunctionLibrary> functions, String contextDescription, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, ExpressionSyntaxException {
Bindings bindings = convertToBindings(variables, objectResolver, functions, contextDescription, task, result);
String codeString = expressionType.getCode();
if (codeString == null) {
throw new ExpressionEvaluationException("No script code in " + contextDescription);
}
boolean allowEmptyValues = false;
if (expressionType.isAllowEmptyValues() != null) {
allowEmptyValues = expressionType.isAllowEmptyValues();
}
CompiledScript compiledScript = createCompiledScript(codeString, contextDescription);
Object evalRawResult;
try {
InternalMonitor.recordScriptExecution();
evalRawResult = compiledScript.eval(bindings);
} catch (Throwable e) {
throw new ExpressionEvaluationException(e.getMessage() + " in " + contextDescription, e);
}
if (outputDefinition == null) {
// No outputDefinition means "void" return type, we can return right now
return null;
}
QName xsdReturnType = outputDefinition.getTypeName();
Class<T> javaReturnType = XsdTypeMapper.toJavaType(xsdReturnType);
if (javaReturnType == null) {
javaReturnType = prismContext.getSchemaRegistry().getCompileTimeClass(xsdReturnType);
}
if (javaReturnType == null) {
// TODO quick and dirty hack - because this could be because of enums defined in schema extension (MID-2399)
// ...and enums (xsd:simpleType) are not parsed into ComplexTypeDefinitions
javaReturnType = (Class) String.class;
}
List<V> pvals = new ArrayList<V>();
// PrismProperty?
if (evalRawResult instanceof Collection) {
for (Object evalRawResultElement : (Collection) evalRawResult) {
T evalResult = convertScalarResult(javaReturnType, additionalConvertor, evalRawResultElement, contextDescription);
if (allowEmptyValues || !ExpressionUtil.isEmpty(evalResult)) {
pvals.add((V) ExpressionUtil.convertToPrismValue(evalResult, outputDefinition, contextDescription, prismContext));
}
}
} else if (evalRawResult instanceof PrismProperty<?>) {
pvals.addAll((Collection<? extends V>) PrismPropertyValue.cloneCollection(((PrismProperty<T>) evalRawResult).getValues()));
} else {
T evalResult = convertScalarResult(javaReturnType, additionalConvertor, evalRawResult, contextDescription);
if (allowEmptyValues || !ExpressionUtil.isEmpty(evalResult)) {
pvals.add((V) ExpressionUtil.convertToPrismValue(evalResult, outputDefinition, contextDescription, prismContext));
}
}
return pvals;
}
use of javax.script.CompiledScript in project OpenAM by OpenRock.
the class SandboxedGroovyScriptEngineTest method shouldApplySandboxToCompiledReaderScripts.
@Test
public void shouldApplySandboxToCompiledReaderScripts() throws Exception {
// Given
String script = "1 + 1";
Reader reader = new StringReader(script);
ScriptContext context = new SimpleScriptContext();
CompiledScript mockCompiledScript = mock(CompiledScript.class);
given(mockScriptEngine.compile(reader)).willReturn(mockCompiledScript);
// When
CompiledScript compiledScript = testEngine.compile(reader);
compiledScript.eval(context);
// Then
verify(mockValueFilter).register();
verify(mockCompiledScript).eval(context);
verify(mockValueFilter).unregister();
}
use of javax.script.CompiledScript in project jmeter by apache.
the class JSR223TestElement method processFileOrScript.
/**
* This method will run inline script or file script with special behaviour for file script:
* - If ScriptEngine implements Compilable script will be compiled and cached
* - If not if will be run
* @param scriptEngine ScriptEngine
* @param bindings {@link Bindings} might be null
* @return Object returned by script
* @throws IOException when reading the script fails
* @throws ScriptException when compiling or evaluation of the script fails
*/
protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings) throws IOException, ScriptException {
if (bindings == null) {
bindings = scriptEngine.createBindings();
}
populateBindings(bindings);
File scriptFile = new File(getFilename());
// Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws
// "java.lang.Error: unimplemented"
boolean supportsCompilable = scriptEngine instanceof Compilable && // NOSONAR // $NON-NLS-1$
!("bsh.engine.BshScriptEngine".equals(scriptEngine.getClass().getName()));
try {
if (!StringUtils.isEmpty(getFilename())) {
if (scriptFile.exists() && scriptFile.canRead()) {
if (supportsCompilable) {
String cacheKey = // $NON-NLS-1$
getScriptLanguage() + "#" + scriptFile.getAbsolutePath() + // $NON-NLS-1$
"#" + scriptFile.lastModified();
CompiledScript compiledScript = compiledScriptsCache.get(cacheKey);
if (compiledScript == null) {
synchronized (compiledScriptsCache) {
compiledScript = compiledScriptsCache.get(cacheKey);
if (compiledScript == null) {
// TODO Charset ?
try (BufferedReader fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length())) {
compiledScript = ((Compilable) scriptEngine).compile(fileReader);
compiledScriptsCache.put(cacheKey, compiledScript);
}
}
}
}
return compiledScript.eval(bindings);
} else {
// TODO Charset ?
try (BufferedReader fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length())) {
return scriptEngine.eval(fileReader, bindings);
}
}
} else {
throw new ScriptException("Script file '" + scriptFile.getAbsolutePath() + "' does not exist or is unreadable for element:" + getName());
}
} else if (!StringUtils.isEmpty(getScript())) {
if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) {
computeScriptMD5();
CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5);
if (compiledScript == null) {
synchronized (compiledScriptsCache) {
compiledScript = compiledScriptsCache.get(this.scriptMd5);
if (compiledScript == null) {
compiledScript = ((Compilable) scriptEngine).compile(getScript());
compiledScriptsCache.put(this.scriptMd5, compiledScript);
}
}
}
return compiledScript.eval(bindings);
} else {
return scriptEngine.eval(getScript(), bindings);
}
} else {
throw new ScriptException("Both script file and script text are empty for element:" + getName());
}
} catch (ScriptException ex) {
Throwable rootCause = ex.getCause();
if (isStopCondition(rootCause)) {
throw (RuntimeException) ex.getCause();
} else {
throw ex;
}
}
}
Aggregations