/* * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. * * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in * compliance with the Licence. You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * * Unless required by applicable law or agreed to in writing, software distributed under the Licence * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the Licence for the specific language governing permissions and limitations under * the Licence. * * This product combines work with different licenses. See the "NOTICE" text file for details on the * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative * works that you distribute must include a readable copy of the "NOTICE" text file. */ package at.gv.egiz.eaaf.core.impl.idp.controller; import java.io.IOException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.ExceptionHandler; import at.gv.egiz.components.eventlog.api.EventConstants; import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egiz.eaaf.core.api.IStatusMessenger; import at.gv.egiz.eaaf.core.api.data.EaafConstants; import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; import at.gv.egiz.eaaf.core.api.idp.IConfigurationWithSP; import at.gv.egiz.eaaf.core.api.idp.auth.services.IProtocolAuthenticationService; import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; import at.gv.egiz.eaaf.core.exceptions.EaafException; import at.gv.egiz.eaaf.core.exceptions.PendingReqIdValidationException; import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; import at.gv.egiz.eaaf.core.impl.data.Pair; import at.gv.egiz.eaaf.core.impl.utils.Random; /** * Basic application controller that implements core error-handling. * * @author tlenz * */ public abstract class AbstractController { private static final Logger log = LoggerFactory.getLogger(AbstractController.class); @Autowired(required = true) protected IProtocolAuthenticationService protAuthService; @Autowired(required = true) protected ApplicationContext applicationContext; @Autowired(required = true) protected IConfigurationWithSP authConfig; @Autowired(required = true) protected ITransactionStorage transactionStorage; @Autowired(required = true) protected IStatusMessenger statusMessager; @Autowired protected IRevisionLogger revisionsLogger; /** * EAAF framework exception handler. * *

* This handler start a protocol-specific error handling. *

* * @param req http request * @param resp http response * @param e exception * @throws IOException in case of an exception handling error */ @ExceptionHandler({ EaafException.class }) public void eaafExceptionHandler(final HttpServletRequest req, final HttpServletResponse resp, final Exception e) throws IOException { try { protAuthService.handleErrorNoRedirect(e, req, resp, true); } catch (final EaafException e1) { log.warn("Can NOT handle an 'EAAFException'. Forwarding to generic error ... ", e); ioExceptionHandler(resp, e); } } /** * Generic exception handler. * *

* This handler wrote an internal server error into http response *

* * @param resp http response * @param exception exception * @throws IOException In case of an internal error. */ @ExceptionHandler({ Exception.class }) public void genericExceptionHandler(final HttpServletResponse resp, final Exception exception) throws IOException { log.error("Internel Server Error.", exception); resp.setContentType(EaafConstants.CONTENTTYPE_HTML_UTF8); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + "(Errorcode=9199" + " | Description=" + StringEscapeUtils.escapeHtml4(StringEscapeUtils.escapeEcmaScript(exception.getMessage())) + ")"); } /** * Generic exception handler. * *

* This handler wrote an internal server error into http response *

* * @param resp http response * @param exception exception */ @ExceptionHandler({ IOException.class }) public void ioExceptionHandler(final HttpServletResponse resp, final Throwable exception) { log.error("Internel Server Error.", exception); resp.setContentType(EaafConstants.CONTENTTYPE_HTML_UTF8); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } protected void handleError(final String errorMessage, final Throwable exceptionThrown, final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) throws IOException, EaafException { final Pair errorToHandle = exractExceptionThatShouldBeLogged(pendingReq, exceptionThrown); try { final String errorKey = storeErrorAndGetErrorToken(errorToHandle); protAuthService.forwardToErrorHandler(errorToHandle, errorKey, req, resp); return; } catch (final Exception e) { log.warn("Default error-handling FAILED. Exception can not be stored ....", e); log.info("Switch to generic generic backup error-handling ... "); protAuthService.handleErrorNoRedirect(errorToHandle.getSecond(), req, resp, true); } } protected String storeErrorAndGetErrorToken(Pair errorToHandle) throws EaafException { // log error directly in debug mode if (log.isDebugEnabled()) { log.warn(errorToHandle.getSecond().getMessage(), errorToHandle.getSecond()); } // put exception into transaction store for redirect final String errorKey = Random.nextLongRandom(); if (errorToHandle.getFirst() != null) { revisionsLogger.logEvent(errorToHandle.getFirst(), EventConstants.TRANSACTION_ERROR); transactionStorage.put(errorKey, new ExceptionContainer(errorToHandle.getFirst(), errorToHandle .getSecond()), -1); } else { transactionStorage.put(errorKey, new ExceptionContainer(null, errorToHandle.getSecond()), -1); } return errorKey; } @Nonnull protected Pair exractExceptionThatShouldBeLogged( @Nullable IRequest pendingReq, @Nonnull Throwable exceptionThrown) { Throwable loggedException = null; final Throwable extractedException = extractOriginalExceptionFromProcessException(exceptionThrown); // extract pendingRequestID and originalException if it was a // TaskExecutionException if (extractedException instanceof TaskExecutionException) { // set original exception loggedException = ((TaskExecutionException) extractedException).getOriginalException(); } else if (exceptionThrown instanceof PendingReqIdValidationException) { log.trace( "Find pendingRequestId validation exception. Looking for invalid pending-request ... "); if (((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq() != null) { pendingReq = ((PendingReqIdValidationException) exceptionThrown).getInvalidPendingReq(); } } // use TaskExecutionException directly, if no Original Exeception is included if (loggedException == null) { loggedException = exceptionThrown; } return Pair.newInstance(pendingReq, loggedException); } /** * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. * * @param exception error * @return Return the latest TaskExecutionExecption if exists, otherwise the * latest ProcessExecutionException */ private Throwable extractOriginalExceptionFromProcessException(final Throwable exception) { Throwable exholder = exception; TaskExecutionException taskExc = null; while (exholder != null && exholder instanceof ProcessExecutionException) { final ProcessExecutionException procExc = (ProcessExecutionException) exholder; if (procExc.getCause() != null && procExc.getCause() instanceof TaskExecutionException) { taskExc = (TaskExecutionException) procExc.getCause(); exholder = taskExc.getOriginalException(); } else { break; } } if (taskExc == null) { return exholder; } else { return taskExc; } } }