001/* 002 * (C) Copyright 2011 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 * matic 018 */ 019package org.nuxeo.ecm.core.management.jtajca.internal; 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.HttpSession; 031 032import org.apache.commons.beanutils.PropertyUtils; 033import org.apache.commons.logging.Log; 034import org.apache.commons.logging.LogFactory; 035import org.apache.log4j.MDC; 036 037/** 038 * @author matic 039 */ 040public class Log4jWebFilter implements Filter { 041 042 private static final Log log = LogFactory.getLog(Log4jWebFilter.class); 043 044 protected FilterConfig config; 045 046 @Override 047 public void init(FilterConfig filterConfig) throws ServletException { 048 config = filterConfig; 049 } 050 051 @Override 052 public void destroy() { 053 054 } 055 056 @Override 057 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, 058 ServletException { 059 try { 060 putProperty(request, "RemoteAddr"); 061 putProperty(request, "PathInfo"); 062 putProperty(request, "RequestURL"); 063 putProperty(request, "ServletPath"); 064 putProperty(request, "UserPrincipal"); 065 final HttpSession session = ((HttpServletRequest) request).getSession(false); 066 if (session != null) { 067 MDC.put("SessionID", session.getId()); 068 } 069 chain.doFilter(request, response); 070 } finally { 071 MDC.remove("RemoteAddr"); 072 MDC.remove("PathInfo"); 073 MDC.remove("RequestURL"); 074 MDC.remove("ServletPath"); 075 MDC.remove("UserPrincipal"); 076 MDC.remove("SessionID"); 077 } 078 079 } 080 081 protected void putProperty(Object object, String propertyName) { 082 try { 083 if (object != null) { 084 String name = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); 085 Object prop = PropertyUtils.getProperty(object, name); 086 if (prop != null) { 087 MDC.put(propertyName, prop); 088 } 089 } 090 } catch (ReflectiveOperationException e) { 091 log.error(e, e); 092 } 093 } 094 095}