Search in sources :

Example 31 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.

the class DataPointRestController method delete.

/**
 * Delete one Data Point
 * @param xid
 * @param request
 * @return
 */
@ApiOperation(value = "Delete a data point", notes = "The user must have permission to the data point")
@RequestMapping(method = RequestMethod.DELETE, value = "/{xid}", produces = { "application/json", "text/csv", "application/sero-json" })
public ResponseEntity<DataPointModel> delete(@PathVariable String xid, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<DataPointModel> result = new RestProcessResult<DataPointModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataPointVO existing = DataPointDao.instance.getByXid(xid);
        if (existing == null) {
            result.addRestMessage(this.getDoesNotExistMessage());
            return result.createResponseEntity();
        } else {
            try {
                // Ensure we have permission to edit the data source
                if (!Permissions.hasDataSourcePermission(user, existing.getDataSourceId())) {
                    result.addRestMessage(this.getUnauthorizedMessage());
                    return result.createResponseEntity();
                }
            } catch (PermissionException e) {
                LOG.warn(e.getMessage(), e);
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            }
            Common.runtimeManager.deleteDataPoint(existing);
            return result.createResponseEntity(new DataPointModel(existing));
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 32 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.

the class DataPointRestController method copy.

@ApiOperation(value = "Copy data point", notes = "Copy the data point with optional new XID and Name and enable/disable state (default disabled)")
@RequestMapping(method = RequestMethod.PUT, value = "/copy/{xid}", produces = { "application/json" })
public ResponseEntity<DataPointModel> copy(@PathVariable String xid, @ApiParam(value = "Copy's new XID", required = false, defaultValue = "null", allowMultiple = false) @RequestParam(required = false, defaultValue = "null") String copyXid, @ApiParam(value = "Copy's name", required = false, defaultValue = "null", allowMultiple = false) @RequestParam(required = false, defaultValue = "null") String copyName, @ApiParam(value = "Enable/disabled state", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean enabled, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<DataPointModel> result = new RestProcessResult<DataPointModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataPointVO existing = this.dao.getByXid(xid);
        if (existing == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, existing.getDataSourceId())) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.warn(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        // Determine the new name
        String name;
        if (StringUtils.isEmpty(copyName))
            name = StringUtils.abbreviate(TranslatableMessage.translate(Common.getTranslations(), "common.copyPrefix", existing.getName()), 40);
        else
            name = copyName;
        // Determine the new xid
        String newXid;
        if (StringUtils.isEmpty(copyXid))
            newXid = dao.generateUniqueXid();
        else
            newXid = copyXid;
        // Setup the Copy
        DataPointVO copy = existing.copy();
        copy.setId(Common.NEW_ID);
        copy.setName(name);
        copy.setXid(newXid);
        copy.setEnabled(enabled);
        copy.getComments().clear();
        // Copy the event detectors
        for (AbstractPointEventDetectorVO<?> ped : copy.getEventDetectors()) {
            ped.setId(Common.NEW_ID);
            ped.njbSetDataPoint(copy);
        }
        ProcessResult validation = new ProcessResult();
        copy.validate(validation);
        DataPointModel model = new DataPointModel(copy);
        if (model.validate()) {
            Common.runtimeManager.saveDataPoint(copy);
        } else {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        }
        // Put a link to the updated data in the header?
        URI location = builder.path("/v1/data-points/{xid}").buildAndExpand(copy.getXid()).toUri();
        result.addRestMessage(getResourceUpdatedMessage(location));
        return result.createResponseEntity(model);
    }
    // Not logged in
    return result.createResponseEntity();
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 33 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.

the class DataPointRestController method saveDataPoints.

@ApiOperation(value = "Insert/Update multiple data points", notes = "CSV content must be limited to 1 type of data source.")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json;charset=UTF-8", "text/csv;charset=UTF-8" }, produces = { "application/json", "application/sero-json" })
public ResponseEntity<List<DataPointModel>> saveDataPoints(@ApiParam(value = "List of updated data point models", required = true) @RequestBody(required = true) List<DataPointModel> models, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<List<DataPointModel>> result = new RestProcessResult<List<DataPointModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        boolean contentTypeCsv = false;
        if (request.getContentType().toLowerCase().contains("text/csv"))
            contentTypeCsv = true;
        DataPointModel first;
        DataSourceVO<?> ds = null;
        if (models.size() > 0) {
            first = models.get(0);
            ds = DataSourceDao.instance.getByXid(first.getDataSourceXid());
        }
        for (DataPointModel model : models) {
            DataPointVO vo = model.getData();
            DataSourceVO<?> myDataSource = DataSourceDao.instance.getByXid(vo.getDataSourceXid());
            if (myDataSource == null) {
                model.addValidationMessage("validate.invalidReference", RestMessageLevel.ERROR, "dataSourceXid");
                continue;
            }
            // If we don't have a reference data source we need to set one
            if (ds == null) {
                ds = myDataSource;
            }
            // First check to see that the data source types match
            if (!ds.getDefinition().getDataSourceTypeName().equals(myDataSource.getDefinition().getDataSourceTypeName())) {
                model.addValidationMessage("validate.incompatibleDataSourceType", RestMessageLevel.ERROR, "dataSourceXid");
                continue;
            }
            // Set the ID for the data source
            vo.setDataSourceId(myDataSource.getId());
            // Are we a new one?
            DataPointVO existingDp = DataPointDao.instance.getByXid(vo.getXid());
            boolean updated = true;
            if (existingDp == null) {
                updated = false;
            } else {
                // Must Do this as ID is NOT in the model
                vo.setId(existingDp.getId());
                // Set all properties that are not in the template or the spreadsheet
                vo.setPointFolderId(existingDp.getPointFolderId());
                // Use ID to get detectors
                DataPointDao.instance.setEventDetectors(vo);
            }
            // Check permissions
            try {
                if (!Permissions.hasDataPointReadPermission(user, vo)) {
                    // TODO add what point
                    result.addRestMessage(getUnauthorizedMessage());
                    continue;
                }
            } catch (PermissionException e) {
                // TODO add what point
                result.addRestMessage(getUnauthorizedMessage());
                continue;
            }
            if (vo.getTextRenderer() == null) {
                vo.setTextRenderer(new PlainRenderer());
            }
            if (vo.getChartColour() == null) {
                vo.setChartColour("");
            }
            // Check the Template and see if we need to use it
            if (model.getTemplateXid() != null) {
                DataPointPropertiesTemplateVO template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
                if (template != null) {
                    template.updateDataPointVO(vo);
                    template.updateDataPointVO(model.getData());
                } else {
                    model.addValidationMessage("validate.invalidReference", RestMessageLevel.ERROR, "templateXid");
                    result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", model.getTemplateXid())));
                    continue;
                }
            } else {
                // We need to update the various pieces
                if (updated) {
                    DataPointPropertiesTemplateVO tempTemplate = new DataPointPropertiesTemplateVO();
                    tempTemplate.updateTemplate(existingDp);
                    tempTemplate.updateDataPointVO(vo);
                    // Kludge to allow this template to not be our real template
                    vo.setTemplateId(null);
                } else {
                    if (contentTypeCsv) {
                        model.addValidationMessage("validate.required", RestMessageLevel.ERROR, "templateXid");
                        result.addRestMessage(this.getValidationFailedError());
                        continue;
                    }
                }
            }
            if (StringUtils.isEmpty(vo.getXid()))
                vo.setXid(DataPointDao.instance.generateUniqueXid());
            // allow empty string, but if its null use the data source name
            if (vo.getDeviceName() == null) {
                vo.setDeviceName(myDataSource.getName());
            }
            if (model.validate()) {
                if (updated)
                    model.addValidationMessage("common.updated", RestMessageLevel.INFORMATION, "all");
                else
                    model.addValidationMessage("common.saved", RestMessageLevel.INFORMATION, "all");
                // Save it
                Common.runtimeManager.saveDataPoint(vo);
            }
        }
        return result.createResponseEntity(models);
    }
    // Not logged in
    return result.createResponseEntity();
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) PlainRenderer(com.serotonin.m2m2.view.text.PlainRenderer) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) List(java.util.List) ArrayList(java.util.ArrayList) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 34 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.

the class DataSourceRestController method getDataSourceById.

@ApiOperation(value = "Get data source by ID", notes = "Only returns data sources available to logged in user")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/by-id/{id}")
public ResponseEntity<AbstractDataSourceModel<?>> getDataSourceById(@ApiParam(value = "Valid Data Source ID", required = true, allowMultiple = false) @PathVariable int id, HttpServletRequest request) {
    RestProcessResult<AbstractDataSourceModel<?>> result = new RestProcessResult<AbstractDataSourceModel<?>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataSourceVO<?> vo = DataSourceDao.instance.get(id);
        if (vo == null) {
            return new ResponseEntity<AbstractDataSourceModel<?>>(HttpStatus.NOT_FOUND);
        } else {
            try {
                if (Permissions.hasDataSourcePermission(user, vo))
                    return result.createResponseEntity(vo.asModel());
                else {
                    result.addRestMessage(getUnauthorizedMessage());
                    return result.createResponseEntity();
                }
            } catch (PermissionException e) {
                LOG.warn(e.getMessage(), e);
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        }
    }
    return result.createResponseEntity();
}
Also used : AbstractDataSourceModel(com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) ResponseEntity(org.springframework.http.ResponseEntity) User(com.serotonin.m2m2.vo.User) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 35 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.

the class DataSourceRestController method saveDataSource.

@ApiOperation(value = "Save data source")
@RequestMapping(method = { RequestMethod.POST }, produces = { "application/json" })
public ResponseEntity<AbstractDataSourceModel<?>> saveDataSource(@RequestBody(required = true) AbstractDataSourceModel<?> model, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<AbstractDataSourceModel<?>> result = new RestProcessResult<AbstractDataSourceModel<?>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        try {
            if (!Permissions.hasDataSourcePermission(user)) {
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException pe) {
            LOG.warn(pe.getMessage(), pe);
            result.addRestMessage(this.getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        DataSourceVO<?> vo = model.getData();
        // Check to see if the data source already exists
        if (!StringUtils.isEmpty(vo.getXid())) {
            DataSourceVO<?> existing = (DataSourceVO<?>) DataSourceDao.instance.getByXid(model.getXid());
            if (existing != null) {
                result.addRestMessage(HttpStatus.CONFLICT, new TranslatableMessage("rest.exception.alreadyExists", model.getXid()));
                return result.createResponseEntity();
            }
        }
        if (StringUtils.isEmpty(vo.getXid()))
            vo.setXid(DataSourceDao.instance.generateUniqueXid());
        if (!model.validate() || !Permissions.hasPermission(vo.getEditPermission(), user.getPermissions())) {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        } else {
            Common.runtimeManager.saveDataSource(vo);
            DataSourceVO<?> created = (DataSourceVO<?>) DataSourceDao.instance.getByXid(model.getXid());
            URI location = builder.path("/v1/data-sources/{xid}").buildAndExpand(new Object[] { created.asModel().getXid() }).toUri();
            result.addRestMessage(this.getResourceCreatedMessage(location));
            return result.createResponseEntity(created.asModel());
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : AbstractDataSourceModel(com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)42 User (com.serotonin.m2m2.vo.User)34 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)29 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)28 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)25 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)25 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)13 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)12 ValidationFailedRestException (com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException)11 RTException (com.serotonin.m2m2.rt.RTException)11 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)11 RestValidationResult (com.infiniteautomation.mango.rest.v2.model.RestValidationResult)10 ArrayList (java.util.ArrayList)10 List (java.util.List)9 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)8 AbstractDataSourceModel (com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel)7 RecentPointValueTimeModel (com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel)7 URI (java.net.URI)7 HashMap (java.util.HashMap)7 AnnotatedPointValueTime (com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime)6