Search in sources :

Example 1 with DataPointPropertiesTemplateVO

use of com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO 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 2 with DataPointPropertiesTemplateVO

use of com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO 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 3 with DataPointPropertiesTemplateVO

use of com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO 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 4 with DataPointPropertiesTemplateVO

use of com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO 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 5 with DataPointPropertiesTemplateVO

use of com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO in project ma-modules-public by infiniteautomation.

the class InternalMenuItem method maybeCreatePoints.

/**
 */
private void maybeCreatePoints(boolean safe, DataSourceVO<?> vo) {
    Map<String, ValueMonitor<?>> monitors = getAllHomePageMonitors();
    Iterator<String> it = monitors.keySet().iterator();
    while (it.hasNext()) {
        String xid = it.next();
        ValueMonitor<?> monitor = monitors.get(xid);
        if (monitor != null) {
            DataPointVO dp = DataPointDao.instance.getByXid(xid);
            if (dp == null) {
                InternalPointLocatorVO pl = new InternalPointLocatorVO();
                pl.setMonitorId(monitor.getId());
                dp = new DataPointVO();
                dp.setXid(xid);
                dp.setName(monitor.getName().translate(Common.getTranslations()));
                dp.setDataSourceId(vo.getId());
                dp.setDeviceName(vo.getName());
                dp.setEventDetectors(new ArrayList<AbstractPointEventDetectorVO<?>>(0));
                dp.defaultTextRenderer();
                dp.setEnabled(true);
                dp.setChartColour("");
                dp.setPointLocator(pl);
                // Use default template
                DataPointPropertiesTemplateVO template = TemplateDao.instance.getDefaultDataPointTemplate(pl.getDataTypeId());
                if (template != null) {
                    template.updateDataPointVO(dp);
                    dp.setTemplateId(template.getId());
                }
                // If we are numeric then we want to log on change
                switch(pl.getDataTypeId()) {
                    case DataTypes.NUMERIC:
                        if (SYSTEM_UPTIME_POINT_XID.equals(xid)) {
                            // This changes every time, so just do an interval instant
                            dp.setLoggingType(LoggingTypes.INTERVAL);
                            dp.setIntervalLoggingPeriodType(Common.TimePeriods.MINUTES);
                            dp.setIntervalLoggingPeriod(5);
                            dp.setIntervalLoggingType(DataPointVO.IntervalLoggingTypes.INSTANT);
                        } else {
                            // Setup to Log on Change
                            dp.setLoggingType(LoggingTypes.ON_CHANGE);
                        }
                        if (dp.getTextRenderer() instanceof AnalogRenderer && !dp.getXid().equals(SYSTEM_UPTIME_POINT_XID)) {
                            // This are count points, no need for decimals.
                            ((AnalogRenderer) dp.getTextRenderer()).setFormat("0");
                        }
                        // No template in use here
                        dp.setTemplateId(null);
                        break;
                }
                ProcessResult result = new ProcessResult();
                dp.validate(result);
                if (!result.getHasMessages()) {
                    if (safe)
                        DataPointDao.instance.saveDataPoint(dp);
                    else
                        Common.runtimeManager.saveDataPoint(dp);
                } else {
                    for (ProcessMessage message : result.getMessages()) {
                        LOG.error(message.toString(Common.getTranslations()));
                    }
                }
            }
        }
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) DataPointPropertiesTemplateVO(com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) AnalogRenderer(com.serotonin.m2m2.view.text.AnalogRenderer) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) ValueMonitor(com.infiniteautomation.mango.monitor.ValueMonitor)

Aggregations

DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)13 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)10 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)8 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)8 PlainRenderer (com.serotonin.m2m2.view.text.PlainRenderer)5 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)4 URI (java.net.URI)4 ArrayList (java.util.ArrayList)4 LicenseViolatedException (com.serotonin.m2m2.LicenseViolatedException)3 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)3 TableChartRenderer (com.serotonin.m2m2.view.chart.TableChartRenderer)3 User (com.serotonin.m2m2.vo.User)3 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)3 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)3 RestMessage (com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage)3 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)3 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)3 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)3