Search in sources :

Example 21 with ScriptError

use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by MangoAutomation.

the class MangoJavaScriptService method compile.

/**
 * Compile a script to be run and add global bindings
 */
public CompiledScript compile(String script, boolean wrapInFunction) throws ScriptError {
    try {
        final ScriptEngine engine = newEngine();
        // Add constants to the context
        Bindings globalBindings = new SimpleBindings();
        // left here for legacy compatibility
        globalBindings.put("SECOND", Common.TimePeriods.SECONDS);
        globalBindings.put("MINUTE", Common.TimePeriods.MINUTES);
        globalBindings.put("HOUR", Common.TimePeriods.HOURS);
        globalBindings.put("DAY", Common.TimePeriods.DAYS);
        globalBindings.put("WEEK", Common.TimePeriods.WEEKS);
        globalBindings.put("MONTH", Common.TimePeriods.MONTHS);
        globalBindings.put("YEAR", Common.TimePeriods.YEARS);
        for (IntStringPair isp : Common.TIME_PERIOD_CODES.getIdKeys()) globalBindings.put(Common.TIME_PERIOD_CODES.getCode(isp.getKey()), isp.getKey());
        for (IntStringPair isp : Common.ROLLUP_CODES.getIdKeys(Common.Rollups.NONE)) globalBindings.put(Common.ROLLUP_CODES.getCode(isp.getKey()), isp.getKey());
        // Add in Additional Utilities with Global Scope
        globalBindings.put(DateTimeUtility.CONTEXT_KEY, new DateTimeUtility());
        globalBindings.put(UnitUtility.CONTEXT_KEY, new UnitUtility());
        engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
        String toCompile;
        if (wrapInFunction) {
            toCompile = SCRIPT_PREFIX + script + SCRIPT_SUFFIX;
        } else {
            toCompile = script;
        }
        return ((Compilable) engine).compile(toCompile);
    } catch (ScriptException e) {
        throw ScriptError.create(e, wrapInFunction);
    }
}
Also used : ScriptException(javax.script.ScriptException) IntStringPair(com.serotonin.db.pair.IntStringPair) SimpleBindings(javax.script.SimpleBindings) Compilable(javax.script.Compilable) DateTimeUtility(com.serotonin.m2m2.rt.script.DateTimeUtility) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) UnitUtility(com.serotonin.m2m2.rt.script.UnitUtility) ScriptEngine(javax.script.ScriptEngine)

Example 22 with ScriptError

use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by MangoAutomation.

the class CompiledMangoJavaScript method initialize.

/**
 * Clear the engine scope and initialize it with an expandable context which is filled with the ScriptContextVariables and returned
 *
 * @throws ScriptPermissionsException - permission denied executing a command
 * @throws ScriptError - Execution failure, generally will have line and column number with message
 * @throws DataPointStateException - If a point is not enabled or missing (unless testRun is true, then a dummy point is created)
 */
public Map<String, IDataPointValueSource> initialize(List<ScriptContextVariable> variables) throws ScriptPermissionsException, ScriptError, DataPointStateException {
    Map<String, IDataPointValueSource> context = new HashMap<>();
    if (variables != null) {
        for (ScriptContextVariable variable : variables) {
            DataPointVO dpvo = DataPointDao.getInstance().get(variable.getDataPointId());
            if (dpvo != null) {
                DataPointRT dprt = Common.runtimeManager.getDataPoint(dpvo.getId());
                // So we can test with points disabled
                if (dprt == null) {
                    if (testRun) {
                        if (dpvo.getDefaultCacheSize() == 0) {
                            dpvo.setDefaultCacheSize(1);
                        }
                        // Generate some fake event detectors
                        DataPointWithEventDetectors dp = new DataPointWithEventDetectors(dpvo, new ArrayList<>());
                        DataSourceRT<? extends DataSourceVO> dataSource = DataSourceDao.getInstance().get(dpvo.getDataSourceId()).createDataSourceRT();
                        dprt = new DataPointRT(dp, dpvo.getPointLocator().createRuntime(), dataSource, null, pointValueDao, pointValueCache);
                    } else {
                        throw new DataPointStateException(variable.getDataPointId(), new TranslatableMessage("event.script.contextPointDisabled", variable.getVariableName(), dpvo.getXid()));
                    }
                }
                if (dprt != null)
                    context.put(variable.getVariableName(), dprt);
            } else {
                throw new DataPointStateException(variable.getDataPointId(), new TranslatableMessage("event.script.contextPointMissing", variable.getVariableName(), variable.getDataPointId()));
            }
        }
    }
    this.initialize(context);
    return context;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HashMap(java.util.HashMap) DataPointStateException(com.serotonin.m2m2.rt.script.DataPointStateException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) ScriptContextVariable(com.serotonin.m2m2.rt.script.ScriptContextVariable) DataPointWithEventDetectors(com.serotonin.m2m2.vo.dataPoint.DataPointWithEventDetectors) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 23 with ScriptError

use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by MangoAutomation.

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)

Example 24 with ScriptError

use of com.serotonin.m2m2.rt.script.ScriptError in project ma-core-public by MangoAutomation.

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)

Aggregations

ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)14 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)14 ScriptError (com.serotonin.m2m2.rt.script.ScriptError)14 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)14 ScriptException (javax.script.ScriptException)12 CompiledMangoJavaScript (com.infiniteautomation.mango.util.script.CompiledMangoJavaScript)10 MangoJavaScriptResult (com.infiniteautomation.mango.util.script.MangoJavaScriptResult)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)10 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)10 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)10 DataPointStateException (com.serotonin.m2m2.rt.script.DataPointStateException)10 HashMap (java.util.HashMap)10 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)8 IntStringPair (com.serotonin.db.pair.IntStringPair)8 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)8 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)8 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)8 ArrayList (java.util.ArrayList)8 MangoJavaScriptService (com.infiniteautomation.mango.spring.service.MangoJavaScriptService)6 DataType (com.serotonin.m2m2.DataType)6