Search in sources :

Example 56 with MangoPermission

use of com.infiniteautomation.mango.permission.MangoPermission in project ma-modules-public by infiniteautomation.

the class Upgrade4 method get.

public MangoPermission get(Integer id) {
    // TODO Mango 4.0 improve performance
    // Fist check to see if it exists as it may have no minterms
    Integer foundId = create.select(PERMISSIONS.id).from(PERMISSIONS).where(PERMISSIONS.id.equal(id)).fetchOneInto(Integer.class);
    if (foundId == null) {
        return null;
    }
    List<Field<?>> fields = new ArrayList<>();
    fields.add(roleTableIdAlias);
    fields.add(roleTableXidAlias);
    fields.add(PERMISSIONS_MINTERMS.mintermId);
    SelectSeekStep2<Record, Integer, Integer> select = create.select(fields).from(PERMISSIONS_MINTERMS).join(MINTERMS_ROLES).on(PERMISSIONS_MINTERMS.mintermId.eq(MINTERMS_ROLES.mintermId)).join(roleTableAsAlias).on(roleTableIdAlias.eq(MINTERMS_ROLES.roleId)).where(PERMISSIONS_MINTERMS.permissionId.eq(id)).orderBy(PERMISSIONS_MINTERMS.permissionId.asc(), PERMISSIONS_MINTERMS.mintermId.asc());
    String sql = select.getSQL();
    List<Object> arguments = select.getBindValues();
    Object[] argumentsArray = arguments.toArray(new Object[arguments.size()]);
    return ejt.query(sql, argumentsArray, new ResultSetExtractor<MangoPermission>() {

        private int roleIdIndex = 1;

        private int roleXidIndex = 2;

        private int minterIdIndex = 3;

        @Override
        public MangoPermission extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs.next()) {
                Set<Set<Role>> roleSet = new HashSet<>();
                Set<Role> minTerm = new HashSet<>();
                roleSet.add(minTerm);
                minTerm.add(new Role(rs.getInt(roleIdIndex), rs.getString(roleXidIndex)));
                int mintermId = rs.getInt(minterIdIndex);
                while (rs.next()) {
                    if (rs.getInt(minterIdIndex) == mintermId) {
                        // Add to current minterm
                        minTerm.add(new Role(rs.getInt(roleIdIndex), rs.getString(roleXidIndex)));
                    } else {
                        // Add to next minterm
                        minTerm = new HashSet<>();
                        roleSet.add(minTerm);
                        minTerm.add(new Role(rs.getInt(roleIdIndex), rs.getString(roleXidIndex)));
                        mintermId = rs.getInt(minterIdIndex);
                    }
                }
                MangoPermission permission = new MangoPermission(roleSet);
                return permission.withId(id);
            } else {
                return new MangoPermission(id);
            }
        }
    });
}
Also used : HashSet(java.util.HashSet) ResultSet(java.sql.ResultSet) Set(java.util.Set) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Role(com.serotonin.m2m2.vo.role.Role) Field(org.jooq.Field) ResultSet(java.sql.ResultSet) Record(org.jooq.Record) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission) DataAccessException(org.springframework.dao.DataAccessException) HashSet(java.util.HashSet)

Example 57 with MangoPermission

use of com.infiniteautomation.mango.permission.MangoPermission in project ma-modules-public by infiniteautomation.

the class PermissionsRestController method update.

@ApiOperation(value = "Update all of a Permission's Roles", notes = "If no roles are supplied then all existing assigned roles are removed")
@RequestMapping(method = RequestMethod.PUT, value = "/{name}")
public PermissionDefinitionModel update(@PathVariable String name, @ApiParam(value = "Permission", required = true) @RequestBody(required = true) PermissionDefinitionModel model) {
    PermissionDefinition def = ModuleRegistry.getPermissionDefinition(name);
    if (def == null) {
        throw new NotFoundRestException();
    }
    MangoPermission permission = model.getPermission() != null ? model.getPermission().getPermission() : null;
    service.update(permission, def);
    return new PermissionDefinitionModel(def);
}
Also used : PermissionDefinitionModel(com.infiniteautomation.mango.rest.latest.model.permissions.PermissionDefinitionModel) PermissionDefinition(com.serotonin.m2m2.module.PermissionDefinition) NotFoundRestException(com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 58 with MangoPermission

use of com.infiniteautomation.mango.permission.MangoPermission 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 59 with MangoPermission

use of com.infiniteautomation.mango.permission.MangoPermission in project ma-core-public by infiniteautomation.

the class DataPointImporter method importImpl.

@Override
protected void importImpl() {
    String xid = json.getString("xid");
    DataSourceVO dsvo = null;
    DataPointWithEventDetectors dp = null;
    if (StringUtils.isBlank(xid)) {
        xid = dataPointService.generateUniqueXid();
    } else {
        try {
            dp = dataPointService.getWithEventDetectors(xid);
        } catch (NotFoundException e) {
        }
    }
    if (dp == null) {
        // Locate the data source for the point.
        String dsxid = json.getString("dataSourceXid");
        try {
            dsvo = dataSourceService.get(dsxid);
        } catch (NotFoundException e) {
            addFailureMessage("emport.dataPoint.badReference", xid);
            return;
        }
        DataPointVO vo = new DataPointVO();
        vo.setXid(xid);
        vo.setDataSourceId(dsvo.getId());
        vo.setDataSourceXid(dsxid);
        vo.setPointLocator(dsvo.createPointLocator());
        dp = new DataPointWithEventDetectors(vo, new ArrayList<>());
    }
    // If there is already an entry, merge the event detectors
    DataPointWithEventDetectors existingMapping = dataPointMap.get(xid);
    if (existingMapping != null) {
        dp.getEventDetectors().addAll(existingMapping.getEventDetectors());
    }
    if (dp != null) {
        try {
            // Read into the VO to get all properties
            ctx.getReader().readInto(dp.getDataPoint(), json);
            // If the name is not provided, default to the XID
            if (StringUtils.isBlank(dp.getDataPoint().getName()))
                dp.getDataPoint().setName(xid);
            // If the chart colour is null provide default of '' to handle legacy code that sets colour to null
            if (dp.getDataPoint().getChartColour() == null)
                dp.getDataPoint().setChartColour("");
            // Ensure we have a default permission since null is valid in Mango 3.x
            if (dp.getDataPoint().getReadPermission() == null) {
                dp.getDataPoint().setReadPermission(new MangoPermission());
            }
            if (dp.getDataPoint().getEditPermission() == null) {
                dp.getDataPoint().setEditPermission(new MangoPermission());
            }
            if (dp.getDataPoint().getSetPermission() == null) {
                dp.getDataPoint().setSetPermission(new MangoPermission());
            }
            // Handle embedded event detectors
            JsonArray pedArray = json.getJsonArray("eventDetectors");
            if (pedArray != null) {
                for (JsonValue jv : pedArray) {
                    JsonObject pedObject = jv.toJsonObject();
                    String pedXid = pedObject.getString("xid");
                    AbstractPointEventDetectorVO ped = null;
                    if (!StringUtils.isBlank(pedXid)) {
                        // Use the ped xid to lookup an existing ped.
                        for (AbstractPointEventDetectorVO existing : dp.getEventDetectors()) {
                            if (StringUtils.equals(pedXid, existing.getXid())) {
                                ped = existing;
                                break;
                            }
                        }
                    }
                    if (ped == null) {
                        String typeStr = pedObject.getString("type");
                        if (typeStr == null)
                            throw new TranslatableJsonException("emport.error.ped.missingAttr", "type");
                        // This assumes that all definitions used for data points are Data Point Event Detectors
                        PointEventDetectorDefinition<?> def = ModuleRegistry.getEventDetectorDefinition(typeStr);
                        if (def == null)
                            throw new TranslatableJsonException("emport.error.ped.invalid", "type", typeStr, ModuleRegistry.getEventDetectorDefinitionTypes());
                        else {
                            ped = def.baseCreateEventDetectorVO(dp.getDataPoint());
                            ped.setDefinition(def);
                        }
                        // Create a new one
                        ped.setId(Common.NEW_ID);
                        ped.setXid(pedXid);
                        dp.addOrReplaceDetector(ped);
                    }
                    JsonArray handlerXids = pedObject.getJsonArray("handlers");
                    if (handlerXids != null)
                        for (int k = 0; k < handlerXids.size(); k += 1) {
                            AbstractEventHandlerVO eh = EventHandlerDao.getInstance().getByXid(handlerXids.getString(k));
                            if (eh == null) {
                                throw new TranslatableJsonException("emport.eventHandler.missing", handlerXids.getString(k));
                            } else {
                                ped.addAddedEventHandler(eh);
                            }
                        }
                    ctx.getReader().readInto(ped, pedObject);
                }
            }
            boolean isNew = dp.getDataPoint().isNew();
            try {
                if (Common.runtimeManager.getLifecycleState() == ILifecycleState.RUNNING) {
                    if (isNew) {
                        dataPointService.insert(dp.getDataPoint());
                        // Update all our event detector source Ids
                        for (AbstractPointEventDetectorVO ed : dp.getEventDetectors()) {
                            ed.setSourceId(dp.getDataPoint().getId());
                        }
                    } else {
                        dataPointService.update(dp.getDataPoint().getId(), dp.getDataPoint());
                        // Update all our event detector source Ids
                        for (AbstractPointEventDetectorVO ed : dp.getEventDetectors()) {
                            ed.setSourceId(dp.getDataPoint().getId());
                        }
                    }
                    dataPointMap.put(xid, dp);
                    addSuccessMessage(isNew, "emport.dataPoint.prefix", xid);
                } else {
                    addFailureMessage("emport.dataPoint.runtimeManagerNotRunning", xid);
                }
            } catch (LicenseViolatedException e) {
                addFailureMessage("emport.DataPoint.notImported", e.getErrorMessage(), xid);
                addDetectorsFailureMessage(dp, xid);
            }
        } catch (ValidationException e) {
            setValidationMessages(e.getValidationResult(), "emport.dataPoint.prefix", xid);
            addDetectorsFailureMessage(dp, xid);
        } catch (TranslatableJsonException e) {
            addFailureMessage("emport.dataPoint.prefix", xid, e.getMsg());
            addDetectorsFailureMessage(dp, xid);
        } catch (JsonException e) {
            addFailureMessage("emport.dataPoint.prefix", xid, getJsonExceptionMessage(e));
            addDetectorsFailureMessage(dp, xid);
        }
    }
}
Also used : DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) ArrayList(java.util.ArrayList) JsonValue(com.serotonin.json.type.JsonValue) DataPointWithEventDetectors(com.serotonin.m2m2.vo.dataPoint.DataPointWithEventDetectors) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) JsonObject(com.serotonin.json.type.JsonObject) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) AbstractEventHandlerVO(com.serotonin.m2m2.vo.event.AbstractEventHandlerVO) JsonArray(com.serotonin.json.type.JsonArray) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission)

Example 60 with MangoPermission

use of com.infiniteautomation.mango.permission.MangoPermission in project ma-core-public by infiniteautomation.

the class MailingListImporter method importImpl.

@Override
protected void importImpl() {
    String xid = json.getString("xid");
    MailingList vo = null;
    if (StringUtils.isBlank(xid)) {
        xid = service.generateUniqueXid();
    } else {
        try {
            vo = service.get(xid);
        } catch (NotFoundException e) {
        }
    }
    if (vo == null) {
        vo = new MailingList();
        vo.setXid(xid);
    }
    try {
        ctx.getReader().readInto(vo, json);
        // Ensure we have a default permission since null is valid in Mango 3.x
        if (vo.getReadPermission() == null) {
            vo.setReadPermission(new MangoPermission());
        }
        if (vo.getEditPermission() == null) {
            vo.setEditPermission(new MangoPermission());
        }
        boolean isnew = vo.getId() == Common.NEW_ID;
        if (isnew) {
            service.insert(vo);
        } else {
            service.update(vo.getId(), vo);
        }
        addSuccessMessage(isnew, "emport.mailingList.prefix", xid);
    } catch (ValidationException e) {
        setValidationMessages(e.getValidationResult(), "emport.mailingList.prefix", xid);
    } catch (TranslatableJsonException e) {
        addFailureMessage("emport.mailingList.prefix", xid, e.getMsg());
    } catch (JsonException e) {
        addFailureMessage("emport.mailingList.prefix", xid, getJsonExceptionMessage(e));
    }
}
Also used : TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) MailingList(com.serotonin.m2m2.vo.mailingList.MailingList) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission)

Aggregations

MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)93 Role (com.serotonin.m2m2.vo.role.Role)22 HashSet (java.util.HashSet)21 Set (java.util.Set)18 HashMap (java.util.HashMap)13 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)12 PermissionDefinition (com.serotonin.m2m2.module.PermissionDefinition)11 JsonException (com.serotonin.json.JsonException)10 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)9 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)8 JsonValue (com.serotonin.json.type.JsonValue)7 ArrayList (java.util.ArrayList)7 JsonArray (com.serotonin.json.type.JsonArray)6 JsonObject (com.serotonin.json.type.JsonObject)6 User (com.serotonin.m2m2.vo.User)6 OutputStream (java.io.OutputStream)5 Test (org.junit.Test)5 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)4 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4