コード例 #1
0
 @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);
   }
 }
コード例 #2
0
  @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);
    }
  }
コード例 #3
0
ファイル: ResponseBuilder.java プロジェクト: sigabort/venus
 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;
 }
コード例 #4
0
 @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;
 }
コード例 #5
0
  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;
  }
コード例 #6
0
 @Override
 protected void applyStatusCode() {
   HttpStatus statusCode = this.getStatusCode();
   if (statusCode != null) {
     getServletResponse().setStatus(statusCode.value());
   }
 }
コード例 #7
0
    public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException)
        throws IOException, ServletException {

      response.setStatus(httpStatus.value());
    }
コード例 #8
0
  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);
  }
コード例 #9
0
  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;
  }
コード例 #10
0
 /**
  * Generates a json error response with the given status code + exception.
  *
  * @param status http status code
  * @param ex exception
  * @return error response
  */
 private ResponseEntity<String> generateJsonErrorResponse(HttpStatus status, Exception ex) {
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.APPLICATION_JSON);
   return new ResponseEntity<>(
       Json.createBuilderFactory(null)
           .createObjectBuilder()
           .add("code", status.value())
           .add("message", ex.getMessage())
           .build()
           .toString(),
       headers,
       status);
 }
コード例 #11
0
  protected DeferredResult<ResponseEntity<Map<String, Object>>> exceptionResult(
      Throwable t, 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", t.getMessage());

    StringWriter stacktrace = new StringWriter();
    t.printStackTrace(new PrintWriter(stacktrace));
    result.put("stacktrace", stacktrace.toString());

    response.setResult((new ResponseEntity<>(result, status)));
    return response;
  }
コード例 #12
0
  /**
   * Send a redirect back to the HTTP client
   *
   * @param request current HTTP request (allows for reacting to request method)
   * @param response current HTTP response (for sending response headers)
   * @param targetUrl the target URL to redirect to
   * @param http10Compatible whether to stay compatible with HTTP 1.0 clients
   * @throws IOException if thrown by response methods
   */
  protected void sendRedirect(
      HttpServletRequest request,
      HttpServletResponse response,
      String targetUrl,
      boolean http10Compatible)
      throws IOException {

    String encodedRedirectURL = response.encodeRedirectURL(targetUrl);

    if (http10Compatible) {
      if (this.statusCode != null) {
        response.setStatus(this.statusCode.value());
        response.setHeader("Location", encodedRedirectURL);
      } else {
        // Send status code 302 by default.
        response.sendRedirect(encodedRedirectURL);
      }
    } else {
      HttpStatus statusCode = getHttp11StatusCode(request, response, targetUrl);
      response.setStatus(statusCode.value());
      response.setHeader("Location", encodedRedirectURL);
    }
  }
コード例 #13
0
  /**
   * Responds to the HTTP request with exception. NOTE: Currently, only application/xml content type
   * is supported.
   */
  private void _responseWithException(
      final Exception ex, final HttpStatus http_status, final HttpServletResponse response) {
    _LOG_.error("response with exception: " + ex.getClass().getName() + " - " + ex.getMessage());

    response.setContentType(MediaType.APPLICATION_XML.toString());
    response.setStatus(http_status.value());

    Writer writer = null;
    try {
      writer = response.getWriter();
      _getNvdXmlMapper().marshal(ex, writer);
    } catch (IOException io_ex) {
      _LOG_.error("ERROR in exception handling: " + io_ex);
    } finally {
      if (writer != null) {
        try {
          writer.flush();
          writer.close();
        } catch (Exception ig_ex) {
          _LOG_.warn("ERROR in exception handling: " + ig_ex);
        }
      }
    }
  }
コード例 #14
0
 public HttpResponseMatcher(HttpStatus status) {
   this.content("HTTP/1.1 " + status.value() + " " + status.getReasonPhrase());
   this.content("");
 }
コード例 #15
0
 public void setStatus(HttpStatus status) {
   response.setStatus(status.value());
 }
コード例 #16
0
  protected ModelAndView doResolveHandlerMethodException(
      HttpServletRequest request,
      HttpServletResponse response,
      HandlerMethod handlerMethod,
      Exception exception) {

    if (handlerMethod == null) {
      return null;
    }

    Method method = handlerMethod.getMethod();

    if (method == null) {
      return null;
    }
    // 如果定义了@ExceptionHandler则返回相应的Map中的数据
    ModelAndView returnValue =
        super.doResolveHandlerMethodException(request, response, handlerMethod, exception);
    ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
    if (responseBodyAnn != null) {
      try {
        ResponseStatus responseStatusAnn =
            AnnotationUtils.findAnnotation(method, ResponseStatus.class);
        if (responseStatusAnn != null) { // 判断是否使用了@ResponseStatus
          HttpStatus responseStatus = responseStatusAnn.value();
          String reason = responseStatusAnn.reason();
          if (!StringUtils.hasText(reason)) {
            response.setStatus(responseStatus.value());
          } else {
            try {
              response.sendError(responseStatus.value(), reason);
            } catch (IOException e) {
            }
          }
        }

        if (exception instanceof ApiException) {
          ApiException apiException = (ApiException) exception;
          // response.setStatus(apiException.getCode());
          response.sendError(apiException.getCode(), apiException.getMessage());
          // handleResponseBody(apiException, request, response);
          return new ModelAndView();
        } else { // 如果不是自己定义好的异常就要记录日志
          String sessionId = request.getSession().getId();
          log.error("系统出错,sessionId=" + sessionId, exception);
        }

        // 如果没有找到@ExceptionHandler注解(controller中的方法出错时,有该注解的方法会被调用并返回数据)的处理方法或者没有返回值,
        // 又或者出错的方法没有标识@ResponseStatus注解
        if (returnValue == null) {
          ApiException res = new ApiException(ApiResponseUtil.STATUS.INTERNAL_SERVER_ERROR);
          handleResponseBody(res, request, response);
          return new ModelAndView();
        }
        return handleResponseError(returnValue, request, response);
      } catch (Exception e) {
        return null;
      }
    }

    if (null == returnValue) {
      returnValue = new ModelAndView();
      if (null == returnValue.getViewName()) {
        returnValue.setViewName(defaultErrorView);
      }
    }
    return returnValue;
  }