Search in sources :

Example 16 with DataPointModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel 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 17 with DataPointModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel 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 18 with DataPointModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel in project ma-modules-public by infiniteautomation.

the class DataPointRestController method getAllDataPoints.

@ApiOperation(value = "Get all data points", notes = "Only returns points available to logged in user")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/list")
public ResponseEntity<QueryArrayStream<DataPointVO>> getAllDataPoints(HttpServletRequest request, @ApiParam(value = "Limit the number of results", required = false) @RequestParam(value = "limit", required = false, defaultValue = "100") int limit) {
    RestProcessResult<QueryArrayStream<DataPointVO>> result = new RestProcessResult<QueryArrayStream<DataPointVO>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        ASTNode root = new ASTNode("limit", limit);
        if (user.isAdmin()) {
            // Admin Users Don't need to filter the results
            return result.createResponseEntity(getStream(root));
        } else {
            // We are going to filter the results, so we need to strip out the limit(limit,offset) or limit(limit) clause.
            DataPointStreamCallback callback = new DataPointStreamCallback(this, user);
            FilteredQueryStream<DataPointVO, DataPointModel, DataPointDao> stream = new FilteredQueryStream<DataPointVO, DataPointModel, DataPointDao>(DataPointDao.instance, this, root, callback);
            stream.setupQuery();
            return result.createResponseEntity(stream);
        }
    }
    return result.createResponseEntity();
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) DataPointStreamCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.DataPointStreamCallback) DataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel) User(com.serotonin.m2m2.vo.User) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) ASTNode(net.jazdw.rql.parser.ASTNode) FilteredQueryStream(com.serotonin.m2m2.web.mvc.rest.v1.model.FilteredQueryStream) QueryArrayStream(com.serotonin.m2m2.web.mvc.rest.v1.model.QueryArrayStream) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 19 with DataPointModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel 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 20 with DataPointModel

use of com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel in project ma-modules-public by infiniteautomation.

the class DataSourceRestController method enableDisable.

@ApiOperation(value = "Enable/disable/restart a data source")
@RequestMapping(method = RequestMethod.PUT, value = "/enable-disable/{xid}")
public ResponseEntity<DataPointModel> enableDisable(@AuthenticationPrincipal User user, @PathVariable String xid, @ApiParam(value = "Enable or disable the data source", required = true, allowMultiple = false) @RequestParam(required = true) boolean enabled, @ApiParam(value = "Restart the data source, enabled must equal true", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean restart) {
    DataSourceVO<?> dsvo = DataSourceDao.instance.getByXid(xid);
    if (dsvo == null)
        throw new NotFoundRestException();
    try {
        Permissions.ensureDataSourcePermission(user, dsvo);
    } catch (PermissionException e) {
        throw new AccessDeniedException("User does not have permission to edit the data source", e);
    }
    if (enabled && restart) {
        dsvo.setEnabled(true);
        // saving will restart it
        Common.runtimeManager.saveDataSource(dsvo);
    } else if (dsvo.isEnabled() != enabled) {
        dsvo.setEnabled(enabled);
        Common.runtimeManager.saveDataSource(dsvo);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ResponseEntity(org.springframework.http.ResponseEntity) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ApiOperation (com.wordnik.swagger.annotations.ApiOperation)18 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)18 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)16 User (com.serotonin.m2m2.vo.User)11 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)11 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)11 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)9 DataPointModel (com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel)8 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)7 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)6 DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)5 URI (java.net.URI)5 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)4 ResponseEntity (org.springframework.http.ResponseEntity)4 DataPointDao (com.serotonin.m2m2.db.dao.DataPointDao)3 PlainRenderer (com.serotonin.m2m2.view.text.PlainRenderer)3 RestMessage (com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage)3 DataPointStreamCallback (com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.DataPointStreamCallback)3 HttpHeaders (org.springframework.http.HttpHeaders)3 VoAction (com.infiniteautomation.mango.rest.v2.bulk.VoAction)2