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 ; 9 import javax.servlet.http.Cookie ; 10 import javax.servlet.http.HttpServletRequest ; 11 import java.io.*; 12 import java.math.BigDecimal ; 13 import java.net.URL ; 14 import java.net.URLDecoder ; 15 import java.net.URLEncoder ; 16 import java.text.*; 17 import java.util.Date ; 18 import java.util.Locale ; 19 import java.util.Properties ; 20 import java.util.StringTokenizer ; 21 import java.util.regex.Matcher ; 22 import java.util.regex.Pattern ; 23 24 public final class GeneralUtil { 25 private static final Category log; 26 27 private static String 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 formattingProperties = new Properties (); 40 41 private static final String EMAIL_PATTERN_STRING = "([\\w-%\\+\\.]+@[\\w-%\\.]+\\.[\\p{Alpha}]+)"; 42 43 private static final Pattern 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 e) { 71 log.error("Error while trying to load the object formatting properties!", e); 72 } 73 } 74 75 public static Date convertToDateWithEnglishLocale(String buildDateString) { 76 DateFormat formatter = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); 77 formatter.setLenient(false); 78 Date 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 getDefaultTimeFormatterPattern() { 94 return formattingProperties.getProperty("time.format", "HH:mm:ss"); 95 } 96 97 public static void setDefaultTimeFormatterPattern(String defaultTimeFormatterPattern) { 98 formattingProperties.setProperty("time.format", defaultTimeFormatterPattern); 99 defaultTimeFormatter = (SimpleDateFormat) createDateFormatter(defaultTimeFormatterPattern); 100 } 101 102 public static String getDefaultDateTimeFormatterPattern() { 103 return formattingProperties.getProperty("datetime.format", "MMM dd, yyyy HH:mm"); 104 } 105 106 public static void setDefaultDateTimeFormatterPattern(String defaultDateTimeFormatterPattern) { 107 formattingProperties.setProperty("datetime.format", defaultDateTimeFormatterPattern); 108 defaultDateTimeFormatter = (SimpleDateFormat) createDateFormatter(defaultDateTimeFormatterPattern); 109 } 110 111 public static String getDefaultDateFormatterPattern() { 112 return formattingProperties.getProperty("date.format", "MMM dd, yyyy"); 113 } 114 115 public static void setDefaultDateFormatterPattern(String defaultDateFormatterPattern) { 116 formattingProperties.setProperty("date.format", defaultDateFormatterPattern); 117 defaultDateFormatter = (SimpleDateFormat) createDateFormatter(defaultDateFormatterPattern); 118 } 119 120 public static String getDefaultLongNumberFormatterPattern() { 121 return formattingProperties.getProperty("long.number.format", "###############"); 122 } 123 124 public static void setDefaultLongNumberFormatterPattern(String defaultLongNumberFormatterPattern) { 125 formattingProperties.setProperty("long.number.format", defaultLongNumberFormatterPattern); 126 defaultLongNumberFormatter = new DecimalFormat(defaultLongNumberFormatterPattern); 127 } 128 129 public static String getDefaultDecimalNumberFormatterPattern() { 130 return formattingProperties.getProperty("decimal.number.format", "###############.##########"); 131 } 132 133 public static void setDefaultDecimalNumberFormatterPattern(String defaultDecimalNumberFormatterPattern) { 134 formattingProperties.getProperty("decimal.number.format", defaultDecimalNumberFormatterPattern); 135 defaultDecimalNumberFormatter = new DecimalFormat(defaultDecimalNumberFormatterPattern); 136 } 137 138 public static String getStackTrace(Throwable 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 format(Number num) { 149 try { 150 if ((num instanceof Double ) || (num instanceof BigDecimal ) || (num instanceof Float )) 151 return defaultDecimalNumberFormatter.format(num); 152 else 153 return defaultLongNumberFormatter.format(num); 154 } catch (Exception e) { 155 return null; 156 } 157 } 158 159 public static String format(Date date) { 160 try { 161 return defaultDateFormatter.format(date); 162 } catch (Exception e) { 163 return ""; 164 } 165 } 166 167 public static String format(String str) { 168 return str == null ? "" : str; 169 } 170 171 public static String format(Object obj) { 172 try { 173 if (obj instanceof Number ) 174 return format((Number ) obj); 175 if (obj instanceof Date ) 176 return format((Date ) obj); 177 if (obj instanceof String ) 178 return format((String ) obj); 179 return obj.toString(); 180 } catch (Exception e) { 181 return ""; 182 } 183 } 184 185 public static String formatDateTime(Date date) { 186 try { 187 return defaultDateTimeFormatter.format(date); 188 } catch (Exception e) { 189 return ""; 190 } 191 } 192 193 public static String formatTime(Date date) { 194 try { 195 return defaultTimeFormatter.format(date); 196 } catch (Exception e) { 197 return ""; 198 } 199 } 200 201 public static Date convertMailFormatDate(String date) throws ParseException { 202 return (new MailDateFormat ()).parse(date); 203 } 204 205 public static Date convertToDate(Object obj) { 206 if (obj instanceof Date ) 207 return (Date ) obj; 208 Date 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 convertToLong(Object obj) { 219 try { 220 if (obj instanceof Long ) 221 return (Long ) obj; 222 return new Long (defaultLongNumberFormatter.parse(obj.toString()).longValue()); 223 } catch (Exception e) { 224 225 return null; 226 } 227 } 228 229 public static Character convertToCharacter(Object obj) { 230 try { 231 if (obj instanceof Character ) 232 return (Character ) obj; 233 return new Character (obj.toString().charAt(0)); 234 } catch (Exception e) { 235 return null; 236 } 237 } 238 239 public static BigDecimal convertToBigDecimal(Object obj) { 240 try { 241 if (obj instanceof BigDecimal ) 242 return (BigDecimal ) obj; 243 return new BigDecimal (defaultDecimalNumberFormatter.parse(obj.toString()).doubleValue()); 244 } catch (Exception e) { 245 return null; 246 } 247 } 248 249 public static Double convertToDouble(Object obj) { 250 try { 251 if (obj instanceof Double ) 252 return (Double ) obj; 253 return new Double (defaultDecimalNumberFormatter.parse(obj.toString()).doubleValue()); 254 } catch (Exception e) { 255 return null; 256 } 257 } 258 259 public static Integer convertToInteger(Object obj) { 260 try { 261 if (obj instanceof Integer ) 262 return (Integer ) obj; 263 return new Integer (defaultLongNumberFormatter.parse(obj.toString()).intValue()); 264 } catch (Exception e) { 265 return null; 266 } 267 } 268 269 public static Boolean convertToBoolean(Object obj) { 270 try { 271 if (obj instanceof Boolean ) 272 return (Boolean ) obj; 273 return new Boolean (obj.toString()); 274 } catch (Exception e) { 275 return null; 276 } 277 } 278 279 public static String convertToString(Object obj) { 280 try { 281 String result = obj.toString(); 282 if (result.equals("")) 283 result = null; 284 return result; 285 } catch (Exception e) { 286 return null; 287 } 288 } 289 290 private static DateFormat createDateFormatter(String pattern) { 291 DateFormat formatter = new SimpleDateFormat(pattern); 292 formatter.setLenient(false); 293 return formatter; 294 } 295 296 public static String urlEncode(String 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 urlDecode(String url) { 308 try { 309 if (url == null) 310 return null; 311 return URLDecoder.decode(url, getCharacterEncoding()); 312 } catch (Exception e) { 313 log.error("Error while trying to decode url" + url, e); 314 return url; 315 } 316 } 317 318 private static boolean hasFormattingCharacters(String text) { 319 if (!TextUtils.stringSet(text)) 320 return false; 321 String illegalChars[] = {"+", "-"}; 322 for (int i = 0; i < illegalChars.length; i++) { 323 String illegalChar = illegalChars[i]; 324 if (text.indexOf(illegalChar) != -1) 325 return true; 326 } 327 328 return false; 329 } 330 331 public static String appendAmpsandOrQuestionMark(String 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 summarise(String 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 summariseWithoutStrippingWikiCharacters(String content) { 358 if (content.length() > 255) 359 return TextUtils.trimToEndingChar(content, 251) + "..."; 360 else 361 return content; 362 } 363 364 public static String wordWrap(String str, int max) { 365 if (!TextUtils.stringSet(str)) 366 return str; 367 StringBuffer sb = new StringBuffer (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 highlight(String content, String searchwords) { 385 if (!TextUtils.stringSet(content) || !TextUtils.stringSet(searchwords)) 386 return content; 387 StringTokenizer st = new StringTokenizer (searchwords, ", "); 388 do { 389 if (!st.hasMoreTokens()) 390 break; 391 String 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 doubleUrlEncode(String s) { 400 return urlEncode(urlEncode(s)); 401 } 402 403 public static boolean isAllAscii(String 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 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 str) { 426 return str != null && str.length() > 0; 427 } 428 429 public static String formatLongTime(long time) { 430 StringBuffer result = new StringBuffer (); 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 buf) { 443 long report = time / scale; 444 time -= report * scale; 445 String 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 formatDateFull(Date date) { 453 return DateFormat.getDateInstance(0).format(date); 454 } 455 456 public static String getCharacterEncoding() { 457 return "UTF-8"; 458 } 459 460 public static String escapeCDATA(String s) { 461 if (s.indexOf("]]") < 0) 462 return s; 463 else 464 return s.replaceAll("\\]\\]", "]] "); 465 } 466 467 public static String unescapeCDATA(String s) { 468 if (s.indexOf("]] ") < 0) 469 return s; 470 else 471 return s.replaceAll("\\]\\] ", "]]"); 472 } 473 474 public static File createTempFile(String directory) { 475 Date date = new Date (); 476 String pattern = "_{0,date,MMddyyyy}_{1,time,HHmmss}"; 477 String uniqueRandomFileName = MessageFormat.format(pattern, new Object []{date, date}); 478 return new File(directory, uniqueRandomFileName); 479 } 480 481 public static String unescapeEntities(String str) { 482 Pattern hexEntityPattern = Pattern.compile("&([a-fA-F0-9]+);"); 483 Pattern decimalEntityPattern = Pattern.compile("&#([0-9]+);"); 484 str = replaceNumericEntities(str, hexEntityPattern, 16); 485 return replaceNumericEntities(str, decimalEntityPattern, 10); 486 } 487 488 private static String replaceNumericEntities(String str, Pattern pattern, int base) { 489 Matcher matcher = pattern.matcher(str); 490 StringBuffer buf = new StringBuffer (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 base64Decode(String s) { 498 try { 499 String s1 = s.replaceAll("_", "/"); 500 String s2 = s1.replaceAll("-", "+"); 501 return new String ((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 base64Encode(String 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 hackSingleQuotes(String s) { 523 if (TextUtils.stringSet(s)) 524 return s.replaceAll("'", "' + '\\\\'' + '"); 525 else 526 return s; 527 } 528 529 public boolean isInLastDays(Date 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 getRelativeTime(Date 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 ret = new StringBuffer (); 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 getFormatDateSimple(Date date) { 571 DateFormat df = new SimpleDateFormat("dd MMM"); 572 return df.format(date); 573 } 574 575 public static Cookie setCookie(String key, String value) { 576 HttpServletRequest request = ServletActionContext.getRequest(); 577 javax.servlet.http.HttpServletResponse response = ServletActionContext.getResponse(); 578 int cookieAge = 31104000; 579 String 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 getCookieValue(String key) { 586 HttpServletRequest request = ServletActionContext.getRequest(); 587 return CookieUtils.getCookieValue(request, key); 588 } 589 590 public static String htmlEncode(String s) { 591 if (!TextUtils.stringSet(s)) 592 return ""; 593 StringBuffer str = new StringBuffer (); 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: str.append("""); 600 break; 601 602 case 38: str.append("&"); 604 break; 605 606 case 60: str.append("<"); 608 break; 609 610 case 62: str.append(">"); 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 plain2html(String text) { 626 return TextUtils.plainTextToHtml(text); 627 } 628 629 public static Properties getProperties(String resource, Class callingClass) { 630 return getPropertiesFromStream(ClassLoaderUtils.getResourceAsStream(resource, callingClass)); 631 } 632 633 public static Properties 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 getPropertiesFromStream(InputStream is) { 643 if (is == null) 644 return null; 645 Properties props = new Properties (); 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 ignore) { 655 } 656 } 657 return props; 658 } 659 660 public static void unzipFile(File zipFile, File dirToExtractTo) throws Exception { 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 zipUrl, File dirToExtractTo) throws Exception { 671 Unzipper urlUnzipper = new UrlUnzipper(zipUrl, dirToExtractTo); 672 urlUnzipper.unzip(); 673 } 674 675 private static String extractGoogleUrl(String url, int indexOfQuery) { 676 try { 677 int indexOfAmpersand = url.indexOf("&", indexOfQuery); 678 String 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 e) { 685 } 686 return url; 687 } 688 689 } 690 691 | Popular Tags |