Search in sources :

Example 1 with MangoJavaScriptResult

use of com.infiniteautomation.mango.util.script.MangoJavaScriptResult in project ma-core-public by infiniteautomation.

the class MangoJavaScriptService method executeScript.

/**
 * The preferred way to execute a script
 */
public MangoJavaScriptResult executeScript(MangoJavaScript vo, ScriptPointValueSetter setter) throws ValidationException, PermissionException {
    PermissionHolder user = Common.getUser();
    ensureValid(vo);
    MangoJavaScriptResult result = new MangoJavaScriptResult();
    final Writer scriptOut;
    final PrintWriter scriptWriter;
    if (vo.isReturnLogOutput()) {
        scriptOut = new StringWriter();
        scriptWriter = new PrintWriter(scriptOut);
    } else {
        NullWriter writer = new NullWriter();
        scriptWriter = new NullPrintWriter(writer);
        scriptOut = writer;
    }
    try {
        try (ScriptLogExtender scriptLog = new ScriptLogExtender("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter, vo.getLog(), vo.isCloseLog())) {
            CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, setter, scriptLog, result, this, pointValueDao, pointValueCache);
            script.compile(vo.getScript(), vo.isWrapInFunction());
            script.initialize(vo.getContext());
            long time = Common.timer.currentTimeMillis();
            runAs.runAsCallable(script.getPermissionHolder(), () -> {
                if (vo.getResultDataType() != null) {
                    script.execute(time, time, vo.getResultDataType());
                } else {
                    script.execute(time, time);
                }
                return null;
            });
        }
    } catch (ScriptError e) {
        // The script exception should be clean as both compile() and execute() clean it
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage(), e.getLineNumber(), e.getColumnNumber()));
    } catch (ResultTypeException | DataPointStateException e) {
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
    } catch (Exception e) {
        result.addError(new MangoJavaScriptError(e.getMessage()));
    } finally {
        if (vo.isReturnLogOutput())
            result.setScriptOutput(scriptOut.toString());
    }
    return result;
}
Also used : MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) NullWriter(com.serotonin.io.NullWriter) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) NullWriter(com.serotonin.io.NullWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter) PrintWriter(java.io.PrintWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter)

Example 2 with MangoJavaScriptResult

use of com.infiniteautomation.mango.util.script.MangoJavaScriptResult in project ma-core-public by infiniteautomation.

the class SetPointHandlerRT method eventInactive.

@Override
public void eventInactive(EventInstance evt) {
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE)
        return;
    // Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetPointMissing"), evt.getEventType());
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetNotSettable"), evt.getEventType());
        return;
    }
    DataType targetDataType = targetPoint.getVO().getPointLocator().getDataType();
    DataValue value = null;
    if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        // Get the source data point.
        DataPointRT sourcePoint = Common.runtimeManager.getDataPoint(vo.getInactivePointId());
        if (sourcePoint == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointMissing"), evt.getEventType());
            return;
        }
        PointValueTime valueTime = sourcePoint.getPointValue();
        if (valueTime == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointValue"), evt.getEventType());
            return;
        }
        if (valueTime.getValue().getDataType() != targetDataType) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.inactivePointDataType"), evt.getEventType());
            return;
        }
        value = valueTime.getValue();
    } else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE)
        value = DataValue.stringToValue(vo.getInactiveValueToSet(), targetDataType);
    else if (vo.getInactiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        ArrayList<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>();
        importExclusions.add(new JsonImportExclusion("xid", vo.getXid()) {

            @Override
            public String getImporterType() {
                return ConfigurationExportData.EVENT_HANDLERS;
            }
        });
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put("target", targetPoint);
        Map<String, Object> additionalContext = new HashMap<String, Object>();
        additionalContext.put(EventInstance.CONTEXT_KEY, evt);
        additionalContext.put(EventInstanceWrapper.CONTEXT_KEY, new EventInstanceWrapper(evt));
        try (ScriptLog scriptLog = new ScriptLog("setPointHandler-" + evt.getId())) {
            for (IntStringPair cxt : vo.getAdditionalContext()) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
                if (dprt != null)
                    context.put(cxt.getValue(), dprt);
            }
            CompiledMangoJavaScript inactiveScript = new CompiledMangoJavaScript(new SetCallback(vo.getScriptRoles()), scriptLog, additionalContext, null, importExclusions, false, service, vo.getScriptRoles());
            inactiveScript.compile(vo.getInactiveScript(), true);
            inactiveScript.initialize(context);
            MangoJavaScriptResult result = inactiveScript.execute(Common.timer.currentTimeMillis(), evt.getRtnTimestamp(), targetPoint.getDataType());
            PointValueTime pvt = (PointValueTime) result.getResult();
            if (pvt != null)
                value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptError e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getTranslatableMessage()), evt.getEventType());
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getMessage()), evt.getEventType());
            return;
        }
    } else
        throw new ShouldNeverHappenException("Unknown active action: " + vo.getInactiveAction());
    if (MangoJavaScriptService.UNCHANGED != value)
        Common.backgroundProcessing.addWorkItem(new SetPointWorkItem(vo.getTargetPointId(), new PointValueTime(value, evt.getRtnTimestamp()), this));
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) DataType(com.serotonin.m2m2.DataType) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) IntStringPair(com.serotonin.db.pair.IntStringPair) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) EventInstanceWrapper(com.serotonin.m2m2.rt.script.EventInstanceWrapper)

Example 3 with MangoJavaScriptResult

use of com.infiniteautomation.mango.util.script.MangoJavaScriptResult in project ma-core-public by infiniteautomation.

the class ScriptingTest method testAnalogStatistics.

@Test
public void testAnalogStatistics() {
    String script = "var a = p1.past(MINUTE,50);";
    script += "return a.average;";
    try {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        List<IDataPoint> vos = createMockDataPoints(1, true, new MangoPermission(), new MangoPermission());
        ScriptContextVariable p1 = new ScriptContextVariable();
        p1.setContextUpdate(true);
        p1.setDataPointId(vos.get(0).getId());
        p1.setVariableName("p1");
        ScriptingTestPointValueRT p1Rt = new ScriptingTestPointValueRT((DataPointVO) vos.get(0));
        context.put(p1.getVariableName(), p1Rt);
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        try (ScriptLog scriptLog = new ScriptLog("testScriptLogger", LogLevel.TRACE, scriptWriter)) {
            ScriptPointValueSetter setter = null;
            CompiledMangoJavaScript compiled = new CompiledMangoJavaScript(setter, scriptLog, new ArrayList<>(), admin);
            compiled.compile(script, true);
            compiled.initialize(context);
            MangoJavaScriptResult result = compiled.execute(Common.timer.currentTimeMillis(), Common.timer.currentTimeMillis(), DataType.NUMERIC);
            PointValueTime pvt = (PointValueTime) result.getResult();
            assertNotNull(pvt);
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) IOException(java.io.IOException) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) IDataPoint(com.serotonin.m2m2.vo.IDataPoint) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 4 with MangoJavaScriptResult

use of com.infiniteautomation.mango.util.script.MangoJavaScriptResult in project ma-core-public by infiniteautomation.

the class MangoJavaScriptService method testScript.

/**
 */
public MangoJavaScriptResult testScript(MangoJavaScript vo, BiFunction<MangoJavaScriptResult, PermissionHolder, ScriptPointValueSetter> createSetter, String noChangeKey) {
    PermissionHolder user = Common.getUser();
    ensureValid(vo);
    final StringWriter scriptOut = new StringWriter();
    MangoJavaScriptResult result = new MangoJavaScriptResult();
    try {
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        try (ScriptLog scriptLog = new ScriptLog("scriptTest-" + user.getPermissionHolderName(), vo.getLogLevel(), scriptWriter)) {
            CompiledMangoJavaScript script = new CompiledMangoJavaScript(vo, createSetter.apply(result, vo.getPermissions()), scriptLog, result, this, pointValueDao, pointValueCache);
            script.compile(vo.getScript(), vo.isWrapInFunction());
            script.initialize(vo.getContext());
            long time = Common.timer.currentTimeMillis();
            runAs.runAsCallable(vo.getPermissions(), () -> {
                if (vo.getResultDataType() != null) {
                    script.execute(time, time, vo.getResultDataType());
                    // Convert the UNCHANGED value
                    Object o = script.getResult().getResult();
                    if (o instanceof PointValueTime && ((PointValueTime) o).getValue() == UNCHANGED) {
                        // TODO fix this display hack:
                        String unchanged = new TranslatableMessage(noChangeKey).translate(Translations.getTranslations(user.getLocaleObject()));
                        script.getResult().setResult(new PointValueTime(unchanged, ((PointValueTime) o).getTime()));
                    }
                } else {
                    script.execute(time, time);
                }
                return null;
            });
        }
    } catch (ScriptError e) {
        // The script exception should be clean as both compile() and execute() clean it
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage(), e.getLineNumber(), e.getColumnNumber()));
    } catch (ResultTypeException e) {
        result.addError(new MangoJavaScriptError(e.getTranslatableMessage()));
    } catch (Exception e) {
        result.addError(new MangoJavaScriptError(e.getMessage()));
    } finally {
        result.setScriptOutput(scriptOut.toString());
    }
    return result;
}
Also used : MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) MangoJavaScriptError(com.infiniteautomation.mango.util.script.MangoJavaScriptError) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) StringWriter(java.io.StringWriter) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PrintWriter(java.io.PrintWriter) NullPrintWriter(com.serotonin.m2m2.util.log.NullPrintWriter)

Example 5 with MangoJavaScriptResult

use of com.infiniteautomation.mango.util.script.MangoJavaScriptResult in project ma-core-public by infiniteautomation.

the class SetPointHandlerRT method eventRaised.

@Override
public void eventRaised(EventInstance evt) {
    if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_NONE)
        return;
    // Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetPointMissing"), evt.getEventType());
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(new TranslatableMessage("event.setPoint.targetNotSettable"), evt.getEventType());
        return;
    }
    DataType targetDataType = targetPoint.getVO().getPointLocator().getDataType();
    DataValue value = null;
    if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_POINT_VALUE) {
        // Get the source data point.
        DataPointRT sourcePoint = Common.runtimeManager.getDataPoint(vo.getActivePointId());
        if (sourcePoint == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointMissing"), evt.getEventType());
            return;
        }
        PointValueTime valueTime = sourcePoint.getPointValue();
        if (valueTime == null) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointValue"), evt.getEventType());
            return;
        }
        if (valueTime.getValue().getDataType() != targetDataType) {
            raiseFailureEvent(new TranslatableMessage("event.setPoint.activePointDataType"), evt.getEventType());
            return;
        }
        value = valueTime.getValue();
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_STATIC_VALUE) {
        value = DataValue.stringToValue(vo.getActiveValueToSet(), targetDataType);
    } else if (vo.getActiveAction() == SetPointEventHandlerVO.SET_ACTION_SCRIPT_VALUE) {
        ArrayList<JsonImportExclusion> importExclusions = new ArrayList<JsonImportExclusion>();
        importExclusions.add(new JsonImportExclusion("xid", vo.getXid()) {

            @Override
            public String getImporterType() {
                return ConfigurationExportData.EVENT_HANDLERS;
            }
        });
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put(SetPointEventHandlerVO.TARGET_CONTEXT_KEY, targetPoint);
        Map<String, Object> additionalContext = new HashMap<String, Object>();
        additionalContext.put(EventInstance.CONTEXT_KEY, evt);
        additionalContext.put(EventInstanceWrapper.CONTEXT_KEY, new EventInstanceWrapper(evt));
        try (ScriptLog scriptLog = new ScriptLog("setPointHandler-" + evt.getId())) {
            for (IntStringPair cxt : vo.getAdditionalContext()) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
                if (dprt != null)
                    context.put(cxt.getValue(), dprt);
            }
            CompiledMangoJavaScript activeScript = new CompiledMangoJavaScript(new SetCallback(vo.getScriptRoles()), scriptLog, additionalContext, null, importExclusions, false, service, vo.getScriptRoles());
            activeScript.compile(vo.getActiveScript(), true);
            activeScript.initialize(context);
            MangoJavaScriptResult result = activeScript.execute(Common.timer.currentTimeMillis(), evt.getActiveTimestamp(), targetPoint.getDataType());
            PointValueTime pvt = (PointValueTime) result.getResult();
            if (pvt != null)
                value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptError e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidActiveScriptError", e.getTranslatableMessage()), evt.getEventType());
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidActiveScriptError", e.getMessage()), evt.getEventType());
            return;
        }
    } else
        throw new ShouldNeverHappenException("Unknown active action: " + vo.getActiveAction());
    // Queue a work item to perform the set point.
    if (MangoJavaScriptService.UNCHANGED != value)
        Common.backgroundProcessing.addWorkItem(new SetPointWorkItem(vo.getTargetPointId(), new PointValueTime(value, evt.getActiveTimestamp()), this));
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) JsonImportExclusion(com.serotonin.m2m2.rt.script.JsonImportExclusion) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptError(com.serotonin.m2m2.rt.script.ScriptError) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) DataType(com.serotonin.m2m2.DataType) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) IntStringPair(com.serotonin.db.pair.IntStringPair) MangoJavaScriptResult(com.infiniteautomation.mango.util.script.MangoJavaScriptResult) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) CompiledMangoJavaScript(com.infiniteautomation.mango.util.script.CompiledMangoJavaScript) EventInstanceWrapper(com.serotonin.m2m2.rt.script.EventInstanceWrapper)

Aggregations

CompiledMangoJavaScript (com.infiniteautomation.mango.util.script.CompiledMangoJavaScript)6 MangoJavaScriptResult (com.infiniteautomation.mango.util.script.MangoJavaScriptResult)6 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)5 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)5 ScriptError (com.serotonin.m2m2.rt.script.ScriptError)5 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)4 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)4 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)4 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)4 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)4 HashMap (java.util.HashMap)4 IntStringPair (com.serotonin.db.pair.IntStringPair)3 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)3 EventInstanceWrapper (com.serotonin.m2m2.rt.script.EventInstanceWrapper)3 JsonImportExclusion (com.serotonin.m2m2.rt.script.JsonImportExclusion)3 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 ArrayList (java.util.ArrayList)3 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)2 MangoJavaScriptError (com.infiniteautomation.mango.util.script.MangoJavaScriptError)2