8

This might not be practical, but I have it as a task. I have an opened ServerSocket in java. Now I want to read a file which contains html and javascript, and output the javascript result to the browser. So this way, I would be evaluating the javascript on the server side. So I want what is inside to be evaluated.

I tried this to test, it worked but it has some issues, for example it prints the message to System.out. And engine.eval("print('Welocme to java worldddd')"); does not return a String so that I can output it to the outputstream of the socket:

import javax.script.*;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
     // evaluate JavaScript code from String
     engine.eval("print('Welocme to java worldddd')");
     //engine.eval("a");
} catch (ScriptException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Abdul Rahim Haddad
  • 689
  • 1
  • 8
  • 14

4 Answers4

12

You can get the output of the script (what is printed with print() in JavaScript) by setting the writer on the ScriptContext:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
ScriptContext context = engine.getContext();
StringWriter writer = new StringWriter();
context.setWriter(writer);

engine.eval("print('Welocme to java worldddd')");

String output = writer.toString();

System.out.println("Script output: " + output);
Jesper
  • 202,709
  • 46
  • 318
  • 350
7

I've solved this in the past by creating a javascript function inside eval() and invoking it to get a result:

import javax.script.*;
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
try {
     // evaluate JavaScript code from String
     engine.eval("function sum(a,b){ return a + b;}");
     System.out.println(((Invocable) engine).invokeFunction("sum", new Object[]{10,20}));
} catch (ScriptException ex) {
     Logger.getLogger(doComms.class.getName()).log(Level.SEVERE, null, ex);
}

Note that the function name in invokeFunction (first argument) should match the one declared previously.

Keep in mind that this might be dangerous. Do you have absolute control as to where the javascript code comes from? Otherwise a simple while(true){} could be pretty catastrophic for your server.

Andre
  • 3,874
  • 3
  • 35
  • 50
0
public static String convertEnumToJson(Class<? extends Enum<?>> cls) throws ScriptException, NoSuchMethodException, IllegalAccessException {
    List<Map<String, Object>> map = createMap(Colors.class);
    return createJson(map);
}

public static List<Map<String, Object>> createMap(Class<? extends Enum<?>> cls) throws IllegalAccessException {
    List<Map<String, Object>> res = new ArrayList<>();

    for (Enum<?> item : cls.getEnumConstants()) {
        Map<String, Object> map = new LinkedHashMap<>();

        for (Field field : item.getClass().getDeclaredFields()) {
            if (field.getType() != item.getClass() && !"$VALUES".equals(field.getName())) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(item));
            }
        }

        res.add(map);
    }

    return res;
}

// It's better to use Jackson or similar lib for read/write json
public static <T> String createJson(T obj) throws ScriptException, NoSuchMethodException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.eval("function sum(a){ return a;}");
    return ((Invocable)engine).invokeFunction("sum", obj).toString();
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

If someone stumbles upon this page recently like I did, please note that Nashorn has been deprecated according to this.

There are other alternatives available that you can explore.

Vikram
  • 170
  • 1
  • 12