View Javadoc

1   /*
2   
3   This software is OSI Certified Open Source Software.
4   OSI Certified is a certification mark of the Open Source Initiative.
5   
6   The license (Mozilla version 1.0) can be read at the MMBase site.
7   See http://www.MMBase.org/license
8   
9   */
10  package net.sf.mmapps.commons.util;
11  
12  import java.io.*;
13  import java.net.*;
14  import java.text.SimpleDateFormat;
15  import java.util.Date;
16  import java.util.Enumeration;
17  
18  import javax.servlet.ServletException;
19  import javax.servlet.http.*;
20  
21  import org.mmbase.util.logging.Logger;
22  import org.mmbase.util.logging.Logging;
23  
24  
25  public class HttpUtil {
26  
27      private static final String IDENT = "   ";
28      private static final String ENDL = "\n";
29      private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
30      
31      /*** MMbase logging system */
32      private static Logger log = Logging.getLoggerInstance(HttpUtil.class.getName());
33      
34      private HttpUtil() {
35          //Utility
36      }
37  
38      /***
39       * The code first sets the Expires header to a date in the
40       * past. This indicates to the recipient that the page's content
41       * have already expired, as a hint that it's contents should not be
42       * cached. The no-cache value for the Pragma header is provided by
43       * version 1.0 of the HTTP protocol to further indicate that
44       * browsers and proxy servers should not cache a page. Version 1.1
45       * of HTTP replaces this header with a more specific Cache-Control
46       * header, but recommends including the Pragma header as well for
47       * backward compatibility.
48       * 
49       * @param response - http response
50       * @param expire - millisecond before content should expire 
51       */
52      public static void addNoCacheHeaders(HttpServletResponse response, int expire) {
53           if (expire <= 0) {
54               // Add some header to make sure these pages are not cached anywhere.
55               // Set standard HTTP/1.1 no-cache headers.
56               response.setHeader("Cache-Control","no-cache, no-store, must-revalidate, proxy-revalidate");
57               // Set IE extended HTTP/1.1 no-cache headers
58               response.addHeader("Cache-Control", "post-check=0, pre-check=0");
59               // Set standard HTTP/1.0 no-cache header.
60               response.setHeader("Pragma", "no-cache");
61               response.setDateHeader ("Expires", -1);
62               
63               // long now = System.currentTimeMillis();                        
64               // according to  rfc2616 sec14 'already expires' means that date-header is expires header
65               // sadly, this does not work:
66               // perhaps because tomcat overrides the date header later, so a difference of a second can occur
67               // response.setDateHeader("Date",     now);                         
68           }
69           else {
70               // calc the string in GMT not localtime and add the offset
71               response.setDateHeader ("Expires", System.currentTimeMillis() + expire);
72               response.setHeader("Cache-Control", "public");
73           }
74      }
75      
76      /*** get WebappUri.
77       * 
78       * @param request HttpServletRequest
79       * @return String
80       */
81      public static String getWebappUri(HttpServletRequest request) {
82         StringBuffer s = new StringBuffer();
83         s.append(request.getScheme()).append("://")
84         .append(request.getServerName()).append(':')
85         .append(Integer.toString(request.getServerPort()))
86         .append(request.getContextPath())
87         .append('/');
88         return s.toString();
89      }
90  
91      /*** get Secure WebappUri. 
92       * 
93       * @param request HttpServletRequest
94       * @return String
95       */
96      public static String getSecureWebappUri(HttpServletRequest request) {
97         StringBuffer s = new StringBuffer();
98         s.append("https://")
99         .append(request.getServerName())
100        .append(request.getContextPath())
101        .append('/');
102        return s.toString();
103     }
104 
105     /***  get Server Document Root
106      *
107      * @param request HttpServletRequest
108      * @return String
109      */
110     public static String getServerDocRoot(HttpServletRequest request) {
111        StringBuffer s = new StringBuffer();
112        s.append(request.getScheme()).append("://")
113        .append(request.getServerName()).append(':')
114        .append(Integer.toString(request.getServerPort()))
115        .append('/');
116        return s.toString();
117     }
118 
119     /*** get Secure Server Document Root
120      *
121      * @param request HttpServletRequest
122      * @return String
123      */
124     public static String getSecureServerDocRoot(HttpServletRequest request) {
125        StringBuffer s = new StringBuffer();
126        s.append("https://")
127        .append(request.getServerName())
128        .append('/');
129        return s.toString();
130     }
131     
132     /***
133      * Determines the relative path to the root (e.g. ../../..) for the given request. Does not end 
134      * with '/'!
135      * 
136      * @param request 
137      * @param uri the uri to use or request.getRequestURL() if null
138      * @return relative path
139      */
140     public static String determinePathToRoot(HttpServletRequest request, String uri) {
141        if (StringUtil.isEmpty(uri)) {
142           uri = request.getRequestURL().toString();
143        }
144        StringBuffer ret = new StringBuffer();
145        String appName = request.getContextPath();
146        String stepUrl = uri.substring(uri.indexOf(appName) + appName.length() + 1);
147        
148        int subdirs = stepUrl.split("/").length;
149        for (int i = 1; i < subdirs; i++) {
150            ret.append("../");
151        }
152        return StringUtil.isEmpty(ret.toString())?".":ret.toString();
153     }
154 
155     
156     /***
157      * get Remote Content
158      *  
159      * @param urlPath - path to resource
160      * @return content of resource
161      */
162     public String getURLContent(String urlPath) {
163        try {
164           return getURLContent(new URL(urlPath));
165        }
166        catch (MalformedURLException e) {
167           return "";
168        }
169     }
170 
171     /***
172      * get Remote Content
173      *  
174      * @param url - url to resource
175      * @return content of resource
176      */
177     public static String getURLContent(URL url) {
178        StringBuffer sb = new StringBuffer();
179 
180        // find the newline character(s) on the current system
181        String newline = null;
182        try {
183           newline = System.getProperty("line.separator");
184        }
185        catch (Exception e) {
186           newline = "\n";
187        }
188        BufferedReader in = null;
189        try {
190           InputStreamReader input =
191              new InputStreamReader(url.openStream());
192           in = new BufferedReader(input);
193           
194           String line;
195           while ((line = in.readLine()) != null) {
196              sb.append(line);
197              sb.append(newline);
198           }
199           return sb.toString();
200        }
201        catch (IOException e) {
202           log.error("Exception " + e.toString(), e);
203           return "";
204        }
205        finally {
206           try {
207              in.close();
208           } catch (IOException e) {
209               log.debug("Exception " + e.toString(), e);
210           }
211        }
212     }
213     
214     /***
215      * Post a string to an URL and get the reply as a string. 
216      * Returns an empty string if things didn't work out.
217      *
218      * @param url - url to resource
219      * @param body - content to post
220      * @return copntent of resource
221      */
222     public static String getURLContentPost(URL url, String body) {
223        BufferedReader rdr = null;
224        try {
225           // URL must use the http protocol!
226           HttpURLConnection conn = (HttpURLConnection) url.openConnection();
227           conn.setRequestMethod("POST");
228           conn.setAllowUserInteraction(false); // you may not ask the user
229           conn.setDoOutput(true); // we want to send things
230           conn.setDoInput(true); // we want to receive things
231           // the Content-type should be default, but we set it anyway
232           conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
233           // the content-length should not be necessary, but we're cautious
234           conn.setRequestProperty("Content-length", Integer.toString(body.length()));
235           // No caching
236           conn.setUseCaches(false);
237           
238           // Post data to url
239           OutputStreamWriter printout = null;
240           try {
241               printout = new OutputStreamWriter(conn.getOutputStream());
242               printout.write(body);
243               printout.flush();
244           }
245           catch (IOException e) {
246               log.debug("" + e.getMessage(), e);
247           }
248           finally {
249               if (printout != null) {
250                   printout.close();
251               }
252           }
253           
254           StringBuffer sb = new StringBuffer();
255 
256           // find the newline character(s) on the current system
257           String newline = null;
258           try {
259              newline = System.getProperty("line.separator");
260           }
261           catch (Exception e) {
262              newline = "\n";
263           }
264           
265           // get the input stream for reading the reply
266           // IMPORTANT! Your body will not get transmitted if you get the
267           // InputStream before completely writing out your output first!
268           InputStream rawInStream = conn.getInputStream();
269 
270           // get response
271           rdr = new BufferedReader(new InputStreamReader(rawInStream));
272           String line;
273           while ((line = rdr.readLine()) != null) {
274              sb.append(line);
275              sb.append(newline);
276           }
277           return sb.toString();
278        }
279        catch (Exception e) {
280           log.error("Exception " + e.toString(), e);
281           return "";
282        }
283        finally {
284           try {
285              rdr.close();
286           } catch (IOException e) {
287               log.debug("Exception " + e.toString(), e);
288           }
289        }
290     }
291 
292     public static String getErrorInfo(HttpServletRequest request, Throwable exception, long ticket, String version) {
293         // prepare error details
294         String msg = "";
295 
296         msg += "TIME: " + DATE_TIME_FORMAT.format(new Date(ticket)) + ENDL;
297         msg += "VERSION: " + version + ENDL;
298         msg += ENDL;
299         msg += getAllRequestInfo(request);
300 
301         if (exception != null) {
302             // add stack stacktrace
303             StringWriter wr = new StringWriter();
304             PrintWriter pw = new PrintWriter(wr);
305 
306             pw.println("EXCEPTION:");
307             exception.printStackTrace(new PrintWriter(wr));
308 
309             Throwable rootEx = exception;
310             while (true) {
311                 if (rootEx instanceof ServletException) {
312                     rootEx = ((ServletException) rootEx).getRootCause();
313                 }
314                 else {
315                     rootEx = rootEx.getCause();
316                 }
317                 if (rootEx != null) {
318                     pw.println("\nCause:");
319                     rootEx.printStackTrace(new PrintWriter(wr));
320                 }
321                 else {
322                     break;
323                 }
324             }
325             
326             msg += ENDL;
327             msg += wr.toString();
328         }
329         return msg;
330     }
331 
332     public static String getAllRequestInfo(HttpServletRequest request) {
333         String msg = getRequestInfo(request);
334         msg += getCookieInfo(request);
335         msg += getSessionInfo(request);
336         return msg;
337     }
338     
339     public static String getRequestInfo(HttpServletRequest request) {
340         String msg = "REQUEST:" + ENDL;
341 
342         // request properties
343         msg += IDENT + "requesturl: " + request.getRequestURL() + ENDL;
344         msg += IDENT + "querystring: " + request.getQueryString() + ENDL;
345         msg += IDENT + "method: " + request.getMethod() + ENDL;
346         msg += IDENT + "user: " + request.getRemoteUser()  + ENDL;
347 
348         // request headers
349         msg += IDENT + "headers: " + ENDL;
350         Enumeration en = request.getHeaderNames();
351         while (en.hasMoreElements()) {
352             String name = (String) en.nextElement();
353             msg += IDENT + IDENT + name + ": " + request.getHeader(name) + ENDL;
354         }
355 
356         // request parameters
357         msg += IDENT + "parameters: " + ENDL;
358         en = request.getParameterNames();
359         while (en.hasMoreElements()) {
360             String name = (String) en.nextElement();
361             msg += IDENT + IDENT + name+": " + request.getParameter(name) + ENDL;
362         }
363 
364         // request attributes
365         msg += IDENT + "attributes: " + ENDL;
366         en = request.getAttributeNames();
367         while (en.hasMoreElements()) {
368             String name = (String) en.nextElement();
369             if (!name.startsWith("javax.servlet")) {
370                 msg += IDENT + IDENT + name+": " + request.getAttribute(name) + ENDL;
371             }
372         }
373         return msg;
374     }
375     
376     public static String getCookieInfo(HttpServletRequest request) {
377         String msg = "";
378         // request cookies
379         Cookie[] cookies = request.getCookies();
380         if (cookies != null) {
381             msg += IDENT + "COOKIES: " + ENDL;
382             for (int i = 0; i < cookies.length; i++) {
383                 Cookie cookie = cookies[i];
384                 msg += IDENT + IDENT + "name: " + cookie.getName();
385                 msg += IDENT + "domain: " + cookie.getDomain();
386                 msg += IDENT + "path: " + cookie.getPath();
387                 msg += IDENT + "version: " + cookie.getVersion();
388                 msg += IDENT + "maxage: " + cookie.getMaxAge();
389                 msg += IDENT + "comment: " + cookie.getComment();
390                 msg += IDENT + "value: " + cookie.getValue() + ENDL;
391             }
392         }
393         return msg;
394     }
395 
396     public static String getSessionInfo(HttpServletRequest request) {
397         String msg = "";
398         HttpSession session = request.getSession(false);
399         if (session != null && !session.isNew()) {
400             msg += ENDL;
401             msg += "SESSION:" + ENDL;
402 
403             // session properties
404             msg += IDENT + "id: " + session.getId() + ENDL;
405             msg += IDENT + "CreationTime: " + DATE_TIME_FORMAT.format(new Date(  session.getCreationTime() )) + ENDL;
406             msg += IDENT + "LastAccessedTime: " + DATE_TIME_FORMAT.format(new Date( session.getLastAccessedTime() )) + ENDL;
407             msg += IDENT + "MaxInactiveInterval: " + session.getMaxInactiveInterval() + ENDL;
408 
409             // session attributes
410             msg += IDENT + "attributes: " + ENDL;
411             Enumeration en = session.getAttributeNames();
412             while (en.hasMoreElements()) {
413                 String name = (String) en.nextElement();
414                 msg += IDENT + IDENT + name+": " + session.getAttribute(name) + ENDL;
415             }
416         }
417         return msg;
418     }
419     
420 }