Example usage for org.springframework.http HttpStatus valueOf

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

Introduction

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

Prototype

public static HttpStatus valueOf(int statusCode) 

Source Link

Document

Return the enum constant of this type with the specified numeric value.

Usage

From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployerImpl.java

@Override
public boolean deleteTarget(String site) {
    boolean toReturn = true;
    String requestUrl = getDeleteTargetUrl(site);

    HttpPost postRequest = new HttpPost(requestUrl);

    try {/*w ww.j  a va  2s.com*/
        CloseableHttpResponse response = httpClient.execute(postRequest);
        if (!HttpStatus.valueOf(response.getStatusLine().getStatusCode()).is2xxSuccessful()) {
            toReturn = false;
        }
    } catch (IOException e) {
        logger.error("Error while sending delete preview target request for site " + site, e);
        toReturn = false;
    } finally {
        postRequest.releaseConnection();
    }
    return toReturn;
}

From source file:org.osiam.addons.selfadministration.controller.LostPasswordController.java

/**
 * Method to change the users password if the preconditions are satisfied.
 * /*  w w  w.j a v a2s. c o  m*/
 * @param authorization
 *        authZ header with valid access token
 * @param oneTimePassword
 *        the previously generated one time password
 * @param newPassword
 *        the new user password
 * @return the response with status code and the updated user if successfully
 * @throws IOException
 */
@RequestMapping(value = "/change", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> change(@RequestHeader("Authorization") final String authorization,
        @RequestParam String oneTimePassword, @RequestParam String newPassword) throws IOException {

    if (Strings.isNullOrEmpty(oneTimePassword)) {
        String errorMessage = "The submitted one time password is invalid!";
        LOGGER.log(Level.SEVERE, errorMessage);
        return getErrorResponseEntity(errorMessage, HttpStatus.UNAUTHORIZED);
    }

    User updatedUser;
    try {
        AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization))
                .build();
        User user = connectorBuilder.createConnector().getCurrentUser(accessToken);

        // validate the oneTimePassword with the saved one from DB
        Extension extension = user.getExtension(internalScimExtensionUrn);
        String savedOneTimePassword = extension.getField(this.oneTimePassword, ExtensionFieldType.STRING);

        if (!savedOneTimePassword.equals(oneTimePassword)) {
            LOGGER.log(Level.SEVERE, "The submitted one time password is invalid!");
            return getErrorResponseEntity("The submitted one time password is invalid!", HttpStatus.FORBIDDEN);
        }

        UpdateUser updateUser = getPreparedUserToChangePassword(extension, newPassword);
        updatedUser = connectorBuilder.createConnector().updateUser(user.getId(), updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.log(Level.WARNING, e.getMessage());
        return getErrorResponseEntity(e.getMessage(), HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        return getErrorResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.osiam.addons.self_administration.controller.ChangeEmailController.java

/**
 * Saving the new E-Mail temporary, generating confirmation token and sending an E-Mail to the old registered
 * address./*w  w w .j  a  v a 2s  .c o m*/
 *
 * @param authorization
 *            Authorization header with HTTP Bearer authorization and a valid access token
 * @param newEmailValue
 *            The new email address value
 * @return The HTTP status code
 * @throws IOException
 *             If the updated user object can't mapped to json
 */
@RequestMapping(method = RequestMethod.POST, value = "/change", produces = "application/json")
public ResponseEntity<String> change(@RequestHeader("Authorization") final String authorization,
        @RequestParam("newEmailValue") final String newEmailValue) throws IOException {

    User updatedUser;
    final OneTimeToken confirmationToken = new OneTimeToken();
    try {
        updatedUser = getUpdatedUserForEmailChange(SelfAdministrationHelper.extractAccessToken(authorization),
                newEmailValue, confirmationToken);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    String activateLink = SelfAdministrationHelper.createLinkForEmail(config.getEmailChangeLinkPrefix(),
            updatedUser.getId(), "confirmToken", confirmationToken.getToken());

    // build the Map with the link for replacement
    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("activatelink", activateLink);
    mailVariables.put("user", updatedUser);

    Locale locale = SelfAdministrationHelper.getLocale(updatedUser.getLocale());

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemail", config.getFromAddress(), newEmailValue,
                locale, mailVariables);
    } catch (OsiamException e) {
        String message = "Problems creating email for confirming new user: " + e.getMessage();
        LOGGER.error(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.osiam.addons.self_administration.controller.ChangeEmailController.java

/**
 * Validating the confirm token and saving the new email value as primary email if the validation was successful.
 *
 * @param authorization//from w  ww.  j  av a2s .c om
 *            Authorization header with HTTP Bearer authorization and a valid access token
 * @param userId
 *            The user id for the user whom email address should be changed
 * @param confirmationToken
 *            The previously generated confirmation token from the confirmation email
 * @return The HTTP status code and the updated user if successful
 * @throws IOException
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/confirm", produces = "application/json")
public ResponseEntity<String> confirm(@RequestHeader("Authorization") final String authorization,
        @RequestParam("userId") final String userId,
        @RequestParam("confirmToken") final String confirmationToken) throws IOException {

    if (Strings.isNullOrEmpty(confirmationToken)) {
        String message = "The submitted confirmation token is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    User updatedUser;
    Optional<Email> oldEmail;

    try {
        AccessToken accessToken = new AccessToken.Builder(
                SelfAdministrationHelper.extractAccessToken(authorization)).build();
        User user = osiamConnector.getUser(userId, accessToken);

        Extension extension = user.getExtension(Config.EXTENSION_URN);
        final OneTimeToken storedConfirmationToken = OneTimeToken
                .fromString(extension.getFieldAsString(Config.CONFIRMATION_TOKEN_FIELD));

        if (storedConfirmationToken.isExpired(config.getConfirmationTokenTimeout())) {
            UpdateUser updateUser = new UpdateUser.Builder()
                    .deleteExtensionField(extension.getUrn(), Config.CONFIRMATION_TOKEN_FIELD)
                    .deleteExtensionField(extension.getUrn(), Config.TEMP_EMAIL_FIELD).build();
            osiamConnector.updateUser(userId, updateUser, accessToken);

            String message = "The submitted confirmation token is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        if (!storedConfirmationToken.getToken().equals(confirmationToken)) {
            String message = "The submitted confirmation token is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        String newEmail = extension.getField(Config.TEMP_EMAIL_FIELD, ExtensionFieldType.STRING);
        oldEmail = SCIMHelper.getPrimaryOrFirstEmail(user);

        UpdateUser updateUser = getPreparedUserForEmailChange(extension, newEmail, oldEmail.get());

        updatedUser = osiamConnector.updateUser(userId, updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (NoSuchElementException e) {
        String message = "The submitted confirmation token is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    Locale locale = SelfAdministrationHelper.getLocale(updatedUser.getLocale());

    // build the Map with the link for replacement
    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("user", updatedUser);

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemailinfo", config.getFromAddress(),
                oldEmail.get().getValue(), locale, mailVariables);
    } catch (OsiamException e) {
        String message = "Problems creating email for confirming new user email: " + e.getMessage();
        LOGGER.error(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
}

From source file:org.osiam.addons.self_administration.controller.LostPasswordController.java

/**
 * This endpoint generates an one time password and send an confirmation email including the one time password to
 * users primary email// ww  w  . j  a v a2s .  co  m
 *
 * @param authorization
 *            authZ header with valid access token
 * @param userId
 *            the user id for whom you want to change the password
 * @return the HTTP status code
 * @throws IOException
 * @throws MessagingException
 */
@RequestMapping(value = "/lost/{userId}", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> lost(@RequestHeader("Authorization") final String authorization,
        @PathVariable final String userId) throws IOException, MessagingException {

    final OneTimeToken newOneTimePassword = new OneTimeToken();

    final Extension extension = new Extension.Builder(Config.EXTENSION_URN)
            .setField(Config.ONETIME_PASSWORD_FIELD, newOneTimePassword.toString()).build();
    final UpdateUser updateUser = new UpdateUser.Builder().updateExtension(extension).build();

    final String token = SelfAdministrationHelper.extractAccessToken(authorization);
    final AccessToken accessToken = new AccessToken.Builder(token).build();
    User updatedUser;
    try {
        updatedUser = osiamConnector.updateUser(userId, updateUser, accessToken);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    Optional<Email> email = SCIMHelper.getPrimaryOrFirstEmail(updatedUser);
    if (!email.isPresent()) {
        String message = "Could not change password. No email of user " + updatedUser.getUserName() + " found!";
        LOGGER.error(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.BAD_REQUEST);
    }

    String passwordLostLink = SelfAdministrationHelper.createLinkForEmail(config.getPasswordLostLinkPrefix(),
            updatedUser.getId(), "oneTimePassword", newOneTimePassword.getToken());

    Map<String, Object> mailVariables = new HashMap<>();
    mailVariables.put("lostpasswordlink", passwordLostLink);
    mailVariables.put("user", updatedUser);

    Locale locale = SelfAdministrationHelper.getLocale(updatedUser.getLocale());

    try {
        renderAndSendEmailService.renderAndSendEmail("lostpassword", config.getFromAddress(),
                email.get().getValue(), locale, mailVariables);
    } catch (OsiamException e) {
        String message = "Problems creating email for lost password: " + e.getMessage();
        LOGGER.error(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.INTERNAL_SERVER_ERROR);
    }

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

From source file:org.osiam.addons.self_administration.controller.LostPasswordController.java

private ResponseEntity<String> changePassword(String userId, String authorization, String oneTimePassword,
        String newPassword) throws IOException {

    if (Strings.isNullOrEmpty(oneTimePassword)) {
        String message = "The submitted one time password is invalid!";
        LOGGER.warn(message);//  w  w  w. j a va2 s  .  c om
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }

    AccessToken accessToken = new AccessToken.Builder(
            SelfAdministrationHelper.extractAccessToken(authorization)).build();

    try {

        User user;
        if (Strings.isNullOrEmpty(userId)) {
            user = osiamConnector.getCurrentUser(accessToken);
        } else {
            user = osiamConnector.getUser(userId, accessToken);
        }

        Extension extension = user.getExtension(Config.EXTENSION_URN);
        final OneTimeToken storedOneTimePassword = OneTimeToken
                .fromString(extension.getFieldAsString(Config.ONETIME_PASSWORD_FIELD));

        if (storedOneTimePassword.isExpired(config.getOneTimePasswordTimeout())) {
            UpdateUser updateUser = new UpdateUser.Builder()
                    .deleteExtensionField(extension.getUrn(), Config.ONETIME_PASSWORD_FIELD).build();
            osiamConnector.updateUser(userId, updateUser, accessToken);

            String message = "The submitted one time password is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        if (!storedOneTimePassword.getToken().equals(oneTimePassword)) {
            String message = "The submitted one time password is invalid!";
            LOGGER.warn(message);
            return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
        }

        UpdateUser updateUser = new UpdateUser.Builder().updatePassword(newPassword)
                .deleteExtensionField(extension.getUrn(), Config.ONETIME_PASSWORD_FIELD).build();

        User updatedUser = osiamConnector.updateUser(user.getId(), updateUser, accessToken);

        return new ResponseEntity<>(mapper.writeValueAsString(updatedUser), HttpStatus.OK);
    } catch (OsiamRequestException e) {
        LOGGER.warn(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.valueOf(e.getHttpStatusCode()));
    } catch (OsiamClientException e) {
        LOGGER.error(e.getMessage());
        return SelfAdministrationHelper.createErrorResponseEntity(e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (NoSuchElementException e) {
        String message = "The submitted one time password is invalid!";
        LOGGER.warn(message);
        return SelfAdministrationHelper.createErrorResponseEntity(message, HttpStatus.FORBIDDEN);
    }
}

From source file:org.slc.sli.api.security.oauth.AuthController.java

private ResponseEntity<String> handleAccessException(OAuthAccessException e) {
    OAuthAccessExceptionHandler handler = new OAuthAccessExceptionHandler();
    Response resp = handler.toResponse(e);
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    try {//from  w w  w.  j a v  a  2 s .co  m
        mapper.writeValue(writer, resp.getEntity());
    } catch (Exception e1) {
        LOG.error("Error handling exception", e1);
    }
    return new ResponseEntity<String>(writer.getBuffer().toString(), HttpStatus.valueOf(resp.getStatus()));
}

From source file:org.springframework.boot.actuate.autoconfigure.MetricsFilter.java

private Series getSeries(int status) {
    try {//from  w  w  w. j a va2  s . c o  m
        return HttpStatus.valueOf(status).series();
    } catch (Exception ex) {
        return null;
    }

}

From source file:org.springframework.boot.actuate.metrics.web.servlet.MetricsFilter.java

private Series getSeries(int status) {
    try {/*from w  w  w  .j  av  a  2 s.c o m*/
        return HttpStatus.valueOf(status).series();
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.springframework.boot.actuate.web.BasicErrorController.java

@RequestMapping(value = "${error.path:/error}")
@ResponseBody/*from   w ww  . jav  a  2 s .c o m*/
public Map<String, Object> error(HttpServletRequest request) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {
        Throwable error = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Object obj = request.getAttribute("javax.servlet.error.status_code");
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            map.put("message", error.getMessage());
            String trace = request.getParameter("trace");
            if (trace != null && !"false".equals(trace.toLowerCase())) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            this.logger.error(error);
        } else {
            Object message = request.getAttribute("javax.servlet.error.message");
            map.put("message", message == null ? "No message available" : message);
        }
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        this.logger.error(ex);
        return map;
    }
}