-
Notifications
You must be signed in to change notification settings - Fork 197
/
React.java
44 lines (38 loc) · 1.56 KB
/
React.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.winterbe.react;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
public class React {
private ThreadLocal<NashornScriptEngine> engineHolder = new ThreadLocal<NashornScriptEngine>() {
@Override
protected NashornScriptEngine initialValue() {
NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
try {
nashornScriptEngine.eval(read("static/nashorn-polyfill.js"));
nashornScriptEngine.eval(read("static/vendor/react.js"));
nashornScriptEngine.eval(read("static/vendor/showdown.min.js"));
nashornScriptEngine.eval(read("static/commentBox.js"));
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return nashornScriptEngine;
}
};
public String renderCommentBox(List<Comment> comments) {
try {
Object html = engineHolder.get().invokeFunction("renderServer", comments);
return String.valueOf(html);
}
catch (Exception e) {
throw new IllegalStateException("failed to render react component", e);
}
}
private Reader read(String path) {
InputStream in = getClass().getClassLoader().getResourceAsStream(path);
return new InputStreamReader(in);
}
}