wikumW

Untitled

Nov 23rd, 2023
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. @Override
  2. public boolean checkRequireExpression(Requireable candidate, AppContextModel contextModel) {
  3. try {
  4. String requireExpression = candidate.getRequire();
  5. if (StringUtils.isBlank(requireExpression)) {
  6. return true;
  7. } else {
  8. // If any properties in contextModel are Maps, we want to allow scripts to access their subproperties
  9. // with dot notation, but ScriptEngine and Bindings don't naturally handle this. Instead we will convert
  10. // all Map-type properties to JSON and use this to define objects directly within the ScriptEngine.
  11. // (Properties that are not Maps don't need this special treatment.)
  12. Bindings bindings = new SimpleBindings();
  13. Map<String, Object> mapProperties = new HashMap<String, Object>();
  14. for (Map.Entry<String, Object> e : contextModel.entrySet()) {
  15. if (e.getValue() instanceof Map) {
  16. mapProperties.put(e.getKey(), e.getValue());
  17. } else {
  18. bindings.put(e.getKey(), e.getValue());
  19. }
  20. }
  21.  
  22. ObjectMapper j = new ObjectMapper();
  23. for (Map.Entry<String, Object> e : contextModel.entrySet()) {
  24. if (!(e.getValue() instanceof Map) && !"util".equals(e.getKey())) {
  25. javascriptEngine.eval("var " + e.getKey() + " = " + j.writeValueAsString(e.getValue()) + ";");
  26. }
  27. }
  28.  
  29. ObjectMapper jackson = new ObjectMapper();
  30. for (Map.Entry<String, Object> e : mapProperties.entrySet()) {
  31. try {
  32. javascriptEngine.eval("var " + e.getKey() + " = " + jackson.writeValueAsString(e.getValue()) + ";");
  33. } catch (Exception ex) {
  34. StringBuilder extraInfo = new StringBuilder();
  35. extraInfo.append("type:").append(e.getValue().getClass().getName());
  36. if (e.getValue() instanceof Map) {
  37. Map<?, ?> map = (Map<?, ?>) e.getValue();
  38. extraInfo.append(" properties:");
  39. for (Map.Entry entry : map.entrySet()) {
  40. extraInfo.append(" ").append(entry.getKey().toString()).append(":").append(entry.getValue() == null ? "null" : entry.getValue().getClass().toString());
  41. }
  42. }
  43. log.error("Failed to set '" + e.getKey() + "' scope variable (" + extraInfo + ") while evaluating require check for " + candidate.getClass().getSimpleName().toLowerCase() + " " + candidate.getId(), ex);
  44. return false;
  45. }
  46. }
  47.  
  48. return javascriptEngine.eval("(" + requireExpression + ") == true").equals(Boolean.TRUE);
  49. }
  50.  
  51. } catch (Exception e) {
  52. log.error("Failed to evaluate 'require' check for extension " + candidate.getId(), e);
  53. return false;
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment