Search in sources :

Example 1 with NotFoundException

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;
}
Also used : AbstractPointEventDetectorModel(com.infiniteautomation.mango.rest.latest.model.event.detectors.AbstractPointEventDetectorModel) DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) AbstractDataSourceModel(com.infiniteautomation.mango.rest.latest.model.datasource.AbstractDataSourceModel) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) HashMap(java.util.HashMap) SystemEventType(com.serotonin.m2m2.rt.event.type.SystemEventType) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) PublisherEventType(com.serotonin.m2m2.rt.event.type.PublisherEventType) AuditEventType(com.serotonin.m2m2.rt.event.type.AuditEventType) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) EventType(com.serotonin.m2m2.rt.event.type.EventType) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) PublisherEventTypeModel(com.infiniteautomation.mango.rest.latest.model.event.PublisherEventTypeModel) ArrayList(java.util.ArrayList) AbstractPublisherModel(com.infiniteautomation.mango.rest.latest.model.publisher.AbstractPublisherModel) SystemEventTypeDefinition(com.serotonin.m2m2.module.SystemEventTypeDefinition) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) EventTypeVO(com.serotonin.m2m2.vo.event.EventTypeVO) SystemEventTypeDefinition(com.serotonin.m2m2.module.SystemEventTypeDefinition) EventTypeDefinition(com.serotonin.m2m2.module.EventTypeDefinition) PublisherEventType(com.serotonin.m2m2.rt.event.type.PublisherEventType) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PublisherVO(com.serotonin.m2m2.vo.publish.PublisherVO) DataPointEventType(com.serotonin.m2m2.rt.event.type.DataPointEventType) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataSourceEventType(com.serotonin.m2m2.rt.event.type.DataSourceEventType) DataPointModel(com.infiniteautomation.mango.rest.latest.model.dataPoint.DataPointModel) DataSourceEventTypeModel(com.infiniteautomation.mango.rest.latest.model.event.DataSourceEventTypeModel) DataPointEventTypeModel(com.infiniteautomation.mango.rest.latest.model.event.DataPointEventTypeModel) SystemEventTypeModel(com.infiniteautomation.mango.rest.latest.model.event.SystemEventTypeModel) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) EventTypeVOModel(com.infiniteautomation.mango.rest.latest.model.event.EventTypeVOModel)

Example 2 with NotFoundException

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);
}
Also used : DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) HttpHeaders(org.springframework.http.HttpHeaders) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) ResponseEntity(org.springframework.http.ResponseEntity) PurgePointValuesResponseModel(com.infiniteautomation.mango.rest.latest.model.pointValue.PurgePointValuesResponseModel) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with NotFoundException

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);
}
Also used : Path(java.nio.file.Path) RemainingPath(com.infiniteautomation.mango.rest.latest.resolver.RemainingPath) Role(com.serotonin.m2m2.vo.role.Role) InputStreamReader(java.io.InputStreamReader) EvalContext(com.infiniteautomation.mango.spring.script.EvalContext) BufferedReader(java.io.BufferedReader) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) PathMangoScript(com.infiniteautomation.mango.spring.script.PathMangoScript) OutputStreamWriter(java.io.OutputStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) Async(org.springframework.scheduling.annotation.Async) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with NotFoundException

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());
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebSocketSendException(com.infiniteautomation.mango.rest.latest.websocket.WebSocketSendException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) WebSocketSendException(com.infiniteautomation.mango.rest.latest.websocket.WebSocketSendException)

Example 5 with NotFoundException

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;
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) IDataPoint(com.serotonin.m2m2.vo.IDataPoint) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException)

Aggregations

NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)47 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)14 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)11 JsonException (com.serotonin.json.JsonException)11 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)11 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)10 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)9 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)9 User (com.serotonin.m2m2.vo.User)8 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)7 ApiOperation (io.swagger.annotations.ApiOperation)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 JsonArray (com.serotonin.json.type.JsonArray)4 JsonObject (com.serotonin.json.type.JsonObject)4 DataSourceVO (com.serotonin.m2m2.vo.dataSource.DataSourceVO)4 ArrayList (java.util.ArrayList)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)3 EventTypeVOModel (com.infiniteautomation.mango.rest.latest.model.event.EventTypeVOModel)3 SystemEventTypeModel (com.infiniteautomation.mango.rest.latest.model.event.SystemEventTypeModel)3