Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.catalina.filters;
 
 import java.util.Date;
 

Implementation of a Filter that logs interesting contents from the specified Request (before processing) and the corresponding Response (after processing). It is especially useful in debugging problems related to headers and cookies.

When using this Filter, it is strongly recommended that the org.apache.catalina.filter.RequestDumperFilter logger is directed to a dedicated file and that the org.apache.juli.VerbatimFormmater is used.

Author(s):
Craig R. McClanahan
 
 
 public class RequestDumperFilter implements Filter {
 
     private static final String NON_HTTP_REQ_MSG =
         "Not available. Non-http request.";
     private static final String NON_HTTP_RES_MSG =
         "Not available. Non-http response.";
     
     private ServletContext context;
 
     private static final ThreadLocal<Timestamptimestamp =
             new ThreadLocal<Timestamp>() {
         @Override
         protected Timestamp initialValue() {
             return new Timestamp();
         }
     };

    
Log the interesting request parameters, invoke the next Filter in the sequence, and log the interesting response parameters.

Parameters:
request The servlet request to be processed
response The servlet response to be created
chain The filter chain being processed
Throws:
java.io.IOException if an input/output error occurs
javax.servlet.ServletException if a servlet error occurs
 
     public void doFilter(ServletRequest requestServletResponse response,
             FilterChain chain)
         throws IOExceptionServletException {
 
         HttpServletRequest hRequest = null;
         HttpServletResponse hResponse = null;
         
         if (request instanceof HttpServletRequest) {
             hRequest = (HttpServletRequestrequest;
         }
         if (response instanceof HttpServletResponse) {
             hResponse = (HttpServletResponseresponse;
         }
 
         // Log pre-service information
         doLog("START TIME        "getTimestamp());
         
         if (hRequest == null) {
             doLog("        requestURI");
             doLog("          authType");
         } else {
            doLog("        requestURI"hRequest.getRequestURI());
            doLog("          authType"hRequest.getAuthType());
        }
        
        doLog(" characterEncoding"request.getCharacterEncoding());
        doLog("     contentLength",
                Integer.valueOf(request.getContentLength()).toString());
        doLog("       contentType"request.getContentType());
        
        if (hRequest == null) {
            doLog("       contextPath");
            doLog("            cookie");
            doLog("            header");
        } else {
            doLog("       contextPath"hRequest.getContextPath());
            Cookie cookies[] = hRequest.getCookies();
            if (cookies != null) {
                for (int i = 0; i < cookies.lengthi++)
                    doLog("            cookie"cookies[i].getName() +
                            "=" + cookies[i].getValue());
            }
            Enumeration<Stringhnames = hRequest.getHeaderNames();
            while (hnames.hasMoreElements()) {
                String hname = hnames.nextElement();
                Enumeration<Stringhvalues = hRequest.getHeaders(hname);
                while (hvalues.hasMoreElements()) {
                    String hvalue = hvalues.nextElement();
                    doLog("            header"hname + "=" + hvalue);
                }
            }
        }
        
        doLog("            locale"request.getLocale().toString());
        
        if (hRequest == null) {
            doLog("            method");
        } else {
            doLog("            method"hRequest.getMethod());
        }
        
        Enumeration<Stringpnames = request.getParameterNames();
        while (pnames.hasMoreElements()) {
            String pname = pnames.nextElement();
            String pvalues[] = request.getParameterValues(pname);
            StringBuilder result = new StringBuilder(pname);
            result.append('=');
            for (int i = 0; i < pvalues.lengthi++) {
                if (i > 0)
                    result.append(", ");
                result.append(pvalues[i]);
            }
            doLog("         parameter"result.toString());
        }
        
        if (hRequest == null) {
            doLog("          pathInfo");
        } else {
            doLog("          pathInfo"hRequest.getPathInfo());
        }
        
        doLog("          protocol"request.getProtocol());
        
        if (hRequest == null) {
            doLog("       queryString");
        } else {
            doLog("       queryString"hRequest.getQueryString());
        }
        
        doLog("        remoteAddr"request.getRemoteAddr());
        doLog("        remoteHost"request.getRemoteHost());
        
        if (hRequest == null) {
            doLog("        remoteUser");
            doLog("requestedSessionId");
        } else {
            doLog("        remoteUser"hRequest.getRemoteUser());
            doLog("requestedSessionId"hRequest.getRequestedSessionId());
        }
        
        doLog("            scheme"request.getScheme());
        doLog("        serverName"request.getServerName());
        doLog("        serverPort",
                Integer.valueOf(request.getServerPort()).toString());
        
        if (hRequest == null) {
            doLog("       servletPath");
        } else {
            doLog("       servletPath"hRequest.getServletPath());
        }
        
        doLog("          isSecure",
                Boolean.valueOf(request.isSecure()).toString());
        doLog("------------------",
                "--------------------------------------------");
        // Perform the request
        chain.doFilter(requestresponse);
        // Log post-service information
        doLog("------------------",
                "--------------------------------------------");
        if (hRequest == null) {
            doLog("          authType");
        } else {
            doLog("          authType"hRequest.getAuthType());
        }
        
        doLog("       contentType"response.getContentType());
        
        if (hResponse == null) {
            doLog("            header");
        } else {
            Iterable<Stringrhnames = hResponse.getHeaderNames();
            for (String rhname : rhnames) {
                Iterable<Stringrhvalues = hResponse.getHeaders(rhname);
                for (String rhvalue : rhvalues)
                    doLog("            header"rhname + "=" + rhvalue);
            }
        }
        if (hRequest == null) {
            doLog("        remoteUser");
        } else {
            doLog("        remoteUser"hRequest.getRemoteUser());
        }
        
        if (hResponse == null) {
            doLog("        remoteUser");
        } else {
            doLog("            status",
                    Integer.valueOf(hResponse.getStatus()).toString());
        }
        doLog("END TIME          "getTimestamp());
        doLog("==================",
                "============================================");
	}
    private void doLog(String attributeString value) {
        StringBuilder sb = new StringBuilder(80);
        sb.append(Thread.currentThread().getName());
        sb.append(' ');
        sb.append(attribute);
        sb.append('=');
        sb.append(value);
        if ( != null) {
            .log(sb.toString());
        }
    }
    private String getTimestamp() {
        Timestamp ts = .get();
        long currentTime = System.currentTimeMillis();
        
        if ((ts.date.getTime() + 999) < currentTime) {
            ts.date.setTime(currentTime - (currentTime % 1000));
            ts.update();
        }
        return ts.dateString;
    }
    @Override
    public void init(FilterConfig filterConfigthrows ServletException {
         = filterConfig.getServletContext();
    }
    @Override
    public void destroy() {
         = null;
    }
    private static final class Timestamp {
        private Date date = new Date(0);
        private SimpleDateFormat format =
            new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        private String dateString = .format();
        private void update() {
             = .format();
        }
    }
New to GrepCode? Check out our FAQ X