001/* 002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * matic 016 */ 017package org.nuxeo.ecm.core.management.jtajca.internal; 018 019import java.io.IOException; 020 021import javax.servlet.Filter; 022import javax.servlet.FilterChain; 023import javax.servlet.FilterConfig; 024import javax.servlet.ServletException; 025import javax.servlet.ServletRequest; 026import javax.servlet.ServletResponse; 027import javax.servlet.http.HttpServletRequest; 028import javax.servlet.http.HttpSession; 029 030import org.apache.commons.beanutils.PropertyUtils; 031import org.apache.commons.logging.Log; 032import org.apache.commons.logging.LogFactory; 033import org.apache.log4j.MDC; 034 035/** 036 * @author matic 037 */ 038public class Log4jWebFilter implements Filter { 039 040 private static final Log log = LogFactory.getLog(Log4jWebFilter.class); 041 042 protected FilterConfig config; 043 044 @Override 045 public void init(FilterConfig filterConfig) throws ServletException { 046 config = filterConfig; 047 } 048 049 @Override 050 public void destroy() { 051 052 } 053 054 @Override 055 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, 056 ServletException { 057 try { 058 putProperty(request, "RemoteAddr"); 059 putProperty(request, "PathInfo"); 060 putProperty(request, "RequestURL"); 061 putProperty(request, "ServletPath"); 062 putProperty(request, "UserPrincipal"); 063 final HttpSession session = ((HttpServletRequest) request).getSession(false); 064 if (session != null) { 065 MDC.put("SessionID", session.getId()); 066 } 067 chain.doFilter(request, response); 068 } finally { 069 MDC.remove("RemoteAddr"); 070 MDC.remove("PathInfo"); 071 MDC.remove("RequestURL"); 072 MDC.remove("ServletPath"); 073 MDC.remove("UserPrincipal"); 074 MDC.remove("SessionID"); 075 } 076 077 } 078 079 protected void putProperty(Object object, String propertyName) { 080 try { 081 if (object != null) { 082 String name = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); 083 Object prop = PropertyUtils.getProperty(object, name); 084 if (prop != null) { 085 MDC.put(propertyName, prop); 086 } 087 } 088 } catch (ReflectiveOperationException e) { 089 log.error(e, e); 090 } 091 } 092 093}