use of com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel in project ma-modules-public by infiniteautomation.
the class PointValueRestController method getRollupPointValues.
@ApiOperation(value = "Rollup values For 1 Data Point, return in time ascending order", notes = "From time inclusive, To time exclusive.", response = PointValueTimeModel.class, responseContainer = "Array")
@RequestMapping(method = RequestMethod.GET, value = "/time-period/{xid}/{rollup}")
public ResponseEntity<PointValueTimeStream<PointValueTimeModel, ZonedDateTimeRangeQueryInfo>> getRollupPointValues(HttpServletRequest request, @ApiParam(value = "Point xid", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Rollup type", required = false, allowMultiple = false) @PathVariable(value = "rollup") RollupEnum rollup, @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 = "From time", required = false, allowMultiple = false) @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime from, @ApiParam(value = "To time", required = false, allowMultiple = false) @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime to, @ApiParam(value = "Time zone", required = false, allowMultiple = false) @RequestParam(value = "timezone", required = false) String timezone, @ApiParam(value = "Limit", required = false, allowMultiple = false) @RequestParam(value = "limit", required = false) Integer limit, @ApiParam(value = "Time Period Type", required = false, allowMultiple = false) @RequestParam(value = "timePeriodType", required = false) TimePeriodType timePeriodType, @ApiParam(value = "Time Periods", required = false, allowMultiple = false) @RequestParam(value = "timePeriods", required = false) Integer timePeriods, @ApiParam(value = "Truncate the from time and expand to time based on the time period settings", required = false, allowMultiple = false) @RequestParam(value = "truncate", required = false, defaultValue = "false") boolean truncate, @ApiParam(value = "Fields to be included in the returned data, default is TIMESTAMP,VALUE", required = false, allowMultiple = false) @RequestParam(required = false) PointValueField[] fields, @AuthenticationPrincipal User user) {
TimePeriod timePeriod = null;
if ((timePeriodType != null) && (timePeriods != null)) {
timePeriod = new TimePeriod(timePeriods, timePeriodType);
}
ZonedDateTimeRangeQueryInfo info = new ZonedDateTimeRangeQueryInfo(from, to, dateTimeFormat, timezone, rollup, timePeriod, limit, true, false, true, PointValueTimeCacheControl.NONE, null, null, truncate, fields);
return generateStream(user, info, new String[] { xid });
}
use of com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel in project ma-modules-public by infiniteautomation.
the class PointValueFunctionalTests method testGetAllAdmin.
@SuppressWarnings({ "rawtypes", "unchecked" })
public void testGetAllAdmin() {
List<User> users = new ArrayList<>();
User adminUser = UserTestData.adminUser();
users.add(adminUser);
users.add(UserTestData.newAdminUser());
users.add(UserTestData.standardUser());
// Setup our Mock DS
DataSourceVO ds = DataSourceTestData.mockDataSource();
// Configure our REST get settings
String xid = ds.getXid();
// Date to = new Date();
// Date from = new Date(to.getTime() - 1000 * 60 * 60);
// RollupEnum rollup = null;
// TimePeriodType timePeriodType = null;
// Integer timePeriods = null;
// This will ensure that the getUsers() method returns
// the mock list of users
when(userDao.getUsers()).thenReturn(users);
try {
MvcResult result = this.mockMvc.perform(get("/v1/pointValues" + xid + ".json").sessionAttr("sessionUser", adminUser).param("from", "2014-08-10T00:00:00.000-10:00").param("to", "2014-08-10T00:00:00.000-10:00").accept(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andReturn();
List<PointValueTimeModel> models = this.objectMapper.readValue(result.getResponse().getContentAsString(), objectMapper.getTypeFactory().constructCollectionType(List.class, PointValueTimeModel.class));
// Check the size
assertEquals(users.size(), models.size());
} catch (Exception e) {
fail(e.getMessage());
}
// Check the data
}
use of com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel in project ma-modules-public by infiniteautomation.
the class PointValueRestController method firstAndLastPointValues.
@ApiOperation(value = "First and last point values", notes = "Retrieves the first and last point values within a time range, used to read accumulators")
@RequestMapping(method = RequestMethod.GET, value = "/{xid}/first-last", produces = { "application/json", "text/csv" })
public ResponseEntity<List<PointValueTimeModel>> firstAndLastPointValues(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 = "From time", required = false, allowMultiple = false) @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime from, @ApiParam(value = "To time", required = false, allowMultiple = false) @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime to, @ApiParam(value = "Time zone of output, used if formatted times are returned", required = false, allowMultiple = false) @RequestParam(value = "timezone", required = false) String timezone) {
RestProcessResult<List<PointValueTimeModel>> result = new RestProcessResult<List<PointValueTimeModel>>(HttpStatus.OK);
User user = this.checkUser(request, result);
if (result.isOk()) {
if (timezone != null) {
try {
ZoneId.of(timezone);
} catch (Exception e) {
RestValidationResult vr = new RestValidationResult();
vr.addError("validate.invalidValue", "timezone");
throw new ValidationFailedRestException(vr);
}
}
DataPointVO vo = DataPointDao.instance.getByXid(xid);
if (vo == null) {
result.addRestMessage(getDoesNotExistMessage());
return result.createResponseEntity();
}
try {
if (Permissions.hasDataPointReadPermission(user, vo)) {
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);
}
PointValueFacade pointValueFacade = new PointValueFacade(vo.getId(), false);
PointValueTime first = pointValueFacade.getPointValueAfter(from.getMillis());
PointValueTime last = pointValueFacade.getPointValueBefore(to.getMillis());
List<PointValueTimeModel> models = new ArrayList<PointValueTimeModel>(2);
if (useRendered) {
if (first != null) {
PointValueTimeModel model = new PointValueTimeModel();
model.setType(DataTypeEnum.convertTo(first.getValue().getDataType()));
model.setValue(Functions.getRenderedText(vo, first));
model.setTimestamp(first.getTime());
if (first.isAnnotated())
model.setAnnotation(((AnnotatedPointValueTime) first).getAnnotation(Common.getTranslations()));
models.add(model);
}
if (last != null) {
PointValueTimeModel model = new PointValueTimeModel();
model.setType(DataTypeEnum.convertTo(last.getValue().getDataType()));
model.setValue(Functions.getRenderedText(vo, last));
model.setTimestamp(last.getTime());
if (last.isAnnotated())
model.setAnnotation(((AnnotatedPointValueTime) last).getAnnotation(Common.getTranslations()));
models.add(model);
}
} else if (unitConversion) {
if (first != null) {
PointValueTimeModel model = new PointValueTimeModel();
model.setType(DataTypeEnum.convertTo(first.getValue().getDataType()));
model.setValue(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(first.getValue().getDoubleValue()));
model.setTimestamp(first.getTime());
if (first.isAnnotated())
model.setAnnotation(((AnnotatedPointValueTime) first).getAnnotation(Common.getTranslations()));
models.add(model);
}
if (last != null) {
PointValueTimeModel model = new PointValueTimeModel();
model.setType(DataTypeEnum.convertTo(last.getValue().getDataType()));
model.setValue(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(last.getValue().getDoubleValue()));
model.setTimestamp(last.getTime());
if (last.isAnnotated())
model.setAnnotation(((AnnotatedPointValueTime) last).getAnnotation(Common.getTranslations()));
models.add(model);
}
} else {
models.add(first == null ? null : new PointValueTimeModel(first));
models.add(last == null ? null : new PointValueTimeModel(last));
}
if (vo.getPointLocator().getDataTypeId() == DataTypes.IMAGE) {
// If we are an image type we should build the URLS
UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/hst{ts}_{id}.jpg");
for (PointValueTimeModel model : models) {
model.setValue(imageServletBuilder.buildAndExpand(model.getTimestamp(), vo.getId()).toUri());
}
}
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.web.mvc.rest.v1.model.pointValue.PointValueTimeModel in project ma-modules-public by infiniteautomation.
the class PointValueRestController method setPointValue.
/**
* Helper method for setting a point value
*
* @param xid
* @param data
* @param unitConversion
* @return
*/
private RestProcessResult<PointValueTimeModel> setPointValue(User user, String xid, PointValueTimeModel model, boolean unitConversion, UriComponentsBuilder builder) {
RestProcessResult<PointValueTimeModel> result = new RestProcessResult<PointValueTimeModel>(HttpStatus.OK);
DataPointVO existingDp = DataPointDao.instance.getByXid(xid);
if (existingDp == null) {
result.addRestMessage(getDoesNotExistMessage());
return result;
}
try {
if (Permissions.hasDataPointSetPermission(user, existingDp)) {
// Set the time to now if it is not present
if (model.getTimestamp() == 0) {
model.setTimestamp(Common.timer.currentTimeMillis());
}
// Validate the model's data type for compatibility
if (DataTypeEnum.convertFrom(model.getType()) != existingDp.getPointLocator().getDataTypeId()) {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
return result;
}
// Validate the timestamp for future dated
if (model.getTimestamp() > Common.timer.currentTimeMillis() + SystemSettingsDao.getFutureDateLimit()) {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Future dated points not acceptable."));
return result;
}
// Are we converting from the rendered Unit?
if (unitConversion) {
if ((model.getType() == DataTypeEnum.NUMERIC) && (model.getValue() instanceof Number)) {
double value;
if (model.getValue() instanceof Integer) {
value = (double) ((Integer) model.getValue());
} else {
value = (double) ((Double) model.getValue());
}
model.setValue(existingDp.getRenderedUnit().getConverterTo(existingDp.getUnit()).convert(value));
} else {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Cannot perform unit conversion on Non Numeric data types."));
return result;
}
}
// to convert it
if ((model.getType() == DataTypeEnum.MULTISTATE) && (model.getValue() instanceof String)) {
try {
DataValue value = existingDp.getTextRenderer().parseText((String) model.getValue(), existingDp.getPointLocator().getDataTypeId());
model.setValue(value.getObjectValue());
} catch (Exception e) {
// Lots can go wrong here so let the user know
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Unable to convert Multistate String representation to any known value."));
}
}
final PointValueTime pvt;
try {
pvt = model.getData();
} catch (Exception e) {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Invalid Format"));
return result;
}
// one last check to ensure we are inserting the correct data type
if (DataTypes.getDataType(pvt.getValue()) != existingDp.getPointLocator().getDataTypeId()) {
result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
return result;
}
final int dataSourceId = existingDp.getDataSourceId();
SetPointSource source = null;
if (model.getAnnotation() != null) {
source = new SetPointSource() {
@Override
public String getSetPointSourceType() {
return "REST";
}
@Override
public int getSetPointSourceId() {
return dataSourceId;
}
@Override
public TranslatableMessage getSetPointSourceMessage() {
return ((AnnotatedPointValueTime) pvt).getSourceMessage();
}
@Override
public void raiseRecursionFailureEvent() {
LOG.error("Recursive failure while setting point via REST");
}
};
}
try {
Common.runtimeManager.setDataPointValue(existingDp.getId(), pvt, source);
// This URI may not always be accurate if the Data Source doesn't use the
// provided time...
URI location = builder.path("/v1/point-values/{xid}/{time}").buildAndExpand(xid, pvt.getTime()).toUri();
result.addRestMessage(getResourceCreatedMessage(location));
return result;
} catch (RTException e) {
// Ok its probably not enabled or settable
result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]" + e.getMessage())));
return result;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
return result;
}
} else {
result.addRestMessage(getUnauthorizedMessage());
return result;
}
} catch (PermissionException e) {
LOG.error(e.getMessage(), e);
result.addRestMessage(getUnauthorizedMessage());
return result;
}
}
use of com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel 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();
}
}
Aggregations