Search in sources :

Example 16 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) 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 17 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 18 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 19 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)

Example 20 with NotFoundException

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

the class UsersService method getUserByEmail.

/**
 * Get a user by their email address
 *
 * @param emailAddress the email address of the user to find
 * @return the user corresponding to the email address
 * @throws NotFoundException if the email address was not found in the database
 * @throws PermissionException if the current user does not have permission to read this user
 */
public User getUserByEmail(String emailAddress) throws NotFoundException, PermissionException {
    User vo = dao.getUserByEmail(emailAddress);
    if (vo == null)
        throw new NotFoundException();
    PermissionHolder currentUser = Common.getUser();
    ensureReadPermission(currentUser, vo);
    return vo;
}
Also used : User(com.serotonin.m2m2.vo.User) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder)

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