Search in sources :

Example 6 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class BackgroundProcessingRestController method setHighPrioritySettings.

@ApiOperation(value = "Update high priority queue settings", notes = "")
@RequestMapping(method = RequestMethod.PUT, produces = { "application/json" }, value = "/high-priority-thread-pool-settings")
public ResponseEntity<ThreadPoolSettingsModel> setHighPrioritySettings(@ApiParam(value = "Settings", required = true, allowMultiple = false) @RequestBody ThreadPoolSettingsModel model, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<ThreadPoolSettingsModel> result = new RestProcessResult<ThreadPoolSettingsModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        if (Permissions.hasAdmin(user)) {
            // Validate the settings
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Common.timer.getExecutorService();
            int currentCorePoolSize = executor.getCorePoolSize();
            int currentMaxPoolSize = executor.getMaximumPoolSize();
            if ((model.getMaximumPoolSize() != null) && (model.getMaximumPoolSize() < BackgroundProcessing.HIGH_PRI_MAX_POOL_SIZE_MIN)) {
                // Test to ensure we aren't setting too low
                model.getMessages().add(new RestValidationMessage(new TranslatableMessage("validate.greaterThanOrEqualTo", BackgroundProcessing.HIGH_PRI_MAX_POOL_SIZE_MIN), RestMessageLevel.ERROR, "corePoolSize"));
                result.addRestMessage(this.getValidationFailedError());
            } else if (!validate(model, currentCorePoolSize, currentMaxPoolSize)) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                if (model.getCorePoolSize() != null) {
                    executor.setCorePoolSize(model.getCorePoolSize());
                    SystemSettingsDao.instance.setIntValue(SystemSettingsDao.HIGH_PRI_CORE_POOL_SIZE, model.getCorePoolSize());
                } else {
                    // Get the info for the user
                    int corePoolSize = executor.getCorePoolSize();
                    model.setCorePoolSize(corePoolSize);
                }
                if (model.getMaximumPoolSize() != null) {
                    executor.setMaximumPoolSize(model.getMaximumPoolSize());
                    SystemSettingsDao.instance.setIntValue(SystemSettingsDao.HIGH_PRI_MAX_POOL_SIZE, model.getMaximumPoolSize());
                } else {
                    // Get the info for the user
                    int maximumPoolSize = executor.getMaximumPoolSize();
                    model.setMaximumPoolSize(maximumPoolSize);
                }
                // Get the settings for the model
                int activeCount = executor.getActiveCount();
                int largestPoolSize = executor.getLargestPoolSize();
                model.setActiveCount(activeCount);
                model.setLargestPoolSize(largestPoolSize);
            }
            return result.createResponseEntity(model);
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to set high priority thread pool settings.");
            result.addRestMessage(this.getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    }
    return result.createResponseEntity();
}
Also used : RestValidationMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage) ThreadPoolSettingsModel(com.serotonin.m2m2.web.mvc.rest.v1.model.backgroundProcessing.ThreadPoolSettingsModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class BackgroundProcessingRestController method setMediumPrioritySettings.

@ApiOperation(value = "Update medium priority queue settings", notes = "Only corePoolSize and maximumPoolSize are used")
@RequestMapping(method = RequestMethod.PUT, produces = { "application/json" }, value = "/medium-priority-thread-pool-settings")
public ResponseEntity<ThreadPoolSettingsModel> setMediumPrioritySettings(@ApiParam(value = "Settings", required = true, allowMultiple = false) @RequestBody ThreadPoolSettingsModel model, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<ThreadPoolSettingsModel> result = new RestProcessResult<ThreadPoolSettingsModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        if (Permissions.hasAdmin(user)) {
            // Validate the settings
            int currentCorePoolSize = SystemSettingsDao.getIntValue(SystemSettingsDao.MED_PRI_CORE_POOL_SIZE);
            if ((model.getCorePoolSize() != null) && (model.getCorePoolSize() < BackgroundProcessing.MED_PRI_MAX_POOL_SIZE_MIN)) {
                // Test to ensure we aren't setting too low
                model.getMessages().add(new RestValidationMessage(new TranslatableMessage("validate.greaterThanOrEqualTo", BackgroundProcessing.MED_PRI_MAX_POOL_SIZE_MIN), RestMessageLevel.ERROR, "corePoolSize"));
                result.addRestMessage(this.getValidationFailedError());
            } else if (!validate(model, currentCorePoolSize, model.getCorePoolSize() == null ? currentCorePoolSize : model.getCorePoolSize())) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                if (model.getCorePoolSize() != null) {
                    Common.backgroundProcessing.setMediumPriorityServiceCorePoolSize(model.getCorePoolSize());
                    SystemSettingsDao.instance.setIntValue(SystemSettingsDao.MED_PRI_CORE_POOL_SIZE, model.getCorePoolSize());
                } else {
                    // Get the info for the user
                    int corePoolSize = Common.backgroundProcessing.getMediumPriorityServiceCorePoolSize();
                    model.setCorePoolSize(corePoolSize);
                }
                if (model.getMaximumPoolSize() == null) {
                    // Get the info for the user
                    int maximumPoolSize = Common.backgroundProcessing.getMediumPriorityServiceMaximumPoolSize();
                    model.setMaximumPoolSize(maximumPoolSize);
                }
                // Get the settings for the model
                int activeCount = Common.backgroundProcessing.getMediumPriorityServiceActiveCount();
                int largestPoolSize = Common.backgroundProcessing.getMediumPriorityServiceLargestPoolSize();
                model.setActiveCount(activeCount);
                model.setLargestPoolSize(largestPoolSize);
            }
            return result.createResponseEntity(model);
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to set medium priority thread pool settings.");
            result.addRestMessage(this.getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    }
    return result.createResponseEntity();
}
Also used : RestValidationMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage) ThreadPoolSettingsModel(com.serotonin.m2m2.web.mvc.rest.v1.model.backgroundProcessing.ThreadPoolSettingsModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class JsonDataRestController method deletePartialJsonData.

@ApiOperation(value = "Partially Delete JSON Data", notes = "{path} is the path to data with dots data.member.submember", response = JsonDataModel.class)
@ApiResponses({ @ApiResponse(code = 201, message = "Data Deleted", response = JsonDataModel.class), @ApiResponse(code = 401, message = "Unauthorized Access", response = ResponseEntity.class), @ApiResponse(code = 403, message = "Data Doesn't Exists") })
@RequestMapping(method = RequestMethod.DELETE, value = "/{xid}/{path:.*}")
public ResponseEntity<JsonDataModel> deletePartialJsonData(@ApiParam(value = "XID", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Data path using dots as separator", required = true, allowMultiple = false) @PathVariable String path, UriComponentsBuilder builder, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<JsonDataModel> result = new RestProcessResult<JsonDataModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        JsonDataVO vo = this.dao.getByXid(xid);
        if (vo != null) {
            // Check existing permissions
            if (!Permissions.hasPermission(user, vo.getEditPermission())) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
            JsonDataModel model = new JsonDataModel(vo);
            String[] pathParts;
            if (path == null || (pathParts = path.split("\\.")).length == 0) {
                // Delete the whole thing
                this.dao.delete(vo.getId());
            } else {
                // Delete something from the map
                JsonNode existingData = (JsonNode) vo.getJsonData();
                boolean deleted = deleteNode(existingData, pathParts);
                if (!deleted) {
                    result.addRestMessage(getDoesNotExistMessage());
                    return result.createResponseEntity();
                }
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                    return result.createResponseEntity(model);
                }
                try {
                    String initiatorId = request.getHeader("initiatorId");
                    this.dao.save(vo, initiatorId);
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                    result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
                }
            }
            return result.createResponseEntity(model);
        } else {
            result.addRestMessage(getDoesNotExistMessage());
        }
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) JsonDataVO(com.serotonin.m2m2.vo.json.JsonDataVO) JsonDataModel(com.serotonin.m2m2.web.mvc.rest.v1.model.jsondata.JsonDataModel) JsonNode(com.fasterxml.jackson.databind.JsonNode) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class UserCommentRestController method createNewUserComment.

/**
 * Create a new User Comment
 *
 * The timestamp and UserID are optional
 * Username is not used for input
 *
 * @param model
 * @param request
 * @return
 * @throws RestValidationFailedException
 */
@ApiOperation(value = "Create New User Comment", notes = "")
@RequestMapping(method = RequestMethod.POST, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" })
public ResponseEntity<UserCommentModel> createNewUserComment(@ApiParam(value = "User Comment to save", required = true) @RequestBody(required = true) UserCommentModel model, UriComponentsBuilder builder, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<UserCommentModel> result = new RestProcessResult<UserCommentModel>(HttpStatus.CREATED);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        // Assign a userId if there isn't one
        if (model.getUserId() == 0) {
            model.setUserId(user.getId());
            model.setUsername(user.getUsername());
        }
        // Don't let non admin users create notes from other people
        if (!hasEditPermission(model.getData(), user)) {
            result.addRestMessage(this.getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        if (model.getTimestamp() <= 0) {
            model.setTimestamp(System.currentTimeMillis());
        }
        if (model.validate()) {
            try {
                String initiatorId = request.getHeader("initiatorId");
                UserCommentDao.instance.save(model.getData(), initiatorId);
                LOG.info("User with name/id: " + user.getUsername() + "/" + user.getId() + " created a User Comment for user: " + model.getData().getUserId());
                URI location = builder.path("v1/comments/{xid}").buildAndExpand(model.getXid()).toUri();
                result.addRestMessage(getResourceCreatedMessage(location));
                return result.createResponseEntity(model);
            } catch (Exception e) {
                result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
                return result.createResponseEntity();
            }
        } else {
            result.addRestMessage(this.getValidationFailedError());
            return result.createResponseEntity(model);
        }
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) UserCommentModel(com.serotonin.m2m2.web.mvc.rest.v1.model.comment.UserCommentModel) URI(java.net.URI) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class UserCommentRestController method deleteUserComment.

@ApiOperation(value = "Delete A User Comment by XID")
@RequestMapping(method = RequestMethod.DELETE, produces = { "application/json" }, value = "/{xid}")
public ResponseEntity<UserCommentModel> deleteUserComment(@ApiParam(value = "xid", required = true, allowMultiple = false) @PathVariable String xid, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<UserCommentModel> result = new RestProcessResult<UserCommentModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        UserCommentVO u = UserCommentDao.instance.getByXid(xid);
        if (u == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Check permissions
        if (hasEditPermission(u, user)) {
            // Delete it
            String initiatorId = request.getHeader("initiatorId");
            UserCommentDao.instance.delete(u.getId(), initiatorId);
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to delete user comment : " + u.getUsername());
            result.addRestMessage(this.getUnauthorizedMessage());
        }
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) UserCommentModel(com.serotonin.m2m2.web.mvc.rest.v1.model.comment.UserCommentModel) UserCommentVO(com.serotonin.m2m2.vo.comment.UserCommentVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)22 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)21 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)21 User (com.serotonin.m2m2.vo.User)20 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)12 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)10 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)7 URI (java.net.URI)6 UserModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel)5 IOException (java.io.IOException)5 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)4 WatchListVO (com.serotonin.m2m2.watchlist.WatchListVO)4 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)3 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)3 RestValidationMessage (com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage)3 WatchListDataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListDataPointModel)3 WatchListModel (com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListModel)3 ThreadPoolSettingsModel (com.serotonin.m2m2.web.mvc.rest.v1.model.backgroundProcessing.ThreadPoolSettingsModel)3 UserCommentModel (com.serotonin.m2m2.web.mvc.rest.v1.model.comment.UserCommentModel)3 ApiResponses (com.wordnik.swagger.annotations.ApiResponses)3