@Override
 public boolean hasError(ClientHttpResponse response) throws IOException {
   HttpStatus httpStatus = getHttpStatusCode(response);
   // We return an error when the default implementation detects that
   // the response is an error and also the status is not 500 (HTTP code for Node)
   return super.hasError(httpStatus) && httpStatus.value() != 500;
 }
 @Override
 public void handleError(ClientHttpResponse response) throws IOException {
   HttpStatus statusCode = response.getStatusCode();
   switch (statusCode.series()) {
     case CLIENT_ERROR:
       CloudFoundryException exception =
           new CloudFoundryException(statusCode, response.getStatusText());
       ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
       if (response.getBody() != null) {
         try {
           @SuppressWarnings("unchecked")
           Map<String, Object> map = mapper.readValue(response.getBody(), Map.class);
           exception.setDescription(CloudUtil.parse(String.class, map.get("description")));
         } catch (JsonParseException e) {
           exception.setDescription("Client error");
         } catch (IOException e) {
           exception.setDescription("Client error");
         }
       } else {
         exception.setDescription("Client error");
       }
       throw exception;
     case SERVER_ERROR:
       throw new HttpServerErrorException(statusCode, response.getStatusText());
     default:
       throw new RestClientException("Unknown status code [" + statusCode + "]");
   }
 }
  public Map convert(RestError re) {
    Map<String, Object> m = createMap();
    HttpStatus status = re.getStatus();
    m.put(getStatusKey(), status.value());

    int code = re.getCode();
    if (code > 0) {
      m.put(getCodeKey(), code);
    }

    String message = re.getMessage();
    if (message != null) {
      m.put(getMessageKey(), message);
    }

    String devMsg = re.getDeveloperMessage();
    if (devMsg != null) {
      m.put(getDeveloperMessageKey(), devMsg);
    }

    String moreInfoUrl = re.getMoreInfoUrl();
    if (moreInfoUrl != null) {
      m.put(getMoreInfoUrlKey(), moreInfoUrl);
    }

    return m;
  }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws ServletException, IOException {

    long start = System.currentTimeMillis();
    try {
      log.info(
          "Request: {} {}",
          request.getMethod(),
          request.getQueryString() == null
              ? request.getRequestURI()
              : request.getRequestURI() + "?" + request.getQueryString());
      log.info("Remote host: {} {}", request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
      log.info("User-Agent: {}", request.getHeader("User-Agent"));

      chain.doFilter(request, response);

    } finally {
      HttpStatus status = HttpStatus.valueOf(response.getStatus());
      log.info(
          "{} {}, in {}ms",
          status.value(),
          status.getReasonPhrase(),
          System.currentTimeMillis() - start);
    }
  }
 @Override
 protected void doFilterInternal(
     HttpServletRequest request, HttpServletResponse response, FilterChain chain)
     throws ServletException, IOException {
   UrlPathHelper helper = new UrlPathHelper();
   String suffix = helper.getPathWithinApplication(request);
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   try {
     chain.doFilter(request, response);
   } finally {
     stopWatch.stop();
     int status = getStatus(response);
     Object bestMatchingPattern =
         request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
     HttpStatus httpStatus = HttpStatus.OK;
     try {
       httpStatus = HttpStatus.valueOf(status);
     } catch (Exception ex) {
       // not convertible
     }
     if (bestMatchingPattern != null) {
       suffix = bestMatchingPattern.toString().replaceAll("[{}]", "-");
     } else if (httpStatus.is4xxClientError()) {
       suffix = UNKNOWN_PATH_SUFFIX;
     }
     String gaugeKey = getKey("response" + suffix);
     MetricFilterAutoConfiguration.this.gaugeService.submit(
         gaugeKey, stopWatch.getTotalTimeMillis());
     String counterKey = getKey("status." + status + suffix);
     MetricFilterAutoConfiguration.this.counterService.increment(counterKey);
   }
 }
 @Override
 protected void applyStatusCode() {
   HttpStatus statusCode = this.getStatusCode();
   if (statusCode != null) {
     getServletResponse().setStatus(statusCode.value());
   }
 }
  /** Test delete entity. */
  @Test
  public void testDeleteEntity() {
    HttpStatus status = deleteEntity(deleteEntityUrl(), getEntity().getId());
    assertEquals(status.toString(), "204");

    // set the Entity to null so we don't try to delete it again in @After
    setEntity(null);
  }
 protected void checkResponse(TumblrResponse tumblrResponse) {
   HttpStatus httpStatus = HttpStatus.valueOf(tumblrResponse.getStatus());
   if (httpStatus.series() == HttpStatus.Series.CLIENT_ERROR) {
     throw new HttpClientErrorException(httpStatus, tumblrResponse.getMessage());
   } else if (httpStatus.series() == HttpStatus.Series.SERVER_ERROR) {
     throw new HttpServerErrorException(httpStatus, tumblrResponse.getMessage());
   }
 }
 protected ResponseEntity<?> createSuccessfulRedirectToResponse(ShortURL l) {
   HttpHeaders h = new HttpHeaders();
   if (!l.getAdvert()) {
     h.setLocation(URI.create(l.getTarget()));
     return new ResponseEntity<>(h, HttpStatus.valueOf(l.getMode()));
   } else {
     h.setLocation(URI.create(l.getSponsor() + "?hash=" + l.getHash()));
     return new ResponseEntity<>(h, HttpStatus.valueOf(l.getMode()));
   }
 }
 @Override
 protected void checkApiCallClientErrors(HttpClientErrorException e) throws RestServiceException {
   HttpStatus status = e.getStatusCode();
   if (status.value() == statusAuthFailed) {
     Log.e(getTag(), "authorization failed - email or password not valid");
     processException(RestServiceException.ERROR_AUTHORIZATION_ERROR, e, false);
   } else if (status.value() == statusOSMFailed) {
     Log.e(getTag(), "osm failed");
     processException(RestServiceException.ERROR_NOT_OSM_CONNECTED, e, false);
   }
 }
 private String getExceptionMessage(Throwable throwable, Integer statusCode) {
   if (throwable != null) {
     return Throwables.getRootCause(throwable).getMessage();
   }
   logger.info("statusCode : " + statusCode);
   if (statusCode != null) {
     HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
     return httpStatus.getReasonPhrase();
   } else {
     return "";
   }
 }
 @RequestMapping
 public ResponseEntity<ApiError> handleErrorPage(
     @RequestParam("errorCode") String errorCode, WebRequest request) {
   HttpStatus httpStatus =
       HttpStatus.valueOf(
           (Integer)
               request.getAttribute(
                   RequestDispatcher.ERROR_STATUS_CODE, RequestAttributes.SCOPE_REQUEST));
   ApiError apiError =
       apiErrorCreator.createApiError(request, errorCode, httpStatus.getReasonPhrase());
   return new ResponseEntity<>(apiError, httpStatus);
 }
  /** Test put entity. */
  @Test
  public void testPutEntity() {
    Map<String, String> uriVariables = new HashMap<String, String>();
    uriVariables.put("id", String.valueOf(getEntity().getId()));

    // call the update for the RESTful API
    HttpStatus status = putEntity(putEntityUrl(), uriVariables, getEntity());
    assertEquals(status.toString(), "204");

    // double-check the Entity info was updated by re-pulling the Entity
    E retrievedEntity = getEntity(getEntityUrl(), getEntity().getId(), getClazz());
    assertEquals(retrievedEntity.getId(), getEntity().getId());
  }
    /**
     * @see
     *     org.springframework.web.client.DefaultResponseErrorHandler#handleError(org.springframework.http.client.ClientHttpResponse)
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
      HttpStatus statusCode = getHttpStatusCode(response);
      switch (statusCode.series()) {
        case CLIENT_ERROR:
          handleClientError(statusCode);

          super.handleError(response);

        case SERVER_ERROR:
          super.handleError(response);
        default:
          throw new RestClientException("Unknown status code [" + statusCode + "]");
      }
    }
Exemplo n.º 15
0
 public static BaseResponse createResponse(HttpStatus status, BindingResult result) {
   BaseResponse response = new BaseResponse();
   if (result.hasErrors()) {
     response.setError(true);
     response.setHttpErrorCode(status.value());
     /* create an array of total error count */
     ArrayList<ErrorDTO> errors = new ArrayList<ErrorDTO>(result.getErrorCount());
     /* append all field errors */
     for (FieldError err : result.getFieldErrors()) {
       System.out.println(
           "I got field error for: "
               + err.getField()
               + ", message: "
               + err.getDefaultMessage()
               + ", code: "
               + err.getCode());
       ErrorDTO dto = new ErrorDTO(err.getField(), err.getCode(), err.getDefaultMessage());
       errors.add(dto);
     }
     /* append global errors now */
     for (ObjectError err : result.getGlobalErrors()) {
       System.out.println(
           "I got global error for: "
               + err.getObjectName()
               + ", message: "
               + err.getDefaultMessage()
               + ", code: "
               + err.getCode());
       ErrorDTO dto = new ErrorDTO(err.getObjectName(), err.getCode(), err.getDefaultMessage());
       errors.add(dto);
     }
     response.setErrors(errors);
   }
   return response;
 }
  /**
   * Create a new user
   *
   * @param message containing the new user
   * @return userCreatedMessage with the appropiate data or an error otherwise
   */
  @RequestMapping(
      value = "/approve/{membershipId}",
      method = RequestMethod.PUT,
      consumes = "application/json")
  @ResponseBody
  public ResponseEntity<Object> approveMembership(
      @RequestHeader("Authorization") String token,
      @RequestHeader("If-Unmodified-Since") String since,
      @PathVariable(value = "membershipId") String uid,
      UriComponentsBuilder builder,
      HttpServletRequest req) {

    HttpHeaders headers = new HttpHeaders();
    Collection<String> cred = new LinkedList<String>();
    cred.add(token);
    try {
      // This method just authenticates... it doesn't do access control
      Collection<IPrincipal> principals = authenticator.authenticatePrincipals(LOG, cred);
      MembershipResponseMessage res =
          (MembershipResponseMessage)
              membershipService.updateEntity(new ApproveMembershipEvent(uid, principals, since));

      return new ResponseEntity<Object>(res, headers, HttpStatus.OK);
    } catch (IdManagementException idm) {
      // since the creation of the exception generated the log entries for the stacktrace, we don't
      // do it again here
      return new ResponseEntity<Object>(
          idm.getErrorAsMap(), headers, HttpStatus.valueOf(idm.getHTTPErrorCode()));
    } catch (Exception e) {
      String s = IdManagementException.getStackTrace(e);
      LOG.error(s);
      return new ResponseEntity<Object>(null, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
  @RequestMapping(value = "/{membershipId}", method = RequestMethod.DELETE)
  @ResponseStatus(HttpStatus.OK)
  @ResponseBody
  public ResponseEntity<Object> DeteMembership(
      @RequestHeader("Authorization") String token,
      @RequestHeader("If-Unmodified-Since") long lastKnownUpdate,
      @PathVariable(value = "membershipId") String uid) {

    HttpHeaders headers = new HttpHeaders();
    Collection<String> cred = new LinkedList<String>();
    cred.add(token);
    try {

      Collection<IPrincipal> principals = authenticator.authenticatePrincipals(LOG, cred);
      membershipService.deleteEntity(
          new DeleteUserMembershipEvent(uid, principals, lastKnownUpdate));
      return new ResponseEntity<Object>(null, headers, HttpStatus.OK);

    } catch (IdManagementException idm) {
      // since the creation of the exception generated the log entries for the stacktrace, we don't
      // do it again here
      return new ResponseEntity<Object>(
          idm.getErrorAsMap(), headers, HttpStatus.valueOf(idm.getHTTPErrorCode()));
    } catch (Exception e) {
      String s = IdManagementException.getStackTrace(e);
      LOG.error(s);
      return new ResponseEntity<Object>(null, headers, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 @ExceptionHandler(NotificationAlreadyUpdatedException.class)
 public ResponseEntity<ResponseWrapper> handleException() {
   ResponseWrapper responseWrapper =
       new ResponseWrapperImpl(
           HttpStatus.CONFLICT, RestMessage.ALREADY_UPDATED, RestStatus.FAILURE);
   return new ResponseEntity<>(responseWrapper, HttpStatus.valueOf(responseWrapper.getCode()));
 }
Exemplo n.º 19
0
 private boolean is4xxClientError(int status) {
   try {
     return HttpStatus.valueOf(status).is4xxClientError();
   } catch (Exception ex) {
     return false;
   }
 }
 public String getStatusText() throws IOException {
   try {
     return this.connection.getResponseMessage();
   } catch (IOException ex) {
     return HttpStatus.valueOf(handleIOException(ex)).getReasonPhrase();
   }
 }
Exemplo n.º 21
0
    public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException)
        throws IOException, ServletException {

      response.setStatus(httpStatus.value());
    }
    // create a JSON deserializer for the response.getBody();
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
      HttpStatus statusCode = response.getStatusCode();
      // response.getStatusText()
      switch (statusCode.series()) {
        case CLIENT_ERROR:
          // IOUtils.toString(response.getBody());
          // throw new HttpClientErrorException(statusCode, response.getStatusText());
          break;
        case SERVER_ERROR:
          // read IOUtils.toString(response.getBody())
          //	throw new HttpServerErrorException(statusCode, response.getStatusText());

        default:
          throw new RestClientException("Unknown status code [" + statusCode + "]");
      }
    }
Exemplo n.º 23
0
 private ResponseEntity toJsonErrorResponse(
     int httpCode, String eMessage) { // todo move to JsonRestUtils
   HttpHeaders headers = new HttpHeaders();
   MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
   headers.setContentType(mediaType);
   headers.set("Reason", eMessage);
   return new ResponseEntity<>(headers, HttpStatus.valueOf(httpCode));
 }
  private static void logAndSendErrorResponse(
      HttpServletResponse response, HttpStatus status, String reason, Exception ex)
      throws IOException {
    long errorId = generateErrorId();
    String errorMessage = ErrorFormatter.formatErrorMessage(reason, errorId);

    LOGGER.error(errorMessage, ex);
    response.sendError(status.value(), errorMessage);
  }
Exemplo n.º 25
0
  // 스케줄러 상태
  // http://localhost:8080/sda/sch/status
  @RequestMapping(value = "/status", method = RequestMethod.GET)
  public @ResponseBody ResponseEntity<ResponseMessage> statusSchList() {
    ResponseMessage resultMsg = new ResponseMessage();
    ResponseEntity<ResponseMessage> entity = null;
    HttpHeaders responseHeaders = new HttpHeaders();
    Gson gson = new Gson();
    String msg = "";

    log.info("status sch begin================>");
    try {
      checkScheduerMainService();
      thm.statusSchList();
      msg = thm.getStatusList();

      resultMsg.setCode(Utils.OK_CODE);
      resultMsg.setMessage(Utils.OK_MSG);
      resultMsg.setContent(gson.toJson(msg));
      entity = new ResponseEntity<ResponseMessage>(resultMsg, responseHeaders, HttpStatus.OK);
    } catch (PersistenceException e) {
      msg = "db connection error...";
      resultMsg = Utils.makeResponseBody(e);
      resultMsg.setContent(gson.toJson(msg));
      entity =
          new ResponseEntity<ResponseMessage>(
              resultMsg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode()));
    } catch (NullPointerException e) {
      msg = "scheduler is not initiated....";
      resultMsg = Utils.makeResponseBody(e);
      resultMsg.setContent(gson.toJson(msg));
      entity =
          new ResponseEntity<ResponseMessage>(
              resultMsg, responseHeaders, HttpStatus.valueOf(resultMsg.getCode()));
    } 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("status sch end ================>");
    return entity;
  }
 private HttpStatus getStatus(HttpServletRequest request) {
   Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
   if (statusCode != null) {
     try {
       return HttpStatus.valueOf(statusCode);
     } catch (Exception ex) {
     }
   }
   return HttpStatus.INTERNAL_SERVER_ERROR;
 }
  private <T> ResponseEntity<T> createResponse(Class<T> clazz, Object instance, Response response) {

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    for (String key : response.headers().keySet()) {
      headers.put(key, new LinkedList<>(response.headers().get(key)));
    }

    return new ResponseEntity<T>(
        clazz.cast(instance), headers, HttpStatus.valueOf(response.status()));
  }
 private HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
   HttpStatus statusCode;
   try {
     statusCode = response.getStatusCode();
   } catch (IllegalArgumentException ex) {
     throw new HttpServerErrorException(
         HttpStatus.valueOf(response.getRawStatusCode()), response.getStatusText());
   }
   return statusCode;
 }
Exemplo n.º 29
0
 @AfterReturning(value = "allOperation()||athenaServiceOperation()||spartanServiceOperation()")
 public void afterReturning(JoinPoint join) throws IOException {
   counterService.increment(
       "counter.HttpStatus."
           + httpStatusCode.name()
           + "."
           + join.getSignature().getDeclaringType().getSimpleName()
           + "."
           + join.getSignature().getName()
           + ".calls");
   counterService.increment("counter.numberof.calls");
 }
  protected DeferredResult<ResponseEntity<Map<String, Object>>> errorResult(
      String errorMessage, HttpStatus status) {
    DeferredResult<ResponseEntity<Map<String, Object>>> response = new DeferredResult<>();
    Map<String, Object> result = new HashMap<>();
    result.put("success", false);
    result.put("errorcode", status.value());
    result.put("errordescription", errorMessage);
    result.put("stacktrace", errorMessage);

    response.setResult((new ResponseEntity<>(result, status)));
    return response;
  }