Example usage for jdk.nashorn.api.scripting ScriptUtils parse

List of usage examples for jdk.nashorn.api.scripting ScriptUtils parse

Introduction

In this page you can find the example usage for jdk.nashorn.api.scripting ScriptUtils parse.

Prototype

public static String parse(final String code, final String name, final boolean includeLoc) 

Source Link

Document

Returns AST as JSON compatible string.

Usage

From source file:com.siemens.ct.exi.javascript.JStoAST.java

License:Open Source License

public static String getAST(String jsCode) throws IOException, EXIException {
    // http://sites.psu.edu/robertbcolton/2015/07/31/java-8-nashorn-script-engine/
    /*/*from www .  ja va2  s .c om*/
     * This JSON encoding provided by Nashorn is compliant with the
     * community standard JavaScript JSON AST model popularized by Mozilla.
     * https://developer.mozilla.org/en-US/docs/Mozilla/Projects/
     * SpiderMonkey/Parser_API
     */
    // Additionally the OpenJDK project is developing a public interface for
    // Java 9 that allows AST traversal in a more standard and user friendly
    // way.
    // String code = "function a() { var b = 5; } function c() { }";
    // String sin = "./data//jquery.min.js";
    // String sin = "./data/animals.js";
    // String code = new String(Files.readAllBytes(Paths.get(sin)));

    // ScriptEngine engine = new
    // ScriptEngineManager().getEngineByName("nashorn");
    // engine.eval("print('Hello World!');");
    // load jquery source file
    // engine.eval("load('" +
    // "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" +
    // "');");
    // engine.eval("load('" + sin + "');");

    Options options = new Options("nashorn");
    options.set("anon.functions", true);
    options.set("parse.only", true);
    options.set("scripting", true);

    ErrorManager errors = new ErrorManager();
    Context contextm = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    Context.setGlobal(contextm.createGlobal());
    String jsonAST = ScriptUtils.parse(jsCode, "<unknown>", false);

    return jsonAST;
}

From source file:me.finalchild.nashornbukkit.util.BukkitImporter.java

License:MIT License

public static Set<String> getUsedIdentifiers(Path file) throws IOException {
    Set<String> result = new HashSet<>();
    String text = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
    String json;//from   ww  w  . ja v a2 s  . c om

    Options options = new Options("");
    ErrorManager errorManager = new ErrorManager();
    Context context = new Context(options, errorManager, NashornBukkit.class.getClassLoader());
    Context.setGlobal(context.createGlobal());
    json = ScriptUtils.parse(text, file.getFileName().toString(), false);

    JsonParser jsonParser = new JsonParser();
    JsonObject rootObj = jsonParser.parse(json).getAsJsonObject();

    addUsedIdentifiers(rootObj, result);
    return result;
}