use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method getLatestPointValues.
/**
* Get the latest point values for a point
*
* @param xid
* @param limit
* @return
*/
@ApiOperation(value = "Get Latest Point Values 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. For the most efficient use of this endpoint " + " the data point's default cache size should be the size that you will typically query the latest values of.")
@RequestMapping(method = RequestMethod.GET, value = "/{xid}/latest", produces = { "application/json", "text/csv" })
public ResponseEntity<List<RecentPointValueTimeModel>> getLatestPointValues(HttpServletRequest request, @ApiParam(value = "Point xid", required = true, allowMultiple = false) @PathVariable String xid, @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) {
RestProcessResult<List<RecentPointValueTimeModel>> result = new RestProcessResult<List<RecentPointValueTimeModel>>(HttpStatus.OK);
User user = this.checkUser(request, result);
if (result.isOk()) {
DataPointVO vo = DataPointDao.instance.getByXid(xid);
if (vo == null) {
result.addRestMessage(getDoesNotExistMessage());
return result.createResponseEntity();
}
try {
if (Permissions.hasDataPointReadPermission(user, vo)) {
// Check to see if we can convert (Must be a Numeric Value)
if (unitConversion && (vo.getPointLocator().getDataTypeId() != DataTypes.NUMERIC)) {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Can't convert non-numeric types."));
return result.createResponseEntity();
}
// If we are an image type we should build the URLS
UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/hst{ts}_{id}.jpg");
List<RecentPointValueTimeModel> models;
if (useCache) {
// In an effort not to expand the PointValueCache we avoid the
// PointValueFacade
DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getId());
if (rt != null) {
List<PointValueTime> cache = rt.getCacheCopy();
if (limit < cache.size()) {
List<PointValueTime> pvts = cache.subList(0, limit);
models = new ArrayList<>(limit);
for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
} else {
// We need to merge 2 lists
List<PointValueTime> disk = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
Set<RecentPointValueTimeModel> all = new HashSet<RecentPointValueTimeModel>(limit);
for (PointValueTime pvt : cache) all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
for (PointValueTime pvt : disk) {
if (all.size() >= limit)
break;
else
all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
}
models = new ArrayList<>(all);
// Override the comparison method
Collections.sort(models, new Comparator<RecentPointValueTimeModel>() {
// Compare such that data sets are returned in time
// descending order
// which turns out is opposite of compare to method for
// PointValueTime objects
@Override
public int compare(RecentPointValueTimeModel o1, RecentPointValueTimeModel o2) {
if (o1.getTimestamp() < o2.getTimestamp())
return 1;
if (o1.getTimestamp() > o2.getTimestamp())
return -1;
return 0;
}
});
}
} else {
List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
models = new ArrayList<>(limit);
for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
}
} else {
models = new ArrayList<>(limit);
List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
}
return result.createResponseEntity(models);
} else {
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
} catch (PermissionException e) {
LOG.error(e.getMessage(), e);
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
} else {
return result.createResponseEntity();
}
}
use of com.serotonin.m2m2.vo.permission.PermissionException 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();
}
}
use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method pointValuesForMultiplePointsAsSingleArray.
private ResponseEntity<QueryArrayStream<PointValueTimeModel>> pointValuesForMultiplePointsAsSingleArray(HttpServletRequest request, String[] xids, boolean useRendered, boolean unitConversion, DateTime from, DateTime to, RollupEnum rollup, TimePeriodType timePeriodType, Integer timePeriods, String timezone, Integer limit, String dateTimeFormat) {
RestProcessResult<QueryArrayStream<PointValueTimeModel>> result = new RestProcessResult<QueryArrayStream<PointValueTimeModel>>(HttpStatus.OK);
User user = this.checkUser(request, result);
if (result.isOk()) {
if (dateTimeFormat != null) {
try {
DateTimeFormatter.ofPattern(dateTimeFormat);
} catch (IllegalArgumentException e) {
RestValidationResult vr = new RestValidationResult();
vr.addError("validate.invalid", "dateTimeFormat");
throw new ValidationFailedRestException(vr);
}
}
Map<Integer, DataPointVO> pointIdMap = new HashMap<Integer, DataPointVO>(xids.length);
DataPointVO vo;
for (String xid : xids) {
vo = DataPointDao.instance.getByXid(xid);
if (vo != null) {
if (Permissions.hasDataPointReadPermission(user, vo))
pointIdMap.put(vo.getId(), vo);
else {
// Abort, invalid permissions
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
}
}
if (timezone != null) {
try {
ZoneId.of(timezone);
} catch (Exception e) {
RestValidationResult vr = new RestValidationResult();
vr.addError("validate.invalidValue", "timezone");
throw new ValidationFailedRestException(vr);
}
}
// Do we have any valid points?
if (pointIdMap.size() == 0) {
result.addRestMessage(getDoesNotExistMessage());
return result.createResponseEntity();
}
try {
long current = Common.timer.currentTimeMillis();
if (from == null)
from = new DateTime(current);
if (to == null)
to = new DateTime(current);
// better not to for RESTfulness
if (timezone != null) {
DateTimeZone zone = DateTimeZone.forID(timezone);
from = from.withZone(zone);
to = to.withZone(zone);
}
// Are we using rollup
if ((rollup != null) && (rollup != RollupEnum.NONE)) {
if (rollup == RollupEnum.FFT) {
// Special Rollup for FFT's with no time rollup action
// TODO Need a way to return frequency or period values
// IdPointValueFftCalculator calc = new
// IdPointValueFftCalculator(pointIdMap, from.getTime(), to.getTime(),
// true);
// return result.createResponseEntity(calc);
} else {
TimePeriod timePeriod = null;
if ((timePeriodType != null) && (timePeriods != null)) {
timePeriod = new TimePeriod(timePeriods, timePeriodType);
}
IdPointValueRollupCalculator calc = new IdPointValueRollupCalculator(pointIdMap, useRendered, unitConversion, rollup, timePeriod, from, to, limit, dateTimeFormat, timezone);
return result.createResponseEntity(calc);
}
return result.createResponseEntity();
} else {
IdPointValueTimeDatabaseStream pvtDatabaseStream = new IdPointValueTimeDatabaseStream(pointIdMap, useRendered, unitConversion, from.getMillis(), to.getMillis(), this.dao, limit, dateTimeFormat, timezone);
return result.createResponseEntity(pvtDatabaseStream);
}
} catch (PermissionException e) {
LOG.error(e.getMessage(), e);
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
} else {
return result.createResponseEntity();
}
}
use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-modules-public by infiniteautomation.
the class RuntimeManagerRestController method forceRefreshDataPoint.
@ApiOperation(value = "Force Refresh a data point", notes = "Not all data sources implement this feature", response = Void.class)
@RequestMapping(method = RequestMethod.PUT, value = "/force-refresh/{xid}")
public ResponseEntity<Void> forceRefreshDataPoint(@ApiParam(value = "Valid Data Point XID", required = true, allowMultiple = false) @PathVariable String xid, HttpServletRequest request) {
RestProcessResult<Void> result = new RestProcessResult<Void>(HttpStatus.OK);
try {
User user = this.checkUser(request, result);
if (result.isOk()) {
if (xid == null) {
result.addRestMessage(getDoesNotExistMessage());
return result.createResponseEntity();
}
DataPointVO vo = DataPointDao.instance.getByXid(xid);
if (vo == null) {
result.addRestMessage(getDoesNotExistMessage());
return result.createResponseEntity();
}
try {
if (!Permissions.hasDataPointReadPermission(user, vo)) {
LOG.warn("User " + user.getUsername() + " attempted to refesh data point with xid: " + vo.getXid() + " without read permission");
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
} catch (PermissionException e) {
LOG.warn("User " + user.getUsername() + " attempted to refesh data point with xid: " + vo.getXid() + " without read permission");
result.addRestMessage(getUnauthorizedMessage());
return result.createResponseEntity();
}
DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getId());
if (rt == null) {
result.addRestMessage(getPointNotEnabledMessage(xid));
return result.createResponseEntity();
}
Common.runtimeManager.forcePointRead(vo.getId());
}
} catch (Exception e) {
result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
}
return result.createResponseEntity();
}
use of com.serotonin.m2m2.vo.permission.PermissionException 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();
}
Aggregations