Search in sources :

Example 1 with IDataPointValueSource

use of com.serotonin.m2m2.rt.dataImage.IDataPointValueSource in project ma-core-public by infiniteautomation.

the class EventHandlersDwr method validateScript.

@DwrPermission(user = true)
public ProcessResult validateScript(String script, Integer targetPointId, int type, List<IntStringPair> additionalContext, ScriptPermissions scriptPermissions) {
    ProcessResult response = new ProcessResult();
    TranslatableMessage message;
    Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
    int targetDataType;
    if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE || type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE) {
        DataPointRT target = targetPointId == null ? null : Common.runtimeManager.getDataPoint(targetPointId.intValue());
        if (target == null) {
            DataPointVO targetVo = targetPointId == null ? null : DataPointDao.instance.getDataPoint(targetPointId.intValue(), false);
            if (targetVo == null) {
                if (// These are passed in the validateScript of eventHandlers.jsp
                type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
                    response.addMessage("activeScript", new TranslatableMessage("eventHandlers.noTargetPoint"));
                else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
                    response.addMessage("inactiveScript", new TranslatableMessage("eventHandlers.noTargetPoint"));
                return response;
            }
            if (targetVo.getDefaultCacheSize() == 0)
                targetVo.setDefaultCacheSize(1);
            target = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
            target.resetValues();
            context.put(SetPointEventHandlerVO.TARGET_CONTEXT_KEY, target);
        }
        targetDataType = target.getDataTypeId();
    } else {
        targetDataType = DataTypes.ALPHANUMERIC;
    }
    for (IntStringPair cxt : additionalContext) {
        DataPointRT dprt = Common.runtimeManager.getDataPoint(cxt.getKey());
        if (dprt == null) {
            DataPointVO dpvo = DataPointDao.instance.getDataPoint(cxt.getKey(), false);
            if (dpvo == null) {
                if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
                    response.addMessage("activeScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
                else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
                    response.addMessage("inactiveScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
                else if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
                    response.addMessage("emailScript", new TranslatableMessage("event.script.contextPointMissing", cxt.getValue(), cxt.getKey()));
                return response;
            }
            if (dpvo.getDefaultCacheSize() == 0)
                dpvo.setDefaultCacheSize(1);
            dprt = new DataPointRT(dpvo, dpvo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(dpvo.getDataSourceId()), null);
            dprt.resetValues();
        }
        context.put(cxt.getValue(), dprt);
    }
    Map<String, Object> otherContext = new HashMap<String, Object>();
    otherContext.put(SetPointEventHandlerVO.EVENT_CONTEXT_KEY, getTestEvent());
    if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
        otherContext.put("model", new HashMap<String, Object>());
    final StringWriter scriptOut = new StringWriter();
    final PrintWriter scriptWriter = new PrintWriter(scriptOut);
    final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
    ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(scriptPermissions) {

        @Override
        public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
            DataPointRT dprt = (DataPointRT) point;
            if (!dprt.getVO().getPointLocator().isSettable()) {
                scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
                return;
            }
            if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
                scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
                return;
            }
            scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
        }

        @Override
        protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
        // not really setting
        }
    };
    try {
        CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
        PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, otherContext, System.currentTimeMillis(), targetDataType, System.currentTimeMillis(), scriptPermissions, scriptWriter, new ScriptLog(SetPointHandlerRT.NULL_WRITER, LogLevel.FATAL), loggingSetter, null, true);
        if (pvt.getValue() == null)
            message = new TranslatableMessage("eventHandlers.script.nullResult");
        else if (CompiledScriptExecutor.UNCHANGED == pvt.getValue())
            message = new TranslatableMessage("eventHandlers.script.successUnchanged");
        else
            message = new TranslatableMessage("eventHandlers.script.success", pvt.getValue());
        // Add the script logging output
        response.addData("out", scriptOut.toString().replaceAll("\n", "<br/>"));
    } catch (ScriptPermissionsException e) {
        message = e.getTranslatableMessage();
    } catch (ScriptException e) {
        message = new TranslatableMessage("eventHandlers.script.failure", e.getMessage());
    } catch (ResultTypeException e) {
        message = e.getTranslatableMessage();
    }
    if (type == SetPointEventHandlerDefinition.ACTIVE_SCRIPT_TYPE)
        response.addMessage("activeScript", message);
    else if (type == SetPointEventHandlerDefinition.INACTIVE_SCRIPT_TYPE)
        response.addMessage("inactiveScript", message);
    else if (type == EmailEventHandlerDefinition.EMAIL_SCRIPT_TYPE)
        response.addMessage("emailScript", message);
    return response;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IntStringPair(com.serotonin.db.pair.IntStringPair) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) Date(java.util.Date) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) StringWriter(java.io.StringWriter) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) PrintWriter(java.io.PrintWriter) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 2 with IDataPointValueSource

use of com.serotonin.m2m2.rt.dataImage.IDataPointValueSource in project ma-core-public by infiniteautomation.

the class RhinoScriptingTest method testAnalogStatistics.

@Test
public void testAnalogStatistics() {
    String script = "var a = p1.past(MINUTE,50);";
    script += "return a.average;";
    // String script = "TIMESTAMP = 100; return 9;";
    ScriptContextVariable p1 = new ScriptContextVariable();
    p1.setContextUpdate(true);
    p1.setDataPointId(1);
    p1.setVariableName("p1");
    try {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        RhinoScriptingTestPointValueRT p1Rt = new RhinoScriptingTestPointValueRT(p1.getDataPointId(), DataTypes.NUMERIC);
        context.put(p1.getVariableName(), p1Rt);
        ScriptPermissions permissions = new ScriptPermissions();
        permissions.setCustomPermissions("superadmin");
        permissions.setDataSourcePermissions("superadmin");
        permissions.setDataPointReadPermissions("superadmin");
        permissions.setDataPointSetPermissions("superadmin");
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        ScriptLog scriptLog = new ScriptLog(scriptWriter, ScriptLog.LogLevel.TRACE);
        CompiledScript s = CompiledScriptExecutor.compile(script);
        PointValueTime pvt = CompiledScriptExecutor.execute(s, context, null, Common.timer.currentTimeMillis(), DataTypes.NUMERIC, -1, permissions, scriptWriter, scriptLog, null, null, true);
        assertNotNull(pvt);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : CompiledScript(javax.script.CompiledScript) HashMap(java.util.HashMap) IOException(java.io.IOException) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 3 with IDataPointValueSource

use of com.serotonin.m2m2.rt.dataImage.IDataPointValueSource in project ma-core-public by infiniteautomation.

the class CompiledScriptExecutor method execute.

/**
 * Execute the script on the common engine
 * @param script
 * @param context
 * @param additionalContext
 * @param runtime
 * @param dataTypeId
 * @param timestamp
 * @param permissions
 * @param scriptWriter
 * @return
 * @throws ScriptException
 * @throws ResultTypeException
 */
public static PointValueTime execute(CompiledScript script, Map<String, IDataPointValueSource> context, Map<String, Object> additionalContext, long runtime, int dataTypeId, long timestamp, ScriptPermissions permissions, PrintWriter scriptWriter, ScriptLog log, ScriptPointValueSetter setter, List<JsonImportExclusion> importExclusions, boolean testRun) throws ScriptException, ResultTypeException {
    // StopWatch stopWatch = new Log4JStopWatch();
    // stopWatch.start();
    ensureInit();
    // Create the wrapper object context.
    ScriptEngine engine = script.getEngine();
    // Prepare the Engine
    Bindings engineScope = prepareEngine(engine, context, additionalContext, runtime, timestamp, permissions, scriptWriter, log, setter, importExclusions, testRun);
    // Execute.
    Object result;
    try {
        result = script.eval(engineScope);
    } catch (ScriptException e) {
        throw prettyScriptMessage(e);
    }
    PointValueTime value = getResult(engine, result, dataTypeId, timestamp);
    // stopWatch.stop("execute()");
    return value;
}
Also used : ScriptException(javax.script.ScriptException) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Example 4 with IDataPointValueSource

use of com.serotonin.m2m2.rt.dataImage.IDataPointValueSource in project ma-core-public by infiniteautomation.

the class ScriptPointValueSetter method set.

// Ensure points are settable and the setter has permissions
public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
    DataPointRT dprt = (DataPointRT) point;
    if (!dprt.getVO().getPointLocator().isSettable())
        return;
    if (permissions != null && !Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions()))
        throw new ScriptPermissionsException(new TranslatableMessage("script.set.permissionDenied", dprt.getVO().getXid()));
    setImpl(point, value, timestamp, annotation);
}
Also used : DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 5 with IDataPointValueSource

use of com.serotonin.m2m2.rt.dataImage.IDataPointValueSource 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;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    DataValue value;
    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 (DataTypes.getDataType(valueTime.getValue()) != 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) {
        if (inactiveScript == null) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScript"), evt.getEventType());
            return;
        }
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put("target", targetPoint);
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(inactiveScript, context, new HashMap<String, Object>(), evt.getRtnTimestamp(), targetPoint.getDataTypeId(), evt.getRtnTimestamp(), vo.getScriptPermissions(), NULL_WRITER, new ScriptLog(NULL_WRITER, LogLevel.FATAL), setCallback, importExclusions, false);
            value = pvt.getValue();
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(e.getTranslatableMessage(), evt.getEventType());
            return;
        } catch (ScriptException e) {
            raiseFailureEvent(new TranslatableMessage("eventHandlers.invalidInactiveScriptError", e.getCause().getMessage()), 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());
    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) SetPointWorkItem(com.serotonin.m2m2.rt.maint.work.SetPointWorkItem) 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) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Aggregations

IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)12 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)11 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)10 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)10 HashMap (java.util.HashMap)9 ScriptException (javax.script.ScriptException)9 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)8 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)7 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)6 PrintWriter (java.io.PrintWriter)6 CompiledScript (javax.script.CompiledScript)6 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)5 StringWriter (java.io.StringWriter)5 IntStringPair (com.serotonin.db.pair.IntStringPair)3 ScriptPointValueSetter (com.serotonin.m2m2.rt.script.ScriptPointValueSetter)3 SimpleDateFormat (java.text.SimpleDateFormat)3 Date (java.util.Date)3 GenericRestException (com.infiniteautomation.mango.rest.v2.exception.GenericRestException)2 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)2 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)2