Search in sources :

Example 41 with NotFoundException

use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.

the class EventsWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        JsonNode tree = this.jacksonMapper.readTree(message.getPayload());
        if (!WebSocketMessageType.REQUEST.messageTypeMatches(tree) || tree.get("requestType") == null) {
            return;
        }
        EventsWebsocketRequest request = this.jacksonMapper.treeToValue(tree, EventsWebsocketRequest.class);
        request.ensureValid();
        if (request instanceof EventsSubscriptionRequest) {
            EventsSubscriptionRequest subscription = (EventsSubscriptionRequest) request;
            Set<AlarmLevels> levels = subscription.getLevels();
            if (levels == null) {
                levels = Collections.emptySet();
            }
            Set<EventActionEnum> actions = subscription.getActions();
            if (actions == null) {
                actions = EnumSet.noneOf(EventActionEnum.class);
            }
            boolean emptySubscriptions = levels.isEmpty() || actions.isEmpty();
            synchronized (this.lock) {
                // Configure listener
                Boolean subscribed = (Boolean) session.getAttributes().get(SUBSCRIPTION_ATTRIBUTE);
                if (subscribed == null || subscribed == Boolean.FALSE) {
                    if (!emptySubscriptions) {
                        changeLevels(levels);
                        changeActions(actions);
                        initialize();
                        session.getAttributes().put(SUBSCRIPTION_ATTRIBUTE, Boolean.TRUE);
                    }
                } else {
                    if (emptySubscriptions) {
                        terminate();
                        session.getAttributes().put(SUBSCRIPTION_ATTRIBUTE, Boolean.FALSE);
                    } else {
                        changeActions(actions);
                        changeLevels(levels);
                    }
                }
            }
            EventsSubscriptionResponse response = new EventsSubscriptionResponse();
            if (subscription.isSendActiveSummary()) {
                List<UserEventLevelSummary> summaries = service.getActiveSummary();
                List<EventLevelSummaryModel> models = summaries.stream().map(s -> {
                    EventInstanceModel instanceModel = s.getLatest() != null ? modelMapper.map(s.getLatest(), EventInstanceModel.class, user) : null;
                    return new EventLevelSummaryModel(s.getAlarmLevel(), s.getCount(), instanceModel);
                }).collect(Collectors.toList());
                response.setActiveSummary(models);
            }
            if (subscription.isSendUnacknowledgedSummary()) {
                List<UserEventLevelSummary> summaries = service.getUnacknowledgedSummary();
                List<EventLevelSummaryModel> models = summaries.stream().map(s -> {
                    EventInstanceModel instanceModel = s.getLatest() != null ? modelMapper.map(s.getLatest(), EventInstanceModel.class, user) : null;
                    return new EventLevelSummaryModel(s.getAlarmLevel(), s.getCount(), instanceModel);
                }).collect(Collectors.toList());
                response.setUnacknowledgedSummary(models);
            }
            this.sendRawMessage(session, new WebSocketResponse<>(request.getSequenceNumber(), response));
        } else if (request instanceof EventsDataPointSummaryRequest) {
            EventsDataPointSummaryRequest query = (EventsDataPointSummaryRequest) request;
            WebSocketResponse<List<DataPointEventSummaryModel>> response = new WebSocketResponse<>(request.getSequenceNumber());
            Collection<DataPointEventLevelSummary> summaries = service.getDataPointEventSummaries(query.getDataPointXids());
            List<DataPointEventSummaryModel> models = summaries.stream().map(s -> new DataPointEventSummaryModel(s.getXid(), s.getCounts())).collect(Collectors.toList());
            response.setPayload(models);
            this.sendRawMessage(session, response);
        } else if (request instanceof AllActiveEventsRequest) {
            WebSocketResponse<List<EventInstanceModel>> response = new WebSocketResponse<>(request.getSequenceNumber());
            List<EventInstance> active = service.getAllActiveUserEvents();
            List<EventInstanceModel> models = new ArrayList<>(active.size());
            for (EventInstance vo : active) {
                models.add(modelMapper.map(vo, EventInstanceModel.class, user));
            }
            response.setPayload(models);
            this.sendRawMessage(session, response);
        } else if (request instanceof ActiveEventsQuery) {
            List<EventInstance> active = service.getAllActiveUserEvents();
            List<EventInstanceModel> models = new ArrayList<>(active.size());
            for (EventInstance vo : active) {
                models.add(modelMapper.map(vo, EventInstanceModel.class, user));
            }
            String query = ((ActiveEventsQuery) request).getQuery();
            ASTNode rql = RQLUtils.parseRQLtoAST(query);
            WebSocketResponse<ArrayWithTotal<Stream<EventInstanceModel>>> response = new WebSocketResponse<>(request.getSequenceNumber());
            response.setPayload(new FilteredStreamWithTotal<>(models, rql, user.getTranslations()));
            this.sendRawMessage(session, response);
        }
    } catch (NotFoundException e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.NOT_FOUND, e.getTranslatableMessage());
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    } catch (PermissionException e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.PERMISSION_DENIED, e.getTranslatableMessage());
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    } catch (Exception e) {
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
}
Also used : FilteredStreamWithTotal(com.infiniteautomation.mango.rest.latest.model.FilteredStreamWithTotal) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) EventInstance(com.serotonin.m2m2.rt.event.EventInstance) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Id(com.fasterxml.jackson.annotation.JsonTypeInfo.Id) ArrayWithTotal(com.infiniteautomation.mango.rest.latest.model.ArrayWithTotal) DataPointEventSummaryModel(com.infiniteautomation.mango.rest.latest.model.event.DataPointEventSummaryModel) WebSocketSession(org.springframework.web.socket.WebSocketSession) CloseStatus(org.springframework.web.socket.CloseStatus) ArrayList(java.util.ArrayList) RestModelMapper(com.infiniteautomation.mango.rest.latest.model.RestModelMapper) UserEventListener(com.serotonin.m2m2.rt.event.UserEventListener) TextMessage(org.springframework.web.socket.TextMessage) As(com.fasterxml.jackson.annotation.JsonTypeInfo.As) DataPointEventLevelSummary(com.serotonin.m2m2.rt.event.DataPointEventLevelSummary) JsonNode(com.fasterxml.jackson.databind.JsonNode) Validatable(com.serotonin.m2m2.vo.Validatable) EnumSet(java.util.EnumSet) Logger(org.slf4j.Logger) JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) Common(com.serotonin.m2m2.Common) Collection(java.util.Collection) EventInstanceModel(com.infiniteautomation.mango.rest.latest.model.event.EventInstanceModel) RQLUtils(com.infiniteautomation.mango.util.RQLUtils) Set(java.util.Set) EventInstanceService(com.infiniteautomation.mango.spring.service.EventInstanceService) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) UserEventLevelSummary(com.serotonin.m2m2.rt.event.UserEventLevelSummary) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) List(java.util.List) Stream(java.util.stream.Stream) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) ASTNode(net.jazdw.rql.parser.ASTNode) EventLevelSummaryModel(com.infiniteautomation.mango.rest.latest.model.event.EventLevelSummaryModel) EventActionEnum(com.infiniteautomation.mango.rest.latest.model.event.EventActionEnum) AlarmLevels(com.serotonin.m2m2.rt.event.AlarmLevels) Collections(java.util.Collections) User(com.serotonin.m2m2.vo.User) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) Type(com.fasterxml.jackson.annotation.JsonSubTypes.Type) EventInstance(com.serotonin.m2m2.rt.event.EventInstance) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) EventActionEnum(com.infiniteautomation.mango.rest.latest.model.event.EventActionEnum) EventLevelSummaryModel(com.infiniteautomation.mango.rest.latest.model.event.EventLevelSummaryModel) ArrayList(java.util.ArrayList) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) EventInstanceModel(com.infiniteautomation.mango.rest.latest.model.event.EventInstanceModel) ASTNode(net.jazdw.rql.parser.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) Stream(java.util.stream.Stream) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) FilteredStreamWithTotal(com.infiniteautomation.mango.rest.latest.model.FilteredStreamWithTotal) UserEventLevelSummary(com.serotonin.m2m2.rt.event.UserEventLevelSummary) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointEventSummaryModel(com.infiniteautomation.mango.rest.latest.model.event.DataPointEventSummaryModel) Collection(java.util.Collection) AlarmLevels(com.serotonin.m2m2.rt.event.AlarmLevels)

Example 42 with NotFoundException

use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.

the class SystemActionTemporaryResourceManager method create.

/**
 * Create the task
 * @param permissionTypeName - To get from system settings
 */
public <T extends SystemActionResult> ResponseEntity<TemporaryResource<T, AbstractRestException>> create(SystemActionModel requestBody, PermissionHolder user, UriComponentsBuilder builder, String permissionTypeName, String resourceType, ResourceTask<SystemActionResult, AbstractRestException> task) {
    requestBody.ensureValid();
    Long expiration = requestBody.getExpiration();
    Long timeout = requestBody.getTimeout();
    if (permissionTypeName != null) {
        PermissionDefinition def = ModuleRegistry.getPermissionDefinition(permissionTypeName);
        if (def == null) {
            throw new NotFoundException();
        } else {
            service.ensurePermission(user, def.getPermission());
        }
    } else {
        service.ensureAdminRole(user);
    }
    @SuppressWarnings("unchecked") TemporaryResource<T, AbstractRestException> responseBody = (TemporaryResource<T, AbstractRestException>) resourceManager.newTemporaryResource(resourceType, null, expiration, timeout, task);
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/system-actions/status/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<TemporaryResource<T, AbstractRestException>>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) PermissionDefinition(com.serotonin.m2m2.module.PermissionDefinition) ResponseEntity(org.springframework.http.ResponseEntity) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TemporaryResource(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException)

Example 43 with NotFoundException

use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.

the class ScriptEventHandlerModel method readInto.

@Override
public void readInto(ScriptEventHandlerVO vo) {
    super.readInto(vo);
    vo.setScript(this.script);
    vo.setEngineName(this.engineName);
    RoleService roleService = Common.getBean(RoleService.class);
    Set<Role> roleXids = scriptRoles.stream().map(xid -> {
        try {
            return roleService.get(xid).getRole();
        } catch (NotFoundException e) {
            return null;
        }
    }).filter(r -> r != null).collect(Collectors.toSet());
    vo.setScriptRoles(roleXids);
}
Also used : Role(com.serotonin.m2m2.vo.role.Role) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) Role(com.serotonin.m2m2.vo.role.Role) Common(com.serotonin.m2m2.Common) ScriptEventHandlerVO(com.serotonin.m2m2.vo.event.ScriptEventHandlerVO) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) Set(java.util.Set) ApiModel(io.swagger.annotations.ApiModel) ScriptEventHandlerDefinition(com.serotonin.m2m2.module.definitions.event.handlers.ScriptEventHandlerDefinition) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) RoleService(com.infiniteautomation.mango.spring.service.RoleService) ModuleRegistry(com.serotonin.m2m2.module.ModuleRegistry) RoleService(com.infiniteautomation.mango.spring.service.RoleService) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException)

Example 44 with NotFoundException

use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.

the class MangoFileSystem method checkAccess.

@Override
public void checkAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions) throws IOException {
    delegate.checkAccess(path, modes, linkOptions);
    PermissionHolder user = Common.getUser();
    try {
        if (permissionService.hasPermission(user, loadFileStorePermission.getPermission())) {
            try {
                if (modes.contains(AccessMode.WRITE)) {
                    fileStoreService.ensureWriteAccess(path);
                } else {
                    fileStoreService.ensureReadAccess(path);
                }
                return;
            } catch (IllegalArgumentException | NotFoundException e) {
            // not a file store path
            }
        }
        permissionService.ensurePermission(user, accessAllPaths);
    } catch (PermissionException e) {
        // file store denied access
        throw new SecurityException(e);
    }
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder)

Example 45 with NotFoundException

use of com.infiniteautomation.mango.util.exception.NotFoundException in project ma-modules-public by infiniteautomation.

the class WatchListEmportDefinition method doImport.

@Override
public void doImport(JsonValue jsonValue, ImportContext importContext, PermissionHolder importer) throws JsonException {
    JsonObject watchListJson = jsonValue.toJsonObject();
    String xid = watchListJson.getString("xid");
    WatchListVO vo = null;
    if (StringUtils.isBlank(xid)) {
        xid = service.generateUniqueXid();
    } else {
        try {
            vo = service.get(xid);
        } catch (NotFoundException e) {
        }
    }
    if (vo == null) {
        vo = new WatchListVO();
        vo.setXid(xid);
    }
    try {
        importContext.getReader().readInto(vo, watchListJson);
        // Ensure we have a default permission since null is valid in Mango 3.x
        if (vo.getReadPermission() == null) {
            vo.setReadPermission(new MangoPermission());
        }
        if (vo.getEditPermission() == null) {
            vo.setEditPermission(new MangoPermission());
        }
        boolean isnew = vo.getId() == Common.NEW_ID;
        if (isnew) {
            service.insert(vo);
        } else {
            service.update(vo.getId(), vo);
        }
        importContext.addSuccessMessage(isnew, "emport.watchList.prefix", xid);
    } catch (ValidationException e) {
        importContext.copyValidationMessages(e.getValidationResult(), "emport.watchList.prefix", xid);
    } catch (TranslatableJsonException e) {
        importContext.getResult().addGenericMessage("emport.watchList.prefix", xid, e.getMsg());
    } catch (JsonException e) {
        importContext.getResult().addGenericMessage("emport.watchList.prefix", xid, importContext.getJsonExceptionMessage(e));
    }
}
Also used : TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) JsonException(com.serotonin.json.JsonException) ValidationException(com.infiniteautomation.mango.util.exception.ValidationException) JsonObject(com.serotonin.json.type.JsonObject) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) TranslatableJsonException(com.serotonin.m2m2.i18n.TranslatableJsonException) MangoPermission(com.infiniteautomation.mango.permission.MangoPermission)

Aggregations

NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)74 ValidationException (com.infiniteautomation.mango.util.exception.ValidationException)26 JsonException (com.serotonin.json.JsonException)20 MangoPermission (com.infiniteautomation.mango.permission.MangoPermission)18 TranslatableJsonException (com.serotonin.m2m2.i18n.TranslatableJsonException)18 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)15 User (com.serotonin.m2m2.vo.User)15 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)15 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)12 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)10 DataSourceVO (com.serotonin.m2m2.vo.dataSource.DataSourceVO)9 JsonArray (com.serotonin.json.type.JsonArray)8 TranslatableIllegalArgumentException (com.infiniteautomation.mango.util.exception.TranslatableIllegalArgumentException)6 TranslatableRuntimeException (com.infiniteautomation.mango.util.exception.TranslatableRuntimeException)6 FileStore (com.serotonin.m2m2.vo.FileStore)6 AbstractEventHandlerVO (com.serotonin.m2m2.vo.event.AbstractEventHandlerVO)6 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)6 PublisherVO (com.serotonin.m2m2.vo.publish.PublisherVO)6 ApiOperation (io.swagger.annotations.ApiOperation)6 IOException (java.io.IOException)6