1 31 package org.blojsom.util; 32 33 import org.blojsom.blog.Blog; 34 import org.blojsom.blog.Response; 35 36 import javax.servlet.http.HttpServletRequest ; 37 import javax.servlet.http.HttpServletResponse ; 38 import java.io.*; 39 import java.net.URLDecoder ; 40 import java.net.URLEncoder ; 41 import java.nio.ByteBuffer ; 42 import java.nio.channels.FileChannel ; 43 import java.security.MessageDigest ; 44 import java.security.NoSuchAlgorithmException ; 45 import java.text.Collator ; 46 import java.text.SimpleDateFormat ; 47 import java.util.*; 48 import java.util.regex.Pattern ; 49 import java.util.regex.Matcher ; 50 51 58 public class BlojsomUtils implements BlojsomConstants { 59 60 private static final int REGEX_OPTIONS = Pattern.DOTALL | Pattern.CASE_INSENSITIVE; 61 private static final Pattern STRIP_HTML_PATTERN = Pattern.compile("^[^<>]*>|<.*?>|<[^<>]*$", REGEX_OPTIONS); 62 63 66 private BlojsomUtils() { 67 } 68 69 72 private static final FileFilter DIRECTORY_FILTER = new FileFilter() { 73 74 82 public boolean accept(File pathname) { 83 return (pathname.isDirectory()); 84 } 85 }; 86 87 90 private static final FileFilter FILE_FILTER = new FileFilter() { 91 92 100 public boolean accept(File pathname) { 101 return (!pathname.isDirectory()); 102 } 103 }; 104 105 110 private static final ThreadLocal RFC_822_DATE_FORMAT_OBJECT = new ThreadLocal () { 111 protected Object initialValue() { 112 return new SimpleDateFormat (RFC_822_DATE_FORMAT, Locale.US); 113 } 114 }; 115 116 121 private static final ThreadLocal ISO_8601_DATE_FORMAT_OBJECT = new ThreadLocal () { 122 protected Object initialValue() { 123 SimpleDateFormat sdf = new SimpleDateFormat (ISO_8601_DATE_FORMAT); 124 sdf.getTimeZone().setID("+00:00"); 125 return sdf; 126 } 127 }; 128 129 134 private static final ThreadLocal UTC_DATE_FORMAT_OBJECT = new ThreadLocal () { 135 protected Object initialValue() { 136 return new SimpleDateFormat (UTC_DATE_FORMAT); 137 } 138 }; 139 140 145 public static FileFilter getDirectoryFilter() { 146 return DIRECTORY_FILTER; 147 } 148 149 156 public static FileFilter getDirectoryFilter(final String [] excludedDirectories) { 157 if (excludedDirectories == null) { 158 return DIRECTORY_FILTER; 159 } 160 161 return new FileFilter() { 162 public boolean accept(File pathname) { 163 if (!pathname.isDirectory()) { 164 return false; 165 } else { 166 for (int i = 0; i < excludedDirectories.length; i++) { 167 String excludedDirectory = excludedDirectories[i]; 168 if (pathname.toString().matches(excludedDirectory)) { 169 return false; 170 } 171 } 172 } 173 return true; 174 } 175 }; 176 } 177 178 184 public static String getRFC822Date(Date date) { 185 return ((SimpleDateFormat ) RFC_822_DATE_FORMAT_OBJECT.get()).format(date); 186 } 187 188 196 public static String getFormattedDate(Date date, String format, Locale locale) { 197 SimpleDateFormat sdf = new SimpleDateFormat (format, locale); 198 return sdf.format(date); 199 } 200 201 208 public static String getISO8601Date(Date date) { 209 return ((SimpleDateFormat ) ISO_8601_DATE_FORMAT_OBJECT.get()).format(date).replaceAll("GMT", ""); 210 } 211 212 218 public static String getUTCDate(Date date) { 219 return ((SimpleDateFormat ) UTC_DATE_FORMAT_OBJECT.get()).format(date); 220 } 221 222 228 public static FileFilter getRegularExpressionFilter(final String [] expressions) { 229 return new FileFilter() { 230 231 private Date today = new Date(); 232 233 public boolean accept(File pathname) { 234 if (pathname.isDirectory()) { 235 return false; 236 } 237 238 for (int i = 0; i < expressions.length; i++) { 239 String expression = expressions[i]; 240 if (pathname.getName().matches(expression)) { 241 return pathname.lastModified() <= today.getTime(); 242 } 243 } 244 245 return false; 246 } 247 }; 248 } 249 250 256 public static FileFilter getExtensionsFilter(final String [] extensions) { 257 return new FileFilter() { 258 public boolean accept(File pathname) { 259 if (pathname.isDirectory()) { 260 return false; 261 } 262 263 for (int i = 0; i < extensions.length; i++) { 264 String extension = extensions[i]; 265 if (pathname.getName().endsWith(extension)) { 266 return true; 267 } 268 } 269 return false; 270 } 271 }; 272 } 273 274 281 public static FileFilter getExtensionsFilter(final String [] extensions, final String [] excludedDirectories, final boolean returnDirectories) { 282 return new FileFilter() { 283 public boolean accept(File pathname) { 284 if (pathname.isDirectory() && returnDirectories) { 285 String path = pathname.toString(); 286 287 for (int i = 0; i < excludedDirectories.length; i++) { 288 String excludedDirectory = excludedDirectories[i]; 289 if (path.matches(excludedDirectory)) { 290 return false; 291 } 292 } 293 294 return true; 295 } 296 297 for (int i = 0; i < extensions.length; i++) { 298 String extension = extensions[i]; 299 if (pathname.getName().matches(extension)) { 300 return true; 301 } 302 } 303 304 return false; 305 } 306 }; 307 } 308 309 315 public static FileFilter getExtensionFilter(final String extension) { 316 return getExtensionsFilter(new String []{extension}); 317 } 318 319 325 public static String [] parseCommaList(String commaList) { 326 return parseDelimitedList(commaList, ", "); 327 } 328 329 335 public static String [] parseOnlyCommaList(String commaList) { 336 return parseOnlyCommaList(commaList, false); 337 } 338 339 346 public static String [] parseOnlyCommaList(String commaList, boolean trim) { 347 return parseDelimitedList(commaList, ",", trim); 348 } 349 350 356 public static String [] parseLastComma(String value) { 357 if (checkNullOrBlank(value)) { 358 return new String []{value}; 359 } 360 361 int lastCommaIndex = value.lastIndexOf(","); 362 363 if (lastCommaIndex == -1) { 364 return new String []{value}; 365 } else { 366 return new String []{value.substring(0, lastCommaIndex), value.substring(lastCommaIndex + 1)}; 367 } 368 } 369 370 377 public static String [] parseDelimitedList(String delimitedList, String delimiter) { 378 return parseDelimitedList(delimitedList, delimiter, false); 379 } 380 381 389 public static String [] parseDelimitedList(String delimitedList, String delimiter, boolean trim) { 390 if (delimitedList == null) { 391 return null; 392 } 393 394 StringTokenizer tokenizer = new StringTokenizer(delimitedList, delimiter); 395 ArrayList list = new ArrayList(); 396 while (tokenizer.hasMoreTokens()) { 397 if (trim) { 398 list.add(tokenizer.nextToken().trim()); 399 } else { 400 list.add(tokenizer.nextToken()); 401 } 402 } 403 404 if (list.size() == 0) { 405 return new String []{}; 406 } 407 408 return (String []) list.toArray(new String [list.size()]); 409 } 410 411 417 public static String convertRequestParams(HttpServletRequest request) { 418 Enumeration paramNames = request.getParameterNames(); 419 StringBuffer buffer = new StringBuffer (); 420 while (paramNames.hasMoreElements()) { 421 String name = (String ) paramNames.nextElement(); 422 String value = request.getParameter(name); 423 try { 424 buffer.append(URLEncoder.encode(name, UTF8)).append("=").append(URLEncoder.encode(value, UTF8)); 425 } catch (UnsupportedEncodingException e) { 426 } 427 if (paramNames.hasMoreElements()) { 428 buffer.append("&"); 429 } 430 } 431 return buffer.toString(); 432 } 433 434 441 public static String convertRequestParams(HttpServletRequest request, Map ignoreParams) { 442 Enumeration paramNames = request.getParameterNames(); 443 StringBuffer buffer = new StringBuffer (); 444 while (paramNames.hasMoreElements()) { 445 String name = (String ) paramNames.nextElement(); 446 String value = request.getParameter(name); 447 try { 449 if (!ignoreParams.containsKey(name)) { 450 buffer.append(URLEncoder.encode(name, UTF8)).append("=").append(URLEncoder.encode(value, UTF8)).append("&"); 451 } 452 } catch (UnsupportedEncodingException e) { 453 } 454 } 455 456 return buffer.toString(); 457 } 458 459 466 public static String getBlogSiteURL(String blogURL, String servletPath) { 467 if (servletPath == null || "".equals(servletPath)) { 468 return blogURL; 469 } 470 int servletPathIndex = blogURL.indexOf(servletPath, 7); 471 if (servletPathIndex == -1) { 472 return blogURL; 473 } 474 475 return blogURL.substring(0, servletPathIndex); 476 } 477 478 484 public static String escapeString(String input) { 485 if (input == null) { 486 return null; 487 } 488 489 String unescaped = replace(input, "&", "&"); 490 unescaped = replace(unescaped, "<", "<"); 491 unescaped = replace(unescaped, ">", ">"); 492 unescaped = replace(unescaped, "\"", """); 493 unescaped = replace(unescaped, "'", "'"); 494 495 return unescaped; 496 } 497 498 504 public static String escapeStringSimple(String input) { 505 if (input == null) { 506 return null; 507 } 508 509 String unescaped = replace(input, "&", "&"); 510 unescaped = replace(unescaped, "<", "<"); 511 unescaped = replace(unescaped, ">", ">"); 512 513 return unescaped; 514 } 515 516 522 public static String escapeBrackets(String input) { 523 if (input == null) { 524 return null; 525 } 526 527 String unescaped = replace(input, "<", "<"); 528 unescaped = replace(unescaped, ">", ">"); 529 530 return unescaped; 531 } 532 533 539 public static String escapeMetaAndLink(String input) { 540 if (input == null) { 541 return null; 542 } 543 544 String cleanedInput = input.replaceAll("<[mM][eE][tT][aA]", "<meta"); 545 cleanedInput = cleanedInput.replaceAll("<[lL][iI][nN][kK]", "<link"); 546 return cleanedInput; 547 } 548 549 557 public static String replace(String str, String pattern, String replace) { 558 if (str == null || "".equals(str)) { 559 return str; 560 } 561 562 if (replace == null) { 563 return str; 564 } 565 566 if ("".equals(pattern)) { 567 return str; 568 } 569 570 int s = 0; 571 int e; 572 StringBuffer result = new StringBuffer (); 573 574 while ((e = str.indexOf(pattern, s)) >= 0) { 575 result.append(str.substring(s, e)); 576 result.append(replace); 577 s = e + pattern.length(); 578 } 579 result.append(str.substring(s)); 580 return result.toString(); 581 } 582 583 590 public static String getFileExtension(String filename) { 591 if (filename == null) { 592 return null; 593 } 594 595 int dotIndex = filename.lastIndexOf("."); 596 if (dotIndex == -1) { 597 return null; 598 } else { 599 return filename.substring(dotIndex + 1); 600 } 601 } 602 603 609 public static String getFilename(String filename) { 610 int dotIndex = filename.lastIndexOf("."); 611 if (dotIndex == -1) { 612 return filename; 613 } else { 614 return filename.substring(0, dotIndex); 615 } 616 } 617 618 627 public static String getFilenameFromPath(String filenameWithPath) { 628 String fileName = new File(filenameWithPath).getName(); 630 631 int colonIndex = fileName.indexOf(":"); 633 if (colonIndex == -1) { 634 colonIndex = fileName.indexOf("\\\\"); 636 } 637 int backslashIndex = fileName.lastIndexOf("\\"); 638 639 if (colonIndex > -1 && backslashIndex > -1) { 640 fileName = fileName.substring(backslashIndex + 1); 643 } 644 645 return fileName; 646 } 647 648 654 public static String getDateKey(Date date) { 655 StringBuffer value = new StringBuffer (); 656 Calendar calendar = Calendar.getInstance(); 657 long l; 658 659 calendar.setTime(date); 660 value.append(calendar.get(Calendar.YEAR)); 661 l = calendar.get(Calendar.MONTH) + 1; 665 if (l < 10) { 666 value.append("0"); 667 } 668 value.append(l); 669 l = calendar.get(Calendar.DAY_OF_MONTH); 670 if (l < 10) { 671 value.append("0"); 672 } 673 value.append(l); 674 677 return value.toString(); 678 } 679 680 686 public static String removeInitialSlash(String input) { 687 if (input == null) { 688 return null; 689 } 690 691 if (!input.startsWith("/")) { 692 return input; 693 } else { 694 return input.substring(1); 695 } 696 } 697 698 704 public static String removeTrailingSlash(String input) { 705 if (input == null) { 706 return null; 707 } 708 709 if (!input.endsWith("/")) { 710 return input; 711 } else { 712 return input.substring(0, input.length() - 1); 713 } 714 } 715 716 722 public static String removeSlashes(String input) { 723 input = removeInitialSlash(input); 724 input = removeTrailingSlash(input); 725 return input; 726 } 727 728 735 public static String getFirstLine(String input, int length) { 736 String result; 737 String lineSeparator = LINE_SEPARATOR; 738 int titleIndex = input.indexOf(lineSeparator); 739 if (titleIndex == -1) { 740 result = input.substring(0, length) + "..."; 741 } else { 742 result = input.substring(0, titleIndex); 743 } 744 return result; 745 } 746 747 754 public static String getTemplateForPage(String flavorTemplate, String page) { 755 int dotIndex = flavorTemplate.lastIndexOf("."); 756 if (dotIndex == -1) { 757 return flavorTemplate + '-' + page; 758 } else { 759 StringBuffer newTemplate = new StringBuffer (); 760 if (page.startsWith("/")) { 761 newTemplate.append(removeInitialSlash(page)); 762 } else { 763 newTemplate.append(flavorTemplate.substring(0, dotIndex)); 764 newTemplate.append("-"); 765 newTemplate.append(page); 766 } 767 newTemplate.append("."); 768 newTemplate.append(flavorTemplate.substring(dotIndex + 1, flavorTemplate.length())); 769 return newTemplate.toString(); 770 } 771 } 772 773 781 public static String getRequestValue(String key, HttpServletRequest httpServletRequest) { 782 return getRequestValue(key, httpServletRequest, false); 783 } 784 785 794 public static String getRequestValue(String key, HttpServletRequest httpServletRequest, boolean preferAttributes) { 795 if (!preferAttributes) { 796 if (httpServletRequest.getParameter(key) != null) { 797 return httpServletRequest.getParameter(key); 798 } else if (httpServletRequest.getAttribute(key) != null) { 799 return httpServletRequest.getAttribute(key).toString(); 800 } 801 } else { 802 if (httpServletRequest.getAttribute(key) != null) { 803 return httpServletRequest.getAttribute(key).toString(); 804 } else if (httpServletRequest.getParameter(key) != null) { 805 return httpServletRequest.getParameter(key); 806 } 807 } 808 809 return null; 810 } 811 812 819 public static String [] getRequestValues(String key, HttpServletRequest httpServletRequest) { 820 String [] values = httpServletRequest.getParameterValues(key); 821 822 if (values == null) { 823 values = new String [0]; 824 } 825 826 return values; 827 } 828 829 836 public static String getFilenameForPermalink(String permalink, String [] blogEntryExtensions) { 837 if (permalink == null) { 838 return null; 839 } 840 841 boolean matchesExtension = false; 842 for (int i = 0; i < blogEntryExtensions.length; i++) { 843 String blogEntryExtension = blogEntryExtensions[i]; 844 if (permalink.matches(blogEntryExtension)) { 845 matchesExtension = true; 846 break; 847 } 848 } 849 850 if (!matchesExtension) { 851 return null; 852 } 853 854 int indexOfSlash = permalink.lastIndexOf("/"); 855 if (indexOfSlash == -1) { 856 indexOfSlash = permalink.lastIndexOf("\\"); 857 } 858 859 if (indexOfSlash == -1) { 860 return permalink; 861 } else { 862 String sanitizedPermalink = permalink.substring(indexOfSlash + 1, permalink.length()); 863 if (sanitizedPermalink.startsWith("..")) { 864 sanitizedPermalink = sanitizedPermalink.substring(2, sanitizedPermalink.length()); 865 } else if (sanitizedPermalink.startsWith(".")) { 866 sanitizedPermalink = sanitizedPermalink.substring(1, sanitizedPermalink.length()); 867 } 868 869 return sanitizedPermalink; 870 } 871 } 872 873 880 public static String urlEncode(String input) { 881 if (input == null) { 882 return null; 883 } 884 885 try { 886 return URLEncoder.encode(input, UTF8); 887 } catch (UnsupportedEncodingException e) { 888 return input; 889 } 890 } 891 892 899 public static String urlEncodeForLink(String input) { 900 if (input == null) { 901 return null; 902 } 903 904 try { 905 String result = URLEncoder.encode(input, UTF8); 906 result = replace(result, "%2F", "/"); 907 result = replace(result, "%20", "+"); 908 return result; 909 } catch (UnsupportedEncodingException e) { 910 return input; 911 } 912 } 913 914 920 public static String urlDecode(String input) { 921 if (input == null) { 922 return null; 923 } 924 925 try { 926 return URLDecoder.decode(input, UTF8); 927 } catch (UnsupportedEncodingException e) { 928 return null; 929 } 930 } 931 932 941 public static String getCalendarNavigationUrl(String prefix, int month, int day, int year) { 942 StringBuffer dateurl = new StringBuffer (prefix); 943 944 if (year != -1) { 945 dateurl.append(year).append("/"); 946 } 947 948 if (month != -1) { 949 if (month < 10) { 950 dateurl.append("0"); 951 } 952 953 dateurl.append(month).append("/"); 954 } 955 956 if (day != -1) { 957 if (day < 10) { 958 dateurl.append("0"); 959 } 960 961 dateurl.append(day).append("/"); 962 } 963 964 return dateurl.toString(); 965 } 966 967 970 public static final Comparator FILE_NAME_COMPARATOR = new Comparator() { 971 public int compare(Object o1, Object o2) { 972 String s1 = (String ) o1; 973 String s2 = (String ) o2; 974 975 return s1.compareTo(s2); 976 } 977 }; 978 979 static final byte[] HEX_DIGITS = { 980 (byte) '0', (byte) '1', (byte) '2', (byte) '3', 981 (byte) '4', (byte) '5', (byte) '6', (byte) '7', 982 (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', 983 (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' 984 }; 985 986 992 public static String digestString(String data) { 993 return digestString(data, DEFAULT_DIGEST_ALGORITHM); 994 } 995 996 1003 public static String digestString(String data, String algorithm) { 1004 String result = null; 1005 if (data != null) { 1006 try { 1007 MessageDigest _md = MessageDigest.getInstance(algorithm); 1008 _md.update(data.getBytes()); 1009 byte[] _digest = _md.digest(); 1010 String _ds; 1011 _ds = toHexString(_digest, 0, _digest.length); 1012 result = _ds; 1013 } catch (NoSuchAlgorithmException e) { 1014 result = null; 1015 } 1016 } 1017 return result; 1018 } 1019 1020 1028 private static void toHexValue(byte[] buf, int offset, int length, int value) { 1029 do { 1030 buf[offset + --length] = HEX_DIGITS[value & 0x0f]; 1031 value >>>= 4; 1032 } while (value != 0 && length > 0); 1033 1034 while (--length >= 0) { 1035 buf[offset + length] = HEX_DIGITS[0]; 1036 } 1037 } 1038 1039 1047 public static String toHexString(byte[] buf, int offset, int length) { 1048 byte[] buf1 = new byte[length * 2]; 1049 for (int i = 0; i < length; i++) { 1050 toHexValue(buf1, i * 2, 2, buf[i + offset]); 1051 } 1052 return new String (buf1); 1053 } 1054 1055 1061 public static String normalize(String path) { 1062 if (path == null) { 1063 return null; 1064 } 1065 1066 String value = path; 1067 value = value.replaceAll("\\.*", ""); 1068 value = value.replaceAll("/{2,}", ""); 1069 return value; 1070 } 1071 1072 1078 public static String nullToBlank(String input) { 1079 return (input == null) ? "" : input; 1080 } 1081 1082 1089 public static Map propertiesToMap(Properties properties) { 1090 if (properties == null) { 1091 return new HashMap(); 1092 } else { 1093 Iterator keyIterator = properties.keySet().iterator(); 1094 Object key; 1095 Object value; 1096 HashMap convertedProperties = new HashMap(); 1097 while (keyIterator.hasNext()) { 1098 key = keyIterator.next(); 1099 value = properties.get(key); 1100 convertedProperties.put(key, value); 1101 } 1102 1103 return convertedProperties; 1104 } 1105 } 1106 1107 1114 public static Map blojsomPropertiesToMap(Properties properties) { 1115 if (properties == null) { 1116 return new HashMap(); 1117 } else { 1118 Iterator keyIterator = properties.keySet().iterator(); 1119 Object key; 1120 Object value; 1121 HashMap convertedProperties = new HashMap(); 1122 while (keyIterator.hasNext()) { 1123 key = keyIterator.next(); 1124 value = properties.get(key); 1125 if (value instanceof List) { 1126 convertedProperties.put(key, value); 1127 } else { 1128 ArrayList values = new ArrayList(); 1129 values.add(value.toString()); 1130 convertedProperties.put(key, values); 1131 } 1132 } 1133 1134 return convertedProperties; 1135 } 1136 } 1137 1138 1146 public static String arrayOfStringsToString(String [] array, String separator) { 1147 if (array == null) { 1148 return null; 1149 } 1150 1151 StringBuffer result = new StringBuffer (); 1152 if (array.length > 0) { 1153 result.append(array[0]); 1154 for (int i = 1; i < array.length; i++) { 1156 result.append(separator); 1157 result.append(array[i]); 1158 } 1159 } 1160 1161 return result.toString(); 1162 } 1163 1164 1171 public static String arrayOfStringsToString(String [] array) { 1172 return arrayOfStringsToString(array, ", "); 1173 } 1174 1175 1183 public static String getCategoryFromPath(String pathInfo) { 1184 if (pathInfo == null || "/".equals(pathInfo)) { 1185 return "/"; 1186 } else { 1187 int categoryStart = pathInfo.indexOf("/", 1); 1188 if (categoryStart == -1) { 1189 return "/"; 1190 } else { 1191 return pathInfo.substring(categoryStart); 1192 } 1193 } 1194 } 1195 1196 1204 public static String getBlogFromPath(String pathInfo) { 1205 if (pathInfo == null || "/".equals(pathInfo)) { 1206 return null; 1207 } else { 1208 int userEnd = pathInfo.indexOf("/", 1); 1209 if (userEnd == -1) { 1210 return pathInfo.substring(1); 1211 } else { 1212 return pathInfo.substring(1, userEnd); 1213 } 1214 } 1215 } 1216 1217 1223 public static boolean deleteDirectory(File directoryOrFile) { 1224 return deleteDirectory(directoryOrFile, true); 1225 } 1226 1227 1234 public static boolean deleteDirectory(File directoryOrFile, boolean removeDirectoryOrFile) { 1235 if (directoryOrFile.isDirectory()) { 1236 File[] children = directoryOrFile.listFiles(); 1237 if (children != null && children.length > 0) { 1238 for (int i = 0; i < children.length; i++) { 1239 boolean success = deleteDirectory(children[i]); 1240 if (!success) { 1241 return false; 1242 } 1243 } 1244 } 1245 } 1246 1247 if (removeDirectoryOrFile) { 1248 return directoryOrFile.delete(); 1249 } 1250 1251 return true; 1252 } 1253 1254 1261 public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { 1262 File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); 1263 File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); 1264 1265 targetDirectory.mkdirs(); 1266 1267 if (sourceFiles != null && sourceFiles.length > 0) { 1269 for (int i = 0; i < sourceFiles.length; i++) { 1270 File sourceFile = sourceFiles[i]; 1271 1272 FileInputStream fis = new FileInputStream(sourceFile); 1273 FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); 1274 FileChannel fcin = fis.getChannel(); 1275 FileChannel fcout = fos.getChannel(); 1276 1277 ByteBuffer buf = ByteBuffer.allocateDirect(8192); 1278 long size = fcin.size(); 1279 long n = 0; 1280 while (n < size) { 1281 buf.clear(); 1282 if (fcin.read(buf) < 0) { 1283 break; 1284 } 1285 buf.flip(); 1286 n += fcout.write(buf); 1287 } 1288 1289 fcin.close(); 1290 fcout.close(); 1291 fis.close(); 1292 fos.close(); 1293 } 1294 } 1295 1296 if (sourceDirectories != null && sourceDirectories.length > 0) { 1298 for (int i = 0; i < sourceDirectories.length; i++) { 1299 File directory = sourceDirectories[i]; 1300 File newTargetDirectory = new File(targetDirectory, directory.getName()); 1301 1302 copyDirectory(directory, newTargetDirectory); 1303 } 1304 } 1305 } 1306 1307 1314 public static Map arrayOfStringsToMap(String [] array) { 1315 if (array == null) { 1316 return new HashMap(); 1317 } 1318 1319 Map result = new HashMap(); 1320 for (int i = 0; i < array.length; i++) { 1321 result.put(array[i], array[i]); 1322 } 1323 1324 return result; 1325 } 1326 1327 1333 public static String checkStartingAndEndingSlash(String input) { 1334 if (input == null) { 1335 return null; 1336 } 1337 1338 if (!input.startsWith("/")) { 1339 input = "/" + input; 1340 } 1341 1342 if (!input.endsWith("/")) { 1343 input += "/"; 1344 } 1345 1346 return input; 1347 } 1348 1349 1355 public static boolean checkNullOrBlank(String input) { 1356 return (input == null || "".equals(input.trim())); 1357 } 1358 1359 1364 public static void setNoCacheControlHeaders(HttpServletResponse httpServletResponse) { 1365 httpServletResponse.setHeader(PRAGMA_HTTP_HEADER, NO_CACHE_HTTP_HEADER_VALUE); 1366 httpServletResponse.setHeader(CACHE_CONTROL_HTTP_HEADER, NO_CACHE_HTTP_HEADER_VALUE); 1367 } 1368 1369 1377 public static boolean checkMapForKey(Map map, String key) { 1378 if (map == null) { 1379 return false; 1380 } 1381 1382 if (key == null) { 1383 return false; 1384 } 1385 1386 return map.containsKey(key); 1387 } 1388 1389 1396 public static int daysBetweenDates(Date startDate, Date endDate) { 1397 if (startDate == null || endDate == null) { 1398 return 0; 1399 } 1400 1401 Calendar calendarStartDate = Calendar.getInstance(); 1402 calendarStartDate.setTime(startDate); 1403 int startDay = calendarStartDate.get(Calendar.DAY_OF_YEAR); 1404 int startYear = calendarStartDate.get(Calendar.YEAR); 1405 Calendar calendarEndDate = Calendar.getInstance(); 1406 calendarEndDate.setTime(endDate); 1407 int endDay = calendarEndDate.get(Calendar.DAY_OF_YEAR); 1408 int endYear = calendarEndDate.get(Calendar.YEAR); 1409 1410 return Math.abs((endDay - startDay) + ((endYear - startYear) * 365)); 1411 } 1412 1413 1419 public static File getFilenameForDate(String filename) { 1420 String filenameWithoutExtension = getFilename(filename); 1421 String fileExtension = getFileExtension(filename); 1422 1423 if (fileExtension == null) { 1424 return null; 1425 } else { 1426 return new File(filenameWithoutExtension + "-" + new Date().getTime() + "." + fileExtension); 1427 } 1428 } 1429 1430 1436 public static String stripLineTerminators(String input) { 1437 return stripLineTerminators(input, ""); 1438 } 1439 1440 1447 public static String stripLineTerminators(String input, String replacement) { 1448 if (input == null) { 1449 return null; 1450 } 1451 1452 return input.replaceAll("[\n\r\f]", replacement); 1453 } 1454 1455 1461 public static String getKeysAsStringList(Map input) { 1462 StringBuffer result = new StringBuffer (); 1463 if (input == null || input.size() == 0) { 1464 return result.toString(); 1465 } 1466 1467 Iterator keyIterator = input.keySet().iterator(); 1468 int counter = 0; 1469 while (keyIterator.hasNext()) { 1470 Object key = keyIterator.next(); 1471 result.append(key); 1472 1473 if (counter < input.size() - 1) { 1474 result.append(", "); 1475 } 1476 1477 counter++; 1478 } 1479 1480 return result.toString(); 1481 } 1482 1483 1491 public static String listToCSV(List values) { 1492 StringBuffer result = new StringBuffer (); 1493 1494 if (values != null && values.size() > 0) { 1495 for (int i = 0; i < values.size(); i++) { 1496 if (values.get(i) == null) { 1497 result.append(" "); 1498 } else { 1499 result.append(values.get(i)); 1500 } 1501 1502 if (i < values.size() - 1) { 1503 result.append(", "); 1504 } 1505 } 1506 } 1507 1508 return result.toString(); 1509 } 1510 1511 1518 public static Map listToMap(List values) { 1519 Map valueMap = new HashMap(); 1520 1521 if (values != null && values.size() > 0) { 1522 Iterator valueIterator = values.iterator(); 1523 Object value; 1524 while (valueIterator.hasNext()) { 1525 value = valueIterator.next(); 1526 if (value != null) { 1527 valueMap.put(value, value); 1528 } 1529 } 1530 } 1531 1532 return valueMap; 1533 } 1534 1535 1541 public static List csvToList(String valuesAsString) { 1542 String [] values = parseOnlyCommaList(valuesAsString); 1543 ArrayList updated = new ArrayList(); 1544 for (int i = 0; i < values.length; i++) { 1545 String value = values[i].trim(); 1546 updated.add(value); 1547 } 1548 1549 return updated; 1550 } 1551 1552 1558 public static String constructBaseURL(HttpServletRequest httpServletRequest) { 1559 StringBuffer result = new StringBuffer (); 1560 1561 result.append(httpServletRequest.getScheme()).append("://"); 1562 result.append(httpServletRequest.getServerName()); 1563 if (httpServletRequest.getServerPort() != 80) { 1564 result.append(":").append(httpServletRequest.getServerPort()); 1565 } 1566 result.append(httpServletRequest.getContextPath()); 1567 1568 return result.toString(); 1569 } 1570 1571 1578 public static String constructBlogURL(HttpServletRequest httpServletRequest, String blogID) { 1579 StringBuffer result = new StringBuffer (constructBaseURL(httpServletRequest)); 1580 1581 result.append(httpServletRequest.getServletPath()).append("/").append(blogID); 1582 1583 return result.toString(); 1584 } 1585 1586 1592 public static String getHashableContent(String content) { 1593 String hashable = content; 1594 1595 if (content.length() > MAX_HASHABLE_LENGTH) { 1596 hashable = hashable.substring(0, MAX_HASHABLE_LENGTH); 1597 } 1598 1599 return digestString(hashable).toUpperCase(); 1600 } 1601 1602 1609 public static String getPostSlug(String title, String content) { 1610 String slug; 1611 1612 if (!checkNullOrBlank(title)) { 1613 slug = title.replaceAll("\\s", "_"); 1614 slug = slug.replaceAll("'", ""); 1615 slug = slug.replaceAll("\\p{Punct}", "_"); 1616 slug = slug.replaceAll("_{2,}", "_"); 1617 slug = slug.replaceAll("_", "-"); 1618 String backup = slug; 1619 slug = slug.replaceAll("^-{1,}", ""); 1620 slug = slug.replaceAll("-{1,}$", ""); 1621 if (checkNullOrBlank(slug)) { 1622 slug = backup; 1623 } 1624 } else { 1625 slug = getHashableContent(content); 1626 } 1627 1628 return slug; 1629 } 1630 1631 1638 public static Locale getLocaleFromString(String locale) { 1639 if (checkNullOrBlank(locale)) { 1640 return Locale.getDefault(); 1641 } 1642 1643 String language = locale; 1644 String country = ""; 1645 String variant = ""; 1646 1647 int index = language.indexOf('_'); 1649 if (index >= 0) { 1650 country = language.substring(index + 1); 1651 language = language.substring(0, index); 1652 } 1653 1654 index = country.indexOf('_'); 1656 if (index >= 0) { 1657 variant = country.substring(index + 1); 1658 country = country.substring(0, index); 1659 } 1660 1661 return new Locale(language, country, variant); 1662 } 1663 1664 1670 public static String [] getLanguagesForSystem(Locale locale) { 1671 Locale[] installedLocales = Locale.getAvailableLocales(); 1672 ArrayList languageList = new ArrayList(installedLocales.length); 1673 String [] languages; 1674 String language; 1675 1676 for (int i = 0; i < installedLocales.length; i++) { 1677 Locale installedLocale = installedLocales[i]; 1678 language = installedLocale.getLanguage(); 1679 if (!languageList.contains(language) && !checkNullOrBlank(language)) { 1680 languageList.add(language); 1681 } 1682 } 1683 1684 languages = (String []) languageList.toArray(new String [languageList.size()]); 1685 Collator collator = Collator.getInstance(locale); 1686 Arrays.sort(languages, collator); 1687 1688 return languages; 1689 } 1690 1691 1697 public static String [] getCountriesForSystem(Locale locale) { 1698 Locale[] installedLocales = Locale.getAvailableLocales(); 1699 ArrayList countryList = new ArrayList(installedLocales.length); 1700 String [] countries; 1701 String country; 1702 1703 for (int i = 0; i < installedLocales.length; i++) { 1704 Locale installedLocale = installedLocales[i]; 1705 country = installedLocale.getCountry(); 1706 if (!countryList.contains(country) && !checkNullOrBlank(country)) { 1707 countryList.add(country); 1708 } 1709 } 1710 1711 countries = (String []) countryList.toArray(new String [countryList.size()]); 1712 Collator collator = Collator.getInstance(locale); 1713 Arrays.sort(countries, collator); 1714 1715 return countries; 1716 } 1717 1718 1724 public static String [] getTimeZonesForSystem(Locale locale) { 1725 String [] timezones = TimeZone.getAvailableIDs(); 1726 1727 Collator collator = Collator.getInstance(locale); 1728 Arrays.sort(timezones, collator); 1729 1730 return timezones; 1731 } 1732 1733 1741 public static void listFilesInSubdirectories(File directory, String parentDirectory, List files) { 1742 if (directory.isDirectory()) { 1743 String [] children = directory.list(); 1744 for (int i = 0; i < children.length; i++) { 1745 listFilesInSubdirectories(new File(directory, children[i]), parentDirectory, files); 1746 } 1747 } else { 1748 if (directory.getPath().startsWith(parentDirectory)) { 1749 files.add(new File(directory.getPath().substring(parentDirectory.length() + 1))); 1750 } 1751 } 1752 } 1753 1754 1762 public static void listDirectoriesInSubdirectories(File directory, String parentDirectory, List directories) { 1763 if (directory.isDirectory()) { 1764 String [] children = directory.list(); 1765 for (int i = 0; i < children.length; i++) { 1766 listDirectoriesInSubdirectories(new File(directory, children[i]), parentDirectory, directories); 1767 } 1768 1769 if (directory.getPath().startsWith(parentDirectory)) { 1770 directories.add(new File(directory.getPath().substring(parentDirectory.length()))); 1771 } 1772 } 1773 } 1774 1775 1781 public static String stripHTML(String text) { 1782 if (checkNullOrBlank(text)) { 1783 return text; 1784 } 1785 1786 Matcher m = STRIP_HTML_PATTERN.matcher(text); 1787 1788 return m.replaceAll(""); 1789 } 1790 1791 1797 public static List arrayToList(String [] input) { 1798 if (input == null || input.length == 0) { 1799 return new ArrayList(); 1800 } else { 1801 ArrayList value = new ArrayList(input.length); 1802 1803 for (int i = 0; i < input.length; i++) { 1804 String s = input[i]; 1805 value.add(s); 1806 } 1807 1808 return value; 1809 } 1810 } 1811 1812 1818 public static List removeNullValues(List input) { 1819 if (input == null) { 1820 return new ArrayList(); 1821 } else { 1822 ArrayList sanitizedList = new ArrayList(input.size()); 1823 1824 for (int i = 0; i < input.size(); i++) { 1825 if (input.get(i) != null) { 1826 sanitizedList.add(input.get(i)); 1827 } 1828 } 1829 1830 return sanitizedList; 1831 } 1832 } 1833 1834 1840 public static String addSlashes(String input) { 1841 if (input == null) { 1842 return "/"; 1843 } 1844 1845 if (!input.startsWith("/")) { 1846 input = "/" + input; 1847 } 1848 1849 if (!input.endsWith("/")) { 1850 input += "/"; 1851 } 1852 1853 return input; 1854 } 1855 1856 1862 public static String addTrailingSlash(String input) { 1863 if (input == null) { 1864 return "/"; 1865 } 1866 1867 if (!input.endsWith("/")) { 1868 input += "/"; 1869 } 1870 1871 return input; 1872 } 1873 1874 1882 public static void resolveDynamicBaseAndBlogURL(HttpServletRequest httpServletRequest, Blog blog, String blogID) { 1883 if (checkNullOrBlank(blog.getBlogBaseURL())) { 1884 blog.setBlogBaseURL(constructBaseURL(httpServletRequest)); 1885 } 1886 1887 if (checkNullOrBlank(blog.getBlogURL())) { 1888 blog.setBlogURL(constructBlogURL(httpServletRequest, blogID)); 1889 } 1890 1891 if (checkNullOrBlank(blog.getBlogAdminURL())) { 1892 blog.setBlogAdminURL(constructBlogURL(httpServletRequest, blogID)); 1893 } 1894 1895 if (checkNullOrBlank(blog.getBlogBaseAdminURL())) { 1896 blog.setBlogBaseAdminURL(constructBaseURL(httpServletRequest)); 1897 } 1898 } 1899 1900 1907 public static String listToString(List values, String separator) { 1908 StringBuffer valuesAsString = new StringBuffer (); 1909 1910 if (values != null && values.size() > 0) { 1911 for (int i = 0; i < values.size(); i++) { 1912 String value = (String ) values.get(i); 1913 valuesAsString.append(value); 1914 if (i < values.size() - 1) { 1915 valuesAsString.append(separator); 1916 } 1917 } 1918 } 1919 1920 return valuesAsString.toString(); 1921 } 1922 1923 public static Comparator RESPONSE_COMPARATOR = new Comparator() { 1924 public int compare(Object object, Object object1) { 1925 if (object instanceof Response && object1 instanceof Response) { 1926 Response obj = (Response) object; 1927 Response obj1 = (Response) object1; 1928 1929 if (obj.getDate().before(obj1.getDate())) { 1930 return -1; 1931 } else if (obj.getDate().after(obj1.getDate())) { 1932 return 1; 1933 } 1934 } 1935 1936 return 0; 1937 } 1938 }; 1939 1940 1947 public static Date getFirstDateOfYear(Locale locale, int year) { 1948 Calendar calendar = Calendar.getInstance(locale); 1949 1950 calendar.set(Calendar.YEAR, year); 1951 calendar.set(Calendar.MONTH, calendar.getActualMinimum(Calendar.MONTH)); 1952 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 1953 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY)); 1954 calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE)); 1955 calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND)); 1956 calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND)); 1957 1958 return calendar.getTime(); 1959 } 1960 1961 1968 public static Date getLastDateOfYear(Locale locale, int year) { 1969 Calendar calendar = Calendar.getInstance(locale); 1970 1971 calendar.set(Calendar.YEAR, year); 1972 calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH)); 1973 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); 1974 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY)); 1975 calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE)); 1976 calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND)); 1977 calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND)); 1978 1979 return calendar.getTime(); 1980 } 1981 1982 1990 public static Date getFirstDateOfYearMonth(Locale locale, int year, int month) { 1991 Calendar calendar = Calendar.getInstance(locale); 1992 1993 calendar.set(Calendar.YEAR, year); 1994 calendar.set(Calendar.MONTH, month); 1995 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 1996 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY)); 1997 calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE)); 1998 calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND)); 1999 calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND)); 2000 2001 return calendar.getTime(); 2002 } 2003 2004 2012 public static Date getLastDateOfYearMonth(Locale locale, int year, int month) { 2013 Calendar calendar = Calendar.getInstance(locale); 2014 2015 calendar.set(Calendar.YEAR, year); 2016 calendar.set(Calendar.MONTH, month); 2017 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); 2018 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY)); 2019 calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE)); 2020 calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND)); 2021 calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND)); 2022 2023 return calendar.getTime(); 2024 } 2025 2026 2035 public static Date getFirstDateOfYearMonthDay(Locale locale, int year, int month, int day) { 2036 Calendar calendar = Calendar.getInstance(locale); 2037 2038 calendar.set(Calendar.YEAR, year); 2039 calendar.set(Calendar.MONTH, month); 2040 if (day < calendar.getActualMinimum(Calendar.DAY_OF_MONTH)) { 2041 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 2042 } else { 2043 calendar.set(Calendar.DAY_OF_MONTH, day); 2044 } 2045 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY)); 2046 calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE)); 2047 calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND)); 2048 calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND)); 2049 2050 return calendar.getTime(); 2051 } 2052 2053 2062 public static Date getLastDateOfYearMonthDay(Locale locale, int year, int month, int day) { 2063 Calendar calendar = Calendar.getInstance(locale); 2064 2065 calendar.set(Calendar.YEAR, year); 2066 calendar.set(Calendar.MONTH, month); 2067 if (day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { 2068 calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); 2069 } else { 2070 calendar.set(Calendar.DAY_OF_MONTH, day); 2071 } 2072 calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY)); 2073 calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE)); 2074 calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND)); 2075 calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND)); 2076 2077 return calendar.getTime(); 2078 } 2079} 2080 | Popular Tags |