Example usage for javax.script Bindings put

List of usage examples for javax.script Bindings put

Introduction

In this page you can find the example usage for javax.script Bindings put.

Prototype

public Object put(String name, Object value);

Source Link

Document

Set a named value.

Usage

From source file:org.red5.server.script.rhino.RhinoScriptUtils.java

/**
 * Create a new Rhino-scripted object from the given script source.
 * /*w  w  w  .j  a  v a2 s  .c  om*/
 * @param scriptSource
 *            the script source text
 * @param interfaces
 *            the interfaces that the scripted Java object is supposed to
 *            implement
 * @param extendedClass
 * @return the scripted Java object
 * @throws ScriptCompilationException
 *             in case of Rhino parsing failure
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static Object createRhinoObject(String scriptSource, Class[] interfaces, Class extendedClass)
        throws ScriptCompilationException, IOException, Exception {
    if (log.isDebugEnabled()) {
        log.debug("Script Engine Manager: " + mgr.getClass().getName());
    }
    ScriptEngine engine = mgr.getEngineByExtension("js");
    if (null == engine) {
        log.warn("Javascript is not supported in this build");
    }
    // set engine scope namespace
    Bindings nameSpace = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    // add the logger to the script
    nameSpace.put("log", log);
    // compile the wrapper script
    CompiledScript wrapper = ((Compilable) engine).compile(jsWrapper);
    nameSpace.put("Wrapper", wrapper);

    // get the function name ie. class name / ctor
    String funcName = RhinoScriptUtils.getFunctionName(scriptSource);
    if (log.isDebugEnabled()) {
        log.debug("New script: " + funcName);
    }
    // set the 'filename'
    nameSpace.put(ScriptEngine.FILENAME, funcName);

    if (null != interfaces) {
        nameSpace.put("interfaces", interfaces);
    }

    if (null != extendedClass) {
        if (log.isDebugEnabled()) {
            log.debug("Extended: " + extendedClass.getName());
        }
        nameSpace.put("supa", extendedClass.newInstance());
    }
    //
    // compile the script
    CompiledScript script = ((Compilable) engine).compile(scriptSource);
    // eval the script with the associated namespace
    Object o = null;
    try {
        o = script.eval();
    } catch (Exception e) {
        log.error("Problem evaluating script", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Result of script call: " + o);
    }
    // script didnt return anything we can use so try the wrapper
    if (null == o) {
        wrapper.eval();
    } else {
        wrapper.eval();
        o = ((Invocable) engine).invokeFunction("Wrapper", new Object[] { engine.get(funcName) });
        if (log.isDebugEnabled()) {
            log.debug("Result of invokeFunction: " + o);
        }
    }
    return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), interfaces,
            new RhinoObjectInvocationHandler(engine, o));
}

From source file:org.jahia.tools.patches.GroovyPatcher.java

public static void executeScripts(Resource[] scripts) {
    long timer = System.currentTimeMillis();
    logger.info("Found new patch scripts {}. Executing...", StringUtils.join(scripts));

    for (Resource script : scripts) {
        try {/* w w  w  .j  a  va 2 s  .com*/
            long timerSingle = System.currentTimeMillis();
            String scriptContent = getContent(script);
            if (StringUtils.isNotEmpty(scriptContent)) {
                ScriptEngine engine = getEngine();
                ScriptContext ctx = new SimpleScriptContext();
                ctx.setWriter(new StringWriter());
                Bindings bindings = engine.createBindings();
                bindings.put("log", new LoggerWrapper(logger, logger.getName(), ctx.getWriter()));
                ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

                engine.eval(scriptContent, ctx);
                String result = ((StringWriter) ctx.getWriter()).getBuffer().toString();
                logger.info("Execution of script {} took {} ms with result:\n{}", new String[] {
                        script.toString(), String.valueOf(System.currentTimeMillis() - timerSingle), result });
            } else {
                logger.warn("Content of the script {} is either empty or cannot be read. Skipping.");
            }
            rename(script, ".installed");
        } catch (Exception e) {
            logger.error("Execution of script " + script + " failed with error: " + e.getMessage(), e);
            rename(script, ".failed");
        }
    }

    logger.info("Execution took {} ms", (System.currentTimeMillis() - timer));
}

From source file:tk.tomby.tedit.services.ScriptingManager.java

/**
 * DOCUMENT ME!/*from   ww w .  j  a va  2  s. c  o m*/
 *
 * @param lang DOCUMENT ME!
 * @param script DOCUMENT ME!
 * @param buffer DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public static Object eval(String lang, String script, IBuffer buffer) {
    Object result = null;

    try {
        ScriptEngine engine = manager.getEngineByName(lang);

        if (buffer != null) {
            Bindings bindings = engine.createBindings();
            bindings.put("buffer", new BufferDecorator(buffer));
            engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        }

        result = engine.eval(script);
    } catch (ScriptException e) {
        log.error("error in script excution", e);
    }

    return result;
}

From source file:org.netbeans.jcode.core.util.FileUtil.java

private static void expandTemplate(InputStream template, Map<String, Object> values, Charset targetEncoding,
        Writer w) throws IOException {
    //        Charset sourceEnc = FileEncodingQuery.getEncoding(template);
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);//from  w  ww  .  ja  va2s.  c o  m
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    Reader is = null;
    try {
        eng.getContext().setWriter(w);
        is = new InputStreamReader(template);
        eng.eval(is);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:tk.tomby.tedit.services.ScriptingManager.java

/**
 * DOCUMENT ME!/* w  ww  .  j a  v  a 2 s. com*/
 *
 * @param lang DOCUMENT ME!
 * @param script DOCUMENT ME!
 * @param buffer DOCUMENT ME!
 */
public static Object exec(String lang, InputStream stream, IBuffer buffer) {
    Object result = null;
    BufferedReader reader = null;

    try {
        ScriptEngine engine = manager.getEngineByName(lang);

        reader = new BufferedReader(new InputStreamReader(stream));

        if (buffer != null) {
            Bindings bindings = engine.createBindings();
            bindings.put("buffer", new BufferDecorator(buffer));
            engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        }

        result = engine.eval(reader);

    } catch (ScriptException e) {
        log.error("error in script excution", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.warn("error closing reader", e);
            }
        }
    }

    return result;
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * Injects the values provided in the bindings into the {@link ScriptContext#ENGINE_SCOPE engine scope}
 * of the provided script engine.//from   ww w  . ja  v  a 2s. c  o m
 * 
 * @param engine the engine
 * @param bindings the bindings
 * @param deleteExistingBindings true if the existing bindings should be replaced by the provided ones, false
 * if the provided bindings should be added to the existing ones (possibly overwriting bindings with the same name).
 */
public static void injectStandardBindings(ScriptEngine engine, StandardBindings bindings,
        boolean deleteExistingBindings) {
    bindings.preInject(engine);

    Bindings engineBindings = deleteExistingBindings ? engine.createBindings()
            : engine.getBindings(ScriptContext.ENGINE_SCOPE);

    for (Map.Entry<String, Object> entry : bindings.entrySet()) {
        engineBindings.put(entry.getKey(), entry.getValue());
    }

    engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);

    bindings.postInject(engine);
}

From source file:io.github.jeddict.jcode.util.FileUtil.java

public static void expandTemplate(Reader reader, Writer writer, Map<String, Object> values,
        Charset targetEncoding) throws IOException {
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);//  w  w w  .  jav  a  2  s.co m
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    try {
        eng.getContext().setWriter(writer);
        eng.eval(reader);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.netbeans.jcode.core.util.FileUtil.java

public static String expandTemplate(String template, 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);/* w  ww .j av  a2 s  .com*/
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new StringReader(template);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();

}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * //w  w w. ja  va 2  s . c o m
 * @param command
 * @return
 */
public static <T> Object interprete(String command, Hstore hstore, AbstractResult<T> object,
        boolean useRecursion, ResultOptions resultOptions) {

    if (jsEngine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        jsEngine = sem.getEngineByName("JavaScript");
        System.out.println("JS Engine: " + jsEngine.getClass().getCanonicalName());
        Bindings b = jsEngine.createBindings();
        b.put("nn", new SystemApi());
        jsEngine.setBindings(b, ScriptContext.GLOBAL_SCOPE);
    }

    command = command.replace("\\%", "{PERCENT}");

    Pattern p;
    if (!useRecursion) {
        p = PATTERN_COMMAND;
    } else {
        p = PATTERN_RECURSIVE_COMMAND;

        Matcher m = p.matcher(command);
        while (m.find()) {
            String replace = m.group(0);
            //System.out.println("found: " + replace);
            String toReplace = String.valueOf(interprete(replace, hstore, object, false, resultOptions));
            //System.out.println("replacing: " + m.group(0) + " -> " + toReplace);
            command = command.replace(m.group(0), toReplace);
        }

        command = command.replace("{PERCENT}", "%");
        return command;
    }

    Matcher m = p.matcher(command);
    command = command.replace("{PERCENT}", "%");

    String scriptCommand;
    String[] args;

    if (m.find()) {
        if (m.groupCount() != 2) {
            return command;
        }
        scriptCommand = m.group(1);

        if (!COMMAND_EVAL.equals(scriptCommand)) {
            args = m.group(2).trim().split("\\s");
        } else {
            args = new String[] { m.group(2).trim() };
        }
    } else {
        return command;
    }

    try {
        if (COMMAND_RANDOM.equals(scriptCommand)) {
            return random(args);
        } else if (COMMAND_PARAM.equals(scriptCommand)) {
            return parse(args, hstore, object, resultOptions);
        } else if (COMMAND_EVAL.equals(scriptCommand)) {
            return eval(args, hstore, object);
        } else if (COMMAND_RANDOM_URL.equals(scriptCommand)) {
            return randomUrl(args);
        } else {
            return command;
        }
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:io.github.jeddict.jcode.util.FileUtil.java

public static String expandTemplate(String inputTemplatePath, Map<String, Object> values) {
    InputStream contentStream = loadResource(inputTemplatePath);
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);//ww w. j  ava 2  s . c o m
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new InputStreamReader(contentStream);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}