View Javadoc

1   /***
2    *  The contents of this file are subject to the Mozilla Public
3    *  License Version 1.1 (the "License"); you may not use this file
4    *  except in compliance with the License. You may obtain a copy of
5    *  the License at http://www.mozilla.org/MPL/
6    *
7    *  Software distributed under the License is distributed on an "AS
8    *  IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9    *  implied. See the License for the specific language governing
10   *  rights and limitations under the License.
11   *
12   *  The Original Code is pow2toolkit library.
13   *
14   *  The Initial Owner of the Original Code is
15   *  Power Of Two S.R.L. (www.pow2.com)
16   *
17   *  Portions created by Power Of Two S.R.L. are
18   *  Copyright (C) Power Of Two S.R.L.
19   *  All Rights Reserved.
20   *
21   * Contributor(s):
22   */
23  
24  package com.pow2.util;
25  
26  
27  import java.io.DataInputStream;
28  import java.io.IOException;
29  import java.net.URL;
30  import java.util.Enumeration;
31  import java.util.Hashtable;
32  
33  import javax.servlet.ServletException;
34  import javax.servlet.http.HttpServletRequest;
35  import javax.servlet.http.HttpUtils;
36  
37  import org.apache.log4j.Category;
38  
39  
40  /***
41   *  Servlet Utility class
42   *
43   * @author  Luca Fossato
44   * @created  10 June 2002
45   */
46  public class ServletUtil
47  {
48    /*** Log4j category. */
49    private static Category cat = Category.getInstance(ServletUtil.class);
50  
51  
52    /***
53     *  Build a query string using the (parameter, value) couples
54     *  retrieved from the input <code>request</code> object.
55     *
56     * @param  request the HttpServletRequest object
57     * @param  args the String array containing the name of the request
58     *              parameters to retrieve
59     * @return  the HTTP query string
60     */
61    public static String buildQueryString(HttpServletRequest request, String[] args)
62    {
63      StringBuffer q   = new StringBuffer();
64      String       arg = null;
65      String       val = null;
66      int          len = args.length;
67  
68      //if (len > 0)
69      //  q.append('?');
70  
71      for (int i = 0; i < len; i++)
72      {
73        arg = args[i];
74        val = request.getParameter(arg);
75  
76        if (!Util.isNull(val, "null"))
77          q.append(arg).append('=').append(val).append('&');
78      }
79  
80      // remove the last '&' character;
81      if (q.length() > 0)
82        q.deleteCharAt(q.length() - 1);
83  
84      //cat.debug("::buildQueryString - returned [" + q.toString() + "]");
85      return q.toString();
86    }
87  
88  
89    /***
90     *  Dumps all the incoming HttpServletRequest informations.
91     *
92     * @param  req the input HttpServletRequest object to dump
93     * @return  a string with dumped information
94     */
95    public static String dumpRequest(HttpServletRequest req)
96    {
97      String s = null;
98  
99      try
100     {
101       s = dump(req);
102     }
103     catch (Exception e)
104     {
105       cat.error("::dumpRequest - exception: ", e);
106     }
107 
108     return s;
109   }
110 
111 
112   /***
113    *  Get the String representation of the HTTP URL for the input servlet.
114    *
115    * @param  req the HttpServletRequest object.
116    * @return  the String representation of the HTTP URL for the input servlet.
117    * @exception  Exception if the URL conversion fails.
118    */
119   public static String getBase(HttpServletRequest req) throws Exception
120   {
121     return (getURLString(req, req.getContextPath(), "http") + "/");
122   }
123 
124 
125   /***
126    *  Get the content of the file retrieved from the input path.
127    *
128    * @param  req the HttpServletRequest object
129    * @param  path the path of the resource file to read
130    * @return  The content value
131    * @exception  Exception if any error occurs
132    */
133   public static String getContent(HttpServletRequest req, String path) throws Exception
134   {
135     return ((path = req.getRealPath(path)) != null) ? FileUtil.read(path).toString() : null;
136   }
137 
138 
139   /***
140    *  Get the input request parameter or attribute string value.
141    *  <br>
142    *  First try to retrieve the request parameter; if it does not exists or
143    *  have a "null" value, retrieve the relative request attribute (if any).
144    *  <br>
145    *  Note: for HTTP servlets, parameters are contained in the query string
146    *  or posted form data, while attributes are request embedded informations.
147    *
148    * @param  req the HttpServletRequest object
149    * @param  attribute the attribute to retrieve from the request object
150    * @return  the input request parameter / attribute string value, or null
151    *         if the input attribute doesn't match any request parameter / attribute
152    */
153   public static String getRequestAttribute(HttpServletRequest req, String attribute)
154   {
155     String val = req.getParameter(attribute);
156 
157     if (Util.isNull(val, "null"))
158       val = (String) req.getAttribute(attribute);
159 
160     return val;
161   }
162 
163 
164   /***
165    *   PRIVATE METHODS here...
166    */
167 
168 
169   /***
170    *  Get the the input path URL.
171    *
172    * @param  req the HttpServletRequest object
173    * @param  path the input path
174    * @return  the input path URL, or null
175    * @exception  Exception if the URL conversion fails
176    */
177   private static URL getURL(HttpServletRequest req, String path)
178        throws Exception
179   {
180     return new URL("http", req.getServerName(), req.getServerPort(), path);
181   }
182 
183 
184   /***
185    *  Get the String representation of the input path URL.
186    *  <br>
187    *  Representation type can be: "file" or "http".
188    *
189    * @param  req the HttpServletRequest object
190    * @param  path the input path
191    * @param  mode "file" for file representation,
192    *              "http" for http representation
193    * @return  the string representation of the input path URL, or null
194    * @exception  Exception if the URL conversion fails
195    */
196   private static String getURLString(HttpServletRequest req, String path, String mode)
197        throws Exception
198   {
199     String s = null;
200     URL url = null;
201 
202     if ((url = getURL(req, path)) != null)
203     {
204       if (mode.compareTo("file") == 0)
205         s = url.getFile();
206       //  ????
207       else if (mode.compareTo("http") == 0)
208         s = url.toString();
209     }
210 
211     return (s);
212   }
213 
214 
215   /***
216    *  Dump the incoming HttpServletRequest object
217    *
218    * @param  req the HttpServletRequest object to dump
219    * @return  Description of the Return Value
220    * @exception  ServletException if any error occurs
221    * @exception  IOException      if any error occurs
222    */
223   private static String dump(HttpServletRequest req)
224   {
225     String queryString = null;
226 
227     // if post occurs, this area will move the query from standard in to the querystring String
228     //  before calling the info Dump routine.
229     try
230     {
231       DataInputStream in = new DataInputStream(req.getInputStream());
232       String          s;
233 
234       queryString = "";
235 
236       while ((s = in.readLine()) != null)
237         queryString += s;
238 
239     }
240     catch (Exception e)
241     {
242       cat.info("::dump - cannot get the request dataInputStream object. Continue to dump the request.");
243     }
244 
245     // this routine simple dumps out HTTP variables and headers.
246     StringBuffer sb = new StringBuffer();
247     String s = null;
248 
249     sb.append("HTTP Snooper Servlet\n\n");
250     sb.append("Request URL:\n");
251     sb.append(" http://" + req.getServerName() + req.getServerPort() + req.getRequestURI() + "\n");
252 
253     sb.append("Request Info:\n");
254     sb.append(" Request Method: " + req.getMethod()).append("\n");
255     sb.append(" Request URI: " + req.getRequestURI()).append("\n");
256     sb.append(" Request Protocol: " + req.getProtocol()).append("\n");
257     sb.append(" Servlet Path: " + req.getServletPath()).append("\n");
258     sb.append(" Path Info: " + req.getPathInfo()).append("\n");
259     sb.append(" Path Translated: " + req.getPathTranslated()).append("\n");
260     sb.append(" Content Length: " + req.getContentLength()).append("\n");
261     sb.append(" Content Type: " + req.getContentType()).append("\n");
262 
263     if (queryString == null)
264       queryString = req.getQueryString();
265 
266     sb.append(" QueryString: " + queryString).append("\n");
267 
268     // convert queryString into an hashTable
269     // and dumps the table values;
270     if (!Util.isNull(queryString))
271     {
272       Hashtable ht = HttpUtils.parseQueryString(queryString);
273       sb.append("\n QueryString parameters:\n");
274  
275       Enumeration e = ht.keys();
276       while (e.hasMoreElements())
277       {
278         String       key    = (String)e.nextElement();
279         String[]     values = (String[])ht.get(key);
280         StringBuffer vSB    = new StringBuffer();
281         
282         for (int i=0; i < values.length; i++)
283         {
284           vSB.append(values[i]);
285           if (i < values.length)
286           {
287             vSB.append("; ");
288           }
289         }
290         
291         sb.append("   ")
292           .append(key)
293           .append(" = ")
294           .append(vSB.toString())
295           .append("\n");
296       }
297       
298       sb.append("\n\n");
299     }
300 
301     sb.append(" Server Name: " + req.getServerName()).append("\n");
302     sb.append(" Server Port: " + req.getServerPort()).append("\n");
303     sb.append(" Remote User: " + req.getRemoteUser()).append("\n");
304     sb.append(" Remote Host: " + req.getRemoteHost()).append("\n");
305     sb.append(" Remote Address: " + req.getRemoteAddr()).append("\n");
306     sb.append(" Authentication Scheme: " + req.getAuthType()).append("\n\n");
307 
308     // return parameters (name/value pairs)
309     Enumeration Params = req.getParameterNames();
310 
311     if (Params.hasMoreElements())
312     {
313       sb.append("Parameters:").append("\n");
314 
315       while (Params.hasMoreElements())
316       {
317         String name = (String) Params.nextElement();
318         sb.append(name + ": ");
319 
320         String[] values = req.getParameterValues(name);
321 
322         for (int x = 0; x < values.length; x++)
323         {
324           if (x > 0)
325             sb.append(", ");
326           sb.append(values[x]);
327         }
328         sb.append("\n");
329       }
330       sb.append("\n");
331     }
332 
333     // return HTTP Headers
334     Enumeration e = req.getHeaderNames();
335 
336     if (e.hasMoreElements())
337     {
338       sb.append("Request Headers:\n");
339 
340       while (e.hasMoreElements())
341       {
342         String name = (String) e.nextElement();
343         sb.append("  " + name + ": " + req.getHeader(name)).append("\n");
344       }
345       sb.append("\n");
346     }
347 
348     sb.append("\n");
349     s = sb.toString();
350 
351     return s;
352   }
353 }