Search in sources :

Example 41 with DataSourceVO

use of com.serotonin.m2m2.vo.dataSource.DataSourceVO in project ma-modules-public by infiniteautomation.

the class PointValueRestController method getLatestPointValuesForDataSourceAsMultipleArrays.

/**
 * Get the latest point values a set of points return as map of xid to array of values
 *
 * @param xid
 * @param limit
 * @return
 */
@ApiOperation(value = "Get Latest Point Values for all points on a data source directly from the Runtime Manager, this makes Cached and Intra-Interval data available.", notes = "Default limit 100, time descending order, Default to return cached data. Returns data as map of xid to values.")
@RequestMapping(method = RequestMethod.GET, value = "/{dataSourceXid}/latest-data-source-multiple-arrays", produces = { "application/json", "text/csv" })
public ResponseEntity<ObjectStream<Map<String, List<PointValueTime>>>> getLatestPointValuesForDataSourceAsMultipleArrays(HttpServletRequest request, @ApiParam(value = "Data source xid", required = true, allowMultiple = true) @PathVariable String dataSourceXid, @ApiParam(value = "Return rendered value as String", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean useRendered, @ApiParam(value = "Return converted value using displayed unit", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @ApiParam(value = "Limit results", allowMultiple = false, defaultValue = "100") @RequestParam(value = "limit", defaultValue = "100") int limit, @ApiParam(value = "Return cached data?", allowMultiple = false, defaultValue = "true") @RequestParam(value = "useCache", defaultValue = "true") boolean useCache, @ApiParam(value = "Date Time format pattern for timestamps as strings, if not included epoch milli number is used", required = false, allowMultiple = false) @RequestParam(value = "dateTimeFormat", required = false) String dateTimeFormat, @ApiParam(value = "Time zone of output, used if formatted times are returned", required = false, allowMultiple = false) @RequestParam(value = "timezone", required = false) String timezone) {
    RestProcessResult<ObjectStream<Map<String, List<PointValueTime>>>> result = new RestProcessResult<ObjectStream<Map<String, List<PointValueTime>>>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataSourceVO<?> ds = DataSourceDao.instance.getByXid(dataSourceXid);
        if (ds == null)
            throw new NotFoundRestException();
        if (dateTimeFormat != null) {
            try {
                DateTimeFormatter.ofPattern(dateTimeFormat);
            } catch (IllegalArgumentException e) {
                RestValidationResult vr = new RestValidationResult();
                vr.addError("validate.invalid", "dateTimeFormat");
                throw new ValidationFailedRestException(vr);
            }
        }
        if (timezone != null) {
            try {
                ZoneId.of(timezone);
            } catch (Exception e) {
                RestValidationResult vr = new RestValidationResult();
                vr.addError("validate.invalidValue", "timezone");
                throw new ValidationFailedRestException(vr);
            }
        }
        List<DataPointVO> points = DataPointDao.instance.getDataPointsForDataSourceStart(ds.getId());
        Map<Integer, DataPointVO> pointIdMap = new HashMap<Integer, DataPointVO>(points.size());
        for (DataPointVO vo : points) {
            if (Permissions.hasDataPointReadPermission(user, vo))
                pointIdMap.put(vo.getId(), vo);
            else {
                // Abort, invalid permissions
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        }
        // Do we have any valid points?
        if (pointIdMap.size() == 0) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        try {
            XidPointValueTimeLatestPointFacadeStream pvtDatabaseStream = new XidPointValueTimeLatestPointFacadeStream(pointIdMap, useRendered, unitConversion, limit, useCache, dateTimeFormat, timezone);
            return result.createResponseEntity(pvtDatabaseStream);
        } catch (PermissionException e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : RestValidationResult(com.infiniteautomation.mango.rest.v2.model.RestValidationResult) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) User(com.serotonin.m2m2.vo.User) ValidationFailedRestException(com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException) HashMap(java.util.HashMap) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) ValidationFailedRestException(com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException) RTException(com.serotonin.m2m2.rt.RTException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) XidPointValueTimeLatestPointFacadeStream(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.XidPointValueTimeLatestPointFacadeStream) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) ObjectStream(com.serotonin.m2m2.web.mvc.rest.v1.model.ObjectStream) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 42 with DataSourceVO

use of com.serotonin.m2m2.vo.dataSource.DataSourceVO in project ma-modules-public by infiniteautomation.

the class DataPointRestController method getDataPointsForDataSource.

@ApiOperation(value = "Get all data points for data source", notes = "Returned as CSV or JSON, only points that user has read permission to are returned")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json", "text/csv", "application/sero-json" }, value = "/data-source/{xid}")
public ResponseEntity<List<DataPointModel>> getDataPointsForDataSource(@ApiParam(value = "Valid Data Source XID", required = true, allowMultiple = false) @PathVariable String xid, HttpServletRequest request) {
    RestProcessResult<List<DataPointModel>> result = new RestProcessResult<List<DataPointModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataSourceVO<?> dataSource = DataSourceDao.instance.getDataSource(xid);
        if (dataSource == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        try {
            if (!Permissions.hasDataSourcePermission(user, dataSource)) {
                LOG.warn("User: " + user.getUsername() + " tried to access data source with xid " + xid);
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.warn(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        List<DataPointVO> dataPoints = DataPointDao.instance.getDataPoints(dataSource.getId(), null);
        List<DataPointModel> userDataPoints = new ArrayList<DataPointModel>();
        for (DataPointVO vo : dataPoints) {
            try {
                if (Permissions.hasDataPointReadPermission(user, vo)) {
                    userDataPoints.add(new DataPointModel(vo));
                }
            } catch (PermissionException e) {
            // Munched
            }
        }
        result.addRestMessage(getSuccessMessage());
        return result.createResponseEntity(userDataPoints);
    }
    return result.createResponseEntity();
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) 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) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 43 with DataSourceVO

use of com.serotonin.m2m2.vo.dataSource.DataSourceVO 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 44 with DataSourceVO

use of com.serotonin.m2m2.vo.dataSource.DataSourceVO in project ma-modules-public by infiniteautomation.

the class DataSourceRestController method queryRQL.

@ApiOperation(value = "Query Data Sources", notes = "Use RQL formatted query", response = AbstractDataSourceModel.class, responseContainer = "List")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<QueryDataPageStream<DataSourceVO<?>>> queryRQL(HttpServletRequest request) {
    RestProcessResult<QueryDataPageStream<DataSourceVO<?>>> result = new RestProcessResult<QueryDataPageStream<DataSourceVO<?>>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        try {
            ASTNode node = parseRQLtoAST(request.getQueryString());
            DataSourceStreamCallback callback = new DataSourceStreamCallback(this, user);
            return result.createResponseEntity(getPageStream(node, callback));
        } catch (InvalidRQLRestException e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
            return result.createResponseEntity();
        }
    }
    return result.createResponseEntity();
}
Also used : DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) QueryDataPageStream(com.serotonin.m2m2.web.mvc.rest.v1.model.QueryDataPageStream) User(com.serotonin.m2m2.vo.User) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) ASTNode(net.jazdw.rql.parser.ASTNode) DataSourceStreamCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.DataSourceStreamCallback) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 45 with DataSourceVO

use of com.serotonin.m2m2.vo.dataSource.DataSourceVO 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)

Aggregations

User (com.serotonin.m2m2.vo.User)31 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)28 ArrayList (java.util.ArrayList)21 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)19 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)18 DataSourceVO (com.serotonin.m2m2.vo.dataSource.DataSourceVO)18 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)18 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)18 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)15 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)15 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)11 List (java.util.List)10 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)9 AbstractDataSourceModel (com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel)8 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)6 MockDataSourceVO (com.serotonin.m2m2.vo.dataSource.mock.MockDataSourceVO)6 DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)6 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)5 URI (java.net.URI)5 HashMap (java.util.HashMap)5