Advertisement
Guest User

Untitled

a guest
May 28th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. package com.winterbe.react;
  2.  
  3. import jdk.nashorn.api.scripting.NashornScriptEngine;
  4.  
  5. import javax.script.ScriptEngineManager;
  6. import javax.script.ScriptException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.Reader;
  10. import java.util.List;
  11.  
  12. public class React {
  13.  
  14. private ThreadLocal<NashornScriptEngine> engineHolder = new ThreadLocal<NashornScriptEngine>() {
  15. @Override
  16. protected NashornScriptEngine initialValue() {
  17. NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
  18. try {
  19. nashornScriptEngine.eval(read("static/nashorn-polyfill.js"));
  20. nashornScriptEngine.eval(read("static/vendor/react.js"));
  21. nashornScriptEngine.eval(read("static/vendor/showdown.min.js"));
  22. nashornScriptEngine.eval(read("static/commentBox.js"));
  23. } catch (ScriptException e) {
  24. throw new RuntimeException(e);
  25. }
  26. return nashornScriptEngine;
  27. }
  28. };
  29.  
  30. public String renderCommentBox(List<Comment> comments) {
  31. try {
  32. Object html = engineHolder.get().invokeFunction("renderServer", comments);
  33. return String.valueOf(html);
  34. }
  35. catch (Exception e) {
  36. throw new IllegalStateException("failed to render react component", e);
  37. }
  38. }
  39.  
  40. private Reader read(String path) {
  41. InputStream in = getClass().getClassLoader().getResourceAsStream(path);
  42. return new InputStreamReader(in);
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement