Search in sources :

Example 6 with DataPointModel

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

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

the class DataPointRestController method updateDataPoint.

@ApiOperation(value = "Update an existing data point")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<DataPointModel> updateDataPoint(@PathVariable String xid, @ApiParam(value = "Updated data point model", required = true) @RequestBody(required = true) DataPointModel model, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    DataPointVO dataPoint = DataPointDao.instance.getByXid(xid);
    if (dataPoint == null) {
        throw new NotFoundRestException();
    }
    Permissions.ensureDataSourcePermission(user, dataPoint.getDataSourceId());
    // check if they are trying to move it to another data source
    String newDataSourceXid = model.getDataSourceXid();
    if (newDataSourceXid != null && !newDataSourceXid.isEmpty() && !newDataSourceXid.equals(dataPoint.getDataSourceXid())) {
        throw new BadRequestException(new TranslatableMessage("rest.error.pointChangeDataSource"));
    }
    DataPointPropertiesTemplateVO template = null;
    if (model.isTemplateXidWasSet()) {
        if (model.getTemplateXid() != null) {
            template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
            if (template == null) {
                throw new BadRequestException(new TranslatableMessage("invalidTemplateXid"));
            }
        }
    } else if (dataPoint.getTemplateId() != null) {
        template = (DataPointPropertiesTemplateVO) TemplateDao.instance.get(dataPoint.getTemplateId());
    }
    DataPointDao.instance.loadPartialRelationalData(dataPoint);
    model.copyPropertiesTo(dataPoint);
    // load the template after copying the properties, template properties override the ones in the data point
    if (template != null) {
        dataPoint.withTemplate(template);
    }
    dataPoint.ensureValid();
    // have to load any existing event detectors for the data point as we are about to replace the VO in the runtime manager
    DataPointDao.instance.setEventDetectors(dataPoint);
    Common.runtimeManager.saveDataPoint(dataPoint);
    URI location = builder.path("/v2/data-points/{xid}").buildAndExpand(xid).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(new DataPointModel(dataPoint), headers, HttpStatus.OK);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HttpHeaders(org.springframework.http.HttpHeaders) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ResponseEntity(org.springframework.http.ResponseEntity) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with DataPointModel

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

the class DataPointRestController method createDataPoint.

@ApiOperation(value = "Create a new data point")
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<DataPointModel> createDataPoint(@ApiParam(value = "Data point model", required = true) @RequestBody(required = true) DataPointModel model, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    DataSourceVO<?> dataSource = DataSourceDao.instance.getByXid(model.getDataSourceXid());
    if (dataSource == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.invalidDataSourceXid"));
    }
    Permissions.ensureDataSourcePermission(user, dataSource);
    DataPointVO dataPoint = new DataPointVO(dataSource);
    model.copyPropertiesTo(dataPoint);
    if (model.getTemplateXid() != null) {
        DataPointPropertiesTemplateVO template = (DataPointPropertiesTemplateVO) TemplateDao.instance.getByXid(model.getTemplateXid());
        if (template == null) {
            throw new BadRequestException(new TranslatableMessage("rest.error.invalidTemplateXid"));
        }
        dataPoint.withTemplate(template);
    }
    dataPoint.ensureValid();
    Common.runtimeManager.saveDataPoint(dataPoint);
    URI location = builder.path("/v2/data-points/{xid}").buildAndExpand(dataPoint.getXid()).toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(location);
    return new ResponseEntity<>(new DataPointModel(dataPoint), headers, HttpStatus.CREATED);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with DataPointModel

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

the class DataPointRestController method bulkDataPointOperation.

@ApiOperation(value = "Bulk get/create/update/delete data points", notes = "User must have read/edit permission for the data point")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>> bulkDataPointOperation(@RequestBody DataPointBulkRequest requestBody, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    VoAction defaultAction = requestBody.getAction();
    DataPointModel defaultBody = requestBody.getBody();
    List<DataPointIndividualRequest> requests = requestBody.getRequests();
    if (requests == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.mustNotBeNull", "requests"));
    }
    String resourceId = requestBody.getId();
    Long expiration = requestBody.getExpiration();
    Long timeout = requestBody.getTimeout();
    TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception> responseBody = bulkResourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_DATA_POINT, resourceId, user.getId(), expiration, timeout, (resource) -> {
        DataPointBulkResponse bulkResponse = new DataPointBulkResponse();
        int i = 0;
        resource.progress(bulkResponse, i++, requests.size());
        for (DataPointIndividualRequest request : requests) {
            UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
            DataPointIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, user, reqBuilder);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/v2/data-points/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.v2.bulk.VoAction) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with DataPointModel

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

the class DataPointRestController method doQuery.

private static StreamedArrayWithTotal doQuery(ASTNode rql, User user) {
    if (user.isAdmin()) {
        return new StreamedVOQueryWithTotal<>(DataPointDao.instance, rql, item -> {
            DataPointDao.instance.loadPartialRelationalData(item);
            return new DataPointModel(item);
        });
    } else {
        // Add some conditions to restrict based on user permissions
        ConditionSortLimitWithTagKeys conditions = DataPointDao.instance.rqlToCondition(rql);
        conditions.addCondition(DataPointDao.instance.userHasPermission(user));
        DataPointFilter dataPointFilter = new DataPointFilter(user);
        return new StreamedVOQueryWithTotal<>(DataPointDao.instance, conditions, item -> {
            boolean oldFilterMatches = dataPointFilter.hasDataPointReadPermission(item);
            // this is just a double check, permissions should be accounted for via SQL restrictions added by DataPointDao.userHasPermission()
            if (!oldFilterMatches) {
                throw new RuntimeException("Data point does not match old permission filter");
            }
            return true;
        }, item -> {
            DataPointDao.instance.loadPartialRelationalData(item);
            return new DataPointModel(item);
        });
    }
}
Also used : StreamedVOQueryWithTotal(com.infiniteautomation.mango.rest.v2.model.StreamedVOQueryWithTotal) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) ConditionSortLimitWithTagKeys(com.infiniteautomation.mango.db.query.ConditionSortLimitWithTagKeys) DataPointFilter(com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.DataPointFilter)

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