KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > util > UtilMethods


1 /*
2  * UtilMethods.java
3  *
4  * Created on March 4, 2002, 2:56 PM
5  */

6 package com.dotmarketing.util;
7
8 import java.io.BufferedReader JavaDoc;
9 import java.io.File JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12 import java.io.LineNumberReader JavaDoc;
13 import java.io.Reader JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.net.URLEncoder JavaDoc;
16 import java.text.NumberFormat JavaDoc;
17 import java.text.SimpleDateFormat JavaDoc;
18 import java.util.ArrayList JavaDoc;
19 import java.util.Date JavaDoc;
20 import java.util.GregorianCalendar JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.NoSuchElementException JavaDoc;
26 import java.util.Random JavaDoc;
27 import java.util.Set JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29 import java.util.TimeZone JavaDoc;
30
31 import javax.servlet.http.Cookie JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33
34 import org.apache.velocity.Template;
35 import org.apache.velocity.app.Velocity;
36
37 import com.dotmarketing.beans.Host;
38 import com.dotmarketing.beans.Identifier;
39 import com.dotmarketing.beans.UserProxy;
40 import com.dotmarketing.beans.WebAsset;
41 import com.dotmarketing.cache.LiveCache;
42 import com.dotmarketing.cache.PageNotFoundCache;
43 import com.dotmarketing.cache.WorkingCache;
44 import com.dotmarketing.cms.factories.PublicUserFactory;
45 import com.dotmarketing.factories.IdentifierFactory;
46 import com.dotmarketing.factories.InodeFactory;
47 import com.dotmarketing.factories.UserProxyFactory;
48 import com.dotmarketing.factories.WebAssetFactory;
49 import com.dotmarketing.menubuilders.RefreshMenus;
50 import com.dotmarketing.portlets.categories.model.Category;
51 import com.dotmarketing.portlets.containers.model.Container;
52 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory;
53 import com.dotmarketing.portlets.contentlet.model.Contentlet;
54 import com.dotmarketing.portlets.discountcode.factories.DiscountCodeFactory;
55 import com.dotmarketing.portlets.discountcode.model.DiscountCode;
56 import com.dotmarketing.portlets.folders.factories.FolderFactory;
57 import com.dotmarketing.portlets.folders.model.Folder;
58 import com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory;
59 import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
60 import com.dotmarketing.portlets.order_manager.factories.OrderFactory;
61 import com.dotmarketing.portlets.order_manager.factories.OrderItemFactory;
62 import com.dotmarketing.portlets.order_manager.model.Order;
63 import com.dotmarketing.portlets.order_manager.model.OrderItem;
64 import com.dotmarketing.portlets.order_manager.struts.OrderForm;
65 import com.dotmarketing.portlets.order_manager.struts.OrderItemForm;
66 import com.dotmarketing.portlets.organization.model.Organization;
67 import com.dotmarketing.portlets.product.factories.ProductFactory;
68 import com.dotmarketing.portlets.product.factories.ProductFormatFactory;
69 import com.dotmarketing.portlets.product.model.Product;
70 import com.dotmarketing.portlets.product.model.ProductFormat;
71 import com.dotmarketing.services.PageServices;
72 import com.liferay.portal.model.User;
73 import com.liferay.util.Randomizer;
74
75 /**
76  * @author will
77  * @created April 23, 2002
78  */

79 public class UtilMethods {
80     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_INT_TIME = new java.text.SimpleDateFormat JavaDoc(
81             "Hmm");
82
83     private static final java.text.SimpleDateFormat JavaDoc JDBC_TO_DATE = new java.text.SimpleDateFormat JavaDoc(
84             "yyyy-M-d H:mm:ss");
85
86     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_HTML_TIME = new java.text.SimpleDateFormat JavaDoc(
87             "h:mma");
88
89     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_JS_TIME = new java.text.SimpleDateFormat JavaDoc(
90             "H:mm");
91
92     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_JDBC = new java.text.SimpleDateFormat JavaDoc(
93             "yyyy-MM-dd H:mm:ss");
94
95     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_SHORT_JDBC = new java.text.SimpleDateFormat JavaDoc(
96             "yyyy-MM-dd");
97
98     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_YEAR = new java.text.SimpleDateFormat JavaDoc(
99             "yyyy");
100
101     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_HTML_DATE = new java.text.SimpleDateFormat JavaDoc(
102             "M/d/yyyy");
103
104     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_DAY_VIEW_DATE = new java.text.SimpleDateFormat JavaDoc(
105             "MMMM d");
106
107     private static final java.text.SimpleDateFormat JavaDoc HTML_DATETIME_TO_DATE = new java.text.SimpleDateFormat JavaDoc(
108             "M/d/yyyy h:mm a");
109
110     private static final java.text.SimpleDateFormat JavaDoc HTML_DATETIME24_TO_DATE = new java.text.SimpleDateFormat JavaDoc(
111             "M/d/yyyy H:mm");
112
113     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_CONTENT_EXPIRES_DATE = new java.text.SimpleDateFormat JavaDoc(
114             "EEE, d MMM yyyy HH:mm:ss");
115
116     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_PRETTY_HTML_DATE = new java.text.SimpleDateFormat JavaDoc(
117             "EEE, MMMM d yyyy");
118
119     private static final java.util.Map JavaDoc<String JavaDoc, String JavaDoc> _CC_MAPPINGS = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
120
121     private static final java.text.SimpleDateFormat JavaDoc PIDMS_TEXT_TO_DATE = new java.text.SimpleDateFormat JavaDoc(
122             "yyyy/MM/dd h:mm a");
123
124     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_LONG_PRETTY_HTML_DATE = new java.text.SimpleDateFormat JavaDoc(
125             "EEE, d MMM yyyy hh:mm a");
126
127     private static final java.text.SimpleDateFormat JavaDoc DATE_TO_PRETTY_HTML_DATE_2 = new java.text.SimpleDateFormat JavaDoc(
128             "MMMM d, yyyy");
129
130     static {
131         _CC_MAPPINGS.put("AMEX", "American Express");
132         _CC_MAPPINGS.put("VISA", "Master Card / Visa");
133         _CC_MAPPINGS.put("CHPW-AMEX", "American Express");
134         _CC_MAPPINGS.put("CHPW-VISA-MC", "Master Card / Visa");
135     }
136
137     static HashMap JavaDoc<String JavaDoc, String JavaDoc> daysOfWeek = null;
138
139     public static final java.util.Date JavaDoc pidmsToDate(String JavaDoc d) {
140         java.text.ParsePosition JavaDoc pos = new java.text.ParsePosition JavaDoc(0);
141
142         return PIDMS_TEXT_TO_DATE.parse(d, pos);
143     }
144
145     public static final String JavaDoc join(String JavaDoc[] strArray, String JavaDoc separator) {
146         StringBuffer JavaDoc strBuff = new StringBuffer JavaDoc();
147
148         for (int k = 0; k < strArray.length; k++) {
149             strBuff.append((String JavaDoc) strArray[k]).append(separator);
150         }
151
152         return strBuff.toString();
153     }
154
155     public static final String JavaDoc getCookieValue(
156             javax.servlet.http.Cookie JavaDoc[] cookies, String JavaDoc cookieName) {
157         if (cookies != null) {
158             for (int i = 0; i < cookies.length; i++) {
159                 javax.servlet.http.Cookie JavaDoc cookie = cookies[i];
160
161                 if (cookieName.equals(cookie.getName())) {
162                     return (cookie.getValue());
163                 }
164             }
165         }
166
167         return null;
168     }
169
170     public static final Cookie JavaDoc getCookie(javax.servlet.http.Cookie JavaDoc[] cookies, String JavaDoc cookieName) {
171         if (cookies != null) {
172             for (int i = 0; i < cookies.length; i++) {
173                 javax.servlet.http.Cookie JavaDoc cookie = cookies[i];
174
175                 if (cookieName.equals(cookie.getName())) {
176                     return cookie;
177                 }
178             }
179         }
180
181         return null;
182     }
183
184     public static final String JavaDoc dateToHTMLTimeRange(java.util.Date JavaDoc x,
185             java.util.Date JavaDoc y) {
186         String JavaDoc k = dateToHTMLTime(x);
187         String JavaDoc l = dateToHTMLTime(y);
188
189         if (k.equals(l)) {
190             return k;
191         } else {
192             return k + "-" + l;
193         }
194     }
195
196     public static final boolean isImage(String JavaDoc x) {
197         if (x == null)
198             return false;
199         return (x.toLowerCase().endsWith(".gif")
200                 || x.toLowerCase().endsWith(".jpg")
201                 || x.toLowerCase().endsWith(".jpe")
202                 || x.toLowerCase().endsWith(".png")
203                 || x.toLowerCase().endsWith(".png") || x.toLowerCase()
204                 .endsWith(".jpeg"));
205     }
206
207     public static final String JavaDoc getMonthFromNow() {
208         java.util.GregorianCalendar JavaDoc cal = new java.util.GregorianCalendar JavaDoc();
209         cal.roll(java.util.Calendar.MONTH, 1);
210
211         return DATE_TO_CONTENT_EXPIRES_DATE.format(cal.getTime());
212     }
213
214     public static String JavaDoc escapeSingleQuotes(String JavaDoc fixme) {
215         fixme = fixme.replaceAll("'", "\\\\'");
216         return fixme;
217     }
218
219     public static final String JavaDoc getMonthName(int x) {
220         if ((x < 1) || (x > 12)) {
221             x = 1;
222         }
223
224         String JavaDoc[] arr = {"", "January", "February", "March", "April", "May",
225                 "June", "July", "August", "September", "October", "November",
226                 "December"};
227
228         return arr[x];
229     }
230
231     public static final String JavaDoc getNextMonthName(int month) {
232         if ((month < 1) || (month > 12)) {
233             month = 1;
234         }
235
236         String JavaDoc[] arr = {"", "February", "March", "April", "May", "June",
237                 "July", "August", "September", "October", "November",
238                 "December", "January"};
239
240         return arr[month];
241     }
242
243     public static final int getNextMonthNumber(int month) {
244         return ((month < 1) || (month > 11)) ? (month = 1) : (month + 1);
245     }
246
247     public static final String JavaDoc getPreviousMonthName(int x) {
248         if ((x < 1) || (x > 12)) {
249             x = 1;
250         }
251
252         String JavaDoc[] arr = {"", "December", "January", "February", "March",
253                 "April", "May", "June", "July", "August", "September",
254                 "October", "November"};
255
256         return arr[x];
257     }
258
259     public static final int getPreviousMonthNumber(int month) {
260         return ((month < 2) || (month > 12)) ? (month = 12) : (month - 1);
261     }
262
263     public static final boolean isSet(String JavaDoc x) {
264         if (x == null) {
265             return false;
266         }
267
268         x = x.toLowerCase();
269
270         if (x.indexOf("null") > -1) {
271             x = x.replaceAll("null", "");
272         }
273
274         return (x.trim().length() > 0);
275     }
276
277     public static final boolean isSet(java.util.Date JavaDoc x) {
278         return ((x != null) && (x.getTime() > 0));
279     }
280
281     public static final boolean isSet(Float JavaDoc x) {
282         return (x != null);
283     }
284
285     public static final boolean isSetCrumb(String JavaDoc x) {
286         return (isSet(x) && !x.equals("index"));
287     }
288
289     public static final boolean isSetHTML(String JavaDoc x) {
290         if (x == null) {
291             return false;
292         }
293
294         x = x.toLowerCase();
295         x = x.replaceAll("null", "");
296         x = x.replaceAll("<[^>]*>", "");
297         x = x.replace('\0', ' ');
298         Logger.debug(UtilMethods.class, "X:" + x + ":X");
299
300         return (x.trim().length() > 1);
301     }
302
303     public static final boolean isValidEmail(String JavaDoc email) {
304         if (email == null) {
305             return false;
306         }
307
308         return java.util.regex.Pattern.matches(
309                 "^[\\w-\\.]{1,}\\@([\\da-zA-Z-]{1,}\\.){1,}[\\da-zA-Z-]{2,3}$",
310                 email);
311     }
312
313     public static final boolean isValidURL(String JavaDoc url) {
314         if (url == null) {
315             return false;
316         }
317
318         return java.util.regex.Pattern
319                 .matches(
320                         "((http|ftp|https):\\/\\/w{3}[\\d]*.|(http|ftp|https):\\/\\/|w{3}[\\d]*.)([\\w\\d\\._\\-#\\(\\)\\[\\]\\\\,;:]+@[\\w\\d\\._\\-#\\(\\)\\[\\]\\\\,;:])?([a-z0-9]+.)*[a-z\\-0-9]+.([a-z]{2,3})?[a-z]{2,6}(:[0-9]+)?(\\/[\\/a-z0-9\\._\\-,]+)*[a-z0-9\\-_\\.\\s\\%]+(\\?[a-z0-9=%&\\.\\-,#]+)?",
321                         url);
322         // UrlValidator val = new UrlValidator();
323
// return val.isValid(url);
324

325     }
326
327     public static final boolean isValidEmail(Object JavaDoc email) {
328         if (email == null) {
329             return false;
330         }
331
332         return isValidEmail((String JavaDoc) email);
333     }
334
335     /**
336      * Description of the Method
337      *
338      * @param cmdline
339      * Description of the Parameter
340      * @return Description of the Return Value
341      */

342     public static final String JavaDoc CmdExec(String JavaDoc cmdline) {
343         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
344
345         try {
346             String JavaDoc line;
347             Process JavaDoc p = Runtime.getRuntime().exec(cmdline);
348             BufferedReader JavaDoc input = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(p
349                     .getInputStream()));
350
351             while ((line = input.readLine()) != null) {
352                 sb.append(line);
353             }
354
355             input.close();
356         } catch (Exception JavaDoc err) {
357             sb.append(err);
358         }
359
360         return sb.toString();
361     }
362
363     public static final String JavaDoc dateToDayViewDate(java.util.Date JavaDoc x) {
364         if (x == null) {
365             return "";
366         }
367
368         return DATE_TO_DAY_VIEW_DATE.format(x);
369     }
370
371     public static final String JavaDoc dateToHTMLDateTimeRange(java.util.Date JavaDoc x,
372             java.util.Date JavaDoc y, TimeZone JavaDoc tz) {
373         String JavaDoc i = dateToHTMLDate(x, tz);
374         String JavaDoc j = dateToHTMLDate(y, tz);
375         String JavaDoc k = dateToHTMLTime(x, tz);
376         String JavaDoc l = dateToHTMLTime(y, tz);
377
378         if (i.equals(j) && k.equals(l)) {
379             return i + " &nbsp; " + k;
380         } else if (i.equals(j)) {
381             return i + " &nbsp; " + k + "-" + l;
382         } else {
383             return i + " - " + j;
384         }
385     }
386
387     public static final String JavaDoc dateToHTMLDate(java.util.Date JavaDoc x) {
388         if (x == null) {
389             return "";
390         }
391         return DATE_TO_HTML_DATE.format(x);
392     }
393
394     public static final String JavaDoc dateToHTMLDate(java.util.Date JavaDoc x, String JavaDoc format) {
395         if (x == null) {
396             return "";
397         }
398         java.text.SimpleDateFormat JavaDoc mySimpleFormat = new java.text.SimpleDateFormat JavaDoc(
399                 format);
400         return mySimpleFormat.format(x);
401     }
402
403     public static final String JavaDoc dateToHTMLDate(java.util.Date JavaDoc x, TimeZone JavaDoc tz) {
404         if (x == null) {
405             return "";
406         }
407         java.text.SimpleDateFormat JavaDoc formatter = new java.text.SimpleDateFormat JavaDoc(
408                 "M/d/yyyy");
409         formatter.setTimeZone(tz);
410         return formatter.format(x);
411     }
412
413     public static final String JavaDoc dateToHTMLDateRange(java.util.Date JavaDoc x,
414             java.util.Date JavaDoc y) {
415         String JavaDoc i = dateToHTMLDate(x);
416         String JavaDoc j = dateToHTMLDate(y);
417
418         if (i.equals(j)) {
419             return i;
420         } else {
421             return i + " - " + j;
422         }
423     }
424
425     public static final String JavaDoc dateToHTMLDateRange(java.util.Date JavaDoc x,
426             java.util.Date JavaDoc y, TimeZone JavaDoc tz) {
427         String JavaDoc i = dateToHTMLDate(x, tz);
428         String JavaDoc j = dateToHTMLDate(y, tz);
429
430         if (i.equals(j)) {
431             return i;
432         } else {
433             return i + " - " + j;
434         }
435     }
436
437     public static final String JavaDoc dateToHTMLDateTimeRange(java.util.Date JavaDoc x,
438             java.util.Date JavaDoc y) {
439         String JavaDoc i = dateToHTMLDate(x);
440         String JavaDoc j = dateToHTMLDate(y);
441         String JavaDoc k = dateToHTMLTime(x);
442         String JavaDoc l = dateToHTMLTime(y);
443
444         if (i.equals(j) && k.equals(l)) {
445             return i + " &nbsp; " + k;
446         } else if (i.equals(j)) {
447             return i + " &nbsp; " + k + "-" + l;
448         } else {
449             return i + " - " + j;
450         }
451     }
452
453     public static final String JavaDoc dateToHTMLTime(java.util.Date JavaDoc x) {
454         if (x == null) {
455             return "";
456         }
457
458         return DATE_TO_HTML_TIME.format(x);
459     }
460
461     public static final String JavaDoc dateToHTMLTime(java.util.Date JavaDoc x, TimeZone JavaDoc tz) {
462         if (x == null) {
463             return "";
464         }
465
466         java.text.SimpleDateFormat JavaDoc formatter = new java.text.SimpleDateFormat JavaDoc(
467                 "h:mm a");
468         formatter.setTimeZone(tz);
469         return formatter.format(x);
470     }
471
472     public static final int dateToIntTime(java.util.Date JavaDoc x) {
473         return Integer.parseInt(DATE_TO_INT_TIME.format(x));
474     }
475
476     public static final String JavaDoc dateToJDBC(java.util.Date JavaDoc x) {
477         return DATE_TO_JDBC.format(x);
478     }
479
480     public static final String JavaDoc dateToShortJDBC(java.util.Date JavaDoc x) {
481         return DATE_TO_SHORT_JDBC.format(x);
482     }
483
484     public static final String JavaDoc dateToJSTime(java.util.Date JavaDoc x) {
485         return DATE_TO_JS_TIME.format(x);
486     }
487
488     public static final String JavaDoc dateToPrettyHTMLDate(java.util.Date JavaDoc x) {
489         if (x == null) {
490             return "";
491         }
492
493         return DATE_TO_PRETTY_HTML_DATE.format(x);
494     }
495
496     public static final String JavaDoc dateToPrettyHTMLDate(java.util.Date JavaDoc x,
497             TimeZone JavaDoc tz) {
498         if (x == null) {
499             return "";
500         }
501         java.text.SimpleDateFormat JavaDoc formatter = new java.text.SimpleDateFormat JavaDoc(
502                 "EEE, MMMM d yyyy");
503         formatter.setTimeZone(tz);
504         return formatter.format(x);
505     }
506
507     public static final String JavaDoc dateToYear(java.util.Date JavaDoc x) {
508         return DATE_TO_YEAR.format(x);
509     }
510
511     public static final String JavaDoc dollarFormat(float f) {
512         if (f == 0) {
513             return "0.00";
514         }
515
516         java.text.DecimalFormat JavaDoc cf = new java.text.DecimalFormat JavaDoc("########.00");
517
518         return cf.format(f);
519     }
520
521     /*
522      * public final static String capitalize(String var) { if (var != null &&
523      * var.length() > 1) { return var.substring(0, 1).toUpperCase() +
524      * var.substring(1); } else { return var; } }
525      */

526     public static final String JavaDoc formatter(String JavaDoc original, String JavaDoc from, String JavaDoc to) {
527         return replace(original, from, to);
528     }
529
530     public static final StringBuffer JavaDoc formatterStringBuffer(
531             StringBuffer JavaDoc original, String JavaDoc from, String JavaDoc to) {
532         return replaceStringBuffer(original, from, to);
533     }
534
535     public static final StringBuffer JavaDoc replaceStringBuffer(StringBuffer JavaDoc original,
536             String JavaDoc from, String JavaDoc to) {
537         StringBuffer JavaDoc finished = new StringBuffer JavaDoc();
538
539         if (original == null) {
540             return finished;
541         }
542
543         // This method takes a string and replaces the line feed with an
544
// html line feed
545
int start = 0;
546         int index = original.indexOf(from);
547
548         while (index != -1) {
549             finished.append(original.substring(start, index));
550             finished.append(to);
551             start = index + from.length();
552             index = original.indexOf(from, start);
553         }
554
555         finished.append(original.substring(start));
556
557         return finished;
558     }
559
560     public static final java.util.Date JavaDoc htmlDateTimeToDate(String JavaDoc d) {
561         java.util.Date JavaDoc rDate = null;
562         java.text.ParsePosition JavaDoc pos = new java.text.ParsePosition JavaDoc(0);
563         rDate = HTML_DATETIME_TO_DATE.parse(d, pos);
564
565         if (rDate == null) {
566             rDate = HTML_DATETIME24_TO_DATE.parse(d, pos);
567         }
568
569         if (rDate == null) {
570             rDate = new java.util.Date JavaDoc();
571         }
572
573         return rDate;
574     }
575
576     public static final String JavaDoc htmlLineBreak(String JavaDoc original) {
577         // This method takes a string and replaces the line feed with an
578
// html line feed
579
if (original == null) {
580             return "";
581         }
582
583         return original.replaceAll("\r", "").replaceAll("\n\n",
584                 "<BR>&nbsp;<BR>").replaceAll("\n", "<BR>");
585
586         // return original;
587
}
588
589     public static final java.util.Date JavaDoc htmlToDate(String JavaDoc d) {
590         java.util.Date JavaDoc rDate = null;
591         java.text.ParsePosition JavaDoc pos = new java.text.ParsePosition JavaDoc(0);
592         DATE_TO_HTML_DATE.setLenient(true);
593         rDate = (java.util.Date JavaDoc) DATE_TO_HTML_DATE.parse(d, pos);
594
595         // need to find non deprecaited method to do this, but it works
596
// rDate.setHours(12);
597
return rDate;
598     }
599
600     public static final java.util.Date JavaDoc jdbcToDate(String JavaDoc d) {
601         java.util.Date JavaDoc rDate = null;
602         java.text.ParsePosition JavaDoc pos = new java.text.ParsePosition JavaDoc(0);
603         rDate = JDBC_TO_DATE.parse(d, pos);
604
605         if (rDate == null) {
606             rDate = new java.util.Date JavaDoc();
607         }
608
609         return rDate;
610     }
611
612     /*
613      * Expecting a string like yyyy-MM-dd hh:mm:ss
614      *
615      */

616     public static String JavaDoc jdbcDateToHtml(String JavaDoc jdbcdate) {
617         if (!isSet(jdbcdate)) {
618             return "";
619         }
620
621         if (jdbcdate.indexOf("/") > 0) {
622             return jdbcdate;
623         }
624
625         StringBuffer JavaDoc out = new StringBuffer JavaDoc("");
626
627         if ((jdbcdate.indexOf("-") > 0)
628                 && (jdbcdate.lastIndexOf("-") > jdbcdate.indexOf("-"))) {
629             // dirty but let's make suer we have 2 dashes
630
String JavaDoc[] parts = jdbcdate.split("-");
631             String JavaDoc day = parts[2];
632
633             if (day.indexOf(" ") > 0) {
634                 day = day.substring(0, day.indexOf(" "));
635             }
636
637             out.append(parts[1]);
638             out.append("/");
639             out.append(day);
640             out.append("/");
641             out.append(parts[0]);
642         }
643
644         return out.toString();
645     }
646
647     public static final String JavaDoc obfuscateEmail(String JavaDoc email) {
648         // This method takes a string and replaces the line feed with an
649
// html line feed
650
if (email == null) {
651             return "";
652         }
653
654         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(email, "@");
655
656         if (st.countTokens() < 2) {
657             return "";
658         }
659
660         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
661         sb.append("<script>document.write('" + st.nextToken() + "');");
662         sb.append("document.write('@');");
663         sb.append("document.write('" + st.nextToken() + "');</script>");
664
665         return sb.toString();
666     }
667
668     public static final String JavaDoc obfuscateEmailHref(String JavaDoc email) {
669         // This method takes a string and replaces the line feed with an
670
// html line feed
671
if (email == null) {
672             return "";
673         }
674
675         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(email, "@");
676
677         if (st.countTokens() < 2) {
678             return "";
679         }
680
681         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
682         sb.append("<script>document.write('<a HREF=\"mailto:" + st.nextToken()
683                 + "');");
684         sb.append("document.write('@');");
685         sb.append("document.write('" + st.nextToken() + "\">');</script>");
686
687         return sb.toString();
688     }
689
690     public static final String JavaDoc obfuscateEmailHrefClass(String JavaDoc email,
691             String JavaDoc className) {
692         // This method takes a string and replaces the line feed with an
693
// html line feed
694
if (email == null) {
695             return "";
696         }
697
698         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(email, "@");
699
700         if (st.countTokens() < 2) {
701             return "";
702         }
703
704         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
705         sb.append("<script>document.write('<a HREF=\"mailto:" + st.nextToken()
706                 + "');");
707         sb.append("document.write('@');");
708         sb.append("document.write('" + st.nextToken() + "\" class=\""
709                 + className + "\">');</script>");
710
711         return sb.toString();
712     }
713
714     public static String JavaDoc prettyShortenString(String JavaDoc text, int maxLength) {
715         if (text == null) {
716             return "";
717
718         }
719         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
720         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(text, " ,-\n&()=;_", true);
721
722         while (st.hasMoreTokens()) {
723             String JavaDoc token = st.nextToken();
724
725             if ((sb.length() + token.length()) > maxLength) {
726                 sb.append("...");
727
728                 break;
729             }
730
731             sb.append(token);
732         }
733
734         return sb.toString();
735     }
736
737     public static final String JavaDoc replace(String JavaDoc original, String JavaDoc from, String JavaDoc to) {
738         if (original == null) {
739             return "";
740         }
741
742         // This method takes a string and replaces the line feed with an
743
// html line feed
744
StringBuffer JavaDoc finished = new StringBuffer JavaDoc();
745         int start = 0;
746         int index = original.indexOf(from);
747
748         while (index != -1) {
749             finished.append(original.substring(start, index));
750             finished.append(to);
751             start = index + from.length();
752             index = original.indexOf(from, start);
753         }
754
755         finished.append(original.substring(start));
756
757         return finished.toString();
758     }
759
760     public static final String JavaDoc shortenString(String JavaDoc s, int l) {
761         s = webifyString(s);
762
763         return (s.length() < l) ? s : (s.substring(0, l) + "...");
764     }
765
766     public static final boolean similarStrings(String JavaDoc a, String JavaDoc b) {
767         if (a == null) {
768             a = "";
769         }
770
771         if (b == null) {
772             b = "";
773         }
774
775         a = ((a.length() < 15) ? a : a.substring(0, 15)).replaceAll("\\W", "");
776         b = ((b.length() < 15) ? b : b.substring(0, 15)).replaceAll("\\W", "");
777
778         return a.equals(b);
779     }
780
781     public static final String JavaDoc webifyString(String JavaDoc x) {
782         if ((x == null) || x.trim().equals("") || x.trim().equals("null")) {
783             return "";
784         } else {
785             x = x.replaceAll("\"", "&quot;");
786         }
787
788         return x.trim();
789     }
790
791     public static final String JavaDoc xmlifyString(String JavaDoc x) {
792         if ((x == null) || x.trim().equals("") || x.trim().equals("null")) {
793             return "";
794         } else {
795             x = x.replaceAll("&", "and");
796             x = x.replaceAll("<", "");
797             x = x.replaceAll(">", "");
798             x = x.replaceAll("\"", "");
799             x = x.replaceAll("'", "");
800         }
801
802         return x.trim();
803     }
804
805     public static final String JavaDoc wrapLines(String JavaDoc original, int wrap) {
806         // This method takes a string and replaces the line feed with an
807
// html line feed
808
if (original == null) {
809             return "";
810         }
811
812         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
813         String JavaDoc[] words = original.split(" ");
814         int charCount = 0;
815
816         for (int i = 0; i < words.length; i++) {
817             if (words[i].indexOf("\r\n\r\n") > -1) {
818                 sb.append("<BR>&nbsp;<BR>");
819             }
820
821             sb.append(words[i] + " ");
822             charCount = charCount + words[i].length() + 1;
823
824             if (charCount > wrap) {
825                 sb.append("<BR>");
826                 charCount = 0;
827             }
828         }
829
830         return sb.toString();
831     }
832
833     public static String JavaDoc getFileExtension(String JavaDoc x) {
834         try {
835             if (x.lastIndexOf(".") != -1) {
836                 return x.substring(x.lastIndexOf(".") + 1).toLowerCase();
837             } else {
838                 return x;
839             }
840         } catch (Exception JavaDoc e) {
841             return "ukn";
842         }
843     }
844
845     public static String JavaDoc getFileName(String JavaDoc x) {
846         try {
847             if (x.lastIndexOf("/") > -1 || x.lastIndexOf("\\") > -1) {
848                 int idx = (x.lastIndexOf("/") > x.lastIndexOf("\\") ? x
849                         .lastIndexOf("/") : x.lastIndexOf("\\")) + 1;
850                 x = x.substring(idx, x.length());
851             }
852             if (x.lastIndexOf(".") != -1) {
853                 int begin = 0;
854                 if (x.lastIndexOf("/") != -1) {
855                     begin = x.lastIndexOf("/") + 1;
856                 }
857                 return x.substring(begin, x.lastIndexOf("."));
858             } else {
859                 return x;
860             }
861         } catch (Exception JavaDoc e) {
862             return "";
863         }
864     }
865
866     public static java.util.List JavaDoc getTimeList(int start, int duration) {
867         java.util.Calendar JavaDoc cal = new java.util.GregorianCalendar JavaDoc();
868         List JavaDoc<String JavaDoc> out = new ArrayList JavaDoc<String JavaDoc>();
869         cal.set(java.util.Calendar.HOUR, start);
870         cal.set(java.util.Calendar.MINUTE, 0);
871
872         if (start >= 12) {
873             cal.set(java.util.Calendar.AM_PM, java.util.Calendar.PM);
874         } else {
875             cal.set(java.util.Calendar.AM_PM, java.util.Calendar.AM);
876         }
877
878         java.text.SimpleDateFormat JavaDoc format = new java.text.SimpleDateFormat JavaDoc(
879                 "hh:mm a");
880
881         for (int i = 0; i < ((duration * 4) + 1); i++) {
882             out.add(format.format(cal.getTime()));
883             cal.add(java.util.Calendar.MINUTE, 15);
884         }
885
886         return out;
887     }
888
889     public static StringBuffer JavaDoc getURL(String JavaDoc URI) {
890         StringBuffer JavaDoc html = new StringBuffer JavaDoc();
891         html.append("");
892
893         try {
894             java.net.URL JavaDoc dbrNewsletter = new java.net.URL JavaDoc(URI);
895             java.net.URLConnection JavaDoc dbrn = dbrNewsletter.openConnection();
896             BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(dbrn
897                     .getInputStream()));
898             String JavaDoc inputLine;
899
900             while ((inputLine = in.readLine()) != null) {
901                 html.append(inputLine + "\n");
902             }
903
904             in.close();
905         } catch (Exception JavaDoc e) {
906             Logger.warn(UtilMethods.class, "Browser class failed to get page: "
907                     +URI+" - "+e, e);
908         }
909
910         return html;
911     }
912
913     public static String JavaDoc capitalize(String JavaDoc s) {
914         if (s == null) {
915             return "";
916         }
917
918         if (s.indexOf(".") > -1) {
919             s = s.substring(0, s.lastIndexOf("."));
920         }
921
922         char[] chars = s.toLowerCase().toCharArray();
923
924         // java.util.ArrayList al = new java.util.ArrayList();
925
boolean capitalNext = true;
926
927         for (int i = 0; i < chars.length; i++) {
928             char x = chars[i];
929
930             if (capitalNext) {
931                 x = Character.toUpperCase(chars[i]);
932                 capitalNext = false;
933             }
934
935             if ((x < 64) || (x > 123) || ((x > 90) && (x < 97))) {
936                 x = ' ';
937                 capitalNext = true;
938             }
939
940             chars[i] = x;
941         }
942
943         return new String JavaDoc(chars);
944     }
945
946     public static String JavaDoc capitalize(Object JavaDoc s) {
947         try {
948             return capitalize(s.toString());
949         } catch (Exception JavaDoc e) {
950             return "";
951         }
952     }
953
954     public static String JavaDoc csvifyString(String JavaDoc x) {
955         return webifyString(x).replace(',', ' ');
956     }
957
958     public static String JavaDoc htmlifyString(String JavaDoc x) {
959         return webifyString(x).replaceAll("<", "&lt;").replaceAll(">", "&gt;");
960     }
961
962     /**
963      * This method will take a url and make sure it has the protocol (http://) portion set. Pass it www.dotcms.org and it will return http://www.dotcms.org. Pass it http://www.dotcms.org and it will return http://www.dotcms.org
964      * @param x The string to check to make sure it starts with http
965      * @return The string with http:// prepended if needed
966      */

967     public static String JavaDoc httpifyString(String JavaDoc x) {
968         if (x == null) {
969             return null;
970         }
971
972         String JavaDoc testString = x.trim().toLowerCase();
973
974         if (testString.startsWith("http://")
975                 || testString.startsWith("https://")
976                 || testString.startsWith("mailto:")
977                 || testString.startsWith("ftp://")) {
978             return x;
979         } else {
980             return ("http://" + x);
981         }
982     }
983
984     public static String JavaDoc javaScriptify(String JavaDoc x) {
985         if (x == null) {
986             return "";
987         } else {
988             return x.replace('\r', ' ').replace('\n', ' ');
989         }
990     }
991
992     public static String JavaDoc javaScriptifyVariable(String JavaDoc x) {
993         if (x == null) {
994             return "";
995         } else {
996             x = x.replaceAll("[^A-Za-z0-9_]", "");
997             return x;
998         }
999     }
1000
1001    public static String JavaDoc truncatify(String JavaDoc x) {
1002        if (x.length() > 15) {
1003            java.util.StringTokenizer JavaDoc st2 = new java.util.StringTokenizer JavaDoc(x,
1004                    "_- ;,.", true);
1005            StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
1006
1007            while (st2.hasMoreTokens()) {
1008                buffer.append(st2.nextToken());
1009
1010                if (buffer.length() > 15) {
1011                    if (st2.hasMoreTokens()) {
1012                        buffer.append("...");
1013                    }
1014
1015                    break;
1016                }
1017            }
1018
1019            return buffer.toString();
1020        } else {
1021            return x;
1022        }
1023    }
1024
1025    public static String JavaDoc truncatify(String JavaDoc x, int len) {
1026        if (x.length() > len) {
1027            java.util.StringTokenizer JavaDoc st2 = new java.util.StringTokenizer JavaDoc(x,
1028                    "_- ;,.", true);
1029            StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
1030
1031            while (st2.hasMoreTokens()) {
1032                buffer.append(st2.nextToken());
1033
1034                if (buffer.length() > len) {
1035                    if (st2.hasMoreTokens()) {
1036                        buffer.append("...");
1037                    }
1038
1039                    break;
1040                }
1041            }
1042
1043            return buffer.toString();
1044        } else {
1045            return x;
1046        }
1047    }
1048
1049    public static String JavaDoc prettyByteify(long x) {
1050        String JavaDoc myBytes = "0b";
1051
1052        if (x > (1024 * 1024)) {
1053            myBytes = ((x / (1024 * 1024)) + 1) + "Mb";
1054        } else if (x > 1024) {
1055            myBytes = ((x / (1024)) + 1) + "kb";
1056        } else {
1057            myBytes = x + "b";
1058        }
1059
1060        return myBytes;
1061    }
1062
1063    public static String JavaDoc cleanURI(String JavaDoc uri) {
1064        // if we are looking for an index page
1065
if (uri.indexOf(".") < 0) {
1066            if (!uri.endsWith("/")) {
1067                uri += "/";
1068            }
1069
1070            uri += "index.html";
1071        }
1072
1073        return uri;
1074    }
1075
1076    public static String JavaDoc cleanFileSystemPathURI(String JavaDoc path) {
1077        if (path.indexOf("..") != -1 && path.indexOf("WEB-INF") != -1
1078                && path.indexOf("META-INF") != -1 && path.indexOf("!") != -1
1079                && path.indexOf(":") != -1 && path.indexOf(";") != -1
1080                && path.indexOf(";") != -1 && path.indexOf("&") != -1
1081                && path.indexOf("?") != -1 && path.indexOf("$") != -1
1082                && path.indexOf("*") != -1 && path.indexOf("\"") != -1
1083                && path.indexOf("/") != -1 && path.indexOf("[") != -1
1084                && path.indexOf("]") != -1 && path.indexOf("=") != -1
1085                && path.indexOf("|") != -1 && path.indexOf(",") != -1) {
1086            return null;
1087
1088        } else {
1089            return path;
1090
1091        }
1092
1093    }
1094
1095    public static String JavaDoc getPageChannel(String JavaDoc uri) {
1096        java.util.StringTokenizer JavaDoc st = new java.util.StringTokenizer JavaDoc(String
1097                .valueOf(uri), "/");
1098        String JavaDoc pageChannel = null;
1099
1100        if (st.hasMoreTokens()) {
1101            pageChannel = st.nextToken();
1102        }
1103
1104        return pageChannel;
1105    }
1106
1107    public static String JavaDoc espaceForVelocity(String JavaDoc text) {
1108        if (isSet(text)) {
1109            text = replace(text, "\"", "${quote}");
1110            text = replace(text, "\n", "${return}");
1111            text = replace(text, "##", "${pounds}");
1112            text = replace(text, "\r", "");
1113            text = replace(text, "’", "'");
1114            text = replace(text, "–", "-");
1115            return text.trim();
1116        }
1117
1118        return "";
1119    }
1120
1121    public static String JavaDoc escapeHTMLSpecialChars(String JavaDoc valueSt) {
1122
1123        // Standard chars
1124
valueSt = valueSt.replaceAll("&", "&amp;");
1125        // inverted exclamation mark ¡
1126
valueSt = valueSt.replaceAll("\\xA1", "&iexcl;");
1127        // cent sign ¢
1128
valueSt = valueSt.replaceAll("\\xA2", "&cent;");
1129        // pound sign £
1130
valueSt = valueSt.replaceAll("\\xA3", "&pound;");
1131        // currency sign ¤
1132
valueSt = valueSt.replaceAll("\\xA4", "&curren;");
1133        // yen sign ¥
1134
valueSt = valueSt.replaceAll("\\xA5", "&yen;");
1135        // broken bar ¦
1136
valueSt = valueSt.replaceAll("\\xA6", "&brvbar;");
1137        // section sign §
1138
valueSt = valueSt.replaceAll("\\xA7", "&sect;");
1139        // diaeresis ¨
1140
valueSt = valueSt.replaceAll("\\xA8", "&uml;");
1141        // copyright sign ©
1142
valueSt = valueSt.replaceAll("\\xA9", "&copy;");
1143        // feminine ordinal indicator ª
1144
valueSt = valueSt.replaceAll("\\xAA", "&ordf;");
1145        // left-pointing double angle quotation mark «
1146
valueSt = valueSt.replaceAll("\\xAB", "&laquo;");
1147        // not sign ¬
1148
valueSt = valueSt.replaceAll("\\xAC", "&not;");
1149        // soft hyphen ­
1150
valueSt = valueSt.replaceAll("\\xAD", "&shy;");
1151        // registered sign ®
1152
valueSt = valueSt.replaceAll("\\xAE", "&reg;");
1153        // macron ¯
1154
valueSt = valueSt.replaceAll("\\xAF", "&macr;");
1155        // degree sign °
1156
valueSt = valueSt.replaceAll("\\xB0", "&deg;");
1157        // plus-minus sign ±
1158
valueSt = valueSt.replaceAll("\\xB1", "&plusmn;");
1159        // superscript two ²
1160
valueSt = valueSt.replaceAll("\\xB2", "&sup2;");
1161        // superscript three ³
1162
valueSt = valueSt.replaceAll("\\xB3", "&sup3;");
1163        // acute accent ´
1164
valueSt = valueSt.replaceAll("\\xB4", "&acute;");
1165        // micro sign µ
1166
valueSt = valueSt.replaceAll("\\xB5", "&micro;");
1167        // pilcrow sign ¶
1168
valueSt = valueSt.replaceAll("\\xB6", "&para;");
1169        // middle dot ·
1170
valueSt = valueSt.replaceAll("\\xB7", "&middot;");
1171        // cedilla ¸
1172
valueSt = valueSt.replaceAll("\\xB8", "&cedil;");
1173        // superscript one ¹
1174
valueSt = valueSt.replaceAll("\\xB9", "&sup1;");
1175        // masculine ordinal indicator º
1176
valueSt = valueSt.replaceAll("\\xBA", "&ordm;");
1177        // right-pointing double angle quotation mark »
1178
valueSt = valueSt.replaceAll("\\xBB", "&raquo;");
1179        // vulgar fraction one quarter ¼
1180
valueSt = valueSt.replaceAll("\\xBC", "&frac14;");
1181        // vulgar fraction one half ½
1182
valueSt = valueSt.replaceAll("\\xBD", "&frac12;");
1183        // vulgar fraction three quarters ¾
1184
valueSt = valueSt.replaceAll("\\xBE", "&frac34;");
1185        // inverted question mark ¿
1186
valueSt = valueSt.replaceAll("\\xBF", "&iquest;");
1187        // latin capital letter A with grave À
1188
valueSt = valueSt.replaceAll("\\xC0", "&Agrave;");
1189        // latin capital letter A with acute Á
1190
valueSt = valueSt.replaceAll("\\xC1", "&Aacute;");
1191        // latin capital letter A with circumflex Â
1192
valueSt = valueSt.replaceAll("\\xC2", "&Acirc;");
1193        // latin capital letter A with tilde Ã
1194
valueSt = valueSt.replaceAll("\\xC3", "&Atilde;");
1195        // latin capital letter A with diaeresis Ä
1196
valueSt = valueSt.replaceAll("\\xC4", "&Auml;");
1197        // latin capital letter A with ring above Å
1198
valueSt = valueSt.replaceAll("\\xC5", "&Aring;");
1199        // latin capital letter AE Æ
1200
valueSt = valueSt.replaceAll("\\xC6", "&AElig;");
1201        // latin capital letter C with cedilla Ç
1202
valueSt = valueSt.replaceAll("\\xC7", "&Ccedil;");
1203        // latin capital letter E with grave È
1204
valueSt = valueSt.replaceAll("\\xC8", "&Egrave;");
1205        // latin capital letter E with acute É
1206
valueSt = valueSt.replaceAll("\\xC9", "&Eacute;");
1207        // latin capital letter E with circumflex Ê
1208
valueSt = valueSt.replaceAll("\\xCA", "&Ecirc;");
1209        // latin capital letter E with diaeresis Ë
1210
valueSt = valueSt.replaceAll("\\xCB", "&Euml;");
1211        // latin capital letter I with grave Ì
1212
valueSt = valueSt.replaceAll("\\xCC", "&Igrave;");
1213        // latin capital letter I with acute Í
1214
valueSt = valueSt.replaceAll("\\xCD", "&Iacute;");
1215        // latin capital letter I with circumflex Î
1216
valueSt = valueSt.replaceAll("\\xCE", "&Icirc;");
1217        // latin capital letter I with diaeresis Ï
1218
valueSt = valueSt.replaceAll("\\xCF", "&Iuml;");
1219        // latin capital letter ETH Ð
1220
valueSt = valueSt.replaceAll("\\xD0", "&ETH;");
1221        // latin capital letter N with tilde Ñ
1222
valueSt = valueSt.replaceAll("\\xD1", "&Ntilde;");
1223        // latin capital letter O with grave Ò
1224
valueSt = valueSt.replaceAll("\\xD2", "&Ograve;");
1225        // latin capital letter O with acute Ó
1226
valueSt = valueSt.replaceAll("\\xD3", "&Oacute;");
1227        // latin capital letter O with circumflex Ô
1228
valueSt = valueSt.replaceAll("\\xD4", "&Ocirc;");
1229        // latin capital letter O with tilde Õ
1230
valueSt = valueSt.replaceAll("\\xD5", "&Otilde;");
1231        // latin capital letter O with diaeresis Ö
1232
valueSt = valueSt.replaceAll("\\xD6", "&Ouml;");
1233        // multiplication sign ×
1234
valueSt = valueSt.replaceAll("\\xD7", "&times;");
1235        // latin capital letter O with stroke Ø
1236
valueSt = valueSt.replaceAll("\\xD8", "&Oslash;");
1237        // latin capital letter U with grave Ù
1238
valueSt = valueSt.replaceAll("\\xD9", "&Ugrave;");
1239        // latin capital letter U with acute Ú
1240
valueSt = valueSt.replaceAll("\\xDA", "&Uacute;");
1241        // latin capital letter U with circumflex Û
1242
valueSt = valueSt.replaceAll("\\xDB", "&Ucirc;");
1243        // latin capital letter U with diaeresis Ü
1244
valueSt = valueSt.replaceAll("\\xDC", "&Uuml;");
1245        // latin capital letter Y with acute Ý
1246
valueSt = valueSt.replaceAll("\\xDD", "&Yacute;");
1247        // latin capital letter THORN Þ
1248
valueSt = valueSt.replaceAll("\\xDE", "&THORN;");
1249        // latin small letter sharp s ß
1250
valueSt = valueSt.replaceAll("\\xDF", "&szlig;");
1251        // latin small letter a with grave à
1252
valueSt = valueSt.replaceAll("\\xE0", "&agrave;");
1253        // latin small letter a with acute á
1254
valueSt = valueSt.replaceAll("\\xE1", "&aacute;");
1255        // latin small letter a with circumflex â
1256
valueSt = valueSt.replaceAll("\\xE2", "&acirc;");
1257        // latin small letter a with tilde ã
1258
valueSt = valueSt.replaceAll("\\xE3", "&atilde;");
1259        // latin small letter a with diaeresis ä
1260
valueSt = valueSt.replaceAll("\\xE4", "&auml;");
1261        // latin small letter a with ring above å
1262
valueSt = valueSt.replaceAll("\\xE5", "&aring;");
1263        // latin small letter ae æ
1264
valueSt = valueSt.replaceAll("\\xE6", "&aelig;");
1265        // latin small letter c with cedilla ç
1266
valueSt = valueSt.replaceAll("\\xE7", "&ccedil;");
1267        // latin small letter e with grave è
1268
valueSt = valueSt.replaceAll("\\xE8", "&egrave;");
1269        // latin small letter e with acute é
1270
valueSt = valueSt.replaceAll("\\xE9", "&eacute;");
1271        // latin small letter e with circumflex ê
1272
valueSt = valueSt.replaceAll("\\xEA", "&ecirc;");
1273        // latin small letter e with diaeresis ë
1274
valueSt = valueSt.replaceAll("\\xEB", "&euml;");
1275        // latin small letter i with grave ì
1276
valueSt = valueSt.replaceAll("\\xEC", "&igrave;");
1277        // latin small letter i with acute í
1278
valueSt = valueSt.replaceAll("\\xED", "&iacute;");
1279        // latin small letter i with circumflex î
1280
valueSt = valueSt.replaceAll("\\xEE", "&icirc;");
1281        // latin small letter i with diaeresis ï
1282
valueSt = valueSt.replaceAll("\\xEF", "&iuml;");
1283        // latin small letter eth ð
1284
valueSt = valueSt.replaceAll("\\xF0", "&eth;");
1285        // latin small letter n with tilde ñ
1286
valueSt = valueSt.replaceAll("\\xF1", "&ntilde;");
1287        // latin small letter o with grave ò
1288
valueSt = valueSt.replaceAll("\\xF2", "&ograve;");
1289        // latin small letter o with acute ó
1290
valueSt = valueSt.replaceAll("\\xF3", "&oacute;");
1291        // latin small letter o with circumflex ô
1292
valueSt = valueSt.replaceAll("\\xF4", "&ocirc;");
1293        // latin small letter o with tilde õ
1294
valueSt = valueSt.replaceAll("\\xF5", "&otilde;");
1295        // latin small letter o with diaeresis ö
1296
valueSt = valueSt.replaceAll("\\xF6", "&ouml;");
1297        // division sign ÷
1298
valueSt = valueSt.replaceAll("\\xF7", "&divide;");
1299        // latin small letter o with stroke, ø
1300
valueSt = valueSt.replaceAll("\\xF8", "&oslash;");
1301        // latin small letter u with grave ù
1302
valueSt = valueSt.replaceAll("\\xF9", "&ugrave;");
1303        // latin small letter u with acute ú
1304
valueSt = valueSt.replaceAll("\\xFA", "&uacute;");
1305        // latin small letter u with circumflex û
1306
valueSt = valueSt.replaceAll("\\xFB", "&ucirc;");
1307        // latin small letter u with diaeresis ü
1308
valueSt = valueSt.replaceAll("\\xFC", "&uuml;");
1309        // latin small letter y with acute ý
1310
valueSt = valueSt.replaceAll("\\xFD", "&yacute;");
1311        // latin small letter thorn þ
1312
valueSt = valueSt.replaceAll("\\xFE", "&thorn;");
1313        // latin small letter y with diaeresis ÿ
1314
valueSt = valueSt.replaceAll("\\xFF", "&yuml;");
1315
1316        // non standards but supported by IE and Mozilla
1317

1318        // non-standard, use &sbquo; ‚
1319
valueSt = valueSt.replaceAll("\\x82", "&sbquo;");
1320        // non-standard, use &fnof; ƒ
1321
valueSt = valueSt.replaceAll("\\x83", "&fnof;");
1322        // non-standard, use &bdquo; „
1323
valueSt = valueSt.replaceAll("\\x84", "&bdquo;");
1324        // non-standard, use &hellip; …
1325
valueSt = valueSt.replaceAll("\\x85", "&hellip;");
1326        // non-standard, use &dagger; †
1327
valueSt = valueSt.replaceAll("\\x86", "&dagger;");
1328        // non-standard, use &Dagger ‡
1329
valueSt = valueSt.replaceAll("\\x87", "&Dagger;");
1330        // non-standard, use &Scaron; Š
1331
valueSt = valueSt.replaceAll("\\x8A", "&Scaron;");
1332        // non-standard, use &OElig; Œ
1333
valueSt = valueSt.replaceAll("\\x8C", "&OElig;");
1334        // unused ?
1335
valueSt = valueSt.replaceAll("\\x8D", "");
1336        // non-standard Ž
1337
valueSt = valueSt.replaceAll("\\x8E", "");
1338        // unused ?
1339
valueSt = valueSt.replaceAll("\\x8F", "");
1340        // unused ?
1341
valueSt = valueSt.replaceAll("\\x90", "");
1342        // non-standard, use &lsquo; ‘
1343
valueSt = valueSt.replaceAll("\\x91", "&lsquo;");
1344        // non-standard, use &rsquo; ’
1345
valueSt = valueSt.replaceAll("\\x92", "&rsquo;");
1346        // non-standard, use &ldquo; “
1347
valueSt = valueSt.replaceAll("\\x93", "&ldquo;");
1348        // non-standard, use &rdquo; ”
1349
valueSt = valueSt.replaceAll("\\x94", "&rdquo;");
1350        // non-standard, use &bull; •
1351
valueSt = valueSt.replaceAll("\\x95", "&bull;");
1352        // non-standard, use &ndash; –
1353
valueSt = valueSt.replaceAll("\\x96", "&ndash;");
1354        // non-standard, use &mdash; —
1355
valueSt = valueSt.replaceAll("\\x97", "&mdash;");
1356        // non-standard, use &tilde; ˜
1357
valueSt = valueSt.replaceAll("\\x98", "&tilde;");
1358        // non-standard, use &trade; ™
1359
valueSt = valueSt.replaceAll("\\x99", "&trade;");
1360        // non-standard, use &scaron; š
1361
valueSt = valueSt.replaceAll("\\x9A", "&scaron;");
1362        // non-standard, use &oelig; œ
1363
valueSt = valueSt.replaceAll("\\x9C", "&oelig;");
1364        // unused ?
1365
valueSt = valueSt.replaceAll("\\x9D", "");
1366        // unused ž
1367
valueSt = valueSt.replaceAll("\\x9E", "");
1368        // non-standard, use &Yuml; Ÿ
1369
valueSt = valueSt.replaceAll("\\x9F", "&Yuml;");
1370
1371        return valueSt;
1372    }
1373
1374    public static String JavaDoc fixBreaks(String JavaDoc fixme) {
1375        if (isSet(fixme)) {
1376            fixme = replace(fixme, "${return}", "\n");
1377            return fixme;
1378        }
1379        return "";
1380    }
1381
1382    /**
1383     * Escape quotation marks so they work in javascript fields
1384     */

1385    public static String JavaDoc escapeQuotes(String JavaDoc fixme) {
1386        String JavaDoc doubleQuote = "\"";
1387
1388        String JavaDoc singleQuote = "'";
1389        String JavaDoc escapedSingleQuote = "\\'";
1390
1391        if (fixme != null) {
1392            fixme = fixme.trim();
1393
1394            try {
1395                // first replace double quotes with single quotes
1396
fixme = fixme.replaceAll(doubleQuote, doubleQuote);
1397
1398                // now escape all the single quotes
1399
fixme = fixme.replaceAll(singleQuote, escapedSingleQuote);
1400
1401                return fixme;
1402            } catch (Exception JavaDoc e) {
1403                Logger.error(UtilMethods.class, "Could not parse string ["
1404                        + fixme + "] for escaping quotes: " + e.toString(), e);
1405                return "";
1406            }
1407        } else {
1408            return "";
1409        }
1410    }
1411
1412    /**
1413     * Escape quotation marks so they work in javascript fields
1414     */

1415    public static String JavaDoc sqlify(String JavaDoc fixme) {
1416        String JavaDoc singleQuote = "'";
1417        String JavaDoc escapedSingleQuote = "''";
1418
1419        if (fixme != null) {
1420            fixme = fixme.trim();
1421
1422            try {
1423                // now escape all the single quotes
1424
fixme = fixme.replaceAll(singleQuote, escapedSingleQuote);
1425
1426                return fixme;
1427            } catch (Exception JavaDoc e) {
1428                Logger.error(UtilMethods.class, "Could not parse string ["
1429                        + fixme + "] for escaping single quotes: "
1430                        + e.toString(), e);
1431                return "";
1432            }
1433        } else {
1434            return "";
1435        }
1436    }
1437
1438    public static boolean inString(String JavaDoc haystack, String JavaDoc needle) {
1439        if ((haystack == null) || (needle == null)) {
1440            return false;
1441        }
1442
1443        return (haystack.indexOf(needle) > -1);
1444    }
1445
1446    public static String JavaDoc dayify(String JavaDoc x) {
1447        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1448
1449        if (daysOfWeek == null) {
1450            daysOfWeek = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1451            daysOfWeek.put("M", "Monday");
1452            daysOfWeek.put("T", "Tuesday");
1453            daysOfWeek.put("W", "Wednesday");
1454            daysOfWeek.put("R", "Thursday");
1455            daysOfWeek.put("F", "Friday");
1456            daysOfWeek.put("S", "Saturday");
1457            daysOfWeek.put("&", "Sunday");
1458        }
1459
1460        if (x.indexOf("ARR") > -1) {
1461            return "to be arranged";
1462        }
1463
1464        char[] chrs = x.toCharArray();
1465
1466        for (int i = 0; i < chrs.length; i++) {
1467            if (daysOfWeek.get(String.valueOf(chrs[i])) != null) {
1468                if (sb.length() > 0)
1469                    sb.append(", ");
1470                sb.append(daysOfWeek.get(String.valueOf(chrs[i])));
1471            }
1472        }
1473
1474        return sb.toString();
1475    }
1476
1477    static final String JavaDoc[] MONTH_NAME = {"Jan", "Feb", "Mar", "Apr", "May",
1478            "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
1479
1480    public static String JavaDoc getShortMonthName(int month) {
1481        try {
1482            return MONTH_NAME[month];
1483        } catch (Exception JavaDoc e) {
1484            return "";
1485        }
1486    }
1487
1488    public static String JavaDoc getShortMonthName(String JavaDoc month) {
1489        try {
1490            return MONTH_NAME[Integer.parseInt(month)];
1491        } catch (Exception JavaDoc e) {
1492            return "";
1493        }
1494    }
1495
1496    public static boolean isUrlLive(String JavaDoc url, Host host) {
1497        return isUrlLive(url, host.getInode());
1498    }
1499
1500    public static boolean isUrlLive(String JavaDoc url, long hostId) {
1501        return (LiveCache.getPathFromCache(url, hostId) != null);
1502    }
1503
1504    public static boolean isUrlPreview(String JavaDoc url, Host host) {
1505        return isUrlPreview(url, host.getInode());
1506    }
1507
1508    public static boolean isUrlPreview(String JavaDoc url, long hostId) {
1509        return (WorkingCache.getPathFromCache(url, hostId) != null);
1510    }
1511
1512    public static String JavaDoc stripUnicode(String JavaDoc x) {
1513        return (x == null) ? x : x.replaceAll("([^\000-\177áéíóúÁÉÍÓÚñÑÇç€])",
1514                " ");
1515
1516    }
1517
1518    public static String JavaDoc obfuscateCreditCard(String JavaDoc ccnum) {
1519        if (ccnum != null && ccnum.length() > 4) {
1520            ccnum = ccnum.substring(ccnum.length() - 4, ccnum.length());
1521            ccnum = "************" + ccnum;
1522            return ccnum;
1523        }
1524        return "";
1525    }
1526
1527    /**
1528     * Special split function, to split csv files exported from access
1529     *
1530     * @param reader
1531     * The file reader
1532     * @param delim
1533     * The columns delimiter
1534     * @param textQualifier
1535     * The text qualifier string
1536     * @return A list of list with the list of lines splitted on columns
1537     * @throws IOException
1538     */

1539    public static List JavaDoc specialSplit(LineNumberReader JavaDoc reader, String JavaDoc delim,
1540            String JavaDoc textQualifier) throws IOException JavaDoc {
1541        ArrayList JavaDoc<String JavaDoc[]> ret = new ArrayList JavaDoc<String JavaDoc[]>();
1542        String JavaDoc text = "";
1543        while ((text = reader.readLine()) != null) {
1544            ArrayList JavaDoc<String JavaDoc> tokens = new ArrayList JavaDoc<String JavaDoc>();
1545            StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(text, delim, true);
1546            boolean delimFound = false;
1547            String JavaDoc lastToken = "";
1548            try {
1549                while (true) {
1550                    String JavaDoc nt = tok.nextToken(delim);
1551                    lastToken = nt;
1552                    if (nt.equals(textQualifier)) {
1553                        delimFound = false;
1554                        continue;
1555                    }
1556                    if (nt.equals(",") && delimFound) {
1557                        tokens.add("");
1558                        continue;
1559                    } else if (nt.equals(",")) {
1560                        delimFound = true;
1561                        continue;
1562                    } else {
1563                        delimFound = false;
1564                    }
1565                    if (nt.trim().startsWith(textQualifier)
1566                            && (!nt.trim().endsWith(textQualifier))) {
1567                        boolean endFound = false;
1568                        while (!endFound) {
1569                            try {
1570                                nt += tok.nextToken(textQualifier);
1571                                if (nt.trim().endsWith("\""))
1572                                    endFound = true;
1573                            } catch (NoSuchElementException JavaDoc e) {
1574                                text = reader.readLine();
1575                                if (text == null)
1576                                    endFound = true;
1577                                tok = new StringTokenizer JavaDoc(text, delim, true);
1578                            }
1579                        }
1580                    }
1581                    nt = nt.trim();
1582                    if (nt.startsWith(textQualifier))
1583                        nt = nt.substring(textQualifier.length(), nt.length());
1584                    if (nt.endsWith(textQualifier))
1585                        nt = nt.substring(0, nt.length()
1586                                - textQualifier.length());
1587                    nt = nt.trim();
1588                    tokens.add(nt);
1589                }
1590            } catch (NoSuchElementException JavaDoc e) {
1591                if (lastToken.equals(delim))
1592                    tokens.add("");
1593            }
1594            String JavaDoc[] values = (String JavaDoc[]) tokens.toArray(new String JavaDoc[0]);
1595            ret.add(values);
1596        }
1597        return ret;
1598    }
1599
1600    public static final String JavaDoc dateToLongPrettyHTMLDate(java.util.Date JavaDoc x) {
1601        if (x == null) {
1602            return "";
1603        }
1604        return DATE_TO_LONG_PRETTY_HTML_DATE.format(x);
1605    }
1606
1607    public static final boolean hasValue(String JavaDoc selectedValues, String JavaDoc value) {
1608        String JavaDoc[] values = selectedValues.split(",");
1609        for (String JavaDoc val : values) {
1610            if (val.trim().equals(value))
1611                return true;
1612        }
1613        return false;
1614    }
1615
1616    public static final String JavaDoc convertToNumbers(String JavaDoc st) {
1617        String JavaDoc result = "";
1618        for (int i = 0; i < st.length(); i++) {
1619            if (Character.isDigit(st.charAt(i)))
1620                result += st.charAt(i);
1621        }
1622        return result;
1623    }
1624
1625    public static final String JavaDoc convertToFolderName(String JavaDoc st) {
1626        return st.replaceAll("\\/", "_");
1627    }
1628
1629    public static String JavaDoc encodeURL(String JavaDoc url) {
1630        try {
1631            return URLEncoder.encode(url, "UTF-8");
1632        } catch (Exception JavaDoc e) {
1633        }
1634        return "";
1635    }
1636
1637    public static boolean revomeDir(String JavaDoc path) {
1638        File JavaDoc dir = new File JavaDoc(path);
1639        if (!dir.isDirectory()) {
1640            return false;
1641        }
1642        File JavaDoc[] children = dir.listFiles();
1643        for (File JavaDoc child : children) {
1644            boolean ok = true;
1645            if (child.isDirectory())
1646                ok = revomeDir(child.getAbsolutePath());
1647            if (ok)
1648                ok = child.delete();
1649            if (!ok)
1650                return ok;
1651        }
1652
1653        return dir.delete();
1654    }
1655
1656    // Liferay users utility methods
1657
public static String JavaDoc getUserFullName(String JavaDoc userId) {
1658        User usr = PublicUserFactory.findUserByUserId(userId);
1659        if (usr == null)
1660            return userId;
1661        if (!isSet(usr.getFirstName()) || !isSet(usr.getLastName()))
1662            return usr.getEmailAddress();
1663        return usr.getFullName();
1664    }
1665
1666    public static String JavaDoc getUserEmailAddress(String JavaDoc userId) {
1667        User usr = PublicUserFactory.findUserByUserId(userId);
1668        if (usr == null)
1669            return "none";
1670        return usr.getEmailAddress();
1671    }
1672
1673    public static String JavaDoc getValidDirectoryName(String JavaDoc phrase) {
1674        if (phrase == null) {
1675            return null;
1676        }
1677        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1678        char[] chars = phrase.toCharArray();
1679        for (int i = 0; i < chars.length; i++) {
1680            char x = chars[i];
1681
1682            if ((x > 64 && x < 91) || (x > 96 && x < 123) || (x > 47 && x < 58)) {
1683                sb.append(x);
1684            }
1685            if (x == 32) {
1686                sb.append('_');
1687            }
1688
1689        }
1690        return sb.toString().toLowerCase();
1691    }
1692
1693    public static boolean isInt(String JavaDoc intString) {
1694        try {
1695            Integer.parseInt(intString);
1696            return true;
1697        } catch (Exception JavaDoc ex) {
1698            return false;
1699        }
1700    }
1701
1702    public static Date JavaDoc addDate(Date JavaDoc date, int amount, int field) {
1703        GregorianCalendar JavaDoc gc = new GregorianCalendar JavaDoc();
1704        gc.setTime(date);
1705        gc.add(field, amount);
1706        return gc.getTime();
1707    }
1708
1709    public static Date JavaDoc addDays(Date JavaDoc date, int amount) {
1710        int field = GregorianCalendar.DAY_OF_MONTH;
1711        GregorianCalendar JavaDoc gc = new GregorianCalendar JavaDoc();
1712        gc.setTime(date);
1713        gc.add(field, amount);
1714        return gc.getTime();
1715    }
1716
1717    public static String JavaDoc elapsedTimeToString(long milliseconds) {
1718
1719        String JavaDoc time = "";
1720
1721        long seconds = milliseconds / 1000;
1722        if (seconds > 0) {
1723            String JavaDoc sec;
1724            sec = "" + (seconds % 60) + "s";
1725            String JavaDoc min;
1726            if (seconds > 60) {
1727                min = "" + (seconds / 60 % 60) + "m";
1728            } else {
1729                min = "";
1730            }
1731            String JavaDoc hours;
1732            if (seconds / 60 > 60) {
1733                hours = "" + (seconds / 60 / 60) + "h";
1734            } else {
1735                hours = "";
1736            }
1737
1738            time = "" + hours + " " + min + " " + sec;
1739
1740        } else {
1741            time = "0 s";
1742        }
1743        return time;
1744    }
1745
1746    /**
1747     * Special split function, to split csv files exported from access, excel, ...
1748     * @param reader
1749     * @param delim
1750     * @param textQualifier
1751     * @return
1752     * @throws IOException
1753     */

1754    public static List JavaDoc<String JavaDoc[]> specialSplit(Reader JavaDoc reader, char delim,
1755            char textQualifier) throws IOException JavaDoc {
1756        List JavaDoc<String JavaDoc[]> ret = new ArrayList JavaDoc<String JavaDoc[]>();
1757
1758        List JavaDoc<String JavaDoc> lineFields = new ArrayList JavaDoc<String JavaDoc>();
1759        StringBuffer JavaDoc fieldBuffer = new StringBuffer JavaDoc();
1760        boolean end = false;
1761        boolean insideTextQualifiers = false;
1762        int nextRead = reader.read();
1763        int read = -1;
1764        while (!end) {
1765            read = nextRead;
1766            nextRead = reader.read();
1767            if (read == -1) {
1768                end = true;
1769            }
1770            if (!end) {
1771                char charRead = (char) read;
1772                char nextCharRead = (char) nextRead;
1773                if (charRead == textQualifier && nextCharRead != textQualifier
1774                        && !insideTextQualifiers)
1775                    insideTextQualifiers = true;
1776                else if (charRead == textQualifier
1777                        && nextCharRead != textQualifier
1778                        && insideTextQualifiers) {
1779                    insideTextQualifiers = false;
1780                } else if (charRead == textQualifier
1781                        && nextCharRead == textQualifier
1782                        && insideTextQualifiers) {
1783                    fieldBuffer.append(charRead);
1784                    nextRead = reader.read();
1785                } else if (!insideTextQualifiers && charRead == delim) {
1786                    lineFields.add(fieldBuffer.toString());
1787                    fieldBuffer = new StringBuffer JavaDoc();
1788                } else if (!insideTextQualifiers
1789                        && ((charRead == '\r' && nextCharRead == '\n') || charRead == '\n')) {
1790                    lineFields.add(fieldBuffer.toString());
1791                    fieldBuffer = new StringBuffer JavaDoc();
1792                    ret.add(lineFields.toArray(new String JavaDoc[0]));
1793                    lineFields = new ArrayList JavaDoc<String JavaDoc>();
1794                    if (charRead == '\r')
1795                        nextRead = reader.read();
1796                } else
1797                    fieldBuffer.append(charRead);
1798
1799            } else {
1800                if (lineFields.size() > 0) {
1801                    ret.add(lineFields.toArray(new String JavaDoc[0]));
1802                }
1803            }
1804        }
1805
1806        return ret;
1807    }
1808
1809    public static Folder getParentFolder(String JavaDoc childPath, Host host) {
1810        Folder childFolder = FolderFactory.getFolderByPath(childPath, host);
1811        return (Folder) InodeFactory
1812                .getParentOfClass(childFolder, Folder.class);
1813    }
1814
1815    /**
1816     * Compares if two dates (yyyy/MM/dd)) have equals values
1817     * @param date1 Actual date
1818     * @param date2 Date to be Compared
1819     * @return int 0 if but dates are equals, less than 0 if date1 is before date2, and more than 0 if date1 id after date2
1820     */

1821    public static int compareDates(Date JavaDoc date1, Date JavaDoc date2) {
1822
1823        GregorianCalendar JavaDoc cal1 = new GregorianCalendar JavaDoc();
1824        cal1.set(GregorianCalendar.DAY_OF_MONTH, date1.getDate());
1825        cal1.set(GregorianCalendar.MONTH, date1.getMonth());
1826        cal1.set(GregorianCalendar.YEAR, date1.getYear());
1827        cal1.set(GregorianCalendar.HOUR_OF_DAY, 0);
1828        cal1.set(GregorianCalendar.MINUTE, 0);
1829        cal1.set(GregorianCalendar.SECOND, 0);
1830        cal1.set(GregorianCalendar.MILLISECOND, 0);
1831
1832        GregorianCalendar JavaDoc cal2 = new GregorianCalendar JavaDoc();
1833        cal2.set(GregorianCalendar.DAY_OF_MONTH, date2.getDate());
1834        cal2.set(GregorianCalendar.MONTH, date2.getMonth());
1835        cal2.set(GregorianCalendar.YEAR, date2.getYear());
1836        cal2.set(GregorianCalendar.HOUR_OF_DAY, 0);
1837        cal2.set(GregorianCalendar.MINUTE, 0);
1838        cal2.set(GregorianCalendar.SECOND, 0);
1839        cal2.set(GregorianCalendar.MILLISECOND, 0);
1840        Logger.debug(UtilMethods.class, "cal1:" + cal1.getTime().toString()
1841                + " - cal2:" + cal2.getTime().toString());
1842        return cal1.compareTo(cal2);
1843    }
1844
1845    /**
1846     * Get the modelu of x % y
1847     * @param x dividend
1848     * @param y divisor
1849     * @return module
1850     */

1851    public static int mod(Integer JavaDoc x, Integer JavaDoc y) {
1852
1853        return x % y;
1854    }
1855
1856    public static final String JavaDoc dateToPrettyHTMLDate2(java.util.Date JavaDoc x) {
1857        if (x == null) {
1858            return "";
1859        }
1860
1861        return DATE_TO_PRETTY_HTML_DATE_2.format(x);
1862    }
1863
1864    public static final String JavaDoc dateToLongHTMLDateRange(java.util.Date JavaDoc x,
1865            java.util.Date JavaDoc y) {
1866
1867        String JavaDoc i = dateToPrettyHTMLDate2(x);
1868        String JavaDoc j = dateToPrettyHTMLDate2(y);
1869
1870        if (i.equals(j)) {
1871            return i;
1872        } else {
1873            return i + " - " + j;
1874        }
1875    }
1876
1877    public static boolean isLong(String JavaDoc longString) {
1878        try {
1879            Long.parseLong(longString);
1880            return true;
1881        } catch (Exception JavaDoc ex) {
1882            return false;
1883        }
1884    }
1885
1886    public static String JavaDoc toPriceFormat(double price) {
1887        int decimals = 2;
1888        return toXNumberFormat(price, decimals);
1889    }
1890
1891    public static String JavaDoc toPriceFormat(float price) {
1892        return toPriceFormat((double) price);
1893    }
1894
1895    public static String JavaDoc toXNumberFormat(double number, int decimals) {
1896        try {
1897            NumberFormat JavaDoc nf = NumberFormat.getInstance();
1898            nf.setMinimumFractionDigits(decimals);
1899            nf.setMaximumFractionDigits(decimals);
1900            String JavaDoc numberS = nf.format(number);
1901            return numberS;
1902        } catch (Exception JavaDoc ex) {
1903            Logger.debug(UtilMethods.class, ex.toString());
1904            return "NAN";
1905        }
1906    }
1907
1908    public static float getItemPriceWithDiscount(OrderItem orderItem,
1909            List JavaDoc<DiscountCode> discounts) {
1910        float totalDiscount = 0;
1911        for (DiscountCode discount : discounts) {
1912            if (DiscountCodeFactory._potentialDiscount(orderItem, discount)) {
1913                if (discount.getDiscountType() == 1) {
1914                    totalDiscount += (discount.getDiscountAmount() / 100)
1915                            * orderItem.getItemPrice();
1916                } else {
1917                    totalDiscount += discount.getDiscountAmount();
1918                }
1919            }
1920        }
1921        return orderItem.getItemPrice() - totalDiscount;
1922    }
1923
1924    public static float getItemPriceWithDiscount(ProductFormat productFormat,
1925            float itemPrice, List JavaDoc<DiscountCode> discounts) {
1926        float totalDiscount = 0;
1927        for (DiscountCode discount : discounts) {
1928            if (DiscountCodeFactory._potentialDiscount(productFormat, discount)) {
1929                if (discount.getDiscountType() == 1) {
1930                    totalDiscount += (discount.getDiscountAmount() / 100)
1931                            * itemPrice;
1932                } else {
1933                    totalDiscount += discount.getDiscountAmount();
1934                }
1935            }
1936        }
1937        return itemPrice - totalDiscount;
1938    }
1939
1940    public static float getItemPriceWithDiscount(OrderItemForm orderItemForm,
1941            List JavaDoc<DiscountCode> discounts) {
1942        float totalDiscount = 0;
1943        for (DiscountCode discount : discounts) {
1944            if (DiscountCodeFactory._potentialDiscount(orderItemForm, discount)) {
1945                if (discount.getDiscountType() == 1) {
1946                    totalDiscount += (discount.getDiscountAmount() / 100)
1947                            * orderItemForm.getItemPrice();
1948                } else {
1949                    totalDiscount += discount.getDiscountAmount();
1950                }
1951            }
1952        }
1953        return orderItemForm.getItemPrice() - totalDiscount;
1954    }
1955
1956    public static Product getProduct(String JavaDoc inode) {
1957        return (Product) ProductFactory.getProduct(inode);
1958    }
1959
1960    public static Product getProduct(long inode) {
1961        return (Product) ProductFactory.getProduct(inode);
1962    }
1963
1964    public static List JavaDoc<DiscountCode> getDiscountsByOrder(OrderForm orderForm) {
1965        List JavaDoc<DiscountCode> discounts = new ArrayList JavaDoc<DiscountCode>();
1966        String JavaDoc discountsString = orderForm.getDiscountCodes();
1967        if (discountsString != null) {
1968            String JavaDoc[] discountsStrings = discountsString.split(":");
1969            for (String JavaDoc discountString : discountsStrings) {
1970                discountString = discountString.trim();
1971                if (UtilMethods.isSet(discountString)) {
1972                    DiscountCode discountCode = DiscountCodeFactory
1973                            .getDiscountCodeById(discountString);
1974                    discounts.add(discountCode);
1975                }
1976            }
1977        }
1978        return discounts;
1979    }
1980
1981    public static List JavaDoc<DiscountCode> getDiscountsByOrder(Order order) {
1982        List JavaDoc<DiscountCode> discounts = new ArrayList JavaDoc<DiscountCode>();
1983        String JavaDoc discountsString = order.getDiscountCodes();
1984        if (discountsString != null) {
1985            String JavaDoc[] discountsStrings = discountsString.split(":");
1986            for (String JavaDoc discountString : discountsStrings) {
1987                discountString = discountString.trim();
1988                if (UtilMethods.isSet(discountString)) {
1989                    DiscountCode discountCode = DiscountCodeFactory
1990                            .getDiscountCodeById(discountString);
1991                    discounts.add(discountCode);
1992                }
1993            }
1994        }
1995        return discounts;
1996    }
1997
1998    public static String JavaDoc getShippingTypeName(int shippingType) {
1999
2000        String JavaDoc typeName = "";
2001        switch (shippingType) {
2002            case 0 :
2003                typeName = "Ground";
2004                break;
2005            case 1 :
2006                typeName = "Second Day";
2007                break;
2008            case 2 :
2009                typeName = "Next Day";
2010                break;
2011
2012        }
2013
2014        return typeName;
2015    }
2016
2017    public static String JavaDoc getPaymentTypeName(int paymentType) {
2018
2019        String JavaDoc typeName = "";
2020        switch (paymentType) {
2021            case 1 :
2022                typeName = "Credit Card";
2023                break;
2024            case 2 :
2025                typeName = "Check";
2026                break;
2027            case 3 :
2028                typeName = "Purchase Order";
2029                break;
2030        }
2031        return typeName;
2032    }
2033
2034    public static OrderForm loadOrderForm(HttpServletRequest JavaDoc request) {
2035        OrderForm orderForm = new OrderForm();
2036        try {
2037            String JavaDoc orderInode = request.getParameter("orderInode");
2038            //Order
2039
Order order = OrderFactory.getOrderById(orderInode);
2040            orderForm.setInode(order.getInode());
2041            orderForm.setUserInode(order.getUserInode());
2042            orderForm.setDatePosted(order.getDatePosted());
2043            orderForm.setLastModDate(order.getLastModDate());
2044            //Billing
2045
orderForm.setBillingAddress1(order.getBillingAddress1());
2046            orderForm.setBillingAddress2(order.getBillingAddress2());
2047            orderForm.setBillingCity(order.getBillingCity());
2048            orderForm.setBillingState(order.getBillingState());
2049            orderForm.setBillingZip(order.getBillingZip());
2050            orderForm.setBillingCountry(order.getBillingCountry());
2051            orderForm.setBillingPhone(order.getBillingPhone());
2052            orderForm.setBillingFax(order.getBillingFax());
2053            orderForm.setBillingContactName(order.getBillingContactName());
2054            orderForm.setBillingContactPhone(order.getBillingContactPhone());
2055            orderForm.setBillingContactEmail(order.getBillingContactEmail());
2056            //Shipping
2057
orderForm.setShippingAddress1(order.getShippingAddress1());
2058            orderForm.setShippingAddress2(order.getShippingAddress2());
2059            orderForm.setShippingCity(order.getShippingCity());
2060
2061            orderForm.setShippingState(order.getShippingState());
2062            orderForm.setShippingZip(order.getShippingZip());
2063            orderForm.setShippingCountry(order.getShippingCountry());
2064            orderForm.setShippingPhone(order.getShippingPhone());
2065            orderForm.setShippingFax(order.getShippingFax());
2066            //Payment
2067
orderForm.setOrderTotal(order.getOrderTotal());
2068            orderForm.setOrderShipping(order.getOrderShipping());
2069            orderForm.setOrderTax(order.getOrderTax());
2070            orderForm.setOrderDiscount(order.getOrderDiscount());
2071            orderForm.setOrderSubTotal(order.getOrderSubTotal());
2072            orderForm.setOrderSubTotalDiscount(order.getOrderSubTotal()
2073                    - order.getOrderDiscount());
2074            orderForm.setDiscountCodes(order.getDiscountCodes());
2075            if (order.getPaymentType().trim().equals(
2076                    Config.getStringProperty("ECOM_CREDIT_CARD"))) {
2077                //CC
2078
orderForm.setCardNumber(order.getCardNumber());
2079                orderForm.setPaymentType("cc");
2080            } else if (order.getPaymentType().trim().equals(
2081                    Config.getStringProperty("ECOM_CHECK"))) {
2082                //Check
2083
orderForm.setCheckNumber(order.getCheckNumber());
2084                orderForm.setCheckBankName(order.getCheckBankName());
2085                orderForm.setPaymentType("ch");
2086            } else if (order.getPaymentType().trim().equals(
2087                    Config.getStringProperty("ECOM_PURCHASE_ORDER"))) {
2088                //PO
2089
orderForm.setPoNumber(order.getPoNumber());
2090                orderForm.setPaymentType("po");
2091            }
2092
2093            //OrderItems
2094
List JavaDoc<OrderItem> orderItems = (List JavaDoc<OrderItem>) OrderItemFactory
2095                    .getAllOrderItemsByParentOrder(order);
2096            List JavaDoc<OrderItemForm> orderItemsForm = new ArrayList JavaDoc<OrderItemForm>();
2097            for (OrderItem orderItem : orderItems) {
2098                ProductFormat format = ProductFormatFactory
2099                        .getProductFormat(orderItem.getProductInode());
2100                OrderItemForm orderItemForm = new OrderItemForm();
2101                orderItemForm.setInode(orderItem.getInode());
2102                orderItemForm.setItemPrice(orderItem.getItemPrice());
2103                orderItemForm.setItemQty(orderItem.getItemQty());
2104                orderItemForm.setOrderInode(orderItem.getOrderInode());
2105                orderItemForm.setProductInode(orderItem.getProductInode());
2106                orderItemsForm.add(orderItemForm);
2107                orderItemForm.setFormatName(format.getFormat());
2108            }
2109            orderForm.setOrderItemList(orderItemsForm);
2110        } catch (Exception JavaDoc ex) {
2111            Logger.debug(UtilMethods.class, ex.getMessage());
2112            System.out.println(ex.getMessage());
2113        }
2114        return orderForm;
2115    }
2116
2117    public static String JavaDoc getUserFullName(OrderForm orderForm) {
2118        String JavaDoc fullName = "";
2119        try {
2120            UserProxy userProxy = UserProxyFactory.getUserProxy(orderForm
2121                    .getUserInode());
2122            User user = PublicUserFactory
2123                    .getUserByUserId(userProxy.getUserId());
2124            fullName = user.getFullName();
2125        } catch (Exception JavaDoc ex) {
2126            Logger.debug(UtilMethods.class, ex.toString());
2127        }
2128        return fullName;
2129    }
2130
2131    public static String JavaDoc getUserCompanyName(HttpServletRequest JavaDoc request,
2132            OrderForm orderForm) {
2133        String JavaDoc companyName = "";
2134        if (request.getSession().getAttribute(WebKeys.CMS_USER) != null) {
2135            UserProxy userProxy = UserProxyFactory.getUserProxy(orderForm
2136                    .getUserInode());
2137            Organization organization = (Organization) InodeFactory
2138                    .getParentOfClass(userProxy, Organization.class);
2139            if (organization.getInode() != 0) {
2140                companyName = organization.getTitle();
2141            }
2142        }
2143        return companyName;
2144    }
2145
2146    public static String JavaDoc getUserCompanyName(HttpServletRequest JavaDoc request) {
2147        String JavaDoc companyName = "";
2148        if (request.getSession().getAttribute(WebKeys.CMS_USER) != null) {
2149            User user = (User) request.getSession().getAttribute(
2150                    WebKeys.CMS_USER);
2151            UserProxy userProxy = UserProxyFactory.getUserProxy(user);
2152            Organization organization = (Organization) InodeFactory
2153                    .getParentOfClass(userProxy, Organization.class);
2154            if (organization.getInode() != 0) {
2155                companyName = organization.getTitle();
2156            }
2157        }
2158        return companyName;
2159    }
2160
2161    public static Product getProductbyProductFormaId(String JavaDoc productFormatInode) {
2162
2163        ProductFormat productF = (ProductFormat) ProductFormatFactory
2164                .getProductFormat(productFormatInode);
2165        return getProductById(productF.getProductInode());
2166    }
2167
2168    public static Product getProductbyProductFormaId(long productFormatInode)
2169            throws Exception JavaDoc {
2170        ProductFormat productF = (ProductFormat) ProductFormatFactory
2171                .getProductFormat(productFormatInode);
2172        return getProductById(productF.getProductInode());
2173    }
2174
2175    public static Product getProductById(long productInode) {
2176
2177        Product product = getProduct(productInode);
2178        return product;
2179    }
2180
2181    public static String JavaDoc getUserEmail(User user) {
2182        String JavaDoc email = "";
2183        if (user != null) {
2184            email = user.getEmailAddress();
2185        }
2186        return email;
2187    }
2188
2189    public static String JavaDoc toPercentageFormat(double weight) {
2190        int decimals = 3;
2191        return toXNumberFormat(weight, decimals);
2192    }
2193
2194    public static String JavaDoc toPercentageFormat(float weight) {
2195        return toWeightFormat((double) weight);
2196    }
2197    public static String JavaDoc toWeightFormat(double weight) {
2198        int decimals = 3;
2199        return toXNumberFormat(weight, decimals);
2200    }
2201
2202    public static String JavaDoc toWeightFormat(float weight) {
2203        return toWeightFormat((double) weight);
2204    }
2205
2206    public static String JavaDoc getActualYear() {
2207        GregorianCalendar JavaDoc calendar = new GregorianCalendar JavaDoc();
2208        return String.valueOf(calendar.get(GregorianCalendar.YEAR));
2209    }
2210
2211    public static String JavaDoc getEventDateRange(Date JavaDoc date1, Date JavaDoc date2) {
2212        if (date1 == null)
2213            return "";
2214        if (date2 == null)
2215            date2 = date1;
2216
2217        String JavaDoc dateRet = "";
2218        GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
2219        GregorianCalendar JavaDoc cal2 = new GregorianCalendar JavaDoc();
2220        cal.setTime(date1);
2221        cal2.setTime(date2);
2222        if (cal.get(GregorianCalendar.MONTH) == cal2
2223                .get(GregorianCalendar.MONTH)
2224                && cal.get(GregorianCalendar.YEAR) == cal2
2225                        .get(GregorianCalendar.YEAR)) {
2226            dateRet += new SimpleDateFormat JavaDoc("MMMM").format(date1) + " ";
2227            if (cal.get(GregorianCalendar.DATE) == cal2
2228                    .get(GregorianCalendar.DATE)) {
2229                dateRet += cal.get(GregorianCalendar.DATE) + " ";
2230            } else {
2231                dateRet += cal.get(GregorianCalendar.DATE) + " - "
2232                        + cal2.get(GregorianCalendar.DATE) + " ";
2233            }
2234            dateRet += cal.get(GregorianCalendar.YEAR);
2235        } else {
2236            if (cal.get(GregorianCalendar.YEAR) == cal2
2237                    .get(GregorianCalendar.YEAR)) {
2238                dateRet += new SimpleDateFormat JavaDoc("MMMM").format(date1) + " ";
2239                dateRet += cal.get(GregorianCalendar.DATE) + " - ";
2240                dateRet += new SimpleDateFormat JavaDoc("MMMM").format(date2) + " ";
2241                dateRet += cal2.get(GregorianCalendar.DATE) + " ";
2242                dateRet += cal.get(GregorianCalendar.YEAR);
2243            } else {
2244                dateRet += new SimpleDateFormat JavaDoc("MMMM").format(date1) + " ";
2245                dateRet += cal.get(GregorianCalendar.DATE) + " ";
2246                dateRet += cal.get(GregorianCalendar.YEAR) + " - ";
2247                dateRet += new SimpleDateFormat JavaDoc("MMMM").format(date2) + " ";
2248                dateRet += cal2.get(GregorianCalendar.DATE) + " ";
2249                dateRet += cal2.get(GregorianCalendar.YEAR);
2250            }
2251        }
2252        return dateRet;
2253    }
2254
2255    public static final String JavaDoc htmlDateToHTMLTime(java.util.Date JavaDoc x) {
2256        if (x == null) {
2257            return "";
2258        }
2259
2260        return HTML_DATETIME_TO_DATE.format(x);
2261    }
2262
2263    public static List JavaDoc<Object JavaDoc> randomList(List JavaDoc<Object JavaDoc> list) {
2264        return randomList(list, list.size());
2265    }
2266
2267    public static List JavaDoc<Object JavaDoc> randomList(List JavaDoc<Object JavaDoc> list, int number) {
2268        List JavaDoc<Object JavaDoc> randomList = new ArrayList JavaDoc<Object JavaDoc>();
2269        try {
2270            if (list.size() > 0) {
2271                ArrayList JavaDoc<Integer JavaDoc> numbers = new ArrayList JavaDoc<Integer JavaDoc>();
2272                Randomizer random = new Randomizer();
2273                for (int i = 0; i < number; i++) {
2274                    int randomInt = random.nextInt(list.size());
2275                    int j = 0;
2276                    while (numbers.contains(randomInt) && j < 20) {
2277                        randomInt = random.nextInt(list.size());
2278                        j++;
2279                    }
2280                    numbers.add(randomInt);
2281                    randomList.add(list.get(randomInt));
2282                }
2283            }
2284        } catch (Exception JavaDoc ex) {
2285            Logger.debug(UtilMethods.class, ex.toString());
2286        }
2287        return randomList;
2288    }
2289
2290    public String JavaDoc toString(Object JavaDoc obj) {
2291        return obj.toString();
2292    }
2293
2294    public String JavaDoc toString(int num) {
2295        return Integer.toString(num);
2296    }
2297
2298    public String JavaDoc toString(long num) {
2299        return Long.toString(num);
2300    }
2301
2302    /**
2303     * This method create a list of element for the getLuceneDocumentForContentlet
2304     * to facilitate the search of multiple elements the contentlet search
2305     * @param stringList
2306     * @return a list of elements for the getLuceneDocumentForContentlet
2307     */

2308    public static String JavaDoc listToString(String JavaDoc stringList) {
2309        StringBuffer JavaDoc result = new StringBuffer JavaDoc();
2310        StringTokenizer JavaDoc token = new StringTokenizer JavaDoc(stringList, ",");
2311        while (token.hasMoreElements()) {
2312            result.append(token.nextToken() + " ");
2313        }
2314        return result.toString();
2315    }
2316
2317    /**
2318     * Generate a ramdom number between 0 and maxRanger number
2319     * @param maxRange
2320     * @return int
2321     */

2322    public static int getRandomNumber(int maxRange) {
2323
2324        Random JavaDoc r = new Random JavaDoc();
2325        int randInt = Math.abs(r.nextInt()) % (maxRange + 1);
2326        return randInt;
2327
2328    }
2329
2330    /**
2331     * get the velocity template fron the liveUrl, if the file is not publish, automatically
2332     * is published
2333     * @param liveUrl
2334     * @return Velocity Template
2335     */

2336    @SuppressWarnings JavaDoc({"deprecation", "unchecked"})
2337    public static Template getVelocityTemplate(String JavaDoc liveUrl) {
2338
2339        try {
2340            try {
2341                URL JavaDoc url = Thread.currentThread().getContextClassLoader()
2342                        .getResource("system-ext.properties");
2343                Velocity.init(url.getPath());
2344
2345            } catch (Exception JavaDoc s) {
2346                Logger.warn(UtilMethods.class, s.toString(), s);
2347            }
2348
2349            Template template = Velocity.getTemplate(liveUrl);
2350            return template;
2351
2352        } catch (Exception JavaDoc e) {
2353            /*Get the htmlpage a publish*/
2354            @SuppressWarnings JavaDoc("unused")
2355            String JavaDoc idStr = liveUrl.substring(liveUrl.indexOf("/") + 1, liveUrl
2356                    .indexOf("."));
2357            long idInode = Long.parseLong(idStr);
2358            HTMLPage htmlPage = (HTMLPage) IdentifierFactory
2359                    .getLiveChildOfClass(InodeFactory.getInode(idInode,
2360                            Identifier.class), HTMLPage.class);
2361
2362            republishHTMLPage(htmlPage);
2363
2364            return getVelocityTemplate(liveUrl);
2365        }
2366
2367    }
2368
2369    /**
2370     * Publish and html page
2371     * @param htmlPage
2372     */

2373    public static void republishHTMLPage(HTMLPage htmlPage) {
2374
2375        com.dotmarketing.portlets.templates.model.Template templateParent = HTMLPageFactory
2376                .getHTMLPageTemplate(htmlPage, true);
2377
2378        if (templateParent.getInode() > 0) {
2379
2380            //if it exists it publishes it
2381
WebAssetFactory.publishAsset(templateParent);
2382
2383            //gets all live container children
2384
java.util.List JavaDoc identifiers = InodeFactory.getChildrenClass(
2385                    templateParent, Identifier.class);
2386            java.util.Iterator JavaDoc identifiersIter = identifiers.iterator();
2387            while (identifiersIter.hasNext()) {
2388
2389                Identifier identifier = (Identifier) identifiersIter.next();
2390                Container container = (Container) IdentifierFactory
2391                        .getWorkingChildOfClass(identifier, Container.class);
2392
2393                List JavaDoc categories = InodeFactory.getParentsOfClass(container,
2394                        Category.class);
2395                List JavaDoc contentlets = null;
2396
2397                if (categories.size() == 0) {
2398                    Identifier idenHtmlPage = IdentifierFactory
2399                            .getIdentifierByInode(htmlPage);
2400                    Identifier idenContainer = IdentifierFactory
2401                            .getIdentifierByInode(container);
2402                    contentlets = ContentletFactory
2403                            .getWorkingContentletsByOrderAndParents(
2404                                    idenHtmlPage.getInode(), idenContainer
2405                                            .getInode());
2406                } else {
2407
2408                    Iterator JavaDoc catsIter = categories.iterator();
2409                    Set JavaDoc contentletSet = new HashSet JavaDoc();
2410
2411                    String JavaDoc condition = "working="
2412                            + com.dotmarketing.db.DbConnectionFactory
2413                                    .getDBTrue()
2414                            + " and deleted="
2415                            + com.dotmarketing.db.DbConnectionFactory
2416                                    .getDBFalse();
2417                    String JavaDoc sort = (container.getSortContentletsBy() == null)
2418                            ? "sort_order"
2419                            : container.getSortContentletsBy();
2420
2421                    while (catsIter.hasNext()) {
2422                        Category category = (Category) catsIter.next();
2423                        List JavaDoc contentletsChildren = InodeFactory
2424                                .getChildrenClassByConditionAndOrderBy(
2425                                        category, Contentlet.class, condition,
2426                                        sort);
2427                        if (contentletsChildren != null
2428                                && contentletsChildren.size() > 0) {
2429                            contentletSet.addAll(contentletsChildren);
2430                        }
2431                    }
2432                    contentlets = new ArrayList JavaDoc();
2433                    contentlets.addAll(contentletSet);
2434                }
2435                //gets all not live contentlet children
2436
java.util.Iterator JavaDoc contentletsIter = contentlets.iterator();
2437                while (contentletsIter.hasNext()) {
2438                    //publishes each one
2439
Contentlet contentlet = (Contentlet) contentletsIter.next();
2440                    WebAssetFactory.publishAsset(contentlet);
2441                }
2442            }
2443
2444        }
2445
2446        LiveCache.addToLiveAssetToCache((WebAsset) htmlPage);
2447        WorkingCache.addToWorkingAssetToCache((WebAsset) htmlPage);
2448        //writes the htmlpage to a live directory under velocity folder
2449
PageServices.publishPageToFile(htmlPage);
2450
2451        //Refreshing the menues
2452
RefreshMenus.deleteMenus();
2453
2454        //If the webassets published is an HTML page, we have to remove
2455
//it from the PageNotFoundCache
2456
PageNotFoundCache.removePageFromCache(htmlPage);
2457
2458    }
2459    
2460     /**
2461     * Return is a date is equals or before the actual date
2462     * @param date
2463     * @return
2464     */

2465    public static Date JavaDoc getCurrentDate(){
2466        
2467        try{
2468            GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
2469            return cal.getTime();
2470            
2471        }catch(Exception JavaDoc e){
2472            
2473        }
2474        return null;
2475    }
2476
2477    public static String JavaDoc truncFull(String JavaDoc x, int len)
2478    {
2479        len -= 3;
2480        if (x.length() >= len)
2481        {
2482            x = x.substring(0,len);
2483            x += "...";
2484        }
2485        return x;
2486    }
2487
2488}
Popular Tags