package org.osiam.addons.administration.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.osiam.addons.administration.model.session.GeneralSessionData;
import org.osiam.addons.administration.util.RedirectBuilder;
import org.osiam.client.exception.UnauthorizedException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * This class is responsible for handling all exceptions thrown by any controller-handler.
 */
@ControllerAdvice
public class GlobalExceptionHandler implements AccessDeniedHandler {
    private static final Logger LOG = Logger.getLogger(GlobalExceptionHandler.class);

    @Inject
    private GeneralSessionData session;

    @ExceptionHandler(UnauthorizedException.class)
    public String handleUnauthorized() {
        session.setAccesstoken(null);

        return new RedirectBuilder().setDestination(LoginController.CONTROLLER_PATH).build();
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {

        response.sendRedirect(LoginController.CONTROLLER_PATH);
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleUncaught(HttpServletRequest req, Exception e) {
        LOG.error("Uncaught exception was thrown.", e);

        ModelAndView mav = new ModelAndView("error");

        mav.addObject("exception", e);
        mav.addObject("stacktrace", getStackTrace(e));
        mav.addObject("request", req);

        return mav;
    }

    private String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        t.printStackTrace(pw);
        return sw.toString();
    }
}

@@ -77,65 +77,8 @@
 ion;
-%0Aimport java.io.PrintWriter;%0Aimport java.io.StringWriter;
 %0A%0Aim
@@ -777,16 +777,59 @@
 dView;%0A%0A
+import com.google.common.base.Throwables;%0A%0A
 /**%0A * T
@@ -2091,151 +2091,49 @@
     
-StringWriter sw = new StringWriter();%0A        PrintWriter pw = new PrintWriter(sw);%0A%0A        t.printStackTrace(pw);%0A        return sw.to
+return Throwables.getStackTraceAs
 String(
+t
 );%0A 

use guava to get stacktrace as string