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:eu.freme.eservices.tilde.translation.TildeETranslation.java

@RequestMapping(value = "/e-translation/tilde", method = RequestMethod.POST)
public ResponseEntity<String> tildeTranslate(@RequestParam(value = "input", required = false) String input,
        @RequestParam(value = "i", required = false) String i,
        @RequestParam(value = "informat", required = false) String informat,
        @RequestParam(value = "f", required = false) String f,
        @RequestParam(value = "outformat", required = false) String outformat,
        @RequestParam(value = "o", required = false) String o,
        @RequestParam(value = "prefix", required = false) String prefix,
        @RequestParam(value = "p", required = false) String p,
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        @RequestBody(required = false) String postBody, @RequestParam(value = "source-lang") String sourceLang,
        @RequestParam(value = "target-lang") String targetLang,
        @RequestParam(value = "domain", defaultValue = "") String domain,
        @RequestParam(value = "system", defaultValue = "full") String system,
        @RequestHeader(value = "key", required = false) String key) {

    // merge long and short parameters - long parameters override short
    // parameters
    if (input == null) {
        input = i;//w  w  w .  java2 s.  c  o  m
    }
    if (informat == null) {
        informat = f;
    }
    if (outformat == null) {
        outformat = o;
    }
    if (prefix == null) {
        prefix = p;
    }
    NIFParameterSet parameters = this.normalizeNif(input, informat, outformat, postBody, acceptHeader,
            contentTypeHeader, prefix);

    // create rdf model
    String plaintext = null;
    Model inputModel = ModelFactory.createDefaultModel();

    if (!parameters.getInformat().equals(RDFConstants.RDFSerialization.PLAINTEXT)) {
        // input is nif
        try {
            inputModel = this.unserializeNif(parameters.getInput(), parameters.getInformat());
        } catch (Exception e) {
            logger.error("failed", e);
            throw new BadRequestException("Error parsing NIF input");
        }
    } else {
        // input is plaintext
        plaintext = parameters.getInput();
        getRdfConversionService().plaintextToRDF(inputModel, plaintext, sourceLang, parameters.getPrefix());
    }

    // send request to tilde mt
    Model responseModel = null;
    try {
        HttpResponse<String> response = Unirest.post(endpoint).routeParam("source-lang", sourceLang)
                .routeParam("target-lang", targetLang).header("Accept", "application/x-turtle")
                .header("Content-Type", "application/x-turtle").queryString("system", system)
                .header("Authentication", "Basic RlJFTUU6dXxGcjNtM19zJGN1ciQ=").queryString("domain", domain)
                .queryString("key", key)
                .body(getRdfConversionService().serializeRDF(inputModel, RDFSerialization.TURTLE)).asString();

        if (response.getStatus() != HttpStatus.OK.value()) {
            throw new ExternalServiceFailedException("External service failed: " + response.getBody(),
                    HttpStatus.valueOf(response.getStatus()));
        }

        String translation = response.getBody();

        responseModel = getRdfConversionService().unserializeRDF(translation, RDFSerialization.TURTLE);

    } catch (Exception e) {
        if (e instanceof ExternalServiceFailedException) {
            throw new ExternalServiceFailedException(e.getMessage(),
                    ((ExternalServiceFailedException) e).getHttpStatusCode());
        } else {
            throw new ExternalServiceFailedException(e.getMessage());
        }
    }

    return createSuccessResponse(responseModel, parameters.getOutformat());
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

private HttpEntity<String> buildBadAuthCodeResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription(Constants.INVALID_OAUTH_CODE)
            .buildJSONMessage();/*  w  w  w .  ja va 2  s  .  c  o m*/
    return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}

From source file:eu.freme.broker.eservices.TildeETranslation.java

@RequestMapping(value = "/e-translation/tilde", method = RequestMethod.POST)
public ResponseEntity<String> tildeTranslate(@RequestParam(value = "input", required = false) String input,
        @RequestParam(value = "i", required = false) String i,
        @RequestParam(value = "informat", required = false) String informat,
        @RequestParam(value = "f", required = false) String f,
        @RequestParam(value = "outformat", required = false) String outformat,
        @RequestParam(value = "o", required = false) String o,
        @RequestParam(value = "prefix", required = false) String prefix,
        @RequestParam(value = "p", required = false) String p,
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        @RequestBody(required = false) String postBody, @RequestParam(value = "source-lang") String sourceLang,
        @RequestParam(value = "target-lang") String targetLang,
        @RequestParam(value = "domain", defaultValue = "") String domain,
        @RequestParam(value = "system", defaultValue = "full") String system,
        @RequestParam(value = "key", required = false) String key) {

    // merge long and short parameters - long parameters override short
    // parameters
    if (input == null) {
        input = i;//from w w w .  java2  s .c o  m
    }
    if (informat == null) {
        informat = f;
    }
    if (outformat == null) {
        outformat = o;
    }
    if (prefix == null) {
        prefix = p;
    }
    NIFParameterSet parameters = this.normalizeNif(input, informat, outformat, postBody, acceptHeader,
            contentTypeHeader, prefix);

    // create rdf model
    String plaintext = null;
    Model inputModel = ModelFactory.createDefaultModel();

    if (!parameters.getInformat().equals(RDFConstants.RDFSerialization.PLAINTEXT)) {
        // input is nif
        try {
            inputModel = this.unserializeNif(parameters.getInput(), parameters.getInformat());
        } catch (Exception e) {
            logger.error("failed", e);
            throw new BadRequestException("Error parsing NIF input");
        }
    } else {
        // input is plaintext
        plaintext = parameters.getInput();
        rdfConversionService.plaintextToRDF(inputModel, plaintext, sourceLang, parameters.getPrefix());
    }

    // send request to tilde mt
    Model responseModel = null;
    try {
        HttpResponse<String> response = Unirest.post(endpoint).routeParam("source-lang", sourceLang)
                .routeParam("target-lang", targetLang).header("Accept", "application/x-turtle")
                .header("Content-Type", "application/x-turtle").queryString("system", system)
                .header("Authentication", "Basic RlJFTUU6dXxGcjNtM19zJGN1ciQ=").queryString("domain", domain)
                .queryString("key", key)
                .body(rdfConversionService.serializeRDF(inputModel, RDFSerialization.TURTLE)).asString();

        if (response.getStatus() != HttpStatus.OK.value()) {
            throw new ExternalServiceFailedException(
                    "External service failed with status code " + response.getStatus(),
                    HttpStatus.valueOf(response.getStatus()));
        }

        String translation = response.getBody();

        responseModel = rdfConversionService.unserializeRDF(translation, RDFSerialization.TURTLE);

    } catch (Exception e) {
        if (e instanceof ExternalServiceFailedException) {
            throw new ExternalServiceFailedException(e.getMessage(),
                    ((ExternalServiceFailedException) e).getHttpStatusCode());
        } else {
            throw new ExternalServiceFailedException(e.getMessage());
        }
    }

    return createSuccessResponse(responseModel, parameters.getOutformat());
}

From source file:eu.freme.broker.eservices.TildeETerminology.java

@RequestMapping(value = "/e-terminology/tilde", method = RequestMethod.POST)
public ResponseEntity<String> tildeTranslate(@RequestParam(value = "input", required = false) String input,
        @RequestParam(value = "i", required = false) String i,
        @RequestParam(value = "informat", required = false) String informat,
        @RequestParam(value = "f", required = false) String f,
        @RequestParam(value = "outformat", required = false) String outformat,
        @RequestParam(value = "o", required = false) String o,
        @RequestParam(value = "prefix", required = false) String prefix,
        @RequestParam(value = "p", required = false) String p,
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        @RequestBody(required = false) String postBody, @RequestParam(value = "source-lang") String sourceLang,
        @RequestParam(value = "target-lang") String targetLang,
        @RequestParam(value = "domain", defaultValue = "") String domain,
        @RequestParam(value = "mode", defaultValue = "full") String mode,
        @RequestParam(value = "collection", required = false) String collection,
        @RequestHeader(value = "key", required = false) String key) {

    // merge long and short parameters - long parameters override short
    // parameters
    if (input == null) {
        input = i;//from w  w  w  .j  a va  2s.com
    }
    if (informat == null) {
        informat = f;
    }
    if (outformat == null) {
        outformat = o;
    }
    if (prefix == null) {
        prefix = p;
    }
    NIFParameterSet parameters = this.normalizeNif(input, informat, outformat, postBody, acceptHeader,
            contentTypeHeader, prefix);

    // create rdf model
    String plaintext = null;
    Model inputModel = ModelFactory.createDefaultModel();

    if (!parameters.getInformat().equals(RDFConstants.RDFSerialization.PLAINTEXT)) {
        // input is nif
        try {
            inputModel = this.unserializeNif(parameters.getInput(), parameters.getInformat());
        } catch (Exception e) {
            logger.error("failed", e);
            throw new BadRequestException("Error parsing NIF input");
        }
    } else {
        // input is plaintext
        plaintext = parameters.getInput();
        rdfConversionService.plaintextToRDF(inputModel, plaintext, sourceLang, parameters.getPrefix());
    }

    // send request to tilde mt
    Model responseModel = null;
    try {
        String nifString = rdfConversionService.serializeRDF(inputModel, RDFSerialization.TURTLE);
        if (logger.isDebugEnabled()) {
            logger.debug("send nif to tilde e-terminology: \n" + nifString);
        }
        HttpResponse<String> response = Unirest.post(endpoint).queryString("sourceLang", sourceLang)
                .queryString("targetLang", targetLang).queryString("domain", domain)
                .header("Accept", "application/turtle").header("Content-Type", "application/turtle")
                .queryString("mode", mode).queryString("collection", collection)
                .header("Authentication", "Basic RlJFTUU6dXxGcjNtM19zJGN1ciQ=").queryString("key", key)
                .body(nifString).asString();

        if (response.getStatus() != HttpStatus.OK.value()) {
            throw new ExternalServiceFailedException(
                    "External service failed with status code " + response.getStatus(),
                    HttpStatus.valueOf(response.getStatus()));
        }

        String translation = response.getBody();

        responseModel = rdfConversionService.unserializeRDF(translation, RDFSerialization.TURTLE);

    } catch (Exception e) {
        if (e instanceof ExternalServiceFailedException) {
            throw new ExternalServiceFailedException(e.getMessage(),
                    ((ExternalServiceFailedException) e).getHttpStatusCode());
        } else {
            throw new ExternalServiceFailedException(e.getMessage());
        }
    }

    return createSuccessResponse(responseModel, parameters.getOutformat());
}

From source file:cz.jirutka.spring.exhandler.RestHandlerExceptionResolverFactoryBean.java

HttpStatus parseHttpStatus(Object value) {
    Assert.notNull(value, "Values of the exceptionHandlers map must not be null");

    if (value instanceof HttpStatus) {
        return (HttpStatus) value;

    } else if (value instanceof Integer) {
        return HttpStatus.valueOf((int) value);

    } else if (value instanceof String) {
        return HttpStatus.valueOf(Integer.valueOf((String) value));

    } else {//  w  w  w  . j a  va 2  s .c om
        throw new IllegalArgumentException(String.format(
                "Values of the exceptionHandlers maps must be instance of ErrorResponseFactory, HttpStatus, "
                        + "String, or int, but %s given",
                value.getClass()));
    }
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

private HttpEntity<String> buildInvalidUserPassResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuthError.TokenResponse.INVALID_GRANT)
            .setErrorDescription(Constants.INVALID_USER_PASSWORD).buildJSONMessage();
    return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}

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

/**
 * Saving the new E-Mail temporary, generating confirmation token and sending an E-Mail to the old registered
 * address./*from  w  w w.  j a  v  a  2  s.  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
 * @throws MessagingException
 */
@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, MessagingException {

    User updatedUser;
    String confirmationToken = UUID.randomUUID().toString();
    try {
        updatedUser = getUpdatedUserForEmailChange(RegistrationHelper.extractAccessToken(authorization),
                newEmailValue, confirmationToken);
    } 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);
    }

    String activateLink = RegistrationHelper.createLinkForEmail(emailChangeLinkPrefix, updatedUser.getId(),
            "confirmToken", confirmationToken);

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

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

    try {
        renderAndSendEmailService.renderAndSendEmail("changeemail", fromAddress, newEmailValue, locale,
                mailVariables);
    } catch (OsiamException e) {
        return getErrorResponseEntity(
                "Problems creating email for confirming new user email: \"" + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

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

From source file:be.solidx.hot.rest.RestController.java

protected ResponseEntity<byte[]> buildResponse(Map content, Map headers, Integer httpStatus,
        Charset requestedEncoding) {
    try {//w  w  w  .  j a  v  a2  s. c om
        HttpHeaders httpHeaders = buildHttpHeaders(headers);
        List<String> contentType = httpHeaders.get(com.google.common.net.HttpHeaders.CONTENT_TYPE);
        if (contentType != null && contentType.size() > 0
                && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
            return new ResponseEntity<byte[]>(objectMapper.writeValueAsBytes(content), httpHeaders,
                    HttpStatus.valueOf(httpStatus));
        } else {
            return new ResponseEntity<byte[]>(content.toString().getBytes(requestedEncoding), httpHeaders,
                    HttpStatus.valueOf(httpStatus));
        }
    } catch (Exception e) {
        logger.error("", e);
        return new ResponseEntity<byte[]>(e.getMessage().toString().getBytes(requestedEncoding),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.github.jmnarloch.spring.cloud.feign.VndErrorDecoder.java

/**
 * Creates the instance of {@link VndErrorException}.
 *
 * @param response  the response// w  w w.j  ava  2s .c om
 * @param body      the response body
 * @param vndErrors the vnd errors  @return the exception instance
 */
private VndErrorException createException(Response response, byte[] body, VndErrors vndErrors) {

    final HttpStatus status = HttpStatus.valueOf(response.status());
    final HttpHeaders headers = mapHeaders(response.headers());
    final Charset charset = getCharset(headers);
    return new VndErrorException(status, status.getReasonPhrase(), headers, body, charset, vndErrors);
}