Search in sources :

Example 1 with RuleNodeJsScriptEngine

use of org.thingsboard.server.service.script.RuleNodeJsScriptEngine in project thingsboard by thingsboard.

the class RuleChainController method testScript.

@ApiOperation(value = "Test JavaScript function", notes = TEST_JS_FUNCTION + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/ruleChain/testScript", method = RequestMethod.POST)
@ResponseBody
public JsonNode testScript(@ApiParam(value = "Test JS request. See API call description above.") @RequestBody JsonNode inputParams) throws ThingsboardException {
    try {
        String script = inputParams.get("script").asText();
        String scriptType = inputParams.get("scriptType").asText();
        JsonNode argNamesJson = inputParams.get("argNames");
        String[] argNames = objectMapper.treeToValue(argNamesJson, String[].class);
        String data = inputParams.get("msg").asText();
        JsonNode metadataJson = inputParams.get("metadata");
        Map<String, String> metadata = objectMapper.convertValue(metadataJson, new TypeReference<Map<String, String>>() {
        });
        String msgType = inputParams.get("msgType").asText();
        String output = "";
        String errorText = "";
        ScriptEngine engine = null;
        try {
            engine = new RuleNodeJsScriptEngine(getTenantId(), jsInvokeService, getCurrentUser().getId(), script, argNames);
            TbMsg inMsg = TbMsg.newMsg(msgType, null, new TbMsgMetaData(metadata), TbMsgDataType.JSON, data);
            switch(scriptType) {
                case "update":
                    output = msgToOutput(engine.executeUpdateAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS));
                    break;
                case "generate":
                    output = msgToOutput(engine.executeGenerateAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS));
                    break;
                case "filter":
                    boolean result = engine.executeFilterAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = Boolean.toString(result);
                    break;
                case "switch":
                    Set<String> states = engine.executeSwitchAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = objectMapper.writeValueAsString(states);
                    break;
                case "json":
                    JsonNode json = engine.executeJsonAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    output = objectMapper.writeValueAsString(json);
                    break;
                case "string":
                    output = engine.executeToStringAsync(inMsg).get(TIMEOUT, TimeUnit.SECONDS);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported script type: " + scriptType);
            }
        } catch (Exception e) {
            log.error("Error evaluating JS function", e);
            errorText = e.getMessage();
        } finally {
            if (engine != null) {
                engine.destroy();
            }
        }
        ObjectNode result = objectMapper.createObjectNode();
        result.put("output", output);
        result.put("error", errorText);
        return result;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) RuleNodeJsScriptEngine(org.thingsboard.server.service.script.RuleNodeJsScriptEngine) JsonNode(com.fasterxml.jackson.databind.JsonNode) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) RuleNodeJsScriptEngine(org.thingsboard.server.service.script.RuleNodeJsScriptEngine) ScriptEngine(org.thingsboard.rule.engine.api.ScriptEngine) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) TbMsg(org.thingsboard.server.common.msg.TbMsg) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 ApiOperation (io.swagger.annotations.ApiOperation)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)1 ScriptEngine (org.thingsboard.rule.engine.api.ScriptEngine)1 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)1 TbMsg (org.thingsboard.server.common.msg.TbMsg)1 TbMsgMetaData (org.thingsboard.server.common.msg.TbMsgMetaData)1 RuleNodeJsScriptEngine (org.thingsboard.server.service.script.RuleNodeJsScriptEngine)1