1 22 23 package org.meshcms.core; 24 25 import java.io.*; 26 import java.nio.charset.*; 27 import java.net.*; 28 import java.text.*; 29 import java.util.*; 30 import javax.activation.*; 31 import javax.servlet.*; 32 import javax.servlet.http.*; 33 import javax.servlet.jsp.*; 34 import javax.xml.parsers.*; 35 import org.w3c.dom.*; 36 import org.meshcms.util.*; 37 38 41 public final class WebUtils { 42 public static final SimpleDateFormat numericDateFormatter = 43 new SimpleDateFormat("yyyyMMddHHmmss"); 44 45 48 public static final String FN_CHARS = 49 "'()-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; 50 51 54 public static final String FN_CHARMAP = 55 "________________________________" + 56 "__'____'()..--._0123456789..(-)." + 57 "_ABCDEFGHIJKLMNOPQRSTUVWXYZ(_)__" + 58 "'abcdefghijklmnopqrstuvwxyz(_)-_" + 59 "________________________________" + 60 "__cL.Y_P_Ca(__R-o-23'mP._10)423_" + 61 "AAAAAAACEEEEIIIIENOOOOOxOUUUUYTS" + 62 "aaaaaaaceeeeiiiienooooo-ouuuuyty"; 63 64 67 public static final String FN_SPACERS = "_!'()-"; 68 69 73 public static final String [] DEFAULT_WELCOME_FILES = 74 {"index.html", "index.htm", "index.jsp"}; 75 76 public static Properties NUMBER_TO_ENTITY; 77 public static Properties ENTITY_TO_NUMBER; 78 79 static { 80 String [] entities = { 81 "39", "#39", "160", "nbsp", "161", "iexcl", "162", "cent", "163", "pound", 82 "164", "curren", "165", "yen", "166", "brvbar", "167", "sect", 83 "168", "uml", "169", "copy", "170", "ordf", "171", "laquo", "172", "not", 84 "173", "shy", "174", "reg", "175", "macr", "176", "deg", "177", "plusmn", 85 "178", "sup2", "179", "sup3", "180", "acute", "181", "micro", 86 "182", "para", "183", "middot", "184", "cedil", "185", "sup1", 87 "186", "ordm", "187", "raquo", "188", "frac14", "189", "frac12", 88 "190", "frac34", "191", "iquest", "192", "Agrave", "193", "Aacute", 89 "194", "Acirc", "195", "Atilde", "196", "Auml", "197", "Aring", 90 "198", "AElig", "199", "Ccedil", "200", "Egrave", "201", "Eacute", 91 "202", "Ecirc", "203", "Euml", "204", "Igrave", "205", "Iacute", 92 "206", "Icirc", "207", "Iuml", "208", "ETH", "209", "Ntilde", 93 "210", "Ograve", "211", "Oacute", "212", "Ocirc", "213", "Otilde", 94 "214", "Ouml", "215", "times", "216", "Oslash", "217", "Ugrave", 95 "218", "Uacute", "219", "Ucirc", "220", "Uuml", "221", "Yacute", 96 "222", "THORN", "223", "szlig", "224", "agrave", "225", "aacute", 97 "226", "acirc", "227", "atilde", "228", "auml", "229", "aring", 98 "230", "aelig", "231", "ccedil", "232", "egrave", "233", "eacute", 99 "234", "ecirc", "235", "euml", "236", "igrave", "237", "iacute", 100 "238", "icirc", "239", "iuml", "240", "eth", "241", "ntilde", 101 "242", "ograve", "243", "oacute", "244", "ocirc", "245", "otilde", 102 "246", "ouml", "247", "divide", "248", "oslash", "249", "ugrave", 103 "250", "uacute", "251", "ucirc", "252", "uuml", "253", "yacute", 104 "254", "thorn", "255", "yuml", "402", "fnof", "913", "Alpha", 105 "914", "Beta", "915", "Gamma", "916", "Delta", "917", "Epsilon", 106 "918", "Zeta", "919", "Eta", "920", "Theta", "921", "Iota", 107 "922", "Kappa", "923", "Lambda", "924", "Mu", "925", "Nu", "926", "Xi", 108 "927", "Omicron", "928", "Pi", "929", "Rho", "931", "Sigma", "932", "Tau", 109 "933", "Upsilon", "934", "Phi", "935", "Chi", "936", "Psi", 110 "937", "Omega", "945", "alpha", "946", "beta", "947", "gamma", 111 "948", "delta", "949", "epsilon", "950", "zeta", "951", "eta", 112 "952", "theta", "953", "iota", "954", "kappa", "955", "lambda", 113 "956", "mu", "957", "nu", "958", "xi", "959", "omicron", "960", "pi", 114 "961", "rho", "962", "sigmaf", "963", "sigma", "964", "tau", 115 "965", "upsilon", "966", "phi", "967", "chi", "968", "psi", 116 "969", "omega", "977", "thetasym", "978", "upsih", "982", "piv", 117 "8226", "bull", "8230", "hellip", "8242", "prime", "8243", "Prime", 118 "8254", "oline", "8260", "frasl", "8472", "weierp", "8465", "image", 119 "8476", "real", "8482", "trade", "8501", "alefsym", "8592", "larr", 120 "8593", "uarr", "8594", "rarr", "8595", "darr", "8596", "harr", 121 "8629", "crarr", "8656", "lArr", "8657", "uArr", "8658", "rArr", 122 "8659", "dArr", "8660", "hArr", "8704", "forall", "8706", "part", 123 "8707", "exist", "8709", "empty", "8711", "nabla", "8712", "isin", 124 "8713", "notin", "8715", "ni", "8719", "prod", "8721", "sum", 125 "8722", "minus", "8727", "lowast", "8730", "radic", "8733", "prop", 126 "8734", "infin", "8736", "ang", "8743", "and", "8744", "or", 127 "8745", "cap", "8746", "cup", "8747", "int", "8756", "there4", 128 "8764", "sim", "8773", "cong", "8776", "asymp", "8800", "ne", 129 "8801", "equiv", "8804", "le", "8805", "ge", "8834", "sub", "8835", "sup", 130 "8836", "nsub", "8838", "sube", "8839", "supe", "8853", "oplus", 131 "8855", "otimes", "8869", "perp", "8901", "sdot", "8968", "lceil", 132 "8969", "rceil", "8970", "lfloor", "8971", "rfloor", "9001", "lang", 133 "9002", "rang", "9674", "loz", "9824", "spades", "9827", "clubs", 134 "9829", "hearts", "9830", "diams", "34", "quot", "38", "amp", "60", "lt", 135 "62", "gt", "338", "OElig", "339", "oelig", "352", "Scaron", 136 "353", "scaron", "376", "Yuml", "710", "circ", "732", "tilde", 137 "8194", "ensp", "8195", "emsp", "8201", "thinsp", "8204", "zwnj", 138 "8205", "zwj", "8206", "lrm", "8207", "rlm", "8211", "ndash", 139 "8212", "mdash", "8216", "lsquo", "8217", "rsquo", "8218", "sbquo", 140 "8220", "ldquo", "8221", "rdquo", "8222", "bdquo", "8224", "dagger", 141 "8225", "Dagger", "8240", "permil", "8249", "lsaquo", "8250", "rsaquo", 142 "8364", "euro" 143 }; 144 145 NUMBER_TO_ENTITY = new Properties(); 146 ENTITY_TO_NUMBER = new Properties(); 147 148 for (int i = 0; i < entities.length; i += 2) { 149 NUMBER_TO_ENTITY.setProperty(entities[i], entities[i + 1]); 150 ENTITY_TO_NUMBER.setProperty(entities[i + 1], entities[i]); 151 } 152 } 153 154 public static String convertToHTMLEntities(String s, boolean encodeTags) { 155 StringBuffer sb = new StringBuffer (s.length()); 156 157 for (int i = 0; i < s.length(); i++) { 158 char c = s.charAt(i); 159 int n = ((int) c) & 0xFFFF; 160 161 if (n > 127) { 162 String ent = NUMBER_TO_ENTITY.getProperty(Integer.toString(c)); 163 164 if (ent == null) { 165 sb.append("&#").append(n).append(';'); 166 } else { 167 sb.append('&').append(ent).append(';'); 168 } 169 } else if (encodeTags && (n == 34 || n == 39 || n == 60 || n == 62)) { 170 sb.append('&').append(NUMBER_TO_ENTITY.getProperty(Integer.toString(c))).append(';'); 171 } else { 172 sb.append(c); 173 } 174 } 175 176 return sb.toString(); 177 } 178 179 187 public static String [] getWelcomeFiles(ServletContext sc) { 188 File webXml = new File(sc.getRealPath("/WEB-INF/web.xml")); 189 String [] welcomeFiles = null; 190 191 try { 192 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 193 DocumentBuilder parser = factory.newDocumentBuilder(); 194 Document document = parser.parse(webXml); 195 Element root = document.getDocumentElement(); 196 Element wfl = (Element) 197 (root.getElementsByTagName("welcome-file-list").item(0)); 198 NodeList wfnl = wfl.getElementsByTagName("welcome-file"); 199 welcomeFiles = new String [wfnl.getLength()]; 200 201 for (int i = 0; i < welcomeFiles.length; i++) { 202 welcomeFiles[i] = wfnl.item(i).getFirstChild().getNodeValue(); 203 } 204 } catch (Exception ex) { 205 ex.printStackTrace(); 206 } 207 208 if (welcomeFiles == null || welcomeFiles.length == 0) { 209 welcomeFiles = DEFAULT_WELCOME_FILES; 210 } 211 212 return welcomeFiles; 213 } 214 215 219 public static String getFullParameter(HttpServletRequest request, String name) { 220 String value = request.getParameter(name); 221 return (value == null) ? "" : "&" + name + "=" + value; 222 } 223 224 227 public static String getPathInContext(HttpServletRequest request, Path path) { 228 return request.getContextPath() + "/" + path; 229 } 230 231 236 public static String getFullRequestURL(HttpServletRequest request) { 237 StringBuffer sb = request.getRequestURL(); 238 String qs = request.getQueryString(); 239 240 if (!Utils.isNullOrEmpty(qs)) { 241 sb.append('?').append(qs); 242 } 243 244 return sb.toString(); 245 } 246 247 251 public static StringBuffer getContextHomeURL(HttpServletRequest request) { 252 StringBuffer sb = new StringBuffer (); 253 String scheme = request.getScheme(); 254 sb.append(scheme).append("://"); 255 sb.append(request.getServerName()); 256 int port = request.getServerPort(); 257 258 if (!(("http".equals(scheme) && port == 80) || 259 ("https".equals(scheme) && port == 443))) { 260 sb.append(':').append(port); 261 } 262 263 return sb.append(request.getContextPath()); 264 } 265 266 272 public static String getFullThemeFolder(HttpServletRequest request) { 273 Path themePath = (Path) request.getAttribute(HitFilter.THEME_PATH_ATTRIBUTE); 274 275 return (themePath == null) ? "" : 276 request.getContextPath() + "/" + themePath; 277 } 278 279 285 public static String getFullThemeFile(HttpServletRequest request) { 286 return getFullThemeFolder(request) + "/" + SiteMap.THEME_DECORATOR; 287 } 288 289 295 public static String getFullThemeCSS(HttpServletRequest request) { 296 return getFullThemeFolder(request) + "/" + SiteMap.THEME_CSS; 297 } 298 299 306 public static String getFullMeshCSS(WebSite webSite, HttpServletRequest request) { 307 Path themePath = (Path) request.getAttribute(HitFilter.THEME_PATH_ATTRIBUTE); 308 Path cssPath = themePath.add(SiteMap.MESHCMS_CSS); 309 310 if (!webSite.getFile(cssPath).exists()) { 311 cssPath = webSite.getAdminThemePath().add(SiteMap.MESHCMS_CSS); 312 } 313 314 return request.getContextPath() + "/" + cssPath; 315 } 316 317 323 public static int getMenuCode(Object o) { 324 return o.hashCode() & 0x7FFFFFFF; 325 } 326 327 330 public static String get2ndLevelDomain(HttpServletRequest request) { 331 return get2ndLevelDomain(request.getRequestURL().toString()); 332 } 333 334 337 public static String get2ndLevelDomain(String urlString) { 338 try { 339 URL url = new URL(urlString); 340 String host = url.getHost(); 341 int dot = host.lastIndexOf('.'); 342 343 if (dot != -1) { 344 String partial = host.substring(0, dot); 345 dot = partial.lastIndexOf('.'); 346 347 if (dot != -1) { 348 host = host.substring(dot + 1); 349 } 350 351 return host; 352 } 353 } catch (Exception ex) {} 354 355 return null; 356 } 357 358 363 public static void setBlockCache(HttpServletRequest request) { 364 request.setAttribute(HitFilter.BLOCK_CACHE_ATTRIBUTE, 365 HitFilter.BLOCK_CACHE_ATTRIBUTE); 366 } 367 368 372 public static boolean isCacheBlocked(HttpServletRequest request) { 373 return request.getAttribute(HitFilter.BLOCK_CACHE_ATTRIBUTE) != null; 374 } 375 376 381 public static Locale getPageLocale(PageContext pageContext) { 382 Locale locale = null; 383 384 UserInfo userInfo = (UserInfo) pageContext.getAttribute("userInfo", 385 PageContext.SESSION_SCOPE); 386 387 if (userInfo != null) { 388 locale = Utils.getLocale(userInfo.getPreferredLocaleCode()); 389 } 390 391 if (locale == null) { 392 locale = (Locale) pageContext.getAttribute(HitFilter.LOCALE_ATTRIBUTE, 393 PageContext.PAGE_SCOPE); 394 } 395 396 Enumeration en = pageContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE); 397 398 while (locale == null && en.hasMoreElements()) { 399 Object obj = pageContext.getAttribute((String ) en.nextElement()); 400 401 if (obj instanceof Locale) { 402 locale = (Locale) obj; 403 } 404 } 405 406 if (locale == null) { 407 locale = (Locale) pageContext.getAttribute(HitFilter.LOCALE_ATTRIBUTE, 408 PageContext.REQUEST_SCOPE); 409 } 410 411 en = pageContext.getAttributeNamesInScope(PageContext.REQUEST_SCOPE); 412 413 while (locale == null && en.hasMoreElements()) { 414 Object obj = pageContext.getAttribute((String ) en.nextElement(), 415 PageContext.REQUEST_SCOPE); 416 417 if (obj instanceof Locale) { 418 locale = (Locale) obj; 419 } 420 } 421 422 if (locale == null) { 423 locale = pageContext.getRequest().getLocale(); 424 } 425 426 if (locale == null) { 427 locale = Locale.getDefault(); 428 } 429 430 return locale; 431 } 432 433 439 public static ResourceBundle getPageResourceBundle(PageContext pageContext) { 440 Enumeration en = pageContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE); 441 442 while (en.hasMoreElements()) { 443 Object obj = pageContext.getAttribute((String ) en.nextElement()); 444 445 if (obj instanceof ResourceBundle) { 446 return (ResourceBundle) obj; 447 } else if (obj instanceof javax.servlet.jsp.jstl.fmt.LocalizationContext) { 448 return ((javax.servlet.jsp.jstl.fmt.LocalizationContext) obj).getResourceBundle(); 449 } 450 } 451 452 en = pageContext.getAttributeNamesInScope(PageContext.REQUEST_SCOPE); 453 454 while (en.hasMoreElements()) { 455 Object obj = pageContext.getAttribute((String ) en.nextElement(), 456 PageContext.REQUEST_SCOPE); 457 458 if (obj instanceof ResourceBundle) { 459 return (ResourceBundle) obj; 460 } else if (obj instanceof javax.servlet.jsp.jstl.fmt.LocalizationContext) { 461 return ((javax.servlet.jsp.jstl.fmt.LocalizationContext) obj).getResourceBundle(); 462 } 463 } 464 465 return null; 466 } 467 468 472 public static String fixFileName(String name, boolean useSpacers) { 473 name = name.trim(); 474 StringBuffer sb = new StringBuffer (name.length()); 475 boolean addSpacer = false; 476 char spacer = FN_SPACERS.charAt(0); 477 char c; 478 479 for (int i = 0; i < name.length(); i++) { 480 c = name.charAt(i); 481 482 if (c < 256) { 483 c = FN_CHARMAP.charAt(c); 484 } else { 485 c = spacer; 486 } 487 488 if (FN_SPACERS.indexOf(c) < 0) { if (addSpacer) { if (useSpacers && sb.length() > 0) { sb.append(spacer); 492 } 493 494 addSpacer = false; 495 } 496 497 sb.append(c); 498 } else { 499 addSpacer = true; } 501 } 502 503 while(sb.length() > 0 && sb.charAt(sb.length() - 1) == '.') { 504 sb.deleteCharAt(sb.length() - 1); 505 } 506 507 if (sb.length() == 0) { 508 sb.append(spacer); 509 } 510 511 return sb.toString(); 512 } 513 514 518 public static String formatFileLength(long length, Locale locale, 519 ResourceBundle bundle) { 520 NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); 521 DecimalFormat format = (DecimalFormat) numberFormat; 522 format.applyPattern("###0.##"); 523 double num = length; 524 String unit; 525 526 if (length < Utils.KBYTE) { 527 unit = "genericUnitBytes"; 528 } else if (length < Utils.MBYTE) { 529 num /= Utils.KBYTE; 530 unit = "genericUnitKilobytes"; 531 } else if (length < Utils.GBYTE) { 532 num /= Utils.MBYTE; 533 unit = "genericUnitMegabytes"; 534 } else { 535 num /= Utils.GBYTE; 536 unit = "genericUnitGigabytes"; 537 } 538 539 return format.format(num) + bundle.getString(unit); 540 } 541 542 public static String getCharsetCanonicalName(String charsetName) { 543 Charset suggestedCharset; 544 545 try { 546 suggestedCharset = Charset.forName(charsetName); 547 charsetName = suggestedCharset.name(); 548 } catch (Exception ex) {} 549 550 return charsetName; 551 } 552 553 public static String parseCharset(String fullValue) { 554 try { 555 return new MimeType(fullValue).getParameter("charset"); 556 } catch (MimeTypeParseException ex) { 557 return null; 558 } 559 } 560 561 public static void updateLastModifiedTime(HttpServletRequest request, File file) { 562 updateLastModifiedTime(request, file.lastModified()); 563 } 564 565 public static void updateLastModifiedTime(HttpServletRequest request, long time) { 566 if (time > getLastModifiedTime(request)) { 567 request.setAttribute(HitFilter.LAST_MODIFIED_ATTRIBUTE, new Long (time)); 568 } 569 } 570 571 public static long getLastModifiedTime(HttpServletRequest request) { 572 long time = 0L; 573 574 try { 575 time = ((Long ) request.getAttribute(HitFilter.LAST_MODIFIED_ATTRIBUTE)).longValue(); 576 } catch (Exception ex) {} 577 578 return time; 579 } 580 581 public static javax.mail.Session getMailSession(WebSite webSite) { 582 Properties props = new Properties(); 583 props.put("mail.smtp.host", webSite.getConfiguration().getMailServer()); 584 final String smtpUsername = webSite.getConfiguration().getSmtpUsername(); 585 final String smtpPassword = webSite.getConfiguration().getSmtpPassword(); 586 587 if (!Utils.isNullOrWhitespace(smtpUsername)) { 588 props.put("mail.smtp.auth", "true"); 589 } 590 591 javax.mail.Session mailSession = javax.mail.Session.getInstance(props, 592 new javax.mail.Authenticator () { 593 protected javax.mail.PasswordAuthentication getPasswordAuthentication() { 594 return new javax.mail.PasswordAuthentication (smtpUsername, smtpPassword); 595 } 596 }); 597 598 return mailSession; 599 } 600 601 public static File getCacheFile(WebSite webSite, SiteMap siteMap, Path pagePath) { 602 if (siteMap == null) { 603 siteMap = webSite.getSiteMap(); 604 } 605 606 pagePath = siteMap.getServedPath(pagePath); 607 File cacheFile = webSite.getRepositoryFile(pagePath, HitFilter.CACHE_FILE_NAME); 608 if (cacheFile.exists() && cacheFile.length() > 256 && 610 cacheFile.lastModified() > siteMap.getLastModified()) { 611 return cacheFile; 612 } 613 614 return null; 615 } 616 617 public static boolean isCached(WebSite webSite, SiteMap siteMap, Path pagePath) { 618 if (siteMap == null) { 619 siteMap = webSite.getSiteMap(); 620 } 621 622 int cacheType = webSite.getConfiguration().getCacheType(); 623 pagePath = siteMap.getServedPath(pagePath); 624 625 if (cacheType == Configuration.IN_MEMORY_CACHE) { 626 return siteMap.isCached(pagePath); 627 } else if (cacheType == Configuration.ON_DISK_CACHE) { 628 return getCacheFile(webSite, siteMap, pagePath) != null; 629 } 630 631 return false; 632 } 633 634 public static void removeFromCache(WebSite webSite, SiteMap siteMap, Path pagePath) { 635 if (siteMap == null) { 636 siteMap = webSite.getSiteMap(); 637 } 638 639 int cacheType = webSite.getConfiguration().getCacheType(); 640 pagePath = siteMap.getServedPath(pagePath); 641 642 if (cacheType == Configuration.IN_MEMORY_CACHE) { 643 siteMap.removeFromCache(pagePath); 644 } else if (cacheType == Configuration.ON_DISK_CACHE) { 645 File cacheFile = getCacheFile(webSite, siteMap, pagePath); 646 647 if (cacheFile != null && cacheFile.exists()) { 648 Utils.forceDelete(cacheFile); 649 } 650 } 651 } 652 653 656 public static String encodeHTML(String html) { 657 return Utils.encodeHTML(html); 658 } 659 660 public static Path getCorrespondingPath(WebSite webSite, Path path, 661 String otherRoot) { 662 Path cPath = path.replace(0, otherRoot); 663 return webSite.getFile(cPath).exists() ? cPath : new Path(otherRoot); 664 } 665 666 public static String [] getAcceptedLanguages(HttpServletRequest request) { 667 Enumeration alEnum = request.getHeaders("Accept-Language"); 668 List list = new ArrayList(); 669 670 while (alEnum.hasMoreElements()) { 671 String s = (String ) alEnum.nextElement(); 672 StringTokenizer st = new StringTokenizer(s, ","); 673 674 while (st.hasMoreTokens()) { 675 String token = st.nextToken(); 676 int sc = token.indexOf(';'); 677 678 if (sc >= 0) { 679 token = token.substring(0, sc); 680 } 681 682 token = token.trim(); 683 token = Utils.replace(token, '-', "_"); 684 685 if (!list.contains(token)) { 686 list.add(token); 687 } 688 } 689 } 690 691 int n = list.size(); 694 695 for (int i = 0; i < n; i++) { 696 String token = (String ) list.get(i); 697 int us = token.indexOf('_'); 698 699 if (us >= 0) { 700 token = token.substring(0, us); 701 702 if (!list.contains(token)) { 703 list.add(token); 704 } 705 } 706 } 707 708 return (String []) list.toArray(new String [list.size()]); 709 } 710 } 711 | Popular Tags |