Skip to content

Instantly share code, notes, and snippets.

@brdloush
Created April 18, 2015 18:20
Show Gist options
  • Save brdloush/cf9824ba2e2bf5c0f31a to your computer and use it in GitHub Desktop.
Save brdloush/cf9824ba2e2bf5c0f31a to your computer and use it in GitHub Desktop.
winterbe/spring-react-example modified to work in multithreaded environment
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment