Java Code Examples for javax.script.Bindings#putAll()

The following examples show how to use javax.script.Bindings#putAll() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TemplateUtil.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String expandTemplate(Reader reader, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    try {
        eng.eval(reader);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}
 
Example 2
Source File: JavaScriptEvaluator.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public int getComplexity(ResolvedField node, int childScore) {
    Resolver resolver = node.getResolver();
    if (resolver == null || Utils.isEmpty(resolver.getComplexityExpression())) {
        GraphQLType fieldType = node.getFieldType();
        if (fieldType instanceof GraphQLScalarType || fieldType instanceof GraphQLEnumType) {
            return 1;
        }
        if (GraphQLUtils.isRelayConnectionType(fieldType)) {
            Integer pageSize = getPageSize(node.getArguments());
            if (pageSize != null) {
                return pageSize * childScore;
            }
        }
        return 1 + childScore;
    }
    Bindings bindings = engine.createBindings();
    bindings.putAll(node.getArguments());
    bindings.put("childScore", childScore);
    try {
        return ((Number) engine.eval(resolver.getComplexityExpression(), bindings)).intValue();
    } catch (Exception e) {
        throw new IllegalArgumentException(String.format("Complexity expression \"%s\" on field %s could not be evaluated",
                resolver.getComplexityExpression(), node.getName()), e);
    }
}
 
Example 3
Source File: Titan0Graph.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Override
public Object executeGremlinScript(ScriptEngine scriptEngine, Map<? extends  String, ? extends  Object> userBindings, String query, boolean isPath) throws ScriptException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeGremlinScript(query={}, userBindings={})", query, userBindings);
    }

    Bindings bindings = scriptEngine.createBindings();

    if (userBindings != null) {
        bindings.putAll(userBindings);
    }

    bindings.put("g", getGraph());

    Object result = scriptEngine.eval(query, bindings);

    return convertGremlinScriptResult(isPath, result);
}
 
Example 4
Source File: ManagedScript.java    From genie with Apache License 2.0 6 votes vote down vote up
protected Object evaluateScript(
    final Map<String, Object> scriptParameters
) throws ScriptExecutionException, ScriptNotConfiguredException {

    final URI scriptUri = this.properties.getSource();

    if (scriptUri == null) {
        throw new ScriptNotConfiguredException("Script source URI not set");
    }

    // NOTE: Avoid the constructor that directly takes the map as it uses it directly as the underlying
    //       implementation and if it's immutable it could cause unexpected side effects not expected by
    //       some implementation.
    final Bindings bindings = new SimpleBindings();
    bindings.putAll(scriptParameters);

    return this.scriptManager.evaluateScript(scriptUri, bindings, this.properties.getTimeout());
}
 
Example 5
Source File: FileUtil.java    From jeddict with Apache License 2.0 6 votes vote down vote up
/**
 * In-memory template api
 *
 * @param templateContent
 * @param values
 * @return
 */
public static String expandTemplateContent(String templateContent, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new StringReader(templateContent);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}
 
Example 6
Source File: GremlinGroovyScriptEngine.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource) throws ScriptException {
    // these validations occur before merging in bytecode bindings which will override existing ones. need to
    // extract the named traversalsource prior to that happening so that bytecode bindings can share the same
    // namespace as global bindings (e.g. traversalsources and graphs).
    if (traversalSource.equals(HIDDEN_G))
        throw new IllegalArgumentException("The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved");

    if (bindings.containsKey(HIDDEN_G))
        throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved");

    if (!bindings.containsKey(traversalSource))
        throw new IllegalArgumentException("The bindings available to the ScriptEngine do not contain a traversalSource named: " + traversalSource);

    final Object b = bindings.get(traversalSource);
    if (!(b instanceof TraversalSource))
        throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName() + " and is not an instance of TraversalSource");

    final Bindings inner = new SimpleBindings();
    inner.putAll(bindings);
    inner.putAll(bytecode.getBindings());
    inner.put(HIDDEN_G, b);
    org.apache.tinkerpop.gremlin.process.traversal.Script script = GroovyTranslator.of(HIDDEN_G, typeTranslator).translate(bytecode);
    script.getParameters().ifPresent(inner::putAll);
    return (Traversal.Admin) this.eval(script.getScript(), inner);
}
 
Example 7
Source File: ScriptRunPerformence.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
private Bindings createBinding(Map<String, Object> vars,
        ScriptEngine scriptEngine) {
    Bindings binds = scriptEngine.createBindings();
    if (null != vars && !vars.isEmpty()) {
        binds.putAll(vars);
    }
    
    return binds;
}
 
Example 8
Source File: JavaScriptingDataTransformer.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Object evaluateExpression(Object expression, Map<String, Object> parameters) {
	try {
		Object result = null;
		StringWriter writer = new StringWriter();			
		
		ScriptContext context = new SimpleScriptContext();
		for (Map.Entry<String, Object> property : engineProperties.entrySet()) {
			context.setAttribute(property.getKey(), property.getValue(), ScriptContext.ENGINE_SCOPE);
		}
		Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
		bindings.putAll(parameters);
		context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
		context.setWriter(writer);
		if (expression instanceof CompiledScript) {
			logger.debug("About to evaluate compiled expression {} with bindings {} on engine", expression, parameters, scriptEngine);
			result = ((CompiledScript) expression).eval(context);
		} else {
			logger.debug("About to evaluate expression {} with bindings {} on engine", expression, parameters, scriptEngine);
			result = scriptEngine.eval(expression.toString(), context);
		}
		if (result == null) {
			result = writer.toString();
		}
		return result;
	} catch (ScriptException e) {
		throw new RuntimeException("Error when evaluating script", e);
	}
}
 
Example 9
Source File: SimpleTemplateEngine.java    From oxygen with Apache License 2.0 5 votes vote down vote up
void apply(Map<String, Object> attrs, Writer writer) throws ScriptException {
  Bindings bindings = ENGINE.createBindings();
  ScriptContext ctx = new SimpleScriptContext();
  ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
  bindings.putAll(attrs);
  bindings.put("$out", writer);
  bindings.put("$data", data);
  if (compiledScript != null) {
    compiledScript.eval(bindings);
  } else {
    ENGINE.eval(parsed, bindings);
  }
}
 
Example 10
Source File: AtlasJanusGraph.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Override
public Object executeGremlinScript(ScriptEngine scriptEngine, Map<? extends String, ? extends Object> userBindings,
                                   String query, boolean isPath) throws ScriptException {
    Bindings bindings = scriptEngine.createBindings();

    bindings.putAll(userBindings);
    bindings.put("g", getGraph().traversal());

    Object result = scriptEngine.eval(query, bindings);

    return convertGremlinValue(result);
}
 
Example 11
Source File: MultiScriptEngineCompare.java    From JavaTutorial with Apache License 2.0 5 votes vote down vote up
private Bindings createBinding(ScriptEngine scriptEngine, Map<String, Object> vars) {
    Bindings binds = scriptEngine.createBindings();
    if (null != vars && !vars.isEmpty()) {
        binds.putAll(vars);
    }
    
    return binds;
}
 
Example 12
Source File: Titan1Graph.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Override
public Object executeGremlinScript(ScriptEngine scriptEngine,
        Map<? extends  String, ? extends  Object> userBindings, String query, boolean isPath)
        throws ScriptException {
    Bindings bindings = scriptEngine.createBindings();

    bindings.putAll(userBindings);
    bindings.put("g", getGraph());

    Object result = scriptEngine.eval(query, bindings);
    return convertGremlinValue(result);
}
 
Example 13
Source File: ScriptingEnvironmentProvider.java    From enhydrator with Apache License 2.0 5 votes vote down vote up
public static Bindings create(ScriptEngineManager scriptEngineManager, Map<String, Object> scriptEngineBindings, Row input) {
    Bindings bindings = scriptEngineManager.getBindings();
    bindings.put("$ROW", input);
    final Row emptyRow = new Row();
    bindings.put("$EMPTY", emptyRow);
    bindings.put("$MEMORY", input.getMemory());
    input.getColumns().forEach(c -> bindings.put(c.getName(), c));
    if (scriptEngineBindings != null) {
        bindings.putAll(scriptEngineBindings);
    }
    return bindings;
}
 
Example 14
Source File: GremlinExecutor.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates bytecode with bindings for a specific language into a {@link Traversal}.
 */
public Traversal.Admin eval(final Bytecode bytecode, final Bindings boundVars, final String language, final String traversalSource) throws ScriptException {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    return gremlinScriptEngineManager.getEngineByName(lang).eval(bytecode, bindings, traversalSource);
}
 
Example 15
Source File: CompiledJavaScriptExecutor.java    From Oceanus with Apache License 2.0 5 votes vote down vote up
@Override
public T execute(String script,Map<String, Object> parameters) throws ScriptException {
	Bindings bindings = compiledScript.getEngine().createBindings();
	if (parameters != null) {
		bindings.putAll(parameters);
	}

	T result = (T) compiledScript.eval(bindings);
	return result;
}
 
Example 16
Source File: InterpretedScriptExecutor.java    From Oceanus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T execute(String script, Map<String, Object> parameters)
		throws ScriptException {
	ScriptEngine scriptEngine = manager.getEngineByName("js");
	Bindings binding = scriptEngine.createBindings();
	if (parameters != null) {
		binding.putAll(parameters);
	}
	Object val = scriptEngine.eval(script, binding);
	return ((T) val);
}
 
Example 17
Source File: ScriptingCreateFromTemplateHandler.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<FileObject> createFromTemplate(CreateDescriptor desc) throws IOException {
    FileObject template = desc.getTemplate();
    String name = desc.getProposedName();
    Map<String, ?> values = desc.getParameters();
    FileObject f = desc.getTarget();
    
    boolean noExt = desc.hasFreeExtension() && name.indexOf('.') != -1;
    
    String extWithDot;
    if (noExt) {
        extWithDot = null;
    } else {
        extWithDot = '.' + template.getExt();
        if (name.endsWith(extWithDot)) { // Test whether the extension happens to be there already
            // And remove it if yes, it will be appended to the unique name.
            name = name.substring(0, name.length() - extWithDot.length());
        }
    }
    
    String nameUniq = FileUtil.findFreeFileName(f, name, noExt ? null : template.getExt());
    FileObject output = FileUtil.createData(f, noExt ? nameUniq : nameUniq + extWithDot);
    Charset targetEnc = FileEncodingQuery.getEncoding(output);
    Charset sourceEnc = FileEncodingQuery.getEncoding(template);
    
    ScriptEngine eng = engine(template);
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);
    
    if(!values.containsKey(ENCODING_PROPERTY_NAME)) {
        bind.put(ENCODING_PROPERTY_NAME, targetEnc.name());
    }
    
    //Document doc = createDocument(template.getMIMEType());
    FileLock lock = output.lock();
    try (Writer w = new OutputStreamWriter(output.getOutputStream(lock), targetEnc);
         Reader is = new InputStreamReader(template.getInputStream(), sourceEnc);
        /*IndentWriter w2 = new IndentWriter(doc, 0, w, false) */) {
        StringWriter sw = new StringWriter();
        ScriptEngine eng2 = desc.isPreformatted() ? null : indentEngine();
        
        eng.getContext().setWriter(new PrintWriter(eng2 != null ? sw : w));
        //eng.getContext().setBindings(bind, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
        eng.getContext().setAttribute(ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE);
        eng.eval(is);
        
        if (eng2 != null) {
            eng2.getContext().setAttribute("mimeType", template.getMIMEType(), ScriptContext.ENGINE_SCOPE);
            eng2.getContext().setWriter(w);
            eng2.eval(new StringReader(sw.toString()));
        }
    }catch (ScriptException ex) {
        IOException io = new IOException(ex.getMessage(), ex);
        throw io;
    } finally {
        lock.releaseLock();
    }
    return Collections.singletonList(output);
}
 
Example 18
Source File: Module.java    From nashorn-commonjs-modules with MIT License 4 votes vote down vote up
private Module compileJavaScriptModule(Folder parent, String fullPath, String code)
    throws ScriptException {

  Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
  Bindings module = createSafeBindings();
  module.putAll(engineScope);

  // If we have cached bindings, use them to rebind exports instead of creating new ones
  Bindings exports = refCache.get().get(fullPath);
  if (exports == null) {
    exports = createSafeBindings();
  }

  Module created = new Module(engine, parent, cache, fullPath, module, exports, this, this.main);

  String[] split = Paths.splitPath(fullPath);
  String filename = split[split.length - 1];
  String dirname = fullPath.substring(0, Math.max(fullPath.length() - filename.length() - 1, 0));

  String previousFilename = (String) engine.get(ScriptEngine.FILENAME);
  // set filename before eval so file names/lines in
  // exceptions are accurate
  engine.put(ScriptEngine.FILENAME, fullPath);

  try {
    // This mimics how Node wraps module in a function. I used to pass a 2nd parameter
    // to eval to override global context, but it caused problems Object.create.
    //
    // The \n at the end is to take care of files ending with a comment
    ScriptObjectMirror function =
        (ScriptObjectMirror)
            engine.eval(
                "(function (exports, require, module, __filename, __dirname) {" + code + "\n})");
    function.call(created, created.exports, created, created.module, filename, dirname);
  } finally {
    engine.put(ScriptEngine.FILENAME, previousFilename);
  }

  // Scripts are free to replace the global exports symbol with their own, so we
  // reload it from the module object after compiling the code.
  created.exports = created.module.get("exports");

  created.setLoaded();
  return created;
}
 
Example 19
Source File: GremlinExecutor.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle.
 *
 * @param script the script to evaluate
 * @param language the language to evaluate it in
 * @param boundVars the bindings to evaluate in the context of the script
 * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process
 */
public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars,  final LifeCycle lifeCycle) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug("Preparing to evaluate script - {} - in thread [{}]", script, Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    // override the timeout if the lifecycle has a value assigned
    final long scriptEvalTimeOut = lifeCycle.getEvaluationTimeoutOverride().orElse(evaluationTimeout);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> evalFuture = new FutureTask<>(() -> {
        try {
            lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings);

            logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName());

            // do this weirdo check until the now deprecated ScriptEngines is gutted
            final Object o = gremlinScriptEngineManager.getEngineByName(lang).eval(script, bindings);

            // apply a transformation before sending back the result - useful when trying to force serialization
            // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some
            // transactional constraints
            final Object result = lifeCycle.getTransformResult().isPresent() ?
                    lifeCycle.getTransformResult().get().apply(o) : o;

            // a mechanism for taking the final result and doing something with it in the same thread, but
            // AFTER the eval and transform are done and that future completed.  this provides a final means
            // for working with the result in the same thread as it was eval'd
            if (lifeCycle.getWithResult().isPresent()) lifeCycle.getWithResult().get().accept(result);

            lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings);

            // the evaluationFuture must be completed after all processing as an exception in lifecycle events
            // that must raise as an exception to the caller who has the returned evaluationFuture. in other words,
            // if it occurs before this point, then the handle() method won't be called again if there is an
            // exception that ends up below trying to completeExceptionally()
            evaluationFuture.complete(result);
        } catch (Throwable ex) {
            final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

            // thread interruptions will typically come as the result of a timeout, so in those cases,
            // check for that situation and convert to TimeoutException
            if (root instanceof InterruptedException
                    || root instanceof TraversalInterruptedException
                    || root instanceof InterruptedIOException) {
                lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings);
                evaluationFuture.completeExceptionally(new TimeoutException(
                        String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]: %s", scriptEvalTimeOut, script, root.getMessage())));
            } else {
                lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root);
                evaluationFuture.completeExceptionally(root);
            }
        }

        return null;
    });

    final WeakReference<CompletableFuture<Object>> evaluationFutureRef = new WeakReference<>(evaluationFuture);
    final Future<?> executionFuture = executorService.submit(evalFuture);
    if (scriptEvalTimeOut > 0) {
        // Schedule a timeout in the thread pool for future execution
        final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> {
            if (executionFuture.cancel(true)) {
                final CompletableFuture<Object> ef = evaluationFutureRef.get();
                if (ef != null) {
                    ef.completeExceptionally(new TimeoutException(
                            String.format("Evaluation exceeded the configured 'evaluationTimeout' threshold of %s ms or evaluation was otherwise cancelled directly for request [%s]", scriptEvalTimeOut, script)));
                }
            }
        }, scriptEvalTimeOut, TimeUnit.MILLISECONDS);

        // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed with exception
        evaluationFuture.handleAsync((v, t) -> {
            if (!sf.isDone()) {
                logger.debug("Killing scheduled timeout on script evaluation - {} - as the eval completed (possibly with exception).", script);
                sf.cancel(true);
            }

            // no return is necessary - nothing downstream is concerned with what happens in here
            return null;
        }, scheduledExecutorService);
    }

    return evaluationFuture;
}
 
Example 20
Source File: GremlinScriptEngine.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Evaluates {@link Traversal} {@link Bytecode} against a traversal source in the global bindings of the
 * {@code ScriptEngine}.
 *
 * @param bytecode of the traversal to execute
 * @param traversalSource to execute the bytecode against which should be in the available bindings.
 */
public default Traversal.Admin eval(final Bytecode bytecode, final String traversalSource) throws ScriptException {
    final Bindings bindings = this.createBindings();
    bindings.putAll(bytecode.getBindings());
    return eval(bytecode, bindings, traversalSource);
}