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:com.castlemock.web.mock.rest.web.rest.controller.AbstractRestServiceController.java

/**
 * The process method provides the functionality to process an incoming request. The request will be identified
 * and a corresponding action will be applied for the request. The following actions are support:
 * Forward, record, mock or disable./*from  w  w w  .  ja va2  s  .  c om*/
 * @param restRequest The incoming request
 * @param projectId The id of the project that the incoming request belongs to
 * @param applicationId The id of the application that the incoming request belongs to
 * @param resourceId The id of the resource that the incoming request belongs to
 * @param restMethod The REST method which the incoming request belongs to
 * @param httpServletResponse The HTTP servlet response
 * @return A response in String format
 */
protected ResponseEntity<String> process(final RestRequestDto restRequest, final String projectId,
        final String applicationId, final String resourceId, final RestMethodDto restMethod,
        final HttpServletResponse httpServletResponse) {
    Preconditions.checkNotNull(restRequest, "Rest request cannot be null");
    RestEventDto event = null;
    RestResponseDto response = null;
    try {
        event = new RestEventDto(restMethod.getName(), restRequest, projectId, applicationId, resourceId,
                restMethod.getId());
        if (RestMethodStatus.DISABLED.equals(restMethod.getStatus())) {
            throw new RestException("The requested REST method, " + restMethod.getName() + ", is disabled");
        } else if (RestMethodStatus.FORWARDED.equals(restMethod.getStatus())) {
            response = forwardRequest(restRequest, projectId, applicationId, resourceId, restMethod);
        } else if (RestMethodStatus.RECORDING.equals(restMethod.getStatus())) {
            response = forwardRequestAndRecordResponse(restRequest, projectId, applicationId, resourceId,
                    restMethod);
        } else if (RestMethodStatus.RECORD_ONCE.equals(restMethod.getStatus())) {
            response = forwardRequestAndRecordResponseOnce(restRequest, projectId, applicationId, resourceId,
                    restMethod);
        } else if (RestMethodStatus.ECHO.equals(restMethod.getStatus())) {
            response = echoResponse(restRequest);
        } else { // Status.MOCKED
            response = mockResponse(restRequest, projectId, applicationId, resourceId, restMethod);
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        for (HttpHeaderDto httpHeader : response.getHttpHeaders()) {
            List<String> headerValues = new LinkedList<String>();
            headerValues.add(httpHeader.getValue());
            responseHeaders.put(httpHeader.getName(), headerValues);
        }

        if (restMethod.getSimulateNetworkDelay() && restMethod.getNetworkDelay() >= 0) {
            try {
                Thread.sleep(restMethod.getNetworkDelay());
            } catch (InterruptedException e) {
                LOGGER.error("Unable to simulate network delay", e);
            }
        }

        return new ResponseEntity<String>(response.getBody(), responseHeaders,
                HttpStatus.valueOf(response.getHttpStatusCode()));
    } finally {
        if (event != null) {
            event.finish(response);
            serviceProcessor.processAsync(new CreateRestEventInput(event));
        }
    }
}

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

/**
 * Validating the confirm token and saving the new email value as primary email if the validation was successful.
 * //from   ww  w  .  ja v a  2s. c  om
 * @param authorization
 *        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 confirmToken
 *        The previously generated confirmation token from the confirmation email
 * @return The HTTP status code and the updated user if successful
 */
@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 confirmToken)
        throws IOException, MessagingException {

    if (Strings.isNullOrEmpty(confirmToken)) {
        LOGGER.log(Level.WARNING, "Confirmation token miss match!");
        return getErrorResponseEntity("No ongoing email change!", HttpStatus.UNAUTHORIZED);
    }

    User updatedUser;
    Optional<Email> oldEmail;

    try {
        AccessToken accessToken = new AccessToken.Builder(RegistrationHelper.extractAccessToken(authorization))
                .build();
        User user = connectorBuilder.createConnector().getUser(userId, accessToken);

        Extension extension = user.getExtension(internalScimExtensionUrn);
        String existingConfirmToken = extension.getField(confirmationTokenField, ExtensionFieldType.STRING);

        if (!existingConfirmToken.equals(confirmToken)) {
            LOGGER.log(Level.WARNING, "Confirmation token mismatch!");
            return getErrorResponseEntity("No ongoing email change!", HttpStatus.FORBIDDEN);
        }

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

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

        updatedUser = connectorBuilder.createConnector().updateUser(userId, 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);
    }

    Locale locale = RegistrationHelper.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", fromAddress, oldEmail.get().getValue(),
                locale, mailVariables);
    } catch (OsiamException e) {
        return getErrorResponseEntity("Problems creating email for confirming new user: \"" + e.getMessage(),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

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

From source file:com.sothawo.taboo2.Taboo2Service.java

/**
 * tries to load the title for a web page.
 *
 * @param url// w w w .j  a va  2 s.  co  m
 *         url for which the title shall be loaded
 * @return ResponseEntity with the title
 */
@RequestMapping(value = MAPPING_TITLE, method = RequestMethod.GET)
@ResponseBody
public final ResponseEntity<Bookmark> loadTitle(
        @RequestParam(value = "url", required = true) final String url) {
    if (MAGIC_TEST_URL.equals(url)) {
        return new ResponseEntity<>(aBookmark().withUrl(url).build(), HttpStatus.OK);
    }

    String urlString = url;
    if (null != urlString && !urlString.isEmpty()) {
        if (!urlString.startsWith("http")) {
            urlString = "http://" + urlString;
        }
        final String finalUrl = urlString;
        LOG.info("loading title for url {}", finalUrl);
        try {
            String htmlTitle = Jsoup.connect(finalUrl).timeout(5000).userAgent(JSOUP_USER_AGENT).get().title();
            LOG.info("got title: {}", htmlTitle);
            return new ResponseEntity<>(aBookmark().withUrl(finalUrl).withTitle(htmlTitle).build(),
                    HttpStatus.OK);
        } catch (HttpStatusException e) {
            LOG.info("loading url http error", e);
            return new ResponseEntity<>(HttpStatus.valueOf(e.getStatusCode()));
        } catch (IOException e) {
            LOG.info("loading url error", e);
        }
    }
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

From source file:org.kuali.mobility.sakai.service.SakaiPrivateTopicServiceImpl.java

public ResponseEntity<String> postMessage(Message message, String siteId, String userId) {
    try {//w ww.j  av a2 s .c  o  m
        String jsonString = "{";
        jsonString += "\"attachments\": [],";
        jsonString += "\"authoredBy\":\"" + userId + "\", ";
        jsonString += "\"body\":\"" + message.getBody() + "\", ";
        jsonString += "\"label\":\"" + "" + "\", ";
        jsonString += "\"recipients\":\"" + message.getRecipients() + "\", ";
        jsonString += "\"replies\":" + "null" + ", ";
        jsonString += "\"replyTo\":" + message.getInReplyTo() + ", ";
        jsonString += "\"title\":\"" + message.getTitle() + "\", ";
        //         jsonString += "\"topicId\":\"" + null + "\", ";
        //         jsonString += "\"typeUuid\":\""+ "4d9593ed-aaee-4826-b74a-b3c3432b384c" + "\", ";
        jsonString += "\"siteId\":\"" + siteId + "\", ";
        jsonString += "\"read\":" + "false" + ", ";
        //         jsonString += "\"entityReference\":\"" + "\\/forum_message" + "\", ";
        //jsonString += "\"entityURL\":\"" + "http:\\/\\/localhost:8080\\/direct\\/forum_message" + "\", ";
        //jsonString += "\"entityTitle\":\"" + subject + "\"";

        jsonString += "}";

        String url = configParamService.findValueByName("Sakai.Url.Base") + "forum_message/new.json";
        ResponseEntity<InputStream> is = oncourseOAuthService.oAuthPostRequest(userId, url, "text/html",
                jsonString);
        return new ResponseEntity<String>(is.getStatusCode());
    } catch (OAuthException e) {
        BufferedReader br = new BufferedReader(new InputStreamReader(e.getResponseBody()));
        String body = "";
        try {
            body = br.readLine();
        } catch (IOException e1) {
        }
        LOG.error(e.getResponseCode() + ", " + body, e);
        return new ResponseEntity<String>(HttpStatus.valueOf(e.getResponseCode()));
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new ResponseEntity<String>(HttpStatus.METHOD_FAILURE);
    }
}

From source file:com.ericsson.eiffel.remrem.publish.service.MessageServiceRMQImpl.java

/**
 * Method returns the Http response code for the events.
 */// ww w  .  j a v  a 2  s  . com
public HttpStatus getHttpStatus() {
    if (statusCodes.size() > 1) {
        return HttpStatus.MULTI_STATUS;
    } else {
        return HttpStatus.valueOf(statusCodes.get(0));

    }
}

From source file:org.kuali.mobility.sakai.service.SakaiForumServiceImpl.java

@Override
public ResponseEntity<String> postMessage(Message message, String userId) {
    try {/*from   www . j a v a2s. c o m*/
        String jsonString = "{";
        jsonString += "\"attachments\": [],";
        jsonString += "\"authoredBy\":\"" + userId + "\", ";
        jsonString += "\"body\":\"" + message.getBody() + "\", ";
        jsonString += "\"label\":\"" + "" + "\", ";
        jsonString += "\"recipients\":\"" + "" + "\", ";
        jsonString += "\"replies\":" + "null" + ", ";
        jsonString += "\"replyTo\":" + message.getInReplyTo() + ", ";
        jsonString += "\"title\":\"" + message.getTitle() + "\", ";
        jsonString += "\"topicId\":\"" + message.getTopicId() + "\", ";
        jsonString += "\"forumId\":\"" + message.getForumId() + "\", ";
        jsonString += "\"read\":" + "false" + ", ";
        jsonString += "\"entityReference\":\"" + "\\/forum_message" + "\"";
        //jsonString += "\"entityURL\":\"" + "http:\\/\\/localhost:8080\\/direct\\/forum_message" + "\", ";
        //jsonString += "\"entityTitle\":\"" + subject + "\"";

        jsonString += "}";

        String url = configParamService.findValueByName("Sakai.Url.Base") + "forum_message/new.json";
        ResponseEntity<InputStream> is = oncourseOAuthService.oAuthPostRequest(userId, url, "application/json",
                jsonString);
        return new ResponseEntity<String>(is.getStatusCode());
    } catch (OAuthException e) {
        BufferedReader br = new BufferedReader(new InputStreamReader(e.getResponseBody()));
        String body = "";
        try {
            body = br.readLine();
        } catch (IOException e1) {
        }
        LOG.error(e.getResponseCode() + ", " + body, e);
        return new ResponseEntity<String>(HttpStatus.valueOf(e.getResponseCode()));
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new ResponseEntity<String>(HttpStatus.METHOD_FAILURE);
    }
}

From source file:org.kuali.mobility.sakai.service.SakaiForumServiceImpl.java

@Override
public ResponseEntity<String> markMessageRead(String siteId, String messageId, String userId) {
    try {/* w  w w .j a  v a  2  s .c om*/
        String url = configParamService.findValueByName("Sakai.Url.Base") + "forum_message/markread/"
                + messageId + "/site/" + siteId;
        ResponseEntity<InputStream> response = oncourseOAuthService.oAuthPostRequest(userId, url, "text/html",
                "");
        return new ResponseEntity<String>(response.getStatusCode());
    } catch (OAuthException e) {
        if (e.getResponseBody() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(e.getResponseBody()));
            String body = "";
            try {
                body = br.readLine();
            } catch (IOException e1) {
            }
            LOG.error(e.getResponseCode() + ", " + body, e);
        } else {
            LOG.error(e.getMessage(), e);
        }
        return new ResponseEntity<String>(HttpStatus.valueOf(e.getResponseCode()));
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        return new ResponseEntity<String>(HttpStatus.METHOD_FAILURE);
    }
}

From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java

/**
 * Helper method for generating error message.
 * /*from  w ww  .  j  av a2 s .com*/
 * @param errorMessage is the error message
 * @param errorDeveloperMessage is more detailed message
 * @param errorCode is the error code
 * @return RestError which encapsulates all the above
 */
public RestError generateRestError(final String errorMessage, final String errorDeveloperMessage,
        final int errorCode) {

    final int statusCode = errorCode / WebServiceConstants.DIVISOR_ERROR_CODE;

    final RestError restError = new RestError(HttpStatus.valueOf(statusCode), errorCode, errorMessage,
            errorDeveloperMessage, WebServiceConstants.DEFAULT_URL);
    return restError;

}

From source file:com.mobileman.kuravis.core.ws.BaseControllerTest.java

protected MvcResult doDelete(String id, String url) throws Exception {
    if (StringUtils.isEmpty(id)) {
        return null;
    }/*w  ww  . j a  v  a2  s  .  c o  m*/
    url = StringUtils.endsWith(url, "/") ? url : url + "/";
    url += id;
    RequestBuilder rb = MockMvcRequestBuilders.delete(url).contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON);
    MvcResult result = this.mockMvc.perform(rb).andReturn();
    assertNull(result.getResolvedException());
    Assert.assertEquals(HttpStatus.OK, HttpStatus.valueOf(result.getResponse().getStatus()));
    return result;
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

public String getContentAsString(String path) {
    String uri = hostUri + path;/*w  ww . j  ava 2s. co m*/
    logger.debug("getContentAsString @ " + uri);

    HttpGet getRequest = new HttpGet(uri);

    String cookieInfo = readCookieInfo();
    getRequest.setHeader("Cookie", cookieInfo == null ? "" : cookieInfo);

    try {
        HttpResponse response = httpClient.execute(getRequest);

        int responseCode = response.getStatusLine().getStatusCode();

        InputStream contentStream = response.getEntity().getContent();
        String contentAsString = IOUtils.toString(contentStream, "UTF-8");

        logger.debug("content as string: " + contentAsString);
        if (responseCode != org.apache.http.HttpStatus.SC_OK) {
            HttpStatus status = HttpStatus.valueOf(responseCode);
            RestErrorHandler.handleHttpErrCode(status, contentAsString);
        }

        return contentAsString;
    } catch (IOException e) {
        throw new CliRestException("HTTP Response Error: " + e.getMessage());
    } finally {
        getRequest.releaseConnection();
    }
}