KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > ServletUtils


1 /* ====================================================================
2  * The LateralNZ Software License, Version 1.0
3  *
4  * Copyright (c) 2003 LateralNZ. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by
21  * LateralNZ (http://www.lateralnz.org/) and other third parties."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "LateralNZ" must not be used to endorse or promote
26  * products derived from this software without prior written
27  * permission. For written permission, please
28  * contact oss@lateralnz.org.
29  *
30  * 5. Products derived from this software may not be called "Panther",
31  * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
32  * "LATERALNZ" appear in their name, without prior written
33  * permission of LateralNZ.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of LateralNZ. For more
51  * information on Lateral, please see http://www.lateralnz.com/ or
52  * http://www.lateralnz.org
53  *
54  */

55 package org.lateralnz.common.util;
56
57 import java.io.BufferedReader JavaDoc;
58 import java.io.IOException JavaDoc;
59 import java.io.InputStream JavaDoc;
60 import java.io.InputStreamReader JavaDoc;
61 import java.io.UnsupportedEncodingException JavaDoc;
62 import java.io.OutputStream JavaDoc;
63 import java.net.URLDecoder JavaDoc;
64 import java.net.URL JavaDoc;
65 import java.net.HttpURLConnection JavaDoc;
66 import java.net.MalformedURLException JavaDoc;
67 import java.net.Socket JavaDoc;
68 import java.util.Enumeration JavaDoc;
69 import java.util.HashMap JavaDoc;
70 import java.util.Iterator JavaDoc;
71 import java.util.Locale JavaDoc;
72 import java.util.Map JavaDoc;
73 import java.util.Properties JavaDoc;
74 import java.util.regex.Matcher JavaDoc;
75 import java.util.regex.Pattern JavaDoc;
76
77 import javax.servlet.RequestDispatcher JavaDoc;
78 import javax.servlet.ServletConfig JavaDoc;
79 import javax.servlet.http.HttpServletRequest JavaDoc;
80 import javax.servlet.http.HttpServletResponse JavaDoc;
81 import javax.servlet.http.HttpSession JavaDoc;
82
83 import org.apache.log4j.Logger;
84
85 /**
86  * common utility functions used by servlets
87  *
88  * @author J R Briggs
89  */

90 public class ServletUtils implements Constants {
91   private static Logger log = Logger.getLogger(ServletUtils.class.getName());
92   
93   private static final String JavaDoc ACCEPT_LANGUAGE = "Accept-Language";
94   private static final String JavaDoc ERROR = "error";
95   private static final String JavaDoc FORWARD = "forward";
96   private static final String JavaDoc GET = "GET ";
97   private static final String JavaDoc CRLF = RETURN + NEWLINE;
98   private static final String JavaDoc HEADER = "header";
99   private static final String JavaDoc HOST = "Host: ";
100   private static final String JavaDoc HTTP1_0 = "HTTP/1.0";
101   static final String JavaDoc LOCALE = "locale";
102   private static final String JavaDoc VARIANT = "variant";
103   public static final String JavaDoc XML_ATTRIBUTE = "xml";
104   
105   private static final Pattern JavaDoc acceptlangPattern = Pattern.compile("^([^;,]*).*");
106   
107   protected ServletUtils() { }
108
109  /**
110   * forward a servlet request, based upon a parameter with the name 'forward'
111   */

112   public static final void forward(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, String JavaDoc forwardTag) {
113     String JavaDoc tmp = getAttrOrParam(request, forwardTag);
114
115     if (!StringUtils.isEmpty(tmp)) {
116       String JavaDoc forward = (String JavaDoc)tmp;
117       
118       if (forward.indexOf(PERCENT) >= 0) {
119         try {
120           forward = URLDecoder.decode(forward, UTF_8);
121         }
122         catch (UnsupportedEncodingException JavaDoc uee) {
123           log.error("unable to decode forward url", uee);
124           return;
125         }
126       }
127
128       if (log.isDebugEnabled()) {
129         log.debug("forwarding on to page " + forward);
130       }
131
132       RequestDispatcher JavaDoc rd = request.getRequestDispatcher(forward);
133       if (rd != null) {
134         try {
135           rd.forward(request, response);
136         }
137         catch (Exception JavaDoc e) {
138           e.printStackTrace();
139         }
140       }
141       else if (log.isDebugEnabled()) {
142         log.debug("the request dispatch for " + forward + " was null");
143       }
144     }
145     else {
146       if (log.isDebugEnabled()) {
147         log.debug("##### No forwarding page defined #####");
148       }
149     }
150   }
151
152  /**
153   * check if there is a forward parameter in the http request object, if so, forward on to it
154   * @param request the servlet request
155   * @param response the servlet response
156   */

157   public static final void forward(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
158     forward(request, response, FORWARD);
159   }
160
161  /**
162   * check if there is an error parameter in the http request object, if so, forward on to it
163   * @param request the servlet request
164   * @param response the servlet response
165   */

166   public static final void forwardError(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
167     forward(request, response, ERROR);
168   }
169
170  /**
171   * get a named attribute, and if it is not found, look for the parameter
172   * instead
173   */

174   public static final String JavaDoc getAttrOrParam(HttpServletRequest JavaDoc request, String JavaDoc name) {
175     Object JavaDoc tmp = request.getAttribute(name);
176     if (tmp == null) {
177       return request.getParameter(name);
178     }
179     else {
180       return (String JavaDoc)tmp;
181     }
182   }
183
184  /**
185   * get a buffered reader for reading from a specific URL
186   */

187   public static final BufferedReader JavaDoc getBufferedReaderForURL(String JavaDoc urlstr, String JavaDoc encoding) throws MalformedURLException JavaDoc, IOException JavaDoc {
188     return getBufferedReaderForURL(urlstr, null, encoding);
189   }
190     
191   public static final BufferedReader JavaDoc getBufferedReaderForURL(String JavaDoc urlstr, Map JavaDoc headers, String JavaDoc encoding) throws MalformedURLException JavaDoc, IOException JavaDoc {
192     URL JavaDoc url = new URL JavaDoc(urlstr);
193     HttpURLConnection JavaDoc con = (HttpURLConnection JavaDoc)url.openConnection();
194
195     if (headers != null) {
196       Iterator JavaDoc iter = headers.entrySet().iterator();
197       while (iter.hasNext()) {
198         Map.Entry JavaDoc entry = (Map.Entry JavaDoc)iter.next();
199         con.setRequestProperty((String JavaDoc)entry.getKey(), (String JavaDoc)entry.getValue());
200       }
201     }
202     
203     con.setDoOutput(false);
204     con.setDoInput(true);
205
206     InputStream JavaDoc in = con.getInputStream();
207     InputStreamReader JavaDoc isr = new InputStreamReader JavaDoc(in, encoding);
208     return new BufferedReader JavaDoc(isr);
209
210   }
211   
212   public static final String JavaDoc getContent(String JavaDoc httpmessage) {
213     String JavaDoc[] split = httpmessage.split("\r\n\r\n");
214     if (split.length == 2) {
215       return split[1];
216     }
217     else {
218       return EMPTY;
219     }
220   }
221   
222   public static final String JavaDoc getHeader(String JavaDoc httpmessage) {
223     String JavaDoc[] split = httpmessage.split("\r\n\r\n");
224     return split[0];
225   }
226
227   
228   public static final String JavaDoc[] getLanguageCountry(String JavaDoc acceptlang) {
229     String JavaDoc[] rtn = new String JavaDoc[2];
230     if (!StringUtils.isEmpty(acceptlang)) {
231       Matcher JavaDoc lmatcher = acceptlangPattern.matcher(acceptlang);
232       if (lmatcher.find()) {
233         String JavaDoc tmp = lmatcher.group(1);
234         if (!StringUtils.isEmpty(tmp)) {
235           String JavaDoc[] split = tmp.split(DASH);
236           rtn[0] = split[0];
237           if (split.length > 1) {
238             rtn[1] = split[1];
239           }
240         }
241       }
242     }
243
244     if (StringUtils.isEmpty(rtn[0])) {
245       rtn[0] = "en";
246     }
247     
248     return rtn;
249   }
250     
251   public static final Locale JavaDoc getLocale(HttpServletRequest JavaDoc request) {
252     return getLocale(request, EMPTY, false);
253   }
254   
255  /**
256   * get the locale being used by this request
257   */

258   public static final Locale JavaDoc getLocale(HttpServletRequest JavaDoc request, String JavaDoc variant, boolean sessionset) {
259     HttpSession JavaDoc session = request.getSession(true);
260     Locale JavaDoc l = (Locale JavaDoc)session.getAttribute(LOCALE);
261
262     if (l == null || (!StringUtils.isEmpty(variant) && !StringUtils.isEqual(variant, l.getVariant()))) {
263       String JavaDoc[] lc = getLanguageCountry(request.getHeader(ACCEPT_LANGUAGE));
264             
265       l = LocaleUtils.getLocale(lc[0], lc[1], variant);
266       
267       if (sessionset) {
268         setLocale(session, l);
269       }
270     }
271     return l;
272   }
273
274  /**
275   * call another server and return its response as a string
276   */

277   public static final String JavaDoc getServerResponse(String JavaDoc url, Map JavaDoc headers, String JavaDoc encoding) throws MalformedURLException JavaDoc, IOException JavaDoc {
278     BufferedReader JavaDoc br = null;
279     try {
280       br = getBufferedReaderForURL(url, headers, encoding);
281       if (br == null) {
282         return EMPTY;
283       }
284
285       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
286       String JavaDoc line;
287       while ((line = br.readLine()) != null) {
288         sb.append(line).append(NEWLINE);
289       }
290
291       return sb.toString();
292     }
293     finally {
294       IOUtils.close(br);
295     }
296   }
297   
298   public static String JavaDoc getParameterFromMap(Map JavaDoc parameterMap, String JavaDoc key, int index) {
299     String JavaDoc[] vals = (String JavaDoc[])parameterMap.get(key);
300     if (vals == null || index > vals.length || index < 0) {
301       return null;
302     }
303     else {
304       return vals[index];
305     }
306   }
307     
308   public static final String JavaDoc getServerResponse(String JavaDoc host, int port, String JavaDoc request, String JavaDoc encoding, int timeout) throws IOException JavaDoc {
309     Socket JavaDoc socket = null;
310         InputStream JavaDoc is = null;
311     OutputStream JavaDoc os = null;
312     try {
313       socket = new Socket JavaDoc(host, port);
314       if (timeout > 0) {
315         socket.setSoTimeout(timeout);
316       }
317       is = socket.getInputStream();
318       os = socket.getOutputStream();
319       
320       os.write((GET + request + SPACE + HTTP1_0 + CRLF + HOST + host + CRLF + CRLF).getBytes());
321       byte[] b = new byte[1024];
322       int len;
323       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
324       while ((len = is.read(b)) != -1) {
325         sb.append(new String JavaDoc(b, 0, len, encoding));
326       }
327       return sb.toString();
328     }
329     finally {
330       IOUtils.close(os);
331       IOUtils.close(is);
332       IOUtils.close(socket);
333     }
334   }
335     
336  /**
337   * set the locale for this session
338   */

339   public static final void setLocale(HttpSession JavaDoc session, Locale JavaDoc locale) {
340     session.setAttribute(LOCALE, locale);
341   }
342
343  /**
344   * convert a servlet config into a properties file
345   */

346   public static final Properties JavaDoc toProperties(ServletConfig JavaDoc config) {
347     Properties JavaDoc props = new Properties JavaDoc();
348     Enumeration JavaDoc en = config.getInitParameterNames();
349     while (en.hasMoreElements()) {
350       String JavaDoc param = (String JavaDoc)en.nextElement();
351       String JavaDoc value = config.getInitParameter(param);
352       
353       props.put(param, value);
354     }
355     return props;
356   }
357   
358  /**
359   * convert a servlet request to a string (for debugging purposes)
360   */

361   public static final String JavaDoc toString(HttpServletRequest JavaDoc request) {
362     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
363     sb.append("**Header**\n");
364     Enumeration JavaDoc en = request.getHeaderNames();
365     while (en.hasMoreElements()) {
366       String JavaDoc header = (String JavaDoc)en.nextElement();
367       sb.append(header).append(EQUALS).append(request.getHeader(header)).append(NEWLINE);
368     }
369
370     sb.append("**Attributes**\n");
371     en = request.getAttributeNames();
372     while (en.hasMoreElements()) {
373       String JavaDoc att = (String JavaDoc)en.nextElement();
374       sb.append(att).append(EQUALS).append(request.getAttribute(att)).append(NEWLINE);
375     }
376
377     sb.append("**Parameters**\n");
378     en = request.getParameterNames();
379     while (en.hasMoreElements()) {
380       String JavaDoc param = (String JavaDoc)en.nextElement();
381       sb.append(param).append(EQUALS).append(request.getParameter(param)).append(NEWLINE);
382     }
383
384     sb.append("**Miscellaneous**\n");
385     sb.append("Query String=").append(request.getQueryString()).append(NEWLINE);
386     sb.append("Request URL=").append(request.getRequestURL()).append(NEWLINE);
387     sb.append("Servlet Path =").append(request.getServletPath()).append(NEWLINE);
388     sb.append("Method = ").append(request.getMethod()).append(NEWLINE);
389     sb.append("User = ").append(request.getRemoteUser()).append(NEWLINE);
390     sb.append("Path Info = ").append(request.getPathInfo()).append(NEWLINE);
391     sb.append("Path Translated = ").append(request.getPathTranslated()).append(NEWLINE);
392     return sb.toString();
393   }
394   
395   public static final String JavaDoc toString(HttpSession JavaDoc session) {
396     Enumeration JavaDoc en = session.getAttributeNames();
397     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
398     while (en.hasMoreElements()) {
399       String JavaDoc name = (String JavaDoc)en.nextElement();
400       sb.append(name).append(EQUALS).append(session.getAttribute(name)).append(NEWLINE);
401     }
402     return sb.toString();
403   }
404   
405   public static final String JavaDoc toString(Map JavaDoc queryMap) {
406     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
407     if (queryMap == null) {
408       return sb.toString();
409     }
410     else {
411       Iterator JavaDoc iter = queryMap.entrySet().iterator();
412       while (iter.hasNext()) {
413         Map.Entry JavaDoc entry = (Map.Entry JavaDoc)iter.next();
414         sb.append(entry.getKey()).append("[");
415         String JavaDoc[] values = (String JavaDoc[])entry.getValue();
416         if (values != null) {
417           for (int i = 0; i < values.length; i++) {
418             sb.append(values[i]);
419             if (i < values.length-1) {
420               sb.append(COMMA);
421             }
422           }
423         }
424         sb.append("]");
425         if (iter.hasNext()) {
426           sb.append(COMMA);
427         }
428       }
429     }
430     return sb.toString();
431   }
432   
433   public static final void main(String JavaDoc[] args) throws Exception JavaDoc {
434     String JavaDoc s = ServletUtils.getServerResponse("test.lateralnz.com", 80, "/error.wml", "UTF-8", 1000);
435     System.out.println(ServletUtils.getHeader(s));
436     System.out.println("\r\n\r\n" + ServletUtils.getContent(s));
437   }
438 }
439
Popular Tags