Java Code Examples for org.springframework.http.HttpStatus#valueOf()
The following examples show how to use
org.springframework.http.HttpStatus#valueOf() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetricStoreImpl.java From griffin with Apache License 2.0 | 6 votes |
private ResponseEntity<?> getResponseEntityFromResponse(Response response) throws IOException { String body = EntityUtils.toString(response.getEntity()); HttpStatus status = HttpStatus.valueOf(response.getStatusLine() .getStatusCode()); return new ResponseEntity<>(body, responseHeaders, status); }
Example 2
Source File: GoogleOauthController.java From urltodrive with MIT License | 6 votes |
private User getUser(@NotNull Token token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(PROFILE_URL); builder.addParameter("access_token", token.getAccessToken()); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet(builder.build()); org.apache.http.HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); if (HttpUtilities.success(statusCode)) { User user = gson.fromJson(new InputStreamReader(inputStream), User.class); user.setToken(token); return user; } throw new ApiException(HttpStatus.valueOf(statusCode)); }
Example 3
Source File: RestHandlerExceptionResolverFactoryBean.java From spring-rest-exception-handler with Apache License 2.0 | 6 votes |
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 { throw new IllegalArgumentException(String.format( "Values of the exceptionHandlers maps must be instance of ErrorResponseFactory, HttpStatus, " + "String, or int, but %s given", value.getClass())); } }
Example 4
Source File: RestExceptionHandler.java From jakduk-api with MIT License | 6 votes |
/** * RequestBody에서 request 값들을 객체화 실패했을때 */ @Override protected ResponseEntity<Object> handleHttpMessageNotReadable( HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ServiceError serviceError = ServiceError.FORM_VALIDATION_FAILED; RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError); try { log.warn(ObjectMapperUtils.writeValueAsString(restErrorResponse), ex); } catch (JsonProcessingException ignore) { log.warn(ex.getLocalizedMessage(), ex); } return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus())); }
Example 5
Source File: JettyXhrTransport.java From spring4-understanding with Apache License 2.0 | 6 votes |
protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, String body) { Request httpRequest = this.httpClient.newRequest(url).method(method); addHttpHeaders(httpRequest, headers); if (body != null) { httpRequest.content(new StringContentProvider(body)); } ContentResponse response; try { response = httpRequest.send(); } catch (Exception ex) { throw new SockJsTransportFailureException("Failed to execute request to " + url, ex); } HttpStatus status = HttpStatus.valueOf(response.getStatus()); HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders()); return (response.getContent() != null ? new ResponseEntity<String>(response.getContentAsString(), responseHeaders, status) : new ResponseEntity<String>(responseHeaders, status)); }
Example 6
Source File: SubscribeController.java From SDA with BSD 2-Clause "Simplified" License | 6 votes |
/** * subscribe 등록 * @param cmid * @return ResponseEntity<ResponseMessage> */ @RequestMapping(value = "/regist/{cmid}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<ResponseMessage> regist(@PathVariable String cmid) { ResponseMessage resultMsg = new ResponseMessage(); ResponseEntity<ResponseMessage> entity = null; HttpHeaders responseHeaders = new HttpHeaders(); log.info("subscribe regist begin================>"); try { subscribeService.regist(cmid); resultMsg.setCode(Utils.OK_CODE); resultMsg.setMessage(Utils.OK_MSG); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.OK); } catch (Exception e) { resultMsg = Utils.makeResponseBody(e); log.debug("Exception : "+resultMsg.getMessage()); responseHeaders.add("ExceptionCause", resultMsg.getMessage()); responseHeaders.add("ExceptionClass", resultMsg.getClass().getName()); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode())); } log.info("subscribe regist end================>"); return entity; }
Example 7
Source File: TemplateController.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * 목록 조회 * @param commandMap * @return ResponseEntity<ResponseMessage> */ @RequestMapping(value = "/template/all", method = RequestMethod.GET) public @ResponseBody ResponseEntity<ResponseMessage> selectList(Map<String, Object> commandMap) { ResponseMessage resultMsg = new ResponseMessage(); ResponseEntity<ResponseMessage> entity = null; HttpHeaders responseHeaders = new HttpHeaders(); Gson gson = new Gson(); String contents; List<TemplateDTO> list = new ArrayList<TemplateDTO>(); log.info("/template/all GET start================>"); try { list = templateService.selectList(commandMap); contents = gson.toJson(list); resultMsg.setCode(Utils.OK_CODE); resultMsg.setMessage(Utils.OK_MSG); resultMsg.setContents(contents); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resultMsg = Utils.makeResponseBody(e); responseHeaders.add("ExceptionCause", e.getMessage()); responseHeaders.add("ExceptionClass", e.getClass().getName()); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode())); } log.info("/template/all GET end================>"); return entity; }
Example 8
Source File: EndpointAdvice.java From jkes with Apache License 2.0 | 5 votes |
@ExceptionHandler(SearchResponseException.class) @ResponseBody ResponseEntity<?> handleResponseException(SearchResponseException ex) { int statusCode = ex.getResponseException().getResponse().getStatusLine().getStatusCode(); HttpStatus status = HttpStatus.valueOf(statusCode); return new ResponseEntity<>(new EndpointError(status.value(), ex.getErrorMessage()), status); }
Example 9
Source File: TemplateController.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * 단건 조회 * @param tmid * @return ResponseEntity<ResponseMessage> */ @RequestMapping(value = "/template/{tmid}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<ResponseMessage> selectOne(@PathVariable String tmid) { Map<String, Object> commandMap = new HashMap<String, Object>(); ResponseMessage resultMsg = new ResponseMessage(); ResponseEntity<ResponseMessage> entity = null; HttpHeaders responseHeaders = new HttpHeaders(); Gson gson = new Gson(); String contents; log.info("/template/{tmid} GET start================>"); try { TemplateDTO templateDTO = new TemplateDTO(); commandMap.put("tmid", tmid); templateDTO = templateService.selectOne(commandMap); contents = gson.toJson(templateDTO); resultMsg.setCode(Utils.OK_CODE); resultMsg.setMessage(Utils.OK_MSG); resultMsg.setContents(contents); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resultMsg = Utils.makeResponseBody(e); responseHeaders.add("ExceptionCause", e.getMessage()); responseHeaders.add("ExceptionClass", e.getClass().getName()); entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode())); } log.info("/template/{tmid} GET end================>"); return entity; }
Example 10
Source File: ExceptionAdvice.java From ProjectStudy with MIT License | 5 votes |
/** * 获取状态码 * @param request * @return */ private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); }
Example 11
Source File: APIClientTest.java From data-prep with Apache License 2.0 | 5 votes |
public DataSetMetadata getPrepMetadata(String preparationId) throws IOException { DataSetMetadata metadata; // when Response transformedResponse = given().when().get("/api/preparations/{id}/metadata", preparationId); HttpStatus responseStatus = HttpStatus.valueOf(transformedResponse.getStatusCode()); if (ACCEPTED.equals(responseStatus)) { // first time we have a 202 with a Location to see asynchronous method status final String asyncMethodStatusUrl = transformedResponse.getHeader("Location"); waitForAsyncMethodToFinishWithSuccess(asyncMethodStatusUrl); Response response = given() // .when() // .expect() // .statusCode(200) // .log() // .ifError() // .get("/api/preparations/{id}/metadata", preparationId); metadata = mapper.readValue(response.asInputStream(), DataSetMetadata.class); } else if (OK.equals(responseStatus)) { metadata = mapper.readValue(transformedResponse.asInputStream(), DataSetMetadata.class); } else { throw new RuntimeException( "Could not get preparation metadata. Response was: " + transformedResponse.print()); } return metadata; }
Example 12
Source File: ControllersConfiguration.java From components with Apache License 2.0 | 5 votes |
private static ResponseEntity<ApiError> buildUnexpectedErrorResponse(ErrorCode code, String message, Throwable cause) { ApiError dto = new ApiError(); dto.setCode(code.getProduct() + "_" + code.getGroup() + "_" + code.getCode()); dto.setMessage(message); dto.setMessageTitle("An unexpected error occurred"); dto.setCause(cause == null ? null : cause.getMessage()); return new ResponseEntity<>(dto, HttpStatus.valueOf(code.getHttpStatus())); }
Example 13
Source File: AdviceTrait.java From problem-spring-web with MIT License | 4 votes |
default ResponseEntity<Problem> create(final Throwable throwable, final Problem problem, final NativeWebRequest request, final HttpHeaders headers) { final HttpStatus status = HttpStatus.valueOf(Optional.ofNullable(problem.getStatus()) .orElse(Status.INTERNAL_SERVER_ERROR) .getStatusCode()); log(throwable, problem, request, status); if (status == HttpStatus.INTERNAL_SERVER_ERROR) { request.setAttribute(ERROR_EXCEPTION, throwable, SCOPE_REQUEST); } return process(negotiate(request).map(contentType -> ResponseEntity .status(status) .headers(headers) .contentType(contentType) .body(problem)) .orElseGet(throwingSupplier(() -> { final ResponseEntity<Problem> fallback = fallback(throwable, problem, request, headers); if (fallback.getBody() == null) { /* * Ugly hack to workaround an issue with Tomcat and Spring as described in * https://github.com/zalando/problem-spring-web/issues/84. * * The default fallback in case content negotiation failed is a 406 Not Acceptable without * a body. Tomcat will then display its error page since no body was written and the response * was not committed. In order to force Spring to flush/commit one would need to provide a * body but that in turn would fail because Spring would then fail to negotiate the correct * content type. * * Writing the status code, headers and flushing the body manually is a dirty way to bypass * both parties, Tomcat and Spring, at the same time. */ final ServerHttpResponse response = new ServletServerHttpResponse( request.getNativeResponse(HttpServletResponse.class)); response.setStatusCode(fallback.getStatusCode()); response.getHeaders().putAll(fallback.getHeaders()); response.getBody(); // just so we're actually flushing the body... response.flush(); } return fallback; })), request); }
Example 14
Source File: HttpStatusCodeException.java From engine with GNU General Public License v3.0 | 4 votes |
public HttpStatusCodeException(int statusCode, String message) { this(HttpStatus.valueOf(statusCode), message); }
Example 15
Source File: AbstractClientHttpResponse.java From spring4-understanding with Apache License 2.0 | 4 votes |
@Override public HttpStatus getStatusCode() throws IOException { return HttpStatus.valueOf(getRawStatusCode()); }
Example 16
Source File: SubscribeServiceImpl.java From SDA with BSD 2-Clause "Simplified" License | 4 votes |
public void unregist(String cmid) throws Exception { String unsubscription_uri = Utils.getSdaProperty("com.pineone.icbms.sda.si.unsubscription_uri"); Map<String, Object> commandMap; // cmid로 삭제 대상 ci목록 가져오기 commandMap = new HashMap<String, Object>(); commandMap.put("cmid", cmid); List<CiDTO> ciList = subscribeDAO.selectList(commandMap); // 데이타가 없으면 오류발생시킴 if (ciList == null || ciList.size() == 0) { throw new UserDefinedException(HttpStatus.NOT_FOUND); } Gson gson = new Gson(); CiDTO[] ciDTO = new CiDTO[ciList.size()]; for (int i = 0; i < ciList.size(); i++) { ciDTO[i] = ciList.get(i); } for (int i = 0; i < ciDTO.length; i++) { // condition을 JENA에 요청하여 uri목록을 얻음 List<String> uriList = new ArrayList<String>(); OneM2MSubscribeUriMapper mapper = new OneM2MSubscribeUriMapper(ciDTO[i].getDomain(), ciDTO[i].getConditions()); uriList = mapper.getSubscribeUri(); log.debug("uriList to unregist ==> \n" + uriList); for (int k = 0; k < uriList.size(); k++) { Map<String, String> map = new HashMap<String, String>(); map.put("_uri", uriList.get(k)); String jsonMsg = gson.toJson(map); log.debug("Request message for unsubscribing => " + jsonMsg); ResponseMessage responseMessage = Utils.requestPost(unsubscription_uri, jsonMsg); // POST log.debug("responseMessage of unsubscribing from SI : " + responseMessage.toString()); if (responseMessage.getCode() != 200) { throw new RemoteSIException(HttpStatus.valueOf(responseMessage.getCode()), responseMessage.getMessage()); } // subscribe테이블에서 삭제함(cmid와 ciid 그리고 uri를 키로 이용하여 삭제함) commandMap = new HashMap<String, Object>(); commandMap.put("cmid", cmid); commandMap.put("ciid", ciDTO[i].getCiid()); commandMap.put("uri", uriList.get(k)); subscribeDAO.deleteByUri(commandMap); } } }
Example 17
Source File: DefaultServerResponseBuilder.java From spring-analysis-note with MIT License | 4 votes |
@Override public final HttpStatus statusCode() { return HttpStatus.valueOf(this.statusCode); }
Example 18
Source File: SubscribeServiceImpl.java From SDA with BSD 2-Clause "Simplified" License | 4 votes |
public void regist(String cmid) throws Exception { String notification_uri = Utils.getSdaProperty("com.pineone.icbms.sda.si.notification_uri"); String subscription_uri = Utils.getSdaProperty("com.pineone.icbms.sda.si.subscription_uri"); Map<String, Object> commandMap; // 확인 commandMap = new HashMap<String, Object>(); commandMap.put("cmid", cmid); List<CiDTO> list = subscribeDAO.selectList(commandMap); // 데이타가 없으면 오류발생시킴 if (list == null || list.size() == 0) { throw new UserDefinedException(HttpStatus.NOT_FOUND); } Gson gson = new Gson(); CiDTO[] ciDTO = new CiDTO[list.size()]; // subscribe테이블에 중복된 값이 있을 수 있으므로 삭제함(cmid를 이용함) commandMap = new HashMap<String, Object>(); commandMap.put("cmid", cmid); subscribeDAO.deleteByCmid(commandMap); // SI에 등록준비(list의 값이 CiDTO테이블과 같으므로 CiDTO에 담는다) for (int i = 0; i < list.size(); i++) { ciDTO[i] = list.get(i); } // 처리시작 for (int i = 0; i < ciDTO.length; i++) { // log.debug("val["+i+"]"+ciDTO[i].toString()); // condition을 JENA에 요청하여 uri목록을 얻음 List<String> uriList = new ArrayList<String>(); OneM2MSubscribeUriMapper mapper = new OneM2MSubscribeUriMapper(ciDTO[i].getDomain(), ciDTO[i].getConditions()); uriList = mapper.getSubscribeUri(); log.debug("uriList to regist ==> \n" + uriList); for (int k = 0; k < uriList.size(); k++) { // tnsda_subscribe에 등록 시작 SubscribeDTO subscribeDTO = new SubscribeDTO(); String subscribe_time = Utils.dateFormat.format(new Date()); subscribeDTO.setCmid(cmid); subscribeDTO.setCiid(ciDTO[i].getCiid()); subscribeDTO.setUri(uriList.get(k)); subscribeDTO.setNotification_uri(notification_uri); subscribeDTO.setSubscribe_time(subscribe_time); subscribeDTO.setCuser(user); subscribeDTO.setUuser(user); subscribeDAO.insert(subscribeDTO); // tnsda_subscribe에 등록 끝 // SI에 등록 시작 Map<String, String> map = new HashMap<String, String>(); map.put("_uri", uriList.get(k)); map.put("_notificationUri", notification_uri); String jsonMsg = gson.toJson(map); log.debug("Request message for subscribing => " + jsonMsg); ResponseMessage responseMessage = Utils.requestData(subscription_uri, jsonMsg); // POST // ResponseMessage responseMessage = // Utils.getMessageFromResponse(response); log.debug("result of responseMessage : " + responseMessage.toString()); if (responseMessage.getCode() != 200) { throw new RemoteSIException(HttpStatus.valueOf(responseMessage.getCode()), responseMessage.getMessage()); } // SI에 등록 끝 } } // 처리끝 }
Example 19
Source File: ReactorClientHttpResponse.java From java-technology-stack with MIT License | 4 votes |
@Override public HttpStatus getStatusCode() { return HttpStatus.valueOf(getRawStatusCode()); }
Example 20
Source File: GlobalExceptionHandler.java From yshopmall with Apache License 2.0 | 2 votes |
/** * 统一返回 * @param apiError * @return */ private ResponseEntity<ApiErr> buildResponseEntity2(ApiErr apiError) { return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus())); }