View Javadoc

1   /*
2   * Licensed to the Apache Software Foundation (ASF) under one or more
3   * contributor license agreements.  See the NOTICE file distributed with
4   * this work for additional information regarding copyright ownership.
5   * The ASF licenses this file to You under the Apache License, Version 2.0
6   * (the "License"); you may not use this file except in compliance with
7   * the License.  You may obtain a copy of the License at
8   *
9   *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17  
18  
19  package filters;
20  
21  
22  import java.io.IOException;
23  import java.io.PrintWriter;
24  import java.io.StringWriter;
25  import java.sql.Timestamp;
26  import java.util.Enumeration;
27  import java.util.Locale;
28  
29  import javax.servlet.Filter;
30  import javax.servlet.FilterChain;
31  import javax.servlet.FilterConfig;
32  import javax.servlet.ServletException;
33  import javax.servlet.ServletRequest;
34  import javax.servlet.ServletResponse;
35  import javax.servlet.http.Cookie;
36  import javax.servlet.http.HttpServletRequest;
37  
38  
39  /**
40   * Example filter that dumps interesting state information about a request
41   * to the associated servlet context log file, before allowing the servlet
42   * to process the request in the usual way.  This can be installed as needed
43   * to assist in debugging problems.
44   *
45   * @author Craig McClanahan
46   * @version $Revision: 664175 $ $Date: 2008-06-06 18:43:44 -0400 (Fri, 06 Jun 2008) $
47   */
48  
49  public final class RequestDumperFilter implements Filter {
50  
51      // ----------------------------------------------------- Instance Variables
52  
53  
54      /**
55       * The filter configuration object we are associated with.  If this value
56       * is null, this filter instance is not currently configured.
57       */
58      private FilterConfig filterConfig = null;
59  
60      // --------------------------------------------------------- Public Methods
61  
62  
63      /**
64       * Take this filter out of service.
65       */
66      public void destroy() {
67  
68          this.filterConfig = null;
69  
70      }
71  
72  
73      /**
74       * Time the processing that is performed by all subsequent filters in the
75       * current filter stack, including the ultimately invoked servlet.
76       *
77       * @param request The servlet request we are processing
78       * @param result  The servlet response we are creating
79       * @param chain   The filter chain we are processing
80       * @throws IOException      if an input/output error occurs
81       * @throws ServletException if a servlet error occurs
82       */
83      public void doFilter(ServletRequest request, ServletResponse response,
84                           FilterChain chain)
85              throws IOException, ServletException {
86  
87          if (filterConfig == null)
88              return;
89  
90          // Render the generic servlet request properties
91          StringWriter sw = new StringWriter();
92          PrintWriter writer = new PrintWriter(sw);
93          writer.println("Request Received at " +
94                  (new Timestamp(System.currentTimeMillis())));
95          writer.println(" characterEncoding=" + request.getCharacterEncoding());
96          writer.println("     contentLength=" + request.getContentLength());
97          writer.println("       contentType=" + request.getContentType());
98          writer.println("            locale=" + request.getLocale());
99          writer.print("           locales=");
100         Enumeration locales = request.getLocales();
101         boolean first = true;
102         while (locales.hasMoreElements()) {
103             Locale locale = (Locale) locales.nextElement();
104             if (first)
105                 first = false;
106             else
107                 writer.print(", ");
108             writer.print(locale.toString());
109         }
110         writer.println();
111         Enumeration names = request.getParameterNames();
112         while (names.hasMoreElements()) {
113             String name = (String) names.nextElement();
114             writer.print("         parameter=" + name + "=");
115             String values[] = request.getParameterValues(name);
116             for (int i = 0; i < values.length; i++) {
117                 if (i > 0)
118                     writer.print(", ");
119                 writer.print(values[i]);
120             }
121             writer.println();
122         }
123         writer.println("          protocol=" + request.getProtocol());
124         writer.println("        remoteAddr=" + request.getRemoteAddr());
125         writer.println("        remoteHost=" + request.getRemoteHost());
126         writer.println("            scheme=" + request.getScheme());
127         writer.println("        serverName=" + request.getServerName());
128         writer.println("        serverPort=" + request.getServerPort());
129         writer.println("          isSecure=" + request.isSecure());
130 
131         // Render the HTTP servlet request properties
132         if (request instanceof HttpServletRequest) {
133             writer.println("---------------------------------------------");
134             HttpServletRequest hrequest = (HttpServletRequest) request;
135             writer.println("       contextPath=" + hrequest.getContextPath());
136             Cookie cookies[] = hrequest.getCookies();
137             if (cookies == null)
138                 cookies = new Cookie[0];
139             for (int i = 0; i < cookies.length; i++) {
140                 writer.println("            cookie=" + cookies[i].getName() +
141                         "=" + cookies[i].getValue());
142             }
143             names = hrequest.getHeaderNames();
144             while (names.hasMoreElements()) {
145                 String name = (String) names.nextElement();
146                 String value = hrequest.getHeader(name);
147                 writer.println("            header=" + name + "=" + value);
148             }
149             writer.println("            method=" + hrequest.getMethod());
150             writer.println("          pathInfo=" + hrequest.getPathInfo());
151             writer.println("       queryString=" + hrequest.getQueryString());
152             writer.println("        remoteUser=" + hrequest.getRemoteUser());
153             writer.println("requestedSessionId=" +
154                     hrequest.getRequestedSessionId());
155             writer.println("        requestURI=" + hrequest.getRequestURI());
156             writer.println("       servletPath=" + hrequest.getServletPath());
157         }
158         writer.println("=============================================");
159 
160         // Log the resulting string
161         writer.flush();
162         filterConfig.getServletContext().log(sw.getBuffer().toString());
163 
164         // Pass control on to the next filter
165         chain.doFilter(request, response);
166 
167     }
168 
169 
170     /**
171      * Place this filter into service.
172      *
173      * @param filterConfig The filter configuration object
174      */
175     public void init(FilterConfig filterConfig) throws ServletException {
176 
177         this.filterConfig = filterConfig;
178 
179     }
180 
181 
182     /**
183      * Return a String representation of this object.
184      */
185     public String toString() {
186 
187         if (filterConfig == null)
188             return ("RequestDumperFilter()");
189         StringBuffer sb = new StringBuffer("RequestDumperFilter(");
190         sb.append(filterConfig);
191         sb.append(")");
192         return (sb.toString());
193 
194     }
195 
196 
197 }
198