KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > portlet > util > GeneralUtil


1 package com.opensymphony.webwork.portlet.util;
2
3 import com.opensymphony.util.TextUtils;
4 import com.opensymphony.webwork.ServletActionContext;
5 import org.apache.log4j.Category;
6 import sun.misc.BASE64Encoder;
7
8 import javax.mail.internet.MailDateFormat JavaDoc;
9 import javax.servlet.http.Cookie JavaDoc;
10 import javax.servlet.http.HttpServletRequest JavaDoc;
11 import java.io.*;
12 import java.math.BigDecimal JavaDoc;
13 import java.net.URL JavaDoc;
14 import java.net.URLDecoder JavaDoc;
15 import java.net.URLEncoder JavaDoc;
16 import java.text.*;
17 import java.util.Date JavaDoc;
18 import java.util.Locale JavaDoc;
19 import java.util.Properties JavaDoc;
20 import java.util.StringTokenizer JavaDoc;
21 import java.util.regex.Matcher JavaDoc;
22 import java.util.regex.Pattern JavaDoc;
23
24 public final class GeneralUtil {
25     private static final Category log;
26
27     private static String JavaDoc DEFAULT_FORMATTING_PROPERTIES_FILE_NAME = "default-formatting.properties";
28
29     private static DecimalFormat defaultDecimalNumberFormatter;
30
31     private static DecimalFormat defaultLongNumberFormatter;
32
33     private static SimpleDateFormat defaultDateFormatter;
34
35     private static SimpleDateFormat defaultDateTimeFormatter;
36
37     private static SimpleDateFormat defaultTimeFormatter;
38
39     private static Properties JavaDoc formattingProperties = new Properties JavaDoc();
40
41     private static final String JavaDoc EMAIL_PATTERN_STRING = "([\\w-%\\+\\.]+@[\\w-%\\.]+\\.[\\p{Alpha}]+)";
42
43     private static final Pattern JavaDoc EMAIL_PATTERN = Pattern.compile("([\\w-%\\+\\.]+@[\\w-%\\.]+\\.[\\p{Alpha}]+)");
44
45     static {
46         log = Category.getInstance(com.opensymphony.webwork.portlet.util.GeneralUtil.class);
47         loadDefaultProperties();
48         try {
49             saveDefaultFormattingPropertiesFile();
50         } catch (IOException e) {
51             log.error("Error while trying to store the default formatting properties!", e);
52         }
53     }
54
55     public GeneralUtil() {
56     }
57
58     public static void loadDefaultProperties() {
59         try {
60
61             InputStream inputStream = ClassLoaderUtils.getResourceAsStream(DEFAULT_FORMATTING_PROPERTIES_FILE_NAME,
62                     com.opensymphony.webwork.portlet.util.GeneralUtil.class);
63
64             formattingProperties.load(inputStream);
65             setDefaultDecimalNumberFormatterPattern(getDefaultDecimalNumberFormatterPattern());
66             setDefaultLongNumberFormatterPattern(getDefaultLongNumberFormatterPattern());
67             setDefaultDateFormatterPattern(getDefaultDateFormatterPattern());
68             setDefaultDateTimeFormatterPattern(getDefaultDateTimeFormatterPattern());
69             setDefaultTimeFormatterPattern(getDefaultTimeFormatterPattern());
70         } catch (Exception JavaDoc e) {
71             log.error("Error while trying to load the object formatting properties!", e);
72         }
73     }
74
75     public static Date JavaDoc convertToDateWithEnglishLocale(String JavaDoc buildDateString) {
76         DateFormat JavaDoc formatter = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH);
77         formatter.setLenient(false);
78         Date JavaDoc date = null;
79         try {
80             date = formatter.parse(buildDateString.toString());
81         } catch (ParseException e) {
82             log.info("Could not parse : " + buildDateString + " : " + e, e);
83         }
84         return date;
85     }
86
87     public static void saveDefaultFormattingPropertiesFile() throws IOException {
88         File defaultFormattingPropertiesFile = new File(DEFAULT_FORMATTING_PROPERTIES_FILE_NAME);
89         FileOutputStream out = new FileOutputStream(defaultFormattingPropertiesFile);
90         formattingProperties.store(out, null);
91     }
92
93     public static String JavaDoc getDefaultTimeFormatterPattern() {
94         return formattingProperties.getProperty("time.format", "HH:mm:ss");
95     }
96
97     public static void setDefaultTimeFormatterPattern(String JavaDoc defaultTimeFormatterPattern) {
98         formattingProperties.setProperty("time.format", defaultTimeFormatterPattern);
99         defaultTimeFormatter = (SimpleDateFormat) createDateFormatter(defaultTimeFormatterPattern);
100     }
101
102     public static String JavaDoc getDefaultDateTimeFormatterPattern() {
103         return formattingProperties.getProperty("datetime.format", "MMM dd, yyyy HH:mm");
104     }
105
106     public static void setDefaultDateTimeFormatterPattern(String JavaDoc defaultDateTimeFormatterPattern) {
107         formattingProperties.setProperty("datetime.format", defaultDateTimeFormatterPattern);
108         defaultDateTimeFormatter = (SimpleDateFormat) createDateFormatter(defaultDateTimeFormatterPattern);
109     }
110
111     public static String JavaDoc getDefaultDateFormatterPattern() {
112         return formattingProperties.getProperty("date.format", "MMM dd, yyyy");
113     }
114
115     public static void setDefaultDateFormatterPattern(String JavaDoc defaultDateFormatterPattern) {
116         formattingProperties.setProperty("date.format", defaultDateFormatterPattern);
117         defaultDateFormatter = (SimpleDateFormat) createDateFormatter(defaultDateFormatterPattern);
118     }
119
120     public static String JavaDoc getDefaultLongNumberFormatterPattern() {
121         return formattingProperties.getProperty("long.number.format", "###############");
122     }
123
124     public static void setDefaultLongNumberFormatterPattern(String JavaDoc defaultLongNumberFormatterPattern) {
125         formattingProperties.setProperty("long.number.format", defaultLongNumberFormatterPattern);
126         defaultLongNumberFormatter = new DecimalFormat(defaultLongNumberFormatterPattern);
127     }
128
129     public static String JavaDoc getDefaultDecimalNumberFormatterPattern() {
130         return formattingProperties.getProperty("decimal.number.format", "###############.##########");
131     }
132
133     public static void setDefaultDecimalNumberFormatterPattern(String JavaDoc defaultDecimalNumberFormatterPattern) {
134         formattingProperties.getProperty("decimal.number.format", defaultDecimalNumberFormatterPattern);
135         defaultDecimalNumberFormatter = new DecimalFormat(defaultDecimalNumberFormatterPattern);
136     }
137
138     public static String JavaDoc getStackTrace(Throwable JavaDoc t) {
139         if (t == null) {
140             return "";
141         } else {
142             StringWriter sw = new StringWriter();
143             t.printStackTrace(new PrintWriter(sw));
144             return sw.toString();
145         }
146     }
147
148     public static String JavaDoc format(Number JavaDoc num) {
149         try {
150             if ((num instanceof Double JavaDoc) || (num instanceof BigDecimal JavaDoc) || (num instanceof Float JavaDoc))
151                 return defaultDecimalNumberFormatter.format(num);
152             else
153                 return defaultLongNumberFormatter.format(num);
154         } catch (Exception JavaDoc e) {
155             return null;
156         }
157     }
158
159     public static String JavaDoc format(Date JavaDoc date) {
160         try {
161             return defaultDateFormatter.format(date);
162         } catch (Exception JavaDoc e) {
163             return "";
164         }
165     }
166
167     public static String JavaDoc format(String JavaDoc str) {
168         return str == null ? "" : str;
169     }
170
171     public static String JavaDoc format(Object JavaDoc obj) {
172         try {
173             if (obj instanceof Number JavaDoc)
174                 return format((Number JavaDoc) obj);
175             if (obj instanceof Date JavaDoc)
176                 return format((Date JavaDoc) obj);
177             if (obj instanceof String JavaDoc)
178                 return format((String JavaDoc) obj);
179             return obj.toString();
180         } catch (Exception JavaDoc e) {
181             return "";
182         }
183     }
184
185     public static String JavaDoc formatDateTime(Date JavaDoc date) {
186         try {
187             return defaultDateTimeFormatter.format(date);
188         } catch (Exception JavaDoc e) {
189             return "";
190         }
191     }
192
193     public static String JavaDoc formatTime(Date JavaDoc date) {
194         try {
195             return defaultTimeFormatter.format(date);
196         } catch (Exception JavaDoc e) {
197             return "";
198         }
199     }
200
201     public static Date JavaDoc convertMailFormatDate(String JavaDoc date) throws ParseException {
202         return (new MailDateFormat JavaDoc()).parse(date);
203     }
204
205     public static Date JavaDoc convertToDate(Object JavaDoc obj) {
206         if (obj instanceof Date JavaDoc)
207             return (Date JavaDoc) obj;
208         Date JavaDoc date = null;
209         if (date == null)
210             try {
211                 date = defaultDateFormatter.parse(obj.toString());
212             } catch (ParseException e) {
213                 log.info("Could not parse : " + obj + " : " + e, e);
214             }
215         return date;
216     }
217
218     public static Long JavaDoc convertToLong(Object JavaDoc obj) {
219         try {
220             if (obj instanceof Long JavaDoc)
221                 return (Long JavaDoc) obj;
222             return new Long JavaDoc(defaultLongNumberFormatter.parse(obj.toString()).longValue());
223         } catch (Exception JavaDoc e) {
224
225             return null;
226         }
227     }
228
229     public static Character JavaDoc convertToCharacter(Object JavaDoc obj) {
230         try {
231             if (obj instanceof Character JavaDoc)
232                 return (Character JavaDoc) obj;
233             return new Character JavaDoc(obj.toString().charAt(0));
234         } catch (Exception JavaDoc e) {
235             return null;
236         }
237     }
238
239     public static BigDecimal JavaDoc convertToBigDecimal(Object JavaDoc obj) {
240         try {
241             if (obj instanceof BigDecimal JavaDoc)
242                 return (BigDecimal JavaDoc) obj;
243             return new BigDecimal JavaDoc(defaultDecimalNumberFormatter.parse(obj.toString()).doubleValue());
244         } catch (Exception JavaDoc e) {
245             return null;
246         }
247     }
248
249     public static Double JavaDoc convertToDouble(Object JavaDoc obj) {
250         try {
251             if (obj instanceof Double JavaDoc)
252                 return (Double JavaDoc) obj;
253             return new Double JavaDoc(defaultDecimalNumberFormatter.parse(obj.toString()).doubleValue());
254         } catch (Exception JavaDoc e) {
255             return null;
256         }
257     }
258
259     public static Integer JavaDoc convertToInteger(Object JavaDoc obj) {
260         try {
261             if (obj instanceof Integer JavaDoc)
262                 return (Integer JavaDoc) obj;
263             return new Integer JavaDoc(defaultLongNumberFormatter.parse(obj.toString()).intValue());
264         } catch (Exception JavaDoc e) {
265             return null;
266         }
267     }
268
269     public static Boolean JavaDoc convertToBoolean(Object JavaDoc obj) {
270         try {
271             if (obj instanceof Boolean JavaDoc)
272                 return (Boolean JavaDoc) obj;
273             return new Boolean JavaDoc(obj.toString());
274         } catch (Exception JavaDoc e) {
275             return null;
276         }
277     }
278
279     public static String JavaDoc convertToString(Object JavaDoc obj) {
280         try {
281             String JavaDoc result = obj.toString();
282             if (result.equals(""))
283                 result = null;
284             return result;
285         } catch (Exception JavaDoc e) {
286             return null;
287         }
288     }
289
290     private static DateFormat JavaDoc createDateFormatter(String JavaDoc pattern) {
291         DateFormat JavaDoc formatter = new SimpleDateFormat(pattern);
292         formatter.setLenient(false);
293         return formatter;
294     }
295
296     public static String JavaDoc urlEncode(String JavaDoc url) {
297         try {
298             if (url == null)
299                 return null;
300             return URLEncoder.encode(url, getCharacterEncoding());
301         } catch (UnsupportedEncodingException e) {
302             log.error("Error while trying to encode the URL!", e);
303             return url;
304         }
305     }
306
307     public static String JavaDoc urlDecode(String JavaDoc url) {
308         try {
309             if (url == null)
310                 return null;
311             return URLDecoder.decode(url, getCharacterEncoding());
312         } catch (Exception JavaDoc e) {
313             log.error("Error while trying to decode url" + url, e);
314             return url;
315         }
316     }
317
318     private static boolean hasFormattingCharacters(String JavaDoc text) {
319         if (!TextUtils.stringSet(text))
320             return false;
321         String JavaDoc illegalChars[] = {"+", "-"};
322         for (int i = 0; i < illegalChars.length; i++) {
323             String JavaDoc illegalChar = illegalChars[i];
324             if (text.indexOf(illegalChar) != -1)
325                 return true;
326         }
327
328         return false;
329     }
330
331     public static String JavaDoc appendAmpsandOrQuestionMark(String JavaDoc str) {
332         if (!TextUtils.stringSet(str))
333             return str;
334         if (str.indexOf("?") != -1)
335             return str + "&";
336         else
337             return str + "?";
338     }
339
340     public static String JavaDoc summarise(String JavaDoc content) {
341         if (!TextUtils.stringSet(content))
342             return content;
343         content = content.replaceAll("h[0-9]\\.", " ");
344         content = content.replaceAll("[\\[\\]\\*_\\^\\-\\~\\+]", "");
345         content = content.replaceAll("\\|", " ");
346         content = content.replaceAll("\\{([^:\\}\\{]+)(?::([^\\}\\{]*))?\\}(?!\\})", " ");
347         content = content.replaceAll("\\n", " ");
348         content = content.replaceAll("\\r", " ");
349         content = content.replaceAll("bq.", " ");
350         content = content.replaceAll(" ", " ");
351         int urlIdx = content.indexOf("http://");
352         if (urlIdx > 0)
353             content = content.substring(0, urlIdx);
354         return summariseWithoutStrippingWikiCharacters(content).trim();
355     }
356
357     public static String JavaDoc summariseWithoutStrippingWikiCharacters(String JavaDoc content) {
358         if (content.length() > 255)
359             return TextUtils.trimToEndingChar(content, 251) + "...";
360         else
361             return content;
362     }
363
364     public static String JavaDoc wordWrap(String JavaDoc str, int max) {
365         if (!TextUtils.stringSet(str))
366             return str;
367         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(str);
368         int nonSpaceChars = 0;
369         for (int i = 0; i < sb.length(); i++) {
370             if (Character.isWhitespace(sb.charAt(i)))
371                 nonSpaceChars = 0;
372             else
373                 nonSpaceChars++;
374             if (nonSpaceChars > max) {
375                 nonSpaceChars = 0;
376                 sb.insert(i, " ");
377                 i++;
378             }
379         }
380
381         return sb.toString().trim();
382     }
383
384     public static String JavaDoc highlight(String JavaDoc content, String JavaDoc searchwords) {
385         if (!TextUtils.stringSet(content) || !TextUtils.stringSet(searchwords))
386             return content;
387         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(searchwords, ", ");
388         do {
389             if (!st.hasMoreTokens())
390                 break;
391             String JavaDoc token = st.nextToken();
392             if (!token.equalsIgnoreCase("span") && !token.equalsIgnoreCase("class") && !token.equalsIgnoreCase("search")
393                     && !token.equalsIgnoreCase("highlight"))
394                 content = Pattern.compile("(" + token + ")", 2).matcher(content).replaceAll("<span class=\"search-highlight\">$0</span>");
395         } while (true);
396         return content;
397     }
398
399     public static String JavaDoc doubleUrlEncode(String JavaDoc s) {
400         return urlEncode(urlEncode(s));
401     }
402
403     public static boolean isAllAscii(String JavaDoc s) {
404         char sChars[] = s.toCharArray();
405         for (int i = 0; i < sChars.length; i++) {
406             char sChar = sChars[i];
407             if (sChar > '\177')
408                 return false;
409         }
410
411         return true;
412     }
413
414     public static boolean isAllLettersOrNumbers(String JavaDoc s) {
415         char sChars[] = s.toCharArray();
416         for (int i = 0; i < sChars.length; i++) {
417             char sChar = sChars[i];
418             if (!Character.isLetterOrDigit(sChar))
419                 return false;
420         }
421
422         return true;
423     }
424
425     public static boolean stringSet(String JavaDoc str) {
426         return str != null && str.length() > 0;
427     }
428
429     public static String JavaDoc formatLongTime(long time) {
430         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
431         if (time > 3600000L) {
432             time = scaleTime(time, 3600000L, result);
433             result.append(":");
434         }
435         time = scaleTime(time, 60000L, result);
436         result.append(":");
437         time = scaleTime(time, 1000L, result);
438         result.append(".").append(time);
439         return result.toString();
440     }
441
442     private static long scaleTime(long time, long scale, StringBuffer JavaDoc buf) {
443         long report = time / scale;
444         time -= report * scale;
445         String JavaDoc result = Long.toString(report);
446         if (report < 10L)
447             result = "0" + result;
448         buf.append(result);
449         return time;
450     }
451
452     public static String JavaDoc formatDateFull(Date JavaDoc date) {
453         return DateFormat.getDateInstance(0).format(date);
454     }
455
456     public static String JavaDoc getCharacterEncoding() {
457         return "UTF-8";
458     }
459
460     public static String JavaDoc escapeCDATA(String JavaDoc s) {
461         if (s.indexOf("]]") < 0)
462             return s;
463         else
464             return s.replaceAll("\\]\\]", "]] ");
465     }
466
467     public static String JavaDoc unescapeCDATA(String JavaDoc s) {
468         if (s.indexOf("]] ") < 0)
469             return s;
470         else
471             return s.replaceAll("\\]\\] ", "]]");
472     }
473
474     public static File createTempFile(String JavaDoc directory) {
475         Date JavaDoc date = new Date JavaDoc();
476         String JavaDoc pattern = "_{0,date,MMddyyyy}_{1,time,HHmmss}";
477         String JavaDoc uniqueRandomFileName = MessageFormat.format(pattern, new Object JavaDoc[]{date, date});
478         return new File(directory, uniqueRandomFileName);
479     }
480
481     public static String JavaDoc unescapeEntities(String JavaDoc str) {
482         Pattern JavaDoc hexEntityPattern = Pattern.compile("&([a-fA-F0-9]+);");
483         Pattern JavaDoc decimalEntityPattern = Pattern.compile("&#([0-9]+);");
484         str = replaceNumericEntities(str, hexEntityPattern, 16);
485         return replaceNumericEntities(str, decimalEntityPattern, 10);
486     }
487
488     private static String JavaDoc replaceNumericEntities(String JavaDoc str, Pattern JavaDoc pattern, int base) {
489         Matcher JavaDoc matcher = pattern.matcher(str);
490         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str.length());
491         for (; matcher.find(); matcher.appendReplacement(buf, Character.toString((char) Integer.parseInt(matcher.group(1), base))))
492             ;
493         matcher.appendTail(buf);
494         return buf.toString();
495     }
496
497     public static String JavaDoc base64Decode(String JavaDoc s) {
498         try {
499             String JavaDoc s1 = s.replaceAll("_", "/");
500             String JavaDoc s2 = s1.replaceAll("-", "+");
501             return new String JavaDoc((new sun.misc.BASE64Decoder()).decodeBuffer(s), "UTF-8");
502         } catch (UnsupportedEncodingException e) {
503             log.error("This Java installation doesn't support UTF-8. Call Mulder");
504             return s;
505         } catch (IOException e) {
506             log.error("IOException from base64Decode " + e);
507             return s;
508         }
509     }
510
511     public static String JavaDoc base64Encode(String JavaDoc s) {
512         try {
513             byte sBytes[] = s.getBytes("UTF-8");
514             BASE64Encoder encoder = new sun.misc.BASE64Encoder();
515             return (encoder.encode(sBytes)).replaceAll("\\n", "").replaceAll("/", "_").replaceAll("\\+", "-").trim();
516         } catch (UnsupportedEncodingException e) {
517             log.error("This Java installation doesn't support UTF-8. Call Mulder");
518             return s;
519         }
520     }
521
522     public static String JavaDoc hackSingleQuotes(String JavaDoc s) {
523         if (TextUtils.stringSet(s))
524             return s.replaceAll("'", "' + '\\\\'' + '");
525         else
526             return s;
527     }
528
529     public boolean isInLastDays(Date JavaDoc date, int maxDays) {
530         if (date == null) {
531             return false;
532         } else {
533             long tstamp = date.getTime();
534             long t0 = System.currentTimeMillis();
535             long dt = t0 - tstamp;
536             long secs = dt / 1000L;
537             long mins = secs / 60L;
538             long hours = mins / 60L;
539             long days = hours / 24L;
540             return days < (long) maxDays;
541         }
542     }
543
544     public String JavaDoc getRelativeTime(Date JavaDoc date) {
545         if (date == null)
546             return "No timestamp.";
547         long tstamp = date.getTime();
548         long t0 = System.currentTimeMillis();
549         long dt = t0 - tstamp;
550         long secs = dt / 1000L;
551         long mins = secs / 60L;
552         long hours = mins / 60L;
553         long days = hours / 24L;
554         StringBuffer JavaDoc ret = new StringBuffer JavaDoc();
555         if (days != 0L)
556             ret.append(days + " day" + (days != 1L ? "s " : " "));
557         hours -= days * 24L;
558         if (hours != 0L)
559             ret.append(hours + " hour" + (hours != 1L ? "s " : " "));
560         mins -= (days * 24L + hours) * 60L;
561         if (mins != 0L)
562             ret.append(mins + " min" + (mins != 1L ? "s " : " "));
563         if (days != 0L || hours != 0L || mins != 0L)
564             ret.append(" ago");
565         else
566             ret.append("less than a minute ago");
567         return ret.toString();
568     }
569
570     public String JavaDoc getFormatDateSimple(Date JavaDoc date) {
571         DateFormat JavaDoc df = new SimpleDateFormat("dd MMM");
572         return df.format(date);
573     }
574
575     public static Cookie JavaDoc setCookie(String JavaDoc key, String JavaDoc value) {
576         HttpServletRequest JavaDoc request = ServletActionContext.getRequest();
577         javax.servlet.http.HttpServletResponse JavaDoc response = ServletActionContext.getResponse();
578         int cookieAge = 31104000;
579         String JavaDoc path = request.getContextPath();
580         if (!TextUtils.stringSet(path))
581             path = "/";
582         return CookieUtils.setCookie(request, response, key, value, cookieAge, path);
583     }
584
585     public static String JavaDoc getCookieValue(String JavaDoc key) {
586         HttpServletRequest JavaDoc request = ServletActionContext.getRequest();
587         return CookieUtils.getCookieValue(request, key);
588     }
589
590     public static String JavaDoc htmlEncode(String JavaDoc s) {
591         if (!TextUtils.stringSet(s))
592             return "";
593         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
594         for (int j = 0; j < s.length(); j++) {
595             char c = s.charAt(j);
596             if (c < '\200')
597                 switch (c) {
598                     case 34: // '"'
599
str.append("&quot;");
600                         break;
601
602                     case 38: // '&'
603
str.append("&amp;");
604                         break;
605
606                     case 60: // '<'
607
str.append("&lt;");
608                         break;
609
610                     case 62: // '>'
611
str.append("&gt;");
612                         break;
613
614                     default:
615                         str.append(c);
616                         break;
617                 }
618             else
619                 str.append(c);
620         }
621
622         return str.toString();
623     }
624
625     public static String JavaDoc plain2html(String JavaDoc text) {
626         return TextUtils.plainTextToHtml(text);
627     }
628
629     public static Properties JavaDoc getProperties(String JavaDoc resource, Class JavaDoc callingClass) {
630         return getPropertiesFromStream(ClassLoaderUtils.getResourceAsStream(resource, callingClass));
631     }
632
633     public static Properties JavaDoc getPropertiesFromFile(File file) {
634         try {
635             return getPropertiesFromStream(new FileInputStream(file));
636         } catch (FileNotFoundException e) {
637             log.error("Error loading properties from file: " + file.getPath() + ". File does not exist.", e);
638             return null;
639         }
640     }
641
642     public static Properties JavaDoc getPropertiesFromStream(InputStream is) {
643         if (is == null)
644             return null;
645         Properties JavaDoc props = new Properties JavaDoc();
646         try {
647             props.load(is);
648         } catch (IOException e) {
649             log.error("Error loading properties from stream.", e);
650         } finally {
651             if (is != null)
652                 try {
653                     is.close();
654                 } catch (Exception JavaDoc ignore) {
655                 }
656         }
657         return props;
658     }
659
660     public static void unzipFile(File zipFile, File dirToExtractTo) throws Exception JavaDoc {
661         if (!zipFile.isFile()) {
662             throw new IOException("Zip file doesn't exist or Confluence doesn't have read access to it. backupedFile=" + zipFile);
663         } else {
664             Unzipper fileUnzipper = new FileUnzipper(zipFile, dirToExtractTo);
665             fileUnzipper.unzip();
666             return;
667         }
668     }
669
670     public static void unzipUrl(URL JavaDoc zipUrl, File dirToExtractTo) throws Exception JavaDoc {
671         Unzipper urlUnzipper = new UrlUnzipper(zipUrl, dirToExtractTo);
672         urlUnzipper.unzip();
673     }
674
675     private static String JavaDoc extractGoogleUrl(String JavaDoc url, int indexOfQuery) {
676         try {
677             int indexOfAmpersand = url.indexOf("&", indexOfQuery);
678             String JavaDoc googleQueryPhrase;
679             if (indexOfAmpersand > -1)
680                 googleQueryPhrase = url.substring(indexOfQuery + 2, indexOfAmpersand);
681             else
682                 googleQueryPhrase = url.substring(indexOfQuery + 2);
683             url = "Google: " + URLDecoder.decode(googleQueryPhrase);
684         } catch (Exception JavaDoc e) {
685         }
686         return url;
687     }
688
689 }
690
691
Popular Tags