use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.
the class EventTypesRestController method getEventTypesForSubtype.
/**
* Generate a list of all event types generalized by sub-type
*/
private List<EventTypeVOModel<?, ?, ?>> getEventTypesForSubtype(String typeName, String subtype, PermissionHolder user) throws NotFoundException {
// track if the type was a default type
List<EventTypeVOModel<?, ?, ?>> types = new ArrayList<>();
boolean found = false;
switch(typeName) {
case EventTypeNames.DATA_POINT:
// There is no subtype for data points
if (subtype != null)
throw new BadRequestException();
// Get Event Detectors, ensure only 1 data point in list
// TODO via query instead
List<AbstractPointEventDetectorVO> detectors = this.eventDetectorDao.getAllPointEventDetectors();
Map<Integer, DataPointVO> uniquePointsMap = new HashMap<>();
for (AbstractPointEventDetectorVO detector : detectors) {
uniquePointsMap.put(detector.getDataPoint().getId(), detector.getDataPoint());
}
for (DataPointVO vo : uniquePointsMap.values()) {
// Shortcut to check permissions via event type
if (dataPointService.hasReadPermission(user, vo)) {
DataPointEventTypeModel model = new DataPointEventTypeModel(new DataPointEventType(vo.getDataSourceId(), vo.getId(), 0, null), modelMapper.map(vo, DataPointModel.class, user));
types.add(new EventTypeVOModel<DataPointEventType, DataPointModel, AbstractPointEventDetectorModel<?>>(model, new TranslatableMessage("event.eventsFor", vo.getName()), false, true, true));
}
}
found = true;
break;
case EventTypeNames.DATA_SOURCE:
// There is no subtype for data sources
if (subtype != null)
throw new BadRequestException();
for (DataSourceVO vo : dataSourceDao.getAll()) {
if (permissionService.hasPermission(user, vo.getReadPermission())) {
AbstractDataSourceModel<?> dsModel = modelMapper.map(vo, AbstractDataSourceModel.class, user);
DataSourceEventTypeModel model = new DataSourceEventTypeModel(new DataSourceEventType(vo.getId(), 0), dsModel);
types.add(new EventTypeVOModel<DataSourceEventType, AbstractDataSourceModel<?>, String>(model, new TranslatableMessage("event.eventsFor", vo.getName()), false, true, true));
}
}
found = true;
break;
case EventTypeNames.PUBLISHER:
// There is no subtype for publishers
if (subtype != null)
throw new BadRequestException();
// There are no permissions for publishers
if (!permissionService.hasAdminRole(user))
break;
for (PublisherVO vo : publisherDao.getAll()) {
AbstractPublisherModel<?, ?> publisherModel = modelMapper.map(vo, AbstractPublisherModel.class, user);
PublisherEventTypeModel model = new PublisherEventTypeModel(new PublisherEventType(vo.getId(), 0), publisherModel);
types.add(new EventTypeVOModel<PublisherEventType, AbstractPublisherModel<?, ?>, String>(model, new TranslatableMessage("event.eventsFor", vo.getName()), false, true, true));
}
found = true;
break;
case EventTypeNames.SYSTEM:
// System
for (SystemEventTypeDefinition def : ModuleRegistry.getDefinitions(SystemEventTypeDefinition.class)) {
if (!StringUtils.equals(def.getTypeName(), subtype))
continue;
found = true;
for (EventTypeVO type : def.generatePossibleEventTypesWithReferenceId1(user, subtype)) {
SystemEventType eventType = (SystemEventType) type.getEventType();
SystemEventTypeModel model = modelMapper.map(eventType, SystemEventTypeModel.class, user);
types.add(new EventTypeVOModel<>(model, type.getDescription(), type.getAlarmLevel(), true, def.supportsReferenceId1(), def.supportsReferenceId2()));
}
break;
}
break;
case EventTypeNames.AUDIT:
// Audit does not yet support reference id 1
throw new BadRequestException();
}
if (!found) {
// Module defined
for (EventTypeDefinition def : ModuleRegistry.getDefinitions(EventTypeDefinition.class)) {
if (StringUtils.equals(typeName, def.getTypeName())) {
found = true;
for (EventTypeVO type : def.generatePossibleEventTypesWithReferenceId1(user, subtype, permissionService)) {
EventType eventType = type.getEventType();
AbstractEventTypeModel<?, ?, ?> model = modelMapper.map(eventType, AbstractEventTypeModel.class, user);
types.add(new EventTypeVOModel<>(model, type.getDescription(), type.getAlarmLevel(), def.supportsSubType(), def.supportsReferenceId1(), def.supportsReferenceId2()));
}
break;
}
}
}
if (!found)
throw new NotFoundException();
return types;
}
use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method purgePointValues.
@ApiOperation(value = "Purge Point Values for one or many data points, or a single data source", notes = "User must have edit access to data source and its points, use created header to track progress/cancel")
@RequestMapping(method = RequestMethod.POST, value = "/purge")
public ResponseEntity<TemporaryResource<PurgePointValuesResponseModel, AbstractRestException>> purgePointValues(@RequestBody() PurgeDataPointValuesModel model, UriComponentsBuilder builder) {
model.ensureValid();
TemporaryResource<PurgePointValuesResponseModel, AbstractRestException> response = resourceManager.newTemporaryResource("DATA_POINT_PURGE", null, model.getExpiry(), model.getTimeout(), (resource) -> {
PurgePointValuesResponseModel result = new PurgePointValuesResponseModel();
Map<Integer, DataSourceVO> dataSourceMap = new HashMap<>();
Map<String, DataPointVO> dataPointsMap = new HashMap<>();
// Build the list of data point Xids
List<String> xids = model.getXids();
if (xids != null && !xids.isEmpty()) {
for (String xid : xids) {
DataPointVO vo = dataPointService.get(xid);
dataPointsMap.put(xid, vo);
if (vo != null) {
dataSourceMap.computeIfAbsent(vo.getDataSourceId(), (key) -> dataSourceService.get(vo.getDataSourceId()));
}
}
} else {
DataSourceVO ds = dataSourceService.get(model.getDataSourceXid());
xids = new ArrayList<>();
if (ds != null) {
dataSourceMap.put(ds.getId(), ds);
List<DataPointVO> points = dataPointService.getDataPoints(ds.getId());
for (DataPointVO point : points) {
xids.add(point.getXid());
dataPointsMap.put(point.getXid(), point);
}
}
}
int maximum = xids.size();
int position = 0;
// Initial status
resource.progressOrSuccess(result, position, maximum);
for (String xid : xids) {
try {
// Get the point and its data source XID
DataPointVO dp = dataPointsMap.get(xid);
if (dp == null)
throw new NotFoundException();
DataSourceVO ds = dataSourceMap.get(dp.getDataSourceId());
if (ds == null)
throw new NotFoundException();
// Do purge based on settings
if (model.isPurgeAll())
Common.runtimeManager.purgeDataPointValues(dp);
else if (model.isUseTimeRange())
Common.runtimeManager.purgeDataPointValuesBetween(dp, model.getTimeRange().getFrom().getTime(), model.getTimeRange().getTo().getTime());
else {
long before = DateUtils.minus(Common.timer.currentTimeMillis(), TimePeriodType.convertFrom(model.getDuration().getType()), model.getDuration().getPeriods());
Common.runtimeManager.purgeDataPointValues(dp, before);
}
result.getSuccessfullyPurged().add(xid);
} catch (NotFoundException e) {
result.getNotFound().add(xid);
} catch (PermissionException e) {
result.getNoEditPermission().add(xid);
}
position++;
resource.progressOrSuccess(result, position, maximum);
}
return null;
});
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/point-values/purge/{id}").buildAndExpand(response.getId()).toUri());
return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
}
use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.
the class ScriptRestController method evalScript.
@Async
@ApiOperation(value = "Evaluate a filestore file as a script on the backend using a scripting engine")
@RequestMapping(method = RequestMethod.POST, value = "/eval-file-store/{fileStoreName}/**")
public CompletableFuture<Void> evalScript(@ApiParam(value = "File store name", required = true) @PathVariable(required = true) String fileStoreName, @ApiParam(value = "Script engine name", required = false) @RequestParam(required = false) String engineName, @ApiParam(value = "Script file character set", required = false, defaultValue = "UTF-8") @RequestParam(required = false, defaultValue = "UTF-8") String fileCharset, @ApiParam(value = "Script roles", required = false, allowMultiple = true) @RequestParam(required = false) String[] roles, @ApiIgnore @RemainingPath String path, @AuthenticationPrincipal PermissionHolder user, HttpServletRequest request, HttpServletResponse response) throws IOException {
Path filePath = fileStoreService.getPathForRead(fileStoreName, path);
if (!Files.exists(filePath)) {
throw new NotFoundException();
}
if (engineName == null) {
engineName = scriptService.findEngineForFile(filePath);
}
Charset fileCharsetParsed = Charset.forName(fileCharset);
Set<Role> roleSet;
if (roles != null) {
roleSet = Arrays.stream(roles).map(xid -> this.roleService.get(xid).getRole()).collect(Collectors.toSet());
} else {
roleSet = user.getRoles();
}
EvalContext evalContext = new EvalContext();
Reader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.forName(request.getCharacterEncoding())));
Writer writer = new OutputStreamWriter(response.getOutputStream(), Charset.forName(response.getCharacterEncoding()));
evalContext.setReader(reader);
evalContext.setWriter(writer);
evalContext.addBinding("reader", reader);
evalContext.addBinding("writer", writer);
if (permissionService.hasPermission(user, requestResponsePermission.getPermission())) {
evalContext.addBinding("request", request);
evalContext.addBinding("response", response);
}
this.scriptService.eval(new PathMangoScript(engineName, roleSet, filePath, fileCharsetParsed), evalContext);
return CompletableFuture.completedFuture(null);
}
use of com.infiniteautomation.mango.util.exception.NotFoundException 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.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.
the class WatchListService method commonValidation.
protected ProcessResult commonValidation(WatchListVO vo) {
ProcessResult response = super.validate(vo);
if (vo.getType() == null) {
String values = Arrays.asList(WatchListType.values()).toString();
response.addContextualMessage("type", "validate.invalidValueWithAcceptable", vo.getType(), values);
}
if (vo.getType() == WatchListType.STATIC) {
// Validate Points, we cannot trust the permissions from the passed in points from vo, we must look them up from the DB
List<IDataPoint> newSummaries = vo.getPointList().stream().map(s -> {
try {
return dataPointService.getSummary(s.getXid());
} catch (PermissionException e) {
response.addContextualMessage("points", "watchlist.validate.pointNoReadPermission", s.getXid());
} catch (NotFoundException e) {
response.addContextualMessage("points", "watchList.validate.pointNotFound", s.getXid());
}
return null;
}).filter(Objects::nonNull).collect(Collectors.toList());
vo.setPointList(newSummaries);
}
return response;
}
Aggregations