Search in sources :

Example 6 with ScriptPermissions

use of com.serotonin.m2m2.rt.script.ScriptPermissions 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 7 with ScriptPermissions

use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-core-public by infiniteautomation.

the class EventHandlersDwr method getInitData.

@DwrPermission(user = true)
public Map<String, Object> getInitData() {
    User user = Common.getHttpUser();
    Permissions.ensureDataSourcePermission(user);
    Map<String, Object> model = new HashMap<>();
    // Get the data sources.
    List<DataSourceVO<?>> dss = DataSourceDao.instance.getDataSources();
    // Create a lookup of data sources to quickly determine data point permissions.
    Map<Integer, DataSourceVO<?>> dslu = new HashMap<>();
    for (DataSourceVO<?> ds : dss) dslu.put(ds.getId(), ds);
    // Get the data points
    List<DataPointBean> allPoints = new ArrayList<>();
    List<EventSourceBean> dataPoints = new ArrayList<>();
    List<DataPointVO> dps = DataPointDao.instance.getDataPoints(DataPointExtendedNameComparator.instance, true);
    final boolean admin = Permissions.hasAdmin(user);
    for (DataPointVO dp : dps) {
        if (!admin && !Permissions.hasDataSourcePermission(user, dslu.get(dp.getDataSourceId())))
            continue;
        allPoints.add(new DataPointBean(dp));
        if (dp.getEventDetectors().size() > 0) {
            EventSourceBean source = new EventSourceBean();
            source.setId(dp.getId());
            source.setName(dp.getExtendedName());
            for (AbstractPointEventDetectorVO<?> ped : dp.getEventDetectors()) {
                EventTypeVO dpet = ped.getEventType();
                dpet.setHandlers(EventHandlerDao.instance.getEventHandlers(dpet));
                source.getEventTypes().add(dpet);
            }
            dataPoints.add(source);
        }
    }
    // Get the data sources
    List<EventSourceBean> dataSources = new ArrayList<>();
    for (DataSourceVO<?> ds : dss) {
        if (!admin && !Permissions.hasDataSourcePermission(user, ds))
            continue;
        if (ds.getEventTypes().size() > 0) {
            EventSourceBean source = new EventSourceBean();
            source.setId(ds.getId());
            source.setName(ds.getName());
            for (EventTypeVO dset : ds.getEventTypes()) {
                dset.setHandlers(EventHandlerDao.instance.getEventHandlers(dset));
                source.getEventTypes().add(dset);
            }
            dataSources.add(source);
        }
    }
    Map<String, Map<String, Object>> userEventTypes = new LinkedHashMap<>();
    model.put("userEventTypes", userEventTypes);
    for (EventTypeDefinition def : ModuleRegistry.getDefinitions(EventTypeDefinition.class)) {
        if (!def.getHandlersRequireAdmin()) {
            List<EventTypeVO> vos = def.getEventTypeVOs();
            for (EventTypeVO vo : vos) vo.setHandlers(EventHandlerDao.instance.getEventHandlers(vo));
            Map<String, Object> info = new HashMap<>();
            info.put("vos", vos);
            info.put("iconPath", def.getIconPath());
            info.put("description", translate(def.getDescriptionKey()));
            userEventTypes.put(def.getTypeName(), info);
        }
    }
    if (admin) {
        // Get the publishers
        List<EventSourceBean> publishers = new ArrayList<>();
        for (PublisherVO<? extends PublishedPointVO> p : PublisherDao.instance.getPublishers(new PublisherDao.PublisherNameComparator())) {
            if (p.getEventTypes().size() > 0) {
                EventSourceBean source = new EventSourceBean();
                source.setId(p.getId());
                source.setName(p.getName());
                for (EventTypeVO pet : p.getEventTypes()) {
                    pet.setHandlers(EventHandlerDao.instance.getEventHandlers(pet));
                    source.getEventTypes().add(pet);
                }
                publishers.add(source);
            }
        }
        model.put(SchemaDefinition.PUBLISHERS_TABLE, publishers);
        // Get the system events
        List<EventTypeVO> systemEvents = new ArrayList<>();
        for (EventTypeVO sets : SystemEventType.EVENT_TYPES) {
            sets.setHandlers(EventHandlerDao.instance.getEventHandlers(sets));
            systemEvents.add(sets);
        }
        model.put("systemEvents", systemEvents);
        // Get the audit events
        List<EventTypeVO> auditEvents = new ArrayList<>();
        for (EventTypeVO aets : AuditEventType.EVENT_TYPES) {
            aets.setHandlers(EventHandlerDao.instance.getEventHandlers(aets));
            auditEvents.add(aets);
        }
        model.put("auditEvents", auditEvents);
        Map<String, Map<String, Object>> adminEventTypes = new LinkedHashMap<>();
        model.put("adminEventTypes", adminEventTypes);
        for (EventTypeDefinition def : ModuleRegistry.getDefinitions(EventTypeDefinition.class)) {
            if (def.getHandlersRequireAdmin()) {
                List<EventTypeVO> vos = def.getEventTypeVOs();
                for (EventTypeVO vo : vos) vo.setHandlers(EventHandlerDao.instance.getEventHandlers(vo));
                Map<String, Object> info = new HashMap<>();
                info.put("vos", vos);
                info.put("iconPath", def.getIconPath());
                info.put("description", translate(def.getDescriptionKey()));
                adminEventTypes.put(def.getTypeName(), info);
            }
        }
    }
    model.put("userNewScriptPermissions", new ScriptPermissions(user));
    // Get the mailing lists.
    model.put(SchemaDefinition.MAILING_LISTS_TABLE, MailingListDao.instance.getMailingLists());
    // Get the users.
    model.put(SchemaDefinition.USERS_TABLE, UserDao.instance.getUsers());
    model.put("allPoints", allPoints);
    model.put(SchemaDefinition.DATAPOINTS_TABLE, dataPoints);
    model.put(SchemaDefinition.DATASOURCES_TABLE, dataSources);
    return model;
}
Also used : DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) User(com.serotonin.m2m2.vo.User) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) DataPointBean(com.serotonin.m2m2.web.dwr.beans.DataPointBean) EventTypeVO(com.serotonin.m2m2.vo.event.EventTypeVO) EventTypeDefinition(com.serotonin.m2m2.module.EventTypeDefinition) LinkedHashMap(java.util.LinkedHashMap) EventSourceBean(com.serotonin.m2m2.web.dwr.beans.EventSourceBean) PublisherDao(com.serotonin.m2m2.db.dao.PublisherDao) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 8 with ScriptPermissions

use of com.serotonin.m2m2.rt.script.ScriptPermissions in project ma-core-public by infiniteautomation.

the class SetPointEventHandlerVO method readObject.

@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    int ver = in.readInt();
    // Switch on the version of the class so that version changes can be elegantly handled.
    if (ver == 1) {
        targetPointId = in.readInt();
        activeAction = in.readInt();
        activeValueToSet = SerializationHelper.readSafeUTF(in);
        activePointId = in.readInt();
        inactiveAction = in.readInt();
        inactiveValueToSet = SerializationHelper.readSafeUTF(in);
        inactivePointId = in.readInt();
        activeScript = inactiveScript = null;
        additionalContext = new ArrayList<IntStringPair>();
        scriptPermissions = new ScriptPermissions();
    } else if (ver == 2) {
        targetPointId = in.readInt();
        activeAction = in.readInt();
        activeValueToSet = SerializationHelper.readSafeUTF(in);
        activePointId = in.readInt();
        inactiveAction = in.readInt();
        inactiveValueToSet = SerializationHelper.readSafeUTF(in);
        inactivePointId = in.readInt();
        activeScript = SerializationHelper.readSafeUTF(in);
        inactiveScript = SerializationHelper.readSafeUTF(in);
        additionalContext = new ArrayList<IntStringPair>();
        scriptPermissions = new ScriptPermissions();
    } else if (ver == 3) {
        targetPointId = in.readInt();
        activeAction = in.readInt();
        activeValueToSet = SerializationHelper.readSafeUTF(in);
        activePointId = in.readInt();
        inactiveAction = in.readInt();
        inactiveValueToSet = SerializationHelper.readSafeUTF(in);
        inactivePointId = in.readInt();
        activeScript = SerializationHelper.readSafeUTF(in);
        inactiveScript = SerializationHelper.readSafeUTF(in);
        additionalContext = (List<IntStringPair>) in.readObject();
        scriptPermissions = (ScriptPermissions) in.readObject();
    }
}
Also used : IntStringPair(com.serotonin.db.pair.IntStringPair) ArrayList(java.util.ArrayList) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions)

Example 9 with ScriptPermissions

use of com.serotonin.m2m2.rt.script.ScriptPermissions 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 10 with ScriptPermissions

use of com.serotonin.m2m2.rt.script.ScriptPermissions 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)

Aggregations

IntStringPair (com.serotonin.db.pair.IntStringPair)8 ScriptPermissions (com.serotonin.m2m2.rt.script.ScriptPermissions)8 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)7 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)7 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)7 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)6 ArrayList (java.util.ArrayList)6 CompiledScript (javax.script.CompiledScript)6 ScriptException (javax.script.ScriptException)6 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)5 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)5 PrintWriter (java.io.PrintWriter)5 StringWriter (java.io.StringWriter)5 HashMap (java.util.HashMap)5 JsonArray (com.serotonin.json.type.JsonArray)4 JsonObject (com.serotonin.json.type.JsonObject)4 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)4 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)3 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)3