Search in sources :

Example 1 with AbstractRestException

use of com.infiniteautomation.mango.rest.latest.exception.AbstractRestException 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 2 with AbstractRestException

use of com.infiniteautomation.mango.rest.latest.exception.AbstractRestException 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);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.latest.bulk.VoAction) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with AbstractRestException

use of com.infiniteautomation.mango.rest.latest.exception.AbstractRestException in project ma-modules-public by infiniteautomation.

the class MangoTaskTemporaryResourceManager method scheduleTask.

private void scheduleTask(TemporaryResource<T, AbstractRestException> resource) {
    TaskData tasks = (TaskData) resource.getData();
    // high priority task will start with user that calls this method in the SecurityContext
    tasks.mainTask = new HighPriorityTask("Temporary resource " + resource.getResourceType() + " " + resource.getId()) {

        @Override
        public void run(long runtime) {
            try {
                resource.runTask();
            } catch (Exception e) {
                AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(e);
                resource.safeError(error);
            }
        }

        @Override
        public void rejected(RejectedTaskReason reason) {
            super.rejected(reason);
            TranslatableMessage msg = null;
            switch(reason.getCode()) {
                case RejectedTaskReason.POOL_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskPoolFull");
                    break;
                case RejectedTaskReason.TASK_QUEUE_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskQueueFull");
                    break;
                case RejectedTaskReason.CURRENTLY_RUNNING:
                    msg = new TranslatableMessage("rest.error.rejectedTaskAlreadyRunning");
                    break;
            }
            ServerErrorException ex = msg == null ? new ServerErrorException() : new ServerErrorException(msg);
            AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(ex);
            resource.safeError(error);
        }
    };
    Common.backgroundProcessing.execute(tasks.mainTask);
    this.scheduleTimeout(resource);
}
Also used : HighPriorityTask(com.serotonin.m2m2.util.timeout.HighPriorityTask) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) StatusUpdateException(com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource.StatusUpdateException) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) RejectedTaskReason(com.serotonin.timer.RejectedTaskReason)

Example 4 with AbstractRestException

use of com.infiniteautomation.mango.rest.latest.exception.AbstractRestException 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 5 with AbstractRestException

use of com.infiniteautomation.mango.rest.latest.exception.AbstractRestException in project ma-modules-public by infiniteautomation.

the class UserRestController method bulkUserOperation.

@ApiOperation(value = "Bulk get/create/update/delete users", notes = "User must have read/edit permission for the user")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<UserBulkResponse, AbstractRestException>> bulkUserOperation(@RequestBody UserBulkRequest requestBody, HttpServletRequest servletRequest, Authentication authentication, UriComponentsBuilder builder) {
    VoAction defaultAction = requestBody.getAction();
    UserModel defaultBody = requestBody.getBody();
    List<UserIndividualRequest> 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<UserBulkResponse, AbstractRestException> responseBody = bulkResourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_USER, resourceId, expiration, timeout, (resource) -> {
        UserBulkResponse bulkResponse = new UserBulkResponse();
        int i = 0;
        resource.progressOrSuccess(bulkResponse, i++, requests.size());
        for (UserIndividualRequest request : requests) {
            UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
            PermissionHolder resourceUser = Common.getUser();
            UserIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, resourceUser, servletRequest, authentication, reqBuilder);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
        return null;
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/users/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.latest.bulk.VoAction) UserIndividualResponse(com.infiniteautomation.mango.rest.latest.model.user.UserIndividualResponse) PermissionHolder(com.serotonin.m2m2.vo.permission.PermissionHolder) UserModel(com.infiniteautomation.mango.rest.latest.model.user.UserModel) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) UserIndividualRequest(com.infiniteautomation.mango.rest.latest.model.user.UserIndividualRequest) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

AbstractRestException (com.infiniteautomation.mango.rest.latest.exception.AbstractRestException)9 HttpHeaders (org.springframework.http.HttpHeaders)7 ResponseEntity (org.springframework.http.ResponseEntity)7 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)6 ApiOperation (io.swagger.annotations.ApiOperation)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)5 VoAction (com.infiniteautomation.mango.rest.latest.bulk.VoAction)4 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)4 PermissionHolder (com.serotonin.m2m2.vo.permission.PermissionHolder)3 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)2 ServerErrorException (com.infiniteautomation.mango.rest.latest.exception.ServerErrorException)1 DataPointModel (com.infiniteautomation.mango.rest.latest.model.dataPoint.DataPointModel)1 PurgePointValuesResponseModel (com.infiniteautomation.mango.rest.latest.model.pointValue.PurgePointValuesResponseModel)1 UserIndividualRequest (com.infiniteautomation.mango.rest.latest.model.user.UserIndividualRequest)1 UserIndividualResponse (com.infiniteautomation.mango.rest.latest.model.user.UserIndividualResponse)1 UserModel (com.infiniteautomation.mango.rest.latest.model.user.UserModel)1 TemporaryResource (com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource)1 StatusUpdateException (com.infiniteautomation.mango.rest.latest.temporaryResource.TemporaryResource.StatusUpdateException)1 PermissionDefinition (com.serotonin.m2m2.module.PermissionDefinition)1