Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Override
- public boolean checkRequireExpression(Requireable candidate, AppContextModel contextModel) {
- try {
- String requireExpression = candidate.getRequire();
- if (StringUtils.isBlank(requireExpression)) {
- return true;
- } else {
- // If any properties in contextModel are Maps, we want to allow scripts to access their subproperties
- // with dot notation, but ScriptEngine and Bindings don't naturally handle this. Instead we will convert
- // all Map-type properties to JSON and use this to define objects directly within the ScriptEngine.
- // (Properties that are not Maps don't need this special treatment.)
- Bindings bindings = new SimpleBindings();
- Map<String, Object> mapProperties = new HashMap<String, Object>();
- for (Map.Entry<String, Object> e : contextModel.entrySet()) {
- if (e.getValue() instanceof Map) {
- mapProperties.put(e.getKey(), e.getValue());
- } else {
- bindings.put(e.getKey(), e.getValue());
- }
- }
- ObjectMapper j = new ObjectMapper();
- for (Map.Entry<String, Object> e : contextModel.entrySet()) {
- if (!(e.getValue() instanceof Map) && !"util".equals(e.getKey())) {
- javascriptEngine.eval("var " + e.getKey() + " = " + j.writeValueAsString(e.getValue()) + ";");
- }
- }
- ObjectMapper jackson = new ObjectMapper();
- for (Map.Entry<String, Object> e : mapProperties.entrySet()) {
- try {
- javascriptEngine.eval("var " + e.getKey() + " = " + jackson.writeValueAsString(e.getValue()) + ";");
- } catch (Exception ex) {
- StringBuilder extraInfo = new StringBuilder();
- extraInfo.append("type:").append(e.getValue().getClass().getName());
- if (e.getValue() instanceof Map) {
- Map<?, ?> map = (Map<?, ?>) e.getValue();
- extraInfo.append(" properties:");
- for (Map.Entry entry : map.entrySet()) {
- extraInfo.append(" ").append(entry.getKey().toString()).append(":").append(entry.getValue() == null ? "null" : entry.getValue().getClass().toString());
- }
- }
- log.error("Failed to set '" + e.getKey() + "' scope variable (" + extraInfo + ") while evaluating require check for " + candidate.getClass().getSimpleName().toLowerCase() + " " + candidate.getId(), ex);
- return false;
- }
- }
- return javascriptEngine.eval("(" + requireExpression + ") == true").equals(Boolean.TRUE);
- }
- } catch (Exception e) {
- log.error("Failed to evaluate 'require' check for extension " + candidate.getId(), e);
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment