1 55 package org.lateralnz.common.util; 56 57 import java.io.BufferedReader ; 58 import java.io.IOException ; 59 import java.io.InputStream ; 60 import java.io.InputStreamReader ; 61 import java.io.UnsupportedEncodingException ; 62 import java.io.OutputStream ; 63 import java.net.URLDecoder ; 64 import java.net.URL ; 65 import java.net.HttpURLConnection ; 66 import java.net.MalformedURLException ; 67 import java.net.Socket ; 68 import java.util.Enumeration ; 69 import java.util.HashMap ; 70 import java.util.Iterator ; 71 import java.util.Locale ; 72 import java.util.Map ; 73 import java.util.Properties ; 74 import java.util.regex.Matcher ; 75 import java.util.regex.Pattern ; 76 77 import javax.servlet.RequestDispatcher ; 78 import javax.servlet.ServletConfig ; 79 import javax.servlet.http.HttpServletRequest ; 80 import javax.servlet.http.HttpServletResponse ; 81 import javax.servlet.http.HttpSession ; 82 83 import org.apache.log4j.Logger; 84 85 90 public class ServletUtils implements Constants { 91 private static Logger log = Logger.getLogger(ServletUtils.class.getName()); 92 93 private static final String ACCEPT_LANGUAGE = "Accept-Language"; 94 private static final String ERROR = "error"; 95 private static final String FORWARD = "forward"; 96 private static final String GET = "GET "; 97 private static final String CRLF = RETURN + NEWLINE; 98 private static final String HEADER = "header"; 99 private static final String HOST = "Host: "; 100 private static final String HTTP1_0 = "HTTP/1.0"; 101 static final String LOCALE = "locale"; 102 private static final String VARIANT = "variant"; 103 public static final String XML_ATTRIBUTE = "xml"; 104 105 private static final Pattern acceptlangPattern = Pattern.compile("^([^;,]*).*"); 106 107 protected ServletUtils() { } 108 109 112 public static final void forward(HttpServletRequest request, HttpServletResponse response, String forwardTag) { 113 String tmp = getAttrOrParam(request, forwardTag); 114 115 if (!StringUtils.isEmpty(tmp)) { 116 String forward = (String )tmp; 117 118 if (forward.indexOf(PERCENT) >= 0) { 119 try { 120 forward = URLDecoder.decode(forward, UTF_8); 121 } 122 catch (UnsupportedEncodingException 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 rd = request.getRequestDispatcher(forward); 133 if (rd != null) { 134 try { 135 rd.forward(request, response); 136 } 137 catch (Exception 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 157 public static final void forward(HttpServletRequest request, HttpServletResponse response) { 158 forward(request, response, FORWARD); 159 } 160 161 166 public static final void forwardError(HttpServletRequest request, HttpServletResponse response) { 167 forward(request, response, ERROR); 168 } 169 170 174 public static final String getAttrOrParam(HttpServletRequest request, String name) { 175 Object tmp = request.getAttribute(name); 176 if (tmp == null) { 177 return request.getParameter(name); 178 } 179 else { 180 return (String )tmp; 181 } 182 } 183 184 187 public static final BufferedReader getBufferedReaderForURL(String urlstr, String encoding) throws MalformedURLException , IOException { 188 return getBufferedReaderForURL(urlstr, null, encoding); 189 } 190 191 public static final BufferedReader getBufferedReaderForURL(String urlstr, Map headers, String encoding) throws MalformedURLException , IOException { 192 URL url = new URL (urlstr); 193 HttpURLConnection con = (HttpURLConnection )url.openConnection(); 194 195 if (headers != null) { 196 Iterator iter = headers.entrySet().iterator(); 197 while (iter.hasNext()) { 198 Map.Entry entry = (Map.Entry )iter.next(); 199 con.setRequestProperty((String )entry.getKey(), (String )entry.getValue()); 200 } 201 } 202 203 con.setDoOutput(false); 204 con.setDoInput(true); 205 206 InputStream in = con.getInputStream(); 207 InputStreamReader isr = new InputStreamReader (in, encoding); 208 return new BufferedReader (isr); 209 210 } 211 212 public static final String getContent(String httpmessage) { 213 String [] 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 getHeader(String httpmessage) { 223 String [] split = httpmessage.split("\r\n\r\n"); 224 return split[0]; 225 } 226 227 228 public static final String [] getLanguageCountry(String acceptlang) { 229 String [] rtn = new String [2]; 230 if (!StringUtils.isEmpty(acceptlang)) { 231 Matcher lmatcher = acceptlangPattern.matcher(acceptlang); 232 if (lmatcher.find()) { 233 String tmp = lmatcher.group(1); 234 if (!StringUtils.isEmpty(tmp)) { 235 String [] 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 getLocale(HttpServletRequest request) { 252 return getLocale(request, EMPTY, false); 253 } 254 255 258 public static final Locale getLocale(HttpServletRequest request, String variant, boolean sessionset) { 259 HttpSession session = request.getSession(true); 260 Locale l = (Locale )session.getAttribute(LOCALE); 261 262 if (l == null || (!StringUtils.isEmpty(variant) && !StringUtils.isEqual(variant, l.getVariant()))) { 263 String [] 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 277 public static final String getServerResponse(String url, Map headers, String encoding) throws MalformedURLException , IOException { 278 BufferedReader br = null; 279 try { 280 br = getBufferedReaderForURL(url, headers, encoding); 281 if (br == null) { 282 return EMPTY; 283 } 284 285 StringBuffer sb = new StringBuffer (); 286 String 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 getParameterFromMap(Map parameterMap, String key, int index) { 299 String [] vals = (String [])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 getServerResponse(String host, int port, String request, String encoding, int timeout) throws IOException { 309 Socket socket = null; 310 InputStream is = null; 311 OutputStream os = null; 312 try { 313 socket = new Socket (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 sb = new StringBuffer (); 324 while ((len = is.read(b)) != -1) { 325 sb.append(new String (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 339 public static final void setLocale(HttpSession session, Locale locale) { 340 session.setAttribute(LOCALE, locale); 341 } 342 343 346 public static final Properties toProperties(ServletConfig config) { 347 Properties props = new Properties (); 348 Enumeration en = config.getInitParameterNames(); 349 while (en.hasMoreElements()) { 350 String param = (String )en.nextElement(); 351 String value = config.getInitParameter(param); 352 353 props.put(param, value); 354 } 355 return props; 356 } 357 358 361 public static final String toString(HttpServletRequest request) { 362 StringBuffer sb = new StringBuffer (); 363 sb.append("**Header**\n"); 364 Enumeration en = request.getHeaderNames(); 365 while (en.hasMoreElements()) { 366 String header = (String )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 att = (String )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 param = (String )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 toString(HttpSession session) { 396 Enumeration en = session.getAttributeNames(); 397 StringBuffer sb = new StringBuffer (); 398 while (en.hasMoreElements()) { 399 String name = (String )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 toString(Map queryMap) { 406 StringBuffer sb = new StringBuffer (); 407 if (queryMap == null) { 408 return sb.toString(); 409 } 410 else { 411 Iterator iter = queryMap.entrySet().iterator(); 412 while (iter.hasNext()) { 413 Map.Entry entry = (Map.Entry )iter.next(); 414 sb.append(entry.getKey()).append("["); 415 String [] values = (String [])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 [] args) throws Exception { 434 String 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 |