/******************************************************************************* * 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.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.IConfiguration; 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.utils.Random; import at.gv.egiz.eaaf.core.impl.utils.ServletUtils; /** * @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 IConfiguration authConfig; @Autowired(required=true) protected ITransactionStorage transactionStorage; @Autowired(required=true) protected IStatusMessenger statusMessager; @Autowired protected IRevisionLogger revisionsLogger; @ExceptionHandler({EAAFException.class}) public void MOAIDExceptionHandler(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); } } @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())) + ")"); return; } @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); return; } protected void handleError(final String errorMessage, final Throwable exceptionThrown, final HttpServletRequest req, final HttpServletResponse resp, IRequest pendingReq) throws IOException, EAAFException { 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; try { //switch to protocol-finalize method to generate a protocol-specific error message //log error directly in debug mode if (log.isDebugEnabled()) log.warn(loggedException.getMessage(), loggedException); //put exception into transaction store for redirect final String key = Random.nextLongRandom(); if (pendingReq != null) { revisionsLogger.logEvent(pendingReq, EventConstants.TRANSACTION_ERROR); transactionStorage.put(key, new ExceptionContainer(pendingReq, loggedException), -1); } else { transactionStorage.put(key, new ExceptionContainer(null, loggedException), -1); } //build up redirect URL String redirectURL = null; redirectURL = ServletUtils.getBaseUrl(req); redirectURL += "/"+ProtocolFinalizationController.ENDPOINT_ERRORHANDLING + "?" + EAAFConstants.PARAM_HTTP_ERROR_CODE + "=" + key; resp.setContentType("text/html"); resp.setStatus(302); resp.addHeader("Location", redirectURL); log.debug("REDIRECT TO: " + redirectURL); 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(loggedException, req, resp, true); } } /** * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. * * @param exception * @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; } }