Example usage for jdk.nashorn.api.scripting ScriptObjectMirror get

List of usage examples for jdk.nashorn.api.scripting ScriptObjectMirror get

Introduction

In this page you can find the example usage for jdk.nashorn.api.scripting ScriptObjectMirror get.

Prototype

@Override
    public Object get(final Object key) 

Source Link

Usage

From source file:JavaScriptTest.java

public static void main4(String[] args) throws ScriptException {
    DataMgr.createInstance(null);/*from  ww w.  ja  va2s .  c  om*/
    DataObject user = new DataObject();
    RuleEngineProvider rep = RuleEngineProvider.getInstance();
    ScriptEngine engine = rep.getEngine("_suri:Cloudino:CloudRule:1", user);
    engine = rep.getEngine("_suri:Cloudino:CloudRule:2", user);
    engine = rep.getEngine("_suri:Cloudino:CloudRule:3", user);
    engine = rep.getEngine("_suri:Cloudino:CloudRule:4", user);
    engine = rep.getEngine("_suri:Cloudino:CloudRule:5", user);
    engine = rep.getEngine("_suri:Cloudino:CloudRule:6", user);
    ScriptObjectMirror bind = ((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE));
    ScriptEngine[] arr1 = useLotsOfMemory();
    System.gc();
    ((ScriptObjectMirror) ((ScriptObjectMirror) bind.get("events")).getSlot(0)).callMember("funct", "hola");
    arr1 = useLotsOfMemory();
    arr1[500].eval("print('memorias....')");
    arr1 = null;
    System.gc();
    engine = rep.getEngine("_suri:Cloudino:CloudRule:1", user);
    bind = ((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE));
    ((ScriptObjectMirror) ((ScriptObjectMirror) bind.get("events")).getSlot(0)).callMember("funct", "hola");
}

From source file:JavaScriptTest.java

public static void main3(String[] args) throws Exception {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    //engine.eval("function p(x){print(x);};var c=function(x){print(x);};var i=function(){x++;};var x=10;var cap=function(z){return function(msg){print(msg+\" \"+z);}}(x);");

    String script = "" + "var events=[];\n" + "var msg;\n" + "{ \n" + "   var _cntx=\"contx1\"; \n"
            + "   events.push({cntx:_cntx,type:\"cdino_ondevice_message\",funct:function(msg){print(msg);},params:{topic:\"topic\"}});\n"
            + "}";
    engine.eval(script);//from   ww w  .  jav a  2s .  c om
    ScriptObjectMirror bind = ((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE));
    //bind.callMember("i");
    //bind.callMember("cap","hola");

    String txt = serialize(bind);
    System.out.println(txt);

    //System.out.println(xml);
    //        long time=System.currentTimeMillis();
    //        for(int x=0;x<1000;x++)
    //        {
    //            engine = factory.getEngineByName("JavaScript");
    //            engine.eval(txt);
    //            bind=((ScriptObjectMirror)engine.getBindings(ScriptContext.ENGINE_SCOPE));
    //            bind.callMember("i");
    ////            bind=(ScriptObjectMirror)engine.createBindings();
    ////            bind.eval(txt);
    ////            bind.callMember("i");
    //            txt=serialize(bind);
    //        }
    //        System.out.println("Time:"+(System.currentTimeMillis()-time));
    engine = factory.getEngineByName("JavaScript");
    engine.eval(txt);

    bind = ((ScriptObjectMirror) engine.getBindings(ScriptContext.ENGINE_SCOPE));

    ((ScriptObjectMirror) ((ScriptObjectMirror) bind.get("events")).getSlot(0)).callMember("funct", "hola");

    //bind.callMember("i");
    //bind.callMember("cap","hola");
    //System.out.println(engine.getFactory().getParameter("THREADING"));
    txt = serialize(bind);
    System.out.println(txt);
}

From source file:com.microchip.mplab.nbide.embedded.arduino.importer.ArduinoBuilderRunner.java

License:Open Source License

private List<Path> findMainLibraryPaths() throws ScriptException, FileNotFoundException {
    LOGGER.info("Looking for main library paths");

    Path includesCachePath = Paths.get(preprocessDirPath.toAbsolutePath().toString(), "includes.cache");
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js");
    ScriptObjectMirror mirror = (ScriptObjectMirror) scriptEngine
            .eval(new FileReader(includesCachePath.toString()));
    List<Path> libraryPaths = new ArrayList<>();
    mirror.entrySet().forEach(e -> {/*w w  w .j  a v a 2 s  .  c  om*/
        if (e.getValue() instanceof ScriptObjectMirror) {
            ScriptObjectMirror m = (ScriptObjectMirror) e.getValue();
            Object sourceFile = m.get("Sourcefile");
            if (sourceFile != null && !sourceFile.toString().trim().isEmpty()) {
                String entry = m.get("Includepath").toString();
                if (!entry.trim().isEmpty()) {
                    if (entry.endsWith(File.separator + "src")) {
                        entry = entry.substring(0, entry.length() - 4);
                    }
                    LOGGER.log(Level.INFO, "Found library path: {0}", entry);
                    libraryPaths.add(Paths.get(entry));
                }
            }
        }
    });

    if (libraryPaths.isEmpty()) {
        LOGGER.info("No main library dependencies found");
    }

    return libraryPaths;
}

From source file:com.qwazr.library.process.ProcessTool.java

License:Apache License

/**
 * Call this command from Javascript to execute a local binary.
 * <pre>// www . j a  v a 2 s.com
 * {@code
 * {
 *     "working_directory": "/path/to/directory",
 *     "environment_variables": {
 *         "lang": "de",
 *         "hello": "world"
 *     },
 *     "commands": ["convert", "my.jpg", "my.gif"],
 *     "output_file": "/path/to/out.log",
 *     "error_file": "/path/to/in.log"
 * }
 * }
 * </pre>
 *
 * @param som The Javascript object
 * @return the launched process
 * @throws ScriptException if any Javascript error occurs
 * @throws IOException     if any I/O error occurs
 */
public Process execute(final ScriptObjectMirror som) throws ScriptException, IOException {

    // Extract the working director
    String workingDirectory = (String) som.get("working_directory");
    final File workingDirectoryFile = workingDirectory != null ? new File(workingDirectory) : null;

    // Extracts the arguments
    ScriptObjectMirror jsCommands = (ScriptObjectMirror) som.get("commands");
    final List<String> commands;
    if (jsCommands != null) {
        commands = new ArrayList<>(jsCommands.size());
        ScriptUtils.fillStringCollection(jsCommands, commands);
    } else
        commands = null;

    // Set the environment variables
    ScriptObjectMirror jsEnv = (ScriptObjectMirror) som.get("environment_variables");
    final Map<String, String> envVars;
    if (jsEnv != null) {
        envVars = new LinkedHashMap<String, String>();
        ScriptUtils.fillStringMap(jsEnv, envVars);
    } else
        envVars = null;

    // Set the output and error files
    String outputPath = (String) som.get("output_file");
    final File outputFile = outputPath != null ? new File(outputPath) : null;
    String errorPath = (String) som.get("error_file");
    final File errorFile = errorPath != null ? new File(errorPath) : null;

    return execute(workingDirectoryFile, commands, envVars, outputFile, errorFile);
}

From source file:com.qwazr.tools.ProcessTool.java

License:Apache License

/**
 * Call this command from Javascript to execute a local binary.
 * <pre>/*  ww w.j  a va 2s  .  com*/
 * {@code
 * {
 *     "working_directory": "/path/to/directory",
 *     "environment_variables": {
 *         "lang": "de",
 *         "hello": "world"
 *     },
 *     "commands": ["convert", "my.jpg", "my.gif"],
 *     "output_file": "/path/to/out.log",
 *     "error_file": "/path/to/in.log"
 * }
 * }
 * </pre>
 *
 * @param som The Javascript object
 * @return the launched process
 * @throws ScriptException if any Javascript error occurs
 * @throws IOException     if any I/O error occurs
 */
public Process execute(ScriptObjectMirror som) throws ScriptException, IOException {

    // Extract the working directoru
    String workingDirectory = (String) som.get("working_directory");
    final File workingDirectoryFile = workingDirectory != null ? new File(workingDirectory) : null;

    // Extracts the arguments
    ScriptObjectMirror jsCommands = (ScriptObjectMirror) som.get("commands");
    final List<String> commands;
    if (jsCommands != null) {
        commands = new ArrayList<String>(jsCommands.size());
        ScriptUtils.fillStringCollection(jsCommands, commands);
    } else
        commands = null;

    // Set the environment variables
    ScriptObjectMirror jsEnv = (ScriptObjectMirror) som.get("environment_variables");
    final Map<String, String> envVars;
    if (jsEnv != null) {
        envVars = new LinkedHashMap<String, String>();
        ScriptUtils.fillStringMap(jsEnv, envVars);
    } else
        envVars = null;

    // Set the output and error files
    String outputPath = (String) som.get("output_file");
    final File outputFile = outputPath != null ? new File(outputPath) : null;
    String errorPath = (String) som.get("error_file");
    final File errorFile = errorPath != null ? new File(errorPath) : null;

    return execute(workingDirectoryFile, commands, envVars, outputFile, errorFile);
}

From source file:com.threecrickets.jvm.json.nashorn.ScriptObjectMirrorEncoder.java

License:Mozilla Public License

public void encode(Object object, JsonContext context) throws IOException {
    ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) object;

    Object wrapped = ScriptObjectMirror.unwrap(scriptObjectMirror, Context.getGlobal());
    if (!(wrapped instanceof ScriptObjectMirror)) {
        context.encode(wrapped);/*from   ww  w .  jav a2  s .  com*/
        return;
    }

    if (scriptObjectMirror.isArray()) {
        context.out.append('[');

        int length = scriptObjectMirror.size();
        if (length > 0) {
            context.newline();

            for (int i = 0; i < length; i++) {
                Object value = scriptObjectMirror.getSlot(i);

                context.indentNested();
                context.nest().encode(value);

                if (i < length - 1)
                    context.comma();
            }

            context.newline();
            context.indent();
        }

        context.out.append(']');
    } else {
        context.out.append('{');

        String[] keys = scriptObjectMirror.getOwnKeys(true);
        int length = keys.length;
        if (length > 0) {
            context.newline();

            for (int i = 0; i < length; i++) {
                String key = keys[i];
                Object value = scriptObjectMirror.get(key);

                context.indentNested();
                context.quoted(key);
                context.colon();
                context.nest().encode(value);

                if (i < length - 1)
                    context.comma();
            }

            context.newline();
            context.indent();
        }

        context.out.append('}');
    }
}

From source file:com.threecrickets.jvm.json.nashorn.util.NashornNativeUtil.java

License:Mozilla Public License

public static Object unwrap(Object object) {
    // Nashorn creates these mirrors when they pass through certain
    // boundaries. However, we are only allowed to unwrap them from the same
    // global context in which they were wrapped. We will try to unwrap them
    // here, but if that doesn't work we will just create a shallow clone.
    // The clone won't function like the original, but will be good enough
    // for our purposes here.

    object = ScriptObjectMirror.unwrap(object, Context.getGlobal());
    if (object instanceof ScriptObjectMirror) {
        ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) object;
        ScriptObject scriptObject = NashornNativeUtil.newObject();
        for (String key : scriptObjectMirror.getOwnKeys(true)) {
            Object value = scriptObjectMirror.get(key);
            scriptObject.put(key, value, false);
        }//  w w  w. j  av a 2  s.  c  om
        object = scriptObject;
    }
    return object;
}

From source file:com.viddu.handlebars.HandlebarsNashornTest.java

License:Apache License

@Test
public void testRegisterHelper() throws HandlebarsException {
    handlebars.registerHelper("link", (ScriptObjectMirror context, ScriptObjectMirror options) -> {
        //            return (String) options.callMember("fn", context);
        String url = (String) context.get("url");
        String name = (String) context.get("name");
        return "<a href=\"" + url + "\">" + name + "</a>";
    });//w  w w.jav a  2 s  . c  o  m
    String template = "{{#link myLink}}{{/link}}";
    String myLink = "{\"myLink\":{\"url\":\"http://www.google.com\", \"name\":\"Google\"}}";
    String result = handlebars.render(template, myLink);
    logger.debug("Result:{}", result);
    assertThat(result, equalTo("<a href=\"http://www.google.com\">Google</a>"));
}

From source file:hmi.flipper.behaviourselection.template.value.AbstractValue.java

License:BSD License

private Object js2Object(Object jsResult) {
    if (jsResult instanceof ScriptObjectMirror) {
        ScriptObjectMirror jsObject = (ScriptObjectMirror) jsResult;
        if (jsObject.size() > 0 && jsObject.containsKey("0")) {
            List list = new DefaultList();
            for (int i = 0; i < jsObject.size(); i++) {
                Object toAdd = js2Object(jsObject.get("" + i));
                if (toAdd == null) {
                    break; // not a integer valued list
                }/*from   www . jav a  2s.  c  o  m*/
                if (toAdd instanceof Double) {
                    list.addItemEnd((Double) toAdd);
                } else if (toAdd instanceof Integer) {
                    list.addItemEnd((Integer) toAdd);
                } else if (toAdd instanceof List) {
                    list.addItemEnd((List) toAdd);
                } else if (toAdd instanceof Record) {
                    list.addItemEnd((Record) toAdd);
                } else {
                    list.addItemEnd(toAdd.toString());
                }
            }
            if (list.size() == ((ScriptObjectMirror) jsObject).size()) {
                return list;
            }
        }
        Record record = new DefaultRecord();
        for (Entry<String, Object> ent : jsObject.entrySet()) {
            record.set(ent.getKey(), js2Object(ent.getValue()));
        }
        return record;
    } else if (jsResult instanceof Long || jsResult instanceof Double || jsResult instanceof Float) {
        if (jsResult instanceof Long) {
            return ((Long) jsResult).doubleValue();
        } else if (jsResult instanceof Float) {
            return ((Long) jsResult).floatValue();
        } else {
            return ((Double) jsResult);
        }
    } else if (jsResult instanceof Integer) {
        return (Integer) jsResult;
    } else if (jsResult instanceof String) {
        return (String) jsResult;
    }
    System.err.println("Could not parse JavaScript result to eligible DefaultRecord type! Type was: "
            + jsResult.getClass());
    return jsResult.toString();
}

From source file:IDE.SyntaxTree.NewEmptyJUnitTest.java

@Test
public void hello() throws ScriptException {
    //jdk.nashorn.api.
    try {/* ww w . j a v a2s .c om*/
        String input = readServerFile(new File("c:\\Projects\\JWeb\\www\\Controller\\indexController.jap"));
        ScriptEngineManager engineManager = new ScriptEngineManager();
        NashornScriptEngine engine = (NashornScriptEngine) engineManager.getEngineByName("nashorn");
        engine.eval("load(\"nashorn:parser.js\")");
        // engine.eval("var tree = Java.type(\"com.sun.source.tree.CompilationUnitTree\")");
        //  engine.eval("tree = parse(\"function Test(){return 1;}\")");

        ScriptObjectMirror sss = (ScriptObjectMirror) engine.invokeFunction("parse", input);
        ScriptObjectMirror RootBody = (ScriptObjectMirror) ((ScriptObjectMirror) sss.get("body")).get("0");

        Parse(RootBody, 0);

        engine.put("fff", sss);

        engine.eval("var empty = [];" + "for(var index in fff['body'][0]){    " + "  /*empty.push(index);*/ "
                + "for(var index2 in fff['body'][0][index]){empty.push(index2);}" + "}" + " ");
        String sss2 = (String) engine.eval("JSON.stringify( empty)");

        //  com.sun.source.tree.CompilationUnitTree
        // sss
        // engine.eval("var ast = parse(\"function Test(){ return 1;}\")");
        System.out.println(sss2);
    } catch (IOException | NoSuchMethodException ex) {
        Logger.getLogger(NewEmptyJUnitTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}