001/* 002 * (C) Copyright 2006-2016 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 */ 019package org.nuxeo.ecm.platform.web.common.exceptionhandling; 020 021import java.io.IOException; 022 023import javax.servlet.Filter; 024import javax.servlet.FilterChain; 025import javax.servlet.FilterConfig; 026import javax.servlet.ServletException; 027import javax.servlet.ServletRequest; 028import javax.servlet.ServletResponse; 029import javax.servlet.http.HttpServletRequest; 030import javax.servlet.http.HttpServletResponse; 031 032import org.apache.commons.logging.Log; 033import org.apache.commons.logging.LogFactory; 034import org.nuxeo.ecm.platform.web.common.exceptionhandling.service.ExceptionHandlingService; 035import org.nuxeo.runtime.api.Framework; 036 037public class NuxeoExceptionFilter implements Filter { 038 039 private NuxeoExceptionHandler exceptionHandler; 040 041 private static final Log log = LogFactory.getLog(NuxeoExceptionFilter.class); 042 043 public void init(FilterConfig filterConfig) throws ServletException { 044 try { 045 getHandler(); 046 } catch (ServletException e) { 047 log.info("NuxeoExceptionHandler will be lazy loaded"); 048 } 049 } 050 051 protected NuxeoExceptionHandler getHandler() throws ServletException { 052 if (exceptionHandler == null) { 053 ExceptionHandlingService service = Framework.getService(ExceptionHandlingService.class); 054 exceptionHandler = service.getExceptionHandler(); 055 } 056 return exceptionHandler; 057 } 058 059 private void handleException(HttpServletRequest request, HttpServletResponse response, Exception e) 060 throws IOException, ServletException { 061 getHandler().handleException(request, response, e); 062 } 063 064 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 065 throws IOException, ServletException { 066 try { 067 chain.doFilter(request, response); 068 } catch (RuntimeException | IOException | ServletException e) { 069 try { 070 handleException((HttpServletRequest) request, (HttpServletResponse) response, e); 071 } catch (ServletException ee) { 072 throw ee; 073 } catch (RuntimeException | IOException ee) { 074 throw new ServletException(ee); 075 } 076 } 077 } 078 079 public void destroy() { 080 } 081 082}