use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.
the class PointValueWebSocketHandler method handleTextMessage.
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
try {
PermissionHolder user = getUser(session);
PointValueRegistrationModel model = this.jacksonMapper.readValue(message.getPayload(), PointValueRegistrationModel.class);
DataPointVO vo;
try {
// This will check for not found and permissions
vo = datapointService.get(model.getDataPointXid());
} catch (NotFoundException e) {
// send not found message back
this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.pointNotFound", model.getDataPointXid()));
return;
} catch (PermissionException e) {
// Send permission denied message here
this.sendErrorMessage(session, MangoWebSocketErrorType.PERMISSION_DENIED, new TranslatableMessage("permission.exception.readDataPoint", user.getPermissionHolderName()));
return;
}
Set<PointValueEventType> eventsTypes = model.getEventTypes();
int dataPointId = vo.getId();
synchronized (pointIdToListenerMap) {
if (this.connectionClosed) {
return;
}
PointValueWebSocketListener publisher = pointIdToListenerMap.get(dataPointId);
if (publisher != null) {
if (eventsTypes.isEmpty()) {
publisher.terminate();
pointIdToListenerMap.remove(dataPointId);
} else {
publisher.setEventTypes(eventsTypes);
}
} else if (!eventsTypes.isEmpty()) {
publisher = new PointValueWebSocketListener(vo, eventsTypes);
publisher.initialize();
// Immediately send the most recent Point Value and the status of the data point
publisher.sendPointStatus();
pointIdToListenerMap.put(dataPointId, publisher);
}
}
} catch (WebSocketSendException e) {
log.warn("Error sending websocket message", e);
} catch (Exception e) {
try {
this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
} catch (Exception e1) {
log.error("An error occurred", e);
}
}
if (log.isDebugEnabled()) {
log.debug(message.getPayload());
}
}
use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.
the class PointValueRestController method deletePointValues.
@ApiOperation(value = "Delete point values >= from and < to", notes = "The user must have set permission to the data point. If date is not supplied it defaults to now.")
@RequestMapping(method = RequestMethod.DELETE, value = "/{xid}")
public ResponseEntity<Long> deletePointValues(@ApiParam(value = "Point xids", required = true) @PathVariable String xid, @ApiParam(value = "From time") @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime from, @ApiParam(value = "To time") @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime to, @ApiParam(value = "Time zone") @RequestParam(value = "timezone", required = false) String timezone, @AuthenticationPrincipal PermissionHolder user) {
DataPointVO vo = dataPointService.get(xid);
dataPointService.ensureSetPermission(user, vo);
ZoneId zoneId;
if (timezone == null) {
if (from != null) {
zoneId = from.getZone();
} else if (to != null)
zoneId = to.getZone();
else
zoneId = TimeZone.getDefault().toZoneId();
} else {
zoneId = ZoneId.of(timezone);
}
// Set the timezone on the from and to dates
long current = Common.timer.currentTimeMillis();
if (from != null)
from = from.withZoneSameInstant(zoneId);
else
from = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
if (to != null)
to = to.withZoneSameInstant(zoneId);
else
to = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
Optional<Long> result = Common.runtimeManager.purgeDataPointValuesBetween(vo, from.toInstant().toEpochMilli(), to.toInstant().toEpochMilli());
return ResponseEntity.ok().body(result.orElse(null));
}
use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.
the class PointValueRestController method putPointValue.
/**
* Update a point value in the system
*/
@ApiOperation(value = "Update an existing data point's value", notes = "Data point must exist and be enabled")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<LegacyPointValueTimeModel> putPointValue(@RequestBody() LegacyPointValueTimeModel model, @PathVariable String xid, @ApiParam(value = "Return converted value using displayed unit", defaultValue = "false") @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @AuthenticationPrincipal PermissionHolder user, UriComponentsBuilder builder) {
DataPointVO vo = this.dataPointService.get(xid);
this.dataPointService.ensureSetPermission(user, vo);
// 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 (model.getDataType() != vo.getPointLocator().getDataType()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
}
// Validate the timestamp for future dated
if (model.getTimestamp() > Common.timer.currentTimeMillis() + SystemSettingsDao.getInstance().getFutureDateLimit()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Future dated points not acceptable."));
}
// Are we converting from the rendered Unit?
if (unitConversion) {
if (model.getDataType() == DataType.NUMERIC && model.getValue() instanceof Number) {
double convertedValue = ((Number) model.getValue()).doubleValue();
UnitConverter inverseConverter = vo.getRenderedUnitConverter().inverse();
double rawValue = inverseConverter.convert(convertedValue);
model.setValue(rawValue);
} else {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Cannot perform unit conversion on Non Numeric data types."));
}
}
// to convert it
if ((model.getDataType() == DataType.MULTISTATE || model.getDataType() == DataType.NUMERIC) && (model.getValue() instanceof String)) {
try {
DataValue value = vo.getTextRenderer().parseText((String) model.getValue(), vo.getPointLocator().getDataType());
model.setValue(value.getObjectValue());
} catch (Exception e) {
// Lots can go wrong here so let the user know
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Unable to convert String representation to any known value."));
}
}
final PointValueTime pvt;
try {
DataValue dataValue;
switch(model.getDataType()) {
case ALPHANUMERIC:
dataValue = new AlphanumericValue((String) model.getValue());
break;
case BINARY:
dataValue = new BinaryValue((Boolean) model.getValue());
break;
case MULTISTATE:
dataValue = new MultistateValue(((Number) model.getValue()).intValue());
break;
case NUMERIC:
dataValue = new NumericValue(((Number) model.getValue()).doubleValue());
break;
default:
throw new UnsupportedOperationException("Setting image values not supported");
}
if (model.getAnnotation() != null)
pvt = new AnnotatedPointValueTime(dataValue, model.getTimestamp(), new TranslatableMessage("common.default", model.getAnnotation()));
else
pvt = new PointValueTime(dataValue, model.getTimestamp());
} catch (Exception e) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Invalid Format"));
}
// one last check to ensure we are inserting the correct data type
if (pvt.getValue().getDataType() != vo.getPointLocator().getDataType()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
}
final int dataSourceId = vo.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(vo.getId(), pvt, source);
// This URI may not always be accurate if the Data Source doesn't use the
// provided time...
URI location = builder.path("/point-values/{xid}/{time}").buildAndExpand(xid, pvt.getTime()).toUri();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(location);
return new ResponseEntity<>(model, headers, HttpStatus.CREATED);
} catch (RTException e) {
// Ok its probably not enabled or settable
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]" + e.getMessage()));
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServerErrorException(e);
}
}
use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.
the class PublishedPointsRestController method bulkPublishedPointOperation.
@ApiOperation(value = "Bulk get/create/update/delete published points", notes = "User be superadmin")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<PublishedPointBulkResponse, AbstractRestException>> bulkPublishedPointOperation(@RequestBody PublishedPointBulkRequest requestBody, UriComponentsBuilder builder) {
VoAction defaultAction = requestBody.getAction();
AbstractPublishedPointModel<?> defaultBody = requestBody.getBody();
List<PublishedPointIndividualRequest> requests = requestBody.getRequests();
if (requests == null) {
throw new BadRequestException(new TranslatableMessage("rest.error.mustNotBeNull", "requests"));
} else if (requests.isEmpty()) {
throw new BadRequestException(new TranslatableMessage("rest.error.cantBeEmpty", "requests"));
}
String resourceId = requestBody.getId();
Long expiration = requestBody.getExpiration();
Long timeout = requestBody.getTimeout();
TemporaryResource<PublishedPointBulkResponse, AbstractRestException> responseBody = resourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_PUBLISHED_POINT, resourceId, expiration, timeout, (resource) -> {
PublishedPointBulkResponse bulkResponse = new PublishedPointBulkResponse();
int i = 0;
resource.progressOrSuccess(bulkResponse, i++, requests.size());
PermissionHolder resourceUser = Common.getUser();
for (PublishedPointIndividualRequest request : requests) {
UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
PublishedPointIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, resourceUser, reqBuilder);
bulkResponse.addResponse(individualResponse);
resource.progressOrSuccess(bulkResponse, i++, requests.size());
}
return null;
});
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/published-points/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
return new ResponseEntity<>(responseBody, headers, HttpStatus.CREATED);
}
use of com.serotonin.m2m2.vo.permission.PermissionHolder in project ma-modules-public by infiniteautomation.
the class PublishedPointsRestController method exportPublishedPoint.
@ApiOperation(value = "Export formatted for Configuration Import")
@RequestMapping(method = RequestMethod.GET, value = "/export/{xid}", produces = MediaTypes.SEROTONIN_JSON_VALUE)
public Map<String, Object> exportPublishedPoint(@ApiParam(value = "Valid published point XID", required = true) @PathVariable String xid, @AuthenticationPrincipal PermissionHolder user) {
PublishedPointVO vo = service.get(xid);
Map<String, Object> export = new LinkedHashMap<>();
export.put("publishedPoints", Collections.singletonList(vo));
return export;
}
Aggregations