Search in sources :

Example 16 with PermissionException

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

the class DataPointRestController method updateDataPoint.

/**
 * Update a data point in the system
 * @param vo
 * @param xid
 * @param builder
 * @param request
 * @return
 */
@ApiOperation(value = "Update an existing data point", notes = "Content may be CSV or JSON")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json", "text/csv", "application/sero-json" }, produces = { "application/json", "text/csv", "application/sero-json" }, value = "/{xid}")
public ResponseEntity<DataPointModel> updateDataPoint(@PathVariable String xid, @ApiParam(value = "Updated data point model", required = true) @RequestBody(required = true) DataPointModel model, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<DataPointModel> result = new RestProcessResult<DataPointModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        boolean contentTypeCsv = false;
        if (request.getContentType().toLowerCase().contains("text/csv"))
            contentTypeCsv = true;
        DataPointVO vo = model.getData();
        DataPointVO existingDp = DataPointDao.instance.getByXid(xid);
        if (existingDp == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // We will always override the DS Info with the one from the XID Lookup
        DataSourceVO<?> dsvo = DataSourceDao.instance.getDataSource(existingDp.getDataSourceXid());
        // TODO this implies that we may need to have a different JSON Converter for data points
        // Need to set DataSourceId among other things
        vo.setDataSourceId(existingDp.getDataSourceId());
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, vo.getDataSourceId())) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        vo.setId(existingDp.getId());
        // Set all properties that are not in the template or the spreadsheet
        // Use ID to get detectors
        DataPointDao.instance.setEventDetectors(vo);
        vo.setPointFolderId(existingDp.getPointFolderId());
        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())));
            }
        } else {
            if (contentTypeCsv) {
                model.addValidationMessage("validate.required", RestMessageLevel.ERROR, "templateXid");
                result.addRestMessage(this.getValidationFailedError());
                return result.createResponseEntity(model);
            }
        }
        if (!model.validate()) {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        } else {
            if (dsvo == null) {
                result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", xid));
                return result.createResponseEntity();
            } else {
                // Does the old point have a different data source?
                if (existingDp.getDataSourceId() != dsvo.getId()) {
                    vo.setDataSourceId(dsvo.getId());
                    vo.setDataSourceName(dsvo.getName());
                }
            }
            Common.runtimeManager.saveDataPoint(vo);
        }
        // Put a link to the updated data in the header?
        URI location = builder.path("/v1/data-points/{xid}").buildAndExpand(vo.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) 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) URI(java.net.URI) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 17 with PermissionException

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

the class DataPointRestController method saveDataPoint.

@ApiOperation(value = "Create a data point", notes = "Content may be CSV or JSON")
@RequestMapping(method = RequestMethod.POST, consumes = { "application/json", "text/csv", "application/sero-json" }, produces = { "application/json", "text/csv", "application/sero-json" })
public ResponseEntity<DataPointModel> saveDataPoint(@ApiParam(value = "Data point model", required = true) @RequestBody(required = true) DataPointModel model, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<DataPointModel> result = new RestProcessResult<DataPointModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        boolean contentTypeCsv = false;
        if (request.getContentType().toLowerCase().contains("text/csv"))
            contentTypeCsv = true;
        DataPointVO vo = model.getData();
        // Check to see if the point already exists
        if (!StringUtils.isEmpty(vo.getXid())) {
            DataPointVO existing = this.dao.getByXid(vo.getXid());
            if (existing != null) {
                result.addRestMessage(HttpStatus.CONFLICT, new TranslatableMessage("rest.exception.alreadyExists", model.getXid()));
                return result.createResponseEntity();
            }
        }
        // Ensure ds exists
        DataSourceVO<?> dataSource = DataSourceDao.instance.getByXid(model.getDataSourceXid());
        // We will always override the DS Info with the one from the XID Lookup
        if (dataSource == null) {
            result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", model.getDataSourceXid()));
            return result.createResponseEntity();
        } else {
            vo.setDataSourceId(dataSource.getId());
            vo.setDataSourceName(dataSource.getName());
        }
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, vo.getDataSourceId())) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        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) {
                model.addValidationMessage("validate.invalidReference", RestMessageLevel.ERROR, "templateXid");
                result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.dataPoint.badReference", model.getTemplateXid())));
            }
        } else {
            if (contentTypeCsv) {
                model.addValidationMessage("validate.required", RestMessageLevel.ERROR, "templateXid");
                result.addRestMessage(this.getValidationFailedError());
                return result.createResponseEntity(model);
            }
        }
        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(dataSource.getName());
        }
        if (!model.validate()) {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        } else {
            try {
                Common.runtimeManager.saveDataPoint(vo);
            } catch (LicenseViolatedException e) {
                result.addRestMessage(HttpStatus.METHOD_NOT_ALLOWED, e.getErrorMessage());
            }
        }
        // Put a link to the updated data in the header?
        URI location = builder.path("/v1/data-points/{xid}").buildAndExpand(vo.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) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) PlainRenderer(com.serotonin.m2m2.view.text.PlainRenderer) LicenseViolatedException(com.serotonin.m2m2.LicenseViolatedException) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) URI(java.net.URI) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with PermissionException

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

the class DataSourceRestController method copy.

@ApiOperation(value = "Copy data source", notes = "Copy the data source with optional new XID and Name and enable/disable state (default disabled)")
@RequestMapping(method = RequestMethod.PUT, value = "/copy/{xid}", produces = { "application/json" })
public ResponseEntity<AbstractDataSourceModel<?>> 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<AbstractDataSourceModel<?>> result = new RestProcessResult<AbstractDataSourceModel<?>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataSourceVO<?> existing = DataSourceDao.instance.getByXid(xid);
        if (existing == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, existing)) {
                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
        DataSourceVO<?> copy = existing.copy();
        copy.setId(Common.NEW_ID);
        copy.setName(name);
        copy.setXid(newXid);
        copy.setEnabled(enabled);
        ProcessResult validation = new ProcessResult();
        copy.validate(validation);
        AbstractDataSourceModel<?> model = copy.asModel();
        if (model.validate()) {
            Common.runtimeManager.saveDataSource(copy);
            this.dao.copyDataSourcePoints(existing.getId(), copy.getId());
        } 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-sources/{xid}").buildAndExpand(copy.getXid()).toUri();
        result.addRestMessage(getResourceUpdatedMessage(location));
        return result.createResponseEntity(model);
    }
    // Not logged in
    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) 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 19 with PermissionException

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

the class DataSourceRestController method updateDataSource.

/**
 * Put a data source into the system
 * @param xid
 * @param model
 * @param builder
 * @param request
 * @return
 */
@ApiOperation(value = "Update data source")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}", produces = { "application/json" })
public ResponseEntity<AbstractDataSourceModel<?>> updateDataSource(@PathVariable String xid, @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()) {
        DataSourceVO<?> vo = model.getData();
        DataSourceVO<?> existing = DataSourceDao.instance.getByXid(xid);
        if (existing == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Check permissions
        try {
            if (!Permissions.hasDataSourcePermission(user, existing)) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.warn(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        vo.setId(existing.getId());
        ProcessResult validation = new ProcessResult();
        vo.validate(validation);
        if (model.validate() && Permissions.hasDataSourcePermission(user, vo)) {
            Common.runtimeManager.saveDataSource(vo);
        } 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-sources/{xid}").buildAndExpand(xid).toUri();
        result.addRestMessage(getResourceUpdatedMessage(location));
        return result.createResponseEntity(model);
    }
    // Not logged in
    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) 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 20 with PermissionException

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

the class DataSourceRestController method deleteDataSource.

@ApiOperation(value = "Delete data source")
@RequestMapping(method = { RequestMethod.DELETE }, value = { "/{xid}" }, produces = { "application/json" })
public ResponseEntity<AbstractDataSourceModel<?>> deleteDataSource(@PathVariable String xid, UriComponentsBuilder builder, HttpServletRequest request) {
    RestProcessResult<AbstractDataSourceModel<?>> result = new RestProcessResult<AbstractDataSourceModel<?>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataSourceVO<?> existing = (DataSourceVO<?>) DataSourceDao.instance.getByXid(xid);
        if (existing == null) {
            result.addRestMessage(this.getDoesNotExistMessage());
            return result.createResponseEntity();
        } else {
            try {
                if (!Permissions.hasDataSourcePermission(user, existing.getId())) {
                    result.addRestMessage(this.getUnauthorizedMessage());
                    return result.createResponseEntity();
                }
            } catch (PermissionException pe) {
                LOG.warn(pe.getMessage(), pe);
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            }
            Common.runtimeManager.deleteDataSource(existing.getId());
            return result.createResponseEntity(existing.asModel());
        }
    }
    return result.createResponseEntity();
}
Also used : AbstractDataSourceModel(com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel) DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) 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