Example usage for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY

List of usage examples for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY.

Prototype

HttpStatus UNPROCESSABLE_ENTITY

To view the source code for org.springframework.http HttpStatus UNPROCESSABLE_ENTITY.

Click Source Link

Document

422 Unprocessable Entity .

Usage

From source file:org.cloudfoundry.identity.uaa.login.ForcePasswordChangeController.java

private String handleUnprocessableEntity(Model model, HttpServletResponse response, String email,
        String messageCode) {/*from ww w.j av a  2 s  . c  o m*/
    model.addAttribute("message_code", messageCode);
    model.addAttribute("email", email);
    response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
    return "force_password_change";
}

From source file:org.cloudfoundry.identity.uaa.login.ResetPasswordController.java

@RequestMapping(value = "/reset_password.do", method = RequestMethod.POST)
public String resetPassword(Model model, @RequestParam("code") String code, @RequestParam("email") String email,
        @RequestParam("password") String password,
        @RequestParam("password_confirmation") String passwordConfirmation, HttpServletResponse response) {

    PasswordConfirmationValidation validation = new PasswordConfirmationValidation(password,
            passwordConfirmation);//from   w  w w .  j ava  2  s . c  o  m
    if (!validation.valid()) {
        model.addAttribute("message_code", validation.getMessageCode());
        model.addAttribute("email", email);
        model.addAttribute("code", code);
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return "reset_password";
    }

    try {
        ScimUser user = resetPasswordService.resetPassword(code, password);
        UaaPrincipal uaaPrincipal = new UaaPrincipal(user.getId(), user.getUserName(), user.getPrimaryEmail(),
                Origin.UAA, null, IdentityZoneHolder.get().getId());
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(uaaPrincipal, null,
                UaaAuthority.USER_AUTHORITIES);
        SecurityContextHolder.getContext().setAuthentication(token);
        return "redirect:home";
    } catch (UaaException e) {
        return handleUnprocessableEntity(model, response, "message_code", "bad_code");
    } catch (InvalidPasswordException e) {
        return handleUnprocessableEntity(model, response, "message", e.getMessagesAsOneString());
    }
}

From source file:org.geoserver.rest.security.AbstractAclController.java

@DeleteMapping(path = "/**")
public void rulesDelete(HttpServletRequest request) throws UnsupportedEncodingException {
    checkUserIsAdmin();//from  w  w  w . j av  a2  s .co  m

    String thePath = request.getPathInfo();
    String ruleString = thePath.substring(getBasePath().length() + 1);
    ruleString = URLDecoder.decode(ruleString, "utf-8");

    String msg = validateRuleKey(ruleString);
    if (msg != null)
        throw new RestException(msg, HttpStatus.UNPROCESSABLE_ENTITY);

    Comparable<?> rule = null;
    for (Comparable<?> ruleCandidate : ruleDAO.getRules()) {
        if (ruleString.equals(keyFor(ruleCandidate))) {
            rule = ruleCandidate;
            break;
        }
    }

    if (rule == null) {
        throw new ResourceNotFoundException("Rule not found: " + ruleString);
    }

    try {
        ruleDAO.removeRule(rule);
        ruleDAO.storeRules();

    } catch (Exception e) {
        throw createRestException(e);
    }
}

From source file:org.geoserver.rest.security.AbstractAclController.java

/**
 * Validates the string representation of rule keys and values
 * /*from   w ww. j  a va  2  s.  c  o  m*/
 * @param ruleMap
 */
protected void validateMap(Map<String, String> ruleMap) {
    for (Entry<String, String> entry : ruleMap.entrySet()) {
        String msg = validateRule(entry.getKey(), entry.getValue());
        if (msg != null) {
            throw new RestException(msg, HttpStatus.UNPROCESSABLE_ENTITY);
        }
    }
}

From source file:org.geoserver.rest.security.MasterPasswordController.java

@PutMapping(consumes = { MediaType.APPLICATION_JSON_VALUE, MediaTypeExtensions.TEXT_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE })
public void masterPasswordPut(@RequestBody Map<String, String> putMap) throws IOException {
    if (!getManager().checkAuthenticationForAdminRole()) {
        // yes, for backwards compat, it's really METHOD_NOT_ALLOWED
        throw new RestException("Amdinistrative privelges required", HttpStatus.METHOD_NOT_ALLOWED);
    }//from ww  w  .  j  a v a  2 s  .c  o  m

    String providerName;
    try {
        providerName = getManager().loadMasterPasswordConfig().getProviderName();
        if (getManager().loadMasterPassswordProviderConfig(providerName).isReadOnly()) {
            throw new RestException("Master password provider does not allow writes",
                    HttpStatus.METHOD_NOT_ALLOWED);
        }
    } catch (IOException e) {
        throw new RestException("Master password provider does not allow writes",
                HttpStatus.METHOD_NOT_ALLOWED);
    }

    String current = putMap.get(MP_CURRENT_KEY);
    String newpass = putMap.get(MP_NEW_KEY);

    if (!StringUtils.isNotBlank(current))
        throw new RestException("no master password", HttpStatus.BAD_REQUEST);

    if (!StringUtils.isNotBlank(newpass))
        throw new RestException("no master password", HttpStatus.BAD_REQUEST);

    char[] currentArray = current.trim().toCharArray();
    char[] newpassArray = newpass.trim().toCharArray();

    GeoServerSecurityManager m = getManager();
    try {
        m.saveMasterPasswordConfig(m.loadMasterPasswordConfig(), currentArray, newpassArray, newpassArray);
    } catch (Exception e) {
        throw new RestException("Cannot change master password", HttpStatus.UNPROCESSABLE_ENTITY, e);
    } finally {
        m.disposePassword(currentArray);
        m.disposePassword(newpassArray);
    }
}

From source file:org.geoserver.rest.security.UserPasswordController.java

@PutMapping(consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE,
        MediaType.TEXT_XML_VALUE, MediaTypeExtensions.TEXT_JSON_VALUE })
public void passwordPut(@RequestBody Map<String, String> putMap) {
    if (!getManager().checkAuthenticationForRole(SecurityContextHolder.getContext().getAuthentication(),
            GeoServerRole.AUTHENTICATED_ROLE))
        // yes, for backwards compat, it's really METHOD_NOT_ALLOWED
        throw new RestException("Amdinistrative privelges required", HttpStatus.METHOD_NOT_ALLOWED);

    try {//from w  w w.jav a 2 s.c  om
        // Look for the service that handles the current user
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();

        GeoServerUserGroupService ugService = null;

        for (GeoServerUserGroupService service : getManager().loadUserGroupServices()) {
            if (service.getUserByUsername(userName) != null) {
                ugService = service;
                break;
            }
        }

        if (ugService == null) {
            throw new RestException("Cannot calculate if PUT is allowed (service not found)",
                    HttpStatus.UNPROCESSABLE_ENTITY);
        }

    } catch (IOException e) {
        throw new RestException("Cannot calculate if PUT is allowed (" + e.getMessage() + ")",
                HttpStatus.UNPROCESSABLE_ENTITY, e);
    }
    String newpass = putMap.get(UP_NEW_PW);

    if (StringUtils.isBlank(newpass))
        throw new RestException("Missing '" + UP_NEW_PW + "'", HttpStatus.BAD_REQUEST);

    GeoServerUser user = null;
    GeoServerUserGroupService ugService = null;

    try {
        // Look for the authentication service
        String userName = SecurityContextHolder.getContext().getAuthentication().getName();

        for (GeoServerUserGroupService service : getManager().loadUserGroupServices()) {
            user = service.getUserByUsername(userName);
            if (user != null) {
                ugService = service;
                break;
            }
        }
    } catch (IOException e) {
        throw new RestException("Cannot retrieve user service", HttpStatus.FAILED_DEPENDENCY, e);
    }

    if (ugService == null) {
        throw new RestException("User service not found", HttpStatus.FAILED_DEPENDENCY);
    }

    // Check again if the provider allows updates
    if (!ugService.canCreateStore()) {
        throw new RestException("User service does not support changing pw", HttpStatus.FAILED_DEPENDENCY);
    }

    try {
        UserGroupStoreValidationWrapper ugStore = new UserGroupStoreValidationWrapper(ugService.createStore());

        user.setPassword(newpass);
        ugStore.updateUser(user);

        ugStore.store();
        ugService.load();

        LOGGER.log(Level.INFO, "Changed password for user {0}", user.getUsername());

    } catch (IOException e) {
        throw new RestException("Internal IO error", HttpStatus.INTERNAL_SERVER_ERROR, e);
    } catch (PasswordPolicyException e) {
        throw new RestException("Bad password", HttpStatus.UNPROCESSABLE_ENTITY, e);
    }
}

From source file:org.opentestsystem.authoring.testspecbank.client.TestSpecBankClient.java

@Override
public Optional<ValidationError> deleteTestSpecification(final String testSpecificationKey) {
    Optional<ValidationError> maybeValidationError = Optional.empty();
    final URI uri = UriComponentsBuilder
            .fromUriString(String.format("%stestSpecification/%s", baseUri, testSpecificationKey)).build()
            .toUri();/*from   w  w w .  jav a2  s  .c o  m*/

    try {
        tsbOauthRestTemplate.delete(uri);
    } catch (final HttpClientErrorException hce) {
        LOGGER.error("Error deleting {0} test specification: ", hce);
        if (hce.getStatusCode() == HttpStatus.UNPROCESSABLE_ENTITY) {
            try {
                // The NoContentResponseResource contains an array of ValidationErrors.  If we got to this point,
                // the TestSpecificationController#deleteTestSpecification endpoint will have returned a
                // NoContentResponseResource with a single ValidationError describing what went wrong.
                final NoContentResponseResource response = objectMapper.readValue(hce.getResponseBodyAsString(),
                        NoContentResponseResource.class);
                maybeValidationError = Optional.of(response.getErrors()[0]);
            } catch (final Exception mapEx) {
                LOGGER.error(String.format("Error mapping response %s to ValidationError: ",
                        hce.getResponseBodyAsString()), mapEx);
                final String errorMessage = mapEx.getMessage() == null ? mapEx.getClass().getName()
                        : mapEx.getMessage();
                maybeValidationError = Optional.of(new ValidationError("mapping exception", errorMessage));
            }
        } else {
            maybeValidationError = Optional.of(new ValidationError("client exception", hce.getMessage()));
        }
    } catch (final Exception e) {
        LOGGER.error("Error deleting {0} test specification: ", e);
        maybeValidationError = Optional.of(new ValidationError("server exception", e.getMessage()));
    }

    return maybeValidationError;
}

From source file:org.opentestsystem.authoring.testspecbank.rest.TestSpecificationController.java

@ResponseStatus(HttpStatus.NO_CONTENT)
@RequestMapping(value = "/{testSpecificationName}", method = RequestMethod.DELETE, produces = {
        MediaType.APPLICATION_JSON_VALUE })
// @Secured({ "ROLE_Test Spec Admin" })
@ResponseBody//from  w w  w .  j a  va2 s .  com
public ResponseEntity<NoContentResponseResource> deleteTestSpecification(
        @PathVariable final String testSpecificationName) {
    final Optional<ValidationError> maybeError = testSpecificationService
            .deleteTestSpecification(testSpecificationName);
    if (maybeError.isPresent()) {
        final ValidationError error = maybeError.get();
        final HttpStatus httpStatus = error.getCode().equalsIgnoreCase(
                ValidationErrorCode.TEST_SPECIFICATION_NOT_FOUND) ? HttpStatus.UNPROCESSABLE_ENTITY
                        : HttpStatus.INTERNAL_SERVER_ERROR;

        return new ResponseEntity<>(new NoContentResponseResource(error), httpStatus);
    }

    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

From source file:uk.ac.ebi.atlas.search.BioentitiesSearchController.java

@ExceptionHandler(value = { MissingServletRequestParameterException.class, IllegalArgumentException.class })
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
public ModelAndView handleException(Exception e) {
    ModelAndView mav = new ModelAndView("bioEntities");
    mav.addObject("exceptionMessage", e.getMessage());
    return mav;/*from w  w w  .  j  a v  a 2  s  . c  om*/
}