/*
 * Copyright 2017 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.kork.web.exceptions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GenericExceptionHandlers {
  private static final Logger logger = LoggerFactory.getLogger(GenericExceptionHandlers.class);

  private final DefaultErrorAttributes defaultErrorAttributes = new DefaultErrorAttributes();

  @ExceptionHandler(AccessDeniedException.class)
  public void handleAccessDeniedException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException {
    logger.error("Access Denied", e);

    storeException(request, response, e);

    // avoid leaking any information that may be in `e.getMessage()` by returning a static error message
    response.sendError(HttpStatus.FORBIDDEN.value(), "Access is denied");
  }

  @ExceptionHandler(NotFoundException.class)
  public void handleNotFoundException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException {
    storeException(request, response, e);
    response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
  }

  @ExceptionHandler(InvalidRequestException.class)
  public void handleInvalidRequestException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException {
    storeException(request, response, e);
    response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
  }

  @ExceptionHandler(Exception.class)
  public void handleException(Exception e, HttpServletResponse response, HttpServletRequest request) throws IOException {
    logger.error("Internal Server Error", e);

    storeException(request, response, e);

    ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class);
    if (responseStatus != null) {
      String message = e.getMessage();
      if (message == null || message.trim().isEmpty()) {
        message = responseStatus.reason();
      }
      response.sendError(responseStatus.value().value(), message);
    } else {
      response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

  }

  private void storeException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
    // store exception as an attribute of HttpServletRequest such that it can be referenced by GenericErrorController
    defaultErrorAttributes.resolveException(request, response, null, ex);
  }
}

@@ -638,24 +638,105 @@
 xceptions;%0A%0A
+import com.google.common.base.Charsets;%0Aimport com.google.common.io.CharStreams;%0A
 import org.s
@@ -744,24 +744,24 @@
 f4j.Logger;%0A
-
 import org.s
@@ -1156,16 +1156,78 @@
 eStatus;
+%0Aimport retrofit.RetrofitError;%0Aimport retrofit.client.Header;
 %0A%0Aimport
@@ -1340,16 +1340,128 @@
 ception;
+%0Aimport java.io.InputStreamReader;%0Aimport java.util.Collections;%0Aimport java.util.HashMap;%0Aimport java.util.Map;
 %0A%0A@Contr
@@ -2743,32 +2743,1176 @@
 essage());%0A  %7D%0A%0A
+  @ExceptionHandler(RetrofitError.class)%0A  public void handleRetrofitError(RetrofitError e, HttpServletResponse response, HttpServletRequest request) throws IOException %7B%0A    if (e.getResponse() != null) %7B%0A      Map%3CString, Object%3E additionalContext = new HashMap%3C%3E();%0A      additionalContext.put(%22url%22, e.getResponse().getUrl());%0A%0A      Header contentTypeHeader = e.getResponse().getHeaders()%0A        .stream()%0A        .filter(h -%3E h.getName().equalsIgnoreCase(%22content-type%22))%0A        .findFirst()%0A        .orElse(null);%0A%0A      if (contentTypeHeader != null && contentTypeHeader.getValue().toLowerCase().contains(%22application/json%22)) %7B%0A        // include any json responses%0A        additionalContext.put(%22body%22, CharStreams.toString(%0A          new InputStreamReader(e.getResponse().getBody().in(), Charsets.UTF_8)%0A        ));%0A      %7D%0A%0A      storeException(request, response, new RetrofitErrorWrapper(e.getMessage(), additionalContext));%0A      response.sendError(e.getResponse().getStatus(), e.getMessage());%0A    %7D else %7B%0A      // no retrofit response (likely) indicates a NETWORK error%0A      handleException(e, response, request);%0A    %7D%0A  %7D%0A%0A
   @ExceptionHand
@@ -4809,16 +4809,16 @@
 troller%0A
-
     defa
@@ -4886,11 +4886,530 @@
 ex);%0A  %7D
+%0A%0A  private static class RetrofitErrorWrapper extends RuntimeException implements HasAdditionalAttributes %7B%0A    private final Map%3CString, Object%3E additionalAttributes;%0A%0A    public RetrofitErrorWrapper(String message, Map%3CString, Object%3E additionalAttributes) %7B%0A      super(message);%0A      this.additionalAttributes = additionalAttributes;%0A    %7D%0A%0A    @Override%0A    public Map%3CString, Object%3E getAdditionalAttributes() %7B%0A      return additionalAttributes != null ? additionalAttributes : Collections.emptyMap();%0A    %7D%0A  %7D
 %0A%7D%0A

Add a generic RetrofitError exception handler (#86)