KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > meshcms > core > WebUtils


1 /*
2  * MeshCMS - A simple CMS based on SiteMesh
3  * Copyright (C) 2004-2007 Luciano Vernaschi
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  *
19  * You can contact the author at http://www.cromoteca.com
20  * and at info@cromoteca.com
21  */

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 /**
39  * A collection of utilities related to a web application.
40  */

41 public final class WebUtils {
42   public static final SimpleDateFormat numericDateFormatter =
43       new SimpleDateFormat("yyyyMMddHHmmss");
44
45   /**
46    * Characters allowed in a file name.
47    */

48   public static final String JavaDoc FN_CHARS =
49       "'()-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
50
51   /**
52    * Mapping of the ISO-8859-1 characters to characters included in FN_CHARS.
53    */

54   public static final String JavaDoc 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   /**
65    * Characters that are considered spacers in a file name.
66    */

67   public static final String JavaDoc FN_SPACERS = "_!'()-";
68
69   /**
70    * The default array of welcome file names. This array is used if the welcome
71    * file names can't be found in the web.xml configuration file.
72    */

73   public static final String JavaDoc[] 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 JavaDoc[] 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 JavaDoc convertToHTMLEntities(String JavaDoc s, boolean encodeTags) {
155     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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 JavaDoc 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 == 38 || */ 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   /**
180    * Parses the web.xml configuration file and returns an array of welcome file
181    * names. If the names can't be found, {@link #DEFAULT_WELCOME_FILES} is
182    * returned.
183    *
184    * @param sc ServletContext required to access the <code>web.xml</code> file
185    * @return an array of welcome file names
186    */

187   public static String JavaDoc[] getWelcomeFiles(ServletContext sc) {
188     File webXml = new File(sc.getRealPath("/WEB-INF/web.xml"));
189     String JavaDoc[] 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 JavaDoc[wfnl.getLength()];
200
201       for (int i = 0; i < welcomeFiles.length; i++) {
202         welcomeFiles[i] = wfnl.item(i).getFirstChild().getNodeValue();
203       }
204     } catch (Exception JavaDoc 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   /**
216    * @return a request parameter in the form <code>&name=value</code>. Returns
217    * null if the value has not been found.
218    */

219   public static String JavaDoc getFullParameter(HttpServletRequest request, String JavaDoc name) {
220     String JavaDoc value = request.getParameter(name);
221     return (value == null) ? "" : "&" + name + "=" + value;
222   }
223
224   /**
225    * @return the full context path of the given path.
226    */

227   public static String JavaDoc getPathInContext(HttpServletRequest request, Path path) {
228     return request.getContextPath() + "/" + path;
229   }
230
231   /**
232    * Reconstructs the full URL of the request.
233    *
234    * @deprecated with no replacement since it uses request.getRequestURL()
235    */

236   public static String JavaDoc getFullRequestURL(HttpServletRequest request) {
237     StringBuffer JavaDoc sb = request.getRequestURL();
238     String JavaDoc qs = request.getQueryString();
239
240     if (!Utils.isNullOrEmpty(qs)) {
241       sb.append('?').append(qs);
242     }
243
244     return sb.toString();
245   }
246
247   /**
248    * Reconstructs the full URL of the context home. The URL is returned as a
249    * StringBuffer so other elements can be added easily.
250    */

251   public static StringBuffer JavaDoc getContextHomeURL(HttpServletRequest request) {
252     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
253     String JavaDoc 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   /**
267    * @return the complete path of the folder of current theme (context
268    * path included).
269    *
270    * @param request used to get the theme name
271    */

272   public static String JavaDoc 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   /**
280    * @return the complete path of the <code>main.jsp</code> file (context
281    * path included).
282    *
283    * @param request used to get the theme name
284    */

285   public static String JavaDoc getFullThemeFile(HttpServletRequest request) {
286     return getFullThemeFolder(request) + "/" + SiteMap.THEME_DECORATOR;
287   }
288
289   /**
290    * @return the complete path of the <code>main.css</code> file (context
291    * path included).
292    *
293    * @param request used to get the theme name
294    */

295   public static String JavaDoc getFullThemeCSS(HttpServletRequest request) {
296     return getFullThemeFolder(request) + "/" + SiteMap.THEME_CSS;
297   }
298
299   /**
300    * @return the complete path of the <code>meshcms.css</code> file (context
301    * path included). If <code>meshcms.css</code> is not found in the theme
302    * folder, the default from the admin theme is returned.
303    *
304    * @param request used to get the theme name
305    */

306   public static String JavaDoc 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   /**
318    * @return a numeric code for an object. This code is used in the menu, but
319    * can be used elsewhere if needed. It is equal to the hash code of the
320    * object, but never negative, since the minus sign creates problems when
321    * converted to a string and used as part of a variable name in JavaScript.
322    */

323   public static int getMenuCode(Object JavaDoc o) {
324     return o.hashCode() & 0x7FFFFFFF;
325   }
326
327   /**
328    * @return the 2nd level domain from which the request comes.
329    */

330   public static String JavaDoc get2ndLevelDomain(HttpServletRequest request) {
331     return get2ndLevelDomain(request.getRequestURL().toString());
332   }
333
334   /**
335    * @return the 2nd level domain from the URL.
336    */

337   public static String JavaDoc get2ndLevelDomain(String JavaDoc urlString) {
338     try {
339       URL url = new URL(urlString);
340       String JavaDoc host = url.getHost();
341       int dot = host.lastIndexOf('.');
342
343       if (dot != -1) {
344         String JavaDoc 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 JavaDoc ex) {}
354
355     return null;
356   }
357
358   /**
359    * This method must be called to avoid the current page to be cached. For
360    * example, some modules will call this method to be sure that they
361    * are parsed again when the page is called another time.
362    */

363   public static void setBlockCache(HttpServletRequest request) {
364     request.setAttribute(HitFilter.BLOCK_CACHE_ATTRIBUTE,
365         HitFilter.BLOCK_CACHE_ATTRIBUTE);
366   }
367
368   /**
369    * Checks the current Request scope to see if some class has called the
370    * {@link #setBlockCache} method.
371    */

372   public static boolean isCacheBlocked(HttpServletRequest request) {
373     return request.getAttribute(HitFilter.BLOCK_CACHE_ATTRIBUTE) != null;
374   }
375
376   /**
377    * Tries to locate a Locale stored in the Page scope or in the Request scope.
378    * If none is found, returns the Locale of the request, or at least the
379    * system default Locale.
380    */

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 JavaDoc obj = pageContext.getAttribute((String JavaDoc) 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 JavaDoc obj = pageContext.getAttribute((String JavaDoc) 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   /**
434    * Tries to locate a ResourceBundle stored in the Page scope or in the Request
435    * scope using the JSTL.
436    *
437    * @return the ResourceBundle, or null if not found
438    */

439   public static ResourceBundle getPageResourceBundle(PageContext pageContext) {
440     Enumeration en = pageContext.getAttributeNamesInScope(PageContext.PAGE_SCOPE);
441
442     while (en.hasMoreElements()) {
443       Object JavaDoc obj = pageContext.getAttribute((String JavaDoc) 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 JavaDoc obj = pageContext.getAttribute((String JavaDoc) 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   /**
469    * @return a modified name that does not contain characters not recommended
470    * in a file name.
471    */

472   public static String JavaDoc fixFileName(String JavaDoc name, boolean useSpacers) {
473     name = name.trim();
474     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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) { // not a spacer
489
if (addSpacer) { // needs to add a spacer due to previous characters
490
if (useSpacers && sb.length() > 0) { // add a spacer only if not as first char
491
sb.append(spacer);
492           }
493
494           addSpacer = false;
495         }
496
497         sb.append(c);
498       } else {
499         addSpacer = true; // it's a spacer, will be added next if needed
500
}
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   /**
515    * @return a nicer representation of the number as a file length. The number
516    * is returned as bytes, kilobytes or megabytes, with the unit attached.
517    */

518   public static String JavaDoc 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 JavaDoc 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 JavaDoc getCharsetCanonicalName(String JavaDoc charsetName) {
543     Charset suggestedCharset;
544
545     try {
546       suggestedCharset = Charset.forName(charsetName);
547       charsetName = suggestedCharset.name();
548     } catch (Exception JavaDoc ex) {}
549
550     return charsetName;
551   }
552
553   public static String JavaDoc parseCharset(String JavaDoc 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 JavaDoc(time));
568     }
569   }
570
571   public static long getLastModifiedTime(HttpServletRequest request) {
572     long time = 0L;
573
574     try {
575       time = ((Long JavaDoc) request.getAttribute(HitFilter.LAST_MODIFIED_ATTRIBUTE)).longValue();
576     } catch (Exception JavaDoc ex) {}
577
578     return time;
579   }
580
581   public static javax.mail.Session JavaDoc getMailSession(WebSite webSite) {
582     Properties props = new Properties();
583     props.put("mail.smtp.host", webSite.getConfiguration().getMailServer());
584     final String JavaDoc smtpUsername = webSite.getConfiguration().getSmtpUsername();
585     final String JavaDoc smtpPassword = webSite.getConfiguration().getSmtpPassword();
586
587     if (!Utils.isNullOrWhitespace(smtpUsername)) {
588       props.put("mail.smtp.auth", "true");
589     }
590
591     javax.mail.Session JavaDoc mailSession = javax.mail.Session.getInstance(props,
592         new javax.mail.Authenticator JavaDoc() {
593       protected javax.mail.PasswordAuthentication JavaDoc getPasswordAuthentication() {
594         return new javax.mail.PasswordAuthentication JavaDoc(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     // a cached page too small is suspicious
609
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   /**
654    * @deprecated use {@link Utils#encodeHTML(java.lang.String)} instead.
655    */

656   public static String JavaDoc encodeHTML(String JavaDoc html) {
657     return Utils.encodeHTML(html);
658   }
659
660   public static Path getCorrespondingPath(WebSite webSite, Path path,
661       String JavaDoc otherRoot) {
662     Path cPath = path.replace(0, otherRoot);
663     return webSite.getFile(cPath).exists() ? cPath : new Path(otherRoot);
664   }
665
666   public static String JavaDoc[] getAcceptedLanguages(HttpServletRequest request) {
667     Enumeration alEnum = request.getHeaders("Accept-Language");
668     List list = new ArrayList();
669
670     while (alEnum.hasMoreElements()) {
671       String JavaDoc s = (String JavaDoc) alEnum.nextElement();
672       StringTokenizer st = new StringTokenizer(s, ",");
673
674       while (st.hasMoreTokens()) {
675         String JavaDoc 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     // add main language codes as fallback (e.g. it_IT, en, en_US becomes
692
// it_IT, en, en_US, it
693
int n = list.size();
694
695     for (int i = 0; i < n; i++) {
696       String JavaDoc token = (String JavaDoc) 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 JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
709   }
710 }
711
Popular Tags