001: /* ====================================================================
002: * The LateralNZ Software License, Version 1.0
003: *
004: * Copyright (c) 2003 LateralNZ. All rights reserved.
005: *
006: * Redistribution and use in source and binary forms, with or without
007: * modification, are permitted provided that the following conditions
008: * are met:
009: *
010: * 1. Redistributions of source code must retain the above copyright
011: * notice, this list of conditions and the following disclaimer.
012: *
013: * 2. Redistributions in binary form must reproduce the above copyright
014: * notice, this list of conditions and the following disclaimer in
015: * the documentation and/or other materials provided with the
016: * distribution.
017: *
018: * 3. The end-user documentation included with the redistribution,
019: * if any, must include the following acknowledgment:
020: * "This product includes software developed by
021: * LateralNZ (http://www.lateralnz.org/) and other third parties."
022: * Alternately, this acknowledgment may appear in the software itself,
023: * if and wherever such third-party acknowledgments normally appear.
024: *
025: * 4. The names "LateralNZ" must not be used to endorse or promote
026: * products derived from this software without prior written
027: * permission. For written permission, please
028: * contact oss@lateralnz.org.
029: *
030: * 5. Products derived from this software may not be called "Panther",
031: * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
032: * "LATERALNZ" appear in their name, without prior written
033: * permission of LateralNZ.
034: *
035: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
036: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
037: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
038: * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
039: * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
040: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
041: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
042: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
043: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
044: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
045: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
046: * SUCH DAMAGE.
047: * ====================================================================
048: *
049: * This software consists of voluntary contributions made by many
050: * individuals on behalf of LateralNZ. For more
051: * information on Lateral, please see http://www.lateralnz.com/ or
052: * http://www.lateralnz.org
053: *
054: */
055: package org.lateralnz.common.util;
056:
057: import java.io.BufferedReader;
058: import java.io.IOException;
059: import java.io.InputStream;
060: import java.io.InputStreamReader;
061: import java.io.UnsupportedEncodingException;
062: import java.io.OutputStream;
063: import java.net.URLDecoder;
064: import java.net.URL;
065: import java.net.HttpURLConnection;
066: import java.net.MalformedURLException;
067: import java.net.Socket;
068: import java.util.Enumeration;
069: import java.util.HashMap;
070: import java.util.Iterator;
071: import java.util.Locale;
072: import java.util.Map;
073: import java.util.Properties;
074: import java.util.regex.Matcher;
075: import java.util.regex.Pattern;
076:
077: import javax.servlet.RequestDispatcher;
078: import javax.servlet.ServletConfig;
079: import javax.servlet.http.HttpServletRequest;
080: import javax.servlet.http.HttpServletResponse;
081: import javax.servlet.http.HttpSession;
082:
083: import org.apache.log4j.Logger;
084:
085: /**
086: * common utility functions used by servlets
087: *
088: * @author J R Briggs
089: */
090: public class ServletUtils implements Constants {
091: private static Logger log = Logger.getLogger(ServletUtils.class
092: .getName());
093:
094: private static final String ACCEPT_LANGUAGE = "Accept-Language";
095: private static final String ERROR = "error";
096: private static final String FORWARD = "forward";
097: private static final String GET = "GET ";
098: private static final String CRLF = RETURN + NEWLINE;
099: private static final String HEADER = "header";
100: private static final String HOST = "Host: ";
101: private static final String HTTP1_0 = "HTTP/1.0";
102: static final String LOCALE = "locale";
103: private static final String VARIANT = "variant";
104: public static final String XML_ATTRIBUTE = "xml";
105:
106: private static final Pattern acceptlangPattern = Pattern
107: .compile("^([^;,]*).*");
108:
109: protected ServletUtils() {
110: }
111:
112: /**
113: * forward a servlet request, based upon a parameter with the name 'forward'
114: */
115: public static final void forward(HttpServletRequest request,
116: HttpServletResponse response, String forwardTag) {
117: String tmp = getAttrOrParam(request, forwardTag);
118:
119: if (!StringUtils.isEmpty(tmp)) {
120: String forward = (String) tmp;
121:
122: if (forward.indexOf(PERCENT) >= 0) {
123: try {
124: forward = URLDecoder.decode(forward, UTF_8);
125: } catch (UnsupportedEncodingException uee) {
126: log.error("unable to decode forward url", uee);
127: return;
128: }
129: }
130:
131: if (log.isDebugEnabled()) {
132: log.debug("forwarding on to page " + forward);
133: }
134:
135: RequestDispatcher rd = request
136: .getRequestDispatcher(forward);
137: if (rd != null) {
138: try {
139: rd.forward(request, response);
140: } catch (Exception e) {
141: e.printStackTrace();
142: }
143: } else if (log.isDebugEnabled()) {
144: log.debug("the request dispatch for " + forward
145: + " was null");
146: }
147: } else {
148: if (log.isDebugEnabled()) {
149: log.debug("##### No forwarding page defined #####");
150: }
151: }
152: }
153:
154: /**
155: * check if there is a forward parameter in the http request object, if so, forward on to it
156: * @param request the servlet request
157: * @param response the servlet response
158: */
159: public static final void forward(HttpServletRequest request,
160: HttpServletResponse response) {
161: forward(request, response, FORWARD);
162: }
163:
164: /**
165: * check if there is an error parameter in the http request object, if so, forward on to it
166: * @param request the servlet request
167: * @param response the servlet response
168: */
169: public static final void forwardError(HttpServletRequest request,
170: HttpServletResponse response) {
171: forward(request, response, ERROR);
172: }
173:
174: /**
175: * get a named attribute, and if it is not found, look for the parameter
176: * instead
177: */
178: public static final String getAttrOrParam(
179: HttpServletRequest request, String name) {
180: Object tmp = request.getAttribute(name);
181: if (tmp == null) {
182: return request.getParameter(name);
183: } else {
184: return (String) tmp;
185: }
186: }
187:
188: /**
189: * get a buffered reader for reading from a specific URL
190: */
191: public static final BufferedReader getBufferedReaderForURL(
192: String urlstr, String encoding)
193: throws MalformedURLException, IOException {
194: return getBufferedReaderForURL(urlstr, null, encoding);
195: }
196:
197: public static final BufferedReader getBufferedReaderForURL(
198: String urlstr, Map headers, String encoding)
199: throws MalformedURLException, IOException {
200: URL url = new URL(urlstr);
201: HttpURLConnection con = (HttpURLConnection) url
202: .openConnection();
203:
204: if (headers != null) {
205: Iterator iter = headers.entrySet().iterator();
206: while (iter.hasNext()) {
207: Map.Entry entry = (Map.Entry) iter.next();
208: con.setRequestProperty((String) entry.getKey(),
209: (String) entry.getValue());
210: }
211: }
212:
213: con.setDoOutput(false);
214: con.setDoInput(true);
215:
216: InputStream in = con.getInputStream();
217: InputStreamReader isr = new InputStreamReader(in, encoding);
218: return new BufferedReader(isr);
219:
220: }
221:
222: public static final String getContent(String httpmessage) {
223: String[] split = httpmessage.split("\r\n\r\n");
224: if (split.length == 2) {
225: return split[1];
226: } else {
227: return EMPTY;
228: }
229: }
230:
231: public static final String getHeader(String httpmessage) {
232: String[] split = httpmessage.split("\r\n\r\n");
233: return split[0];
234: }
235:
236: public static final String[] getLanguageCountry(String acceptlang) {
237: String[] rtn = new String[2];
238: if (!StringUtils.isEmpty(acceptlang)) {
239: Matcher lmatcher = acceptlangPattern.matcher(acceptlang);
240: if (lmatcher.find()) {
241: String tmp = lmatcher.group(1);
242: if (!StringUtils.isEmpty(tmp)) {
243: String[] split = tmp.split(DASH);
244: rtn[0] = split[0];
245: if (split.length > 1) {
246: rtn[1] = split[1];
247: }
248: }
249: }
250: }
251:
252: if (StringUtils.isEmpty(rtn[0])) {
253: rtn[0] = "en";
254: }
255:
256: return rtn;
257: }
258:
259: public static final Locale getLocale(HttpServletRequest request) {
260: return getLocale(request, EMPTY, false);
261: }
262:
263: /**
264: * get the locale being used by this request
265: */
266: public static final Locale getLocale(HttpServletRequest request,
267: String variant, boolean sessionset) {
268: HttpSession session = request.getSession(true);
269: Locale l = (Locale) session.getAttribute(LOCALE);
270:
271: if (l == null
272: || (!StringUtils.isEmpty(variant) && !StringUtils
273: .isEqual(variant, l.getVariant()))) {
274: String[] lc = getLanguageCountry(request
275: .getHeader(ACCEPT_LANGUAGE));
276:
277: l = LocaleUtils.getLocale(lc[0], lc[1], variant);
278:
279: if (sessionset) {
280: setLocale(session, l);
281: }
282: }
283: return l;
284: }
285:
286: /**
287: * call another server and return its response as a string
288: */
289: public static final String getServerResponse(String url,
290: Map headers, String encoding) throws MalformedURLException,
291: IOException {
292: BufferedReader br = null;
293: try {
294: br = getBufferedReaderForURL(url, headers, encoding);
295: if (br == null) {
296: return EMPTY;
297: }
298:
299: StringBuffer sb = new StringBuffer();
300: String line;
301: while ((line = br.readLine()) != null) {
302: sb.append(line).append(NEWLINE);
303: }
304:
305: return sb.toString();
306: } finally {
307: IOUtils.close(br);
308: }
309: }
310:
311: public static String getParameterFromMap(Map parameterMap,
312: String key, int index) {
313: String[] vals = (String[]) parameterMap.get(key);
314: if (vals == null || index > vals.length || index < 0) {
315: return null;
316: } else {
317: return vals[index];
318: }
319: }
320:
321: public static final String getServerResponse(String host, int port,
322: String request, String encoding, int timeout)
323: throws IOException {
324: Socket socket = null;
325: InputStream is = null;
326: OutputStream os = null;
327: try {
328: socket = new Socket(host, port);
329: if (timeout > 0) {
330: socket.setSoTimeout(timeout);
331: }
332: is = socket.getInputStream();
333: os = socket.getOutputStream();
334:
335: os.write((GET + request + SPACE + HTTP1_0 + CRLF + HOST
336: + host + CRLF + CRLF).getBytes());
337: byte[] b = new byte[1024];
338: int len;
339: StringBuffer sb = new StringBuffer();
340: while ((len = is.read(b)) != -1) {
341: sb.append(new String(b, 0, len, encoding));
342: }
343: return sb.toString();
344: } finally {
345: IOUtils.close(os);
346: IOUtils.close(is);
347: IOUtils.close(socket);
348: }
349: }
350:
351: /**
352: * set the locale for this session
353: */
354: public static final void setLocale(HttpSession session,
355: Locale locale) {
356: session.setAttribute(LOCALE, locale);
357: }
358:
359: /**
360: * convert a servlet config into a properties file
361: */
362: public static final Properties toProperties(ServletConfig config) {
363: Properties props = new Properties();
364: Enumeration en = config.getInitParameterNames();
365: while (en.hasMoreElements()) {
366: String param = (String) en.nextElement();
367: String value = config.getInitParameter(param);
368:
369: props.put(param, value);
370: }
371: return props;
372: }
373:
374: /**
375: * convert a servlet request to a string (for debugging purposes)
376: */
377: public static final String toString(HttpServletRequest request) {
378: StringBuffer sb = new StringBuffer();
379: sb.append("**Header**\n");
380: Enumeration en = request.getHeaderNames();
381: while (en.hasMoreElements()) {
382: String header = (String) en.nextElement();
383: sb.append(header).append(EQUALS).append(
384: request.getHeader(header)).append(NEWLINE);
385: }
386:
387: sb.append("**Attributes**\n");
388: en = request.getAttributeNames();
389: while (en.hasMoreElements()) {
390: String att = (String) en.nextElement();
391: sb.append(att).append(EQUALS).append(
392: request.getAttribute(att)).append(NEWLINE);
393: }
394:
395: sb.append("**Parameters**\n");
396: en = request.getParameterNames();
397: while (en.hasMoreElements()) {
398: String param = (String) en.nextElement();
399: sb.append(param).append(EQUALS).append(
400: request.getParameter(param)).append(NEWLINE);
401: }
402:
403: sb.append("**Miscellaneous**\n");
404: sb.append("Query String=").append(request.getQueryString())
405: .append(NEWLINE);
406: sb.append("Request URL=").append(request.getRequestURL())
407: .append(NEWLINE);
408: sb.append("Servlet Path =").append(request.getServletPath())
409: .append(NEWLINE);
410: sb.append("Method = ").append(request.getMethod()).append(
411: NEWLINE);
412: sb.append("User = ").append(request.getRemoteUser()).append(
413: NEWLINE);
414: sb.append("Path Info = ").append(request.getPathInfo()).append(
415: NEWLINE);
416: sb.append("Path Translated = ").append(
417: request.getPathTranslated()).append(NEWLINE);
418: return sb.toString();
419: }
420:
421: public static final String toString(HttpSession session) {
422: Enumeration en = session.getAttributeNames();
423: StringBuffer sb = new StringBuffer();
424: while (en.hasMoreElements()) {
425: String name = (String) en.nextElement();
426: sb.append(name).append(EQUALS).append(
427: session.getAttribute(name)).append(NEWLINE);
428: }
429: return sb.toString();
430: }
431:
432: public static final String toString(Map queryMap) {
433: StringBuffer sb = new StringBuffer();
434: if (queryMap == null) {
435: return sb.toString();
436: } else {
437: Iterator iter = queryMap.entrySet().iterator();
438: while (iter.hasNext()) {
439: Map.Entry entry = (Map.Entry) iter.next();
440: sb.append(entry.getKey()).append("[");
441: String[] values = (String[]) entry.getValue();
442: if (values != null) {
443: for (int i = 0; i < values.length; i++) {
444: sb.append(values[i]);
445: if (i < values.length - 1) {
446: sb.append(COMMA);
447: }
448: }
449: }
450: sb.append("]");
451: if (iter.hasNext()) {
452: sb.append(COMMA);
453: }
454: }
455: }
456: return sb.toString();
457: }
458:
459: public static final void main(String[] args) throws Exception {
460: String s = ServletUtils.getServerResponse("test.lateralnz.com",
461: 80, "/error.wml", "UTF-8", 1000);
462: System.out.println(ServletUtils.getHeader(s));
463: System.out.println("\r\n\r\n" + ServletUtils.getContent(s));
464: }
465: }
|