1 3 package com.sslexplorer.boot; 4 5 import java.io.BufferedReader ; 6 import java.io.ByteArrayOutputStream ; 7 import java.io.File ; 8 import java.io.FileInputStream ; 9 import java.io.FileOutputStream ; 10 import java.io.IOException ; 11 import java.io.InputStream ; 12 import java.io.InputStreamReader ; 13 import java.io.OutputStream ; 14 import java.io.PrintWriter ; 15 import java.io.StringReader ; 16 import java.io.StringWriter ; 17 import java.io.UnsupportedEncodingException ; 18 import java.net.URL ; 19 import java.net.URLClassLoader ; 20 import java.net.URLDecoder ; 21 import java.net.URLEncoder ; 22 import java.util.Calendar ; 23 import java.util.Enumeration ; 24 import java.util.HashMap ; 25 import java.util.Iterator ; 26 import java.util.List ; 27 import java.util.Map ; 28 import java.util.Vector ; 29 30 import javax.servlet.ServletContext ; 31 import javax.servlet.http.HttpServletRequest ; 32 import javax.servlet.http.HttpServletResponse ; 33 import javax.servlet.http.HttpSession ; 34 35 import org.apache.commons.logging.Log; 36 import org.apache.commons.logging.LogFactory; 37 38 44 public class Util { 45 46 final static Log log = LogFactory.getLog(Util.class); 47 48 51 public static int BUFFER_SIZE = 8192; 52 53 56 private Util() { 57 super(); 58 } 59 60 68 public static String getCurrentStatement(int depth) { 69 try { 70 throw new Exception (); 71 } catch (Exception e) { 72 try { 73 StringWriter sw = new StringWriter (); 74 e.printStackTrace(new PrintWriter (sw)); 75 BufferedReader reader = new BufferedReader (new StringReader (sw.toString())); 76 reader.readLine(); 77 reader.readLine(); 78 sw = new StringWriter (); 79 PrintWriter pw = new PrintWriter (sw, true); 80 for (int i = 0; i < depth; i++) { 81 String s = reader.readLine(); 82 pw.println(s.substring(7)); 83 } 84 return sw.toString(); 85 86 } catch (Throwable t) { 87 return "Unknown."; 88 } 89 } 90 } 91 92 98 public static String trimBoth(String string) { 99 string = string.trim(); 100 for (int i = 0; i < string.length(); i++) { 101 if (string.charAt(i) != ' ') { 102 return string.substring(i); 103 } 104 } 105 return string; 106 } 107 108 114 public static void closeStream(OutputStream outputStream) { 115 if (outputStream != null) { 116 try { 117 outputStream.close(); 118 } catch (IOException ioe) { 119 120 } 121 } 122 } 123 124 130 public static void closeStream(InputStream inputStream) { 131 if (inputStream != null) { 132 try { 133 inputStream.close(); 134 } catch (IOException ioe) { 135 136 } 137 } 138 } 139 140 147 public static String valueOfNameValuePair(String nameEqualsValue) { 148 String value = nameEqualsValue.substring(nameEqualsValue.indexOf('=') + 1).trim(); 149 150 int i = value.indexOf(';'); 151 if (i > 0) 152 value = value.substring(0, i); 153 if (value.startsWith("\"")) { 154 value = value.substring(1, value.indexOf('"', 1)); 155 } 156 157 else { 158 i = value.indexOf(' '); 159 if (i > 0) 160 value = value.substring(0, i); 161 } 162 return value; 163 } 164 165 171 public static String toHexString(byte[] data) { 172 return toHexString(data, 0, data.length); 173 } 174 175 183 public static String toHexString(byte[] data, int offset, int len) { 184 StringBuffer buf = new StringBuffer (); 185 for (int i = offset; i < len; i++) { 186 String s = Integer.toHexString(((byte)data[i] & 0xFF)); 187 if (s.length() < 2) { 188 buf.append("0"); 189 } 190 buf.append(s); 191 } 192 return buf.toString(); 193 } 194 195 202 public static String getOriginalRequest(HttpServletRequest request) { 203 StringBuffer req = new StringBuffer (request.getServletPath()); 204 if (request.getQueryString() != null && request.getQueryString().length() > 0) { 205 req.append("?"); 206 req.append(request.getQueryString()); 207 } 208 return req.toString(); 209 } 210 211 219 public static String loadStreamToString(InputStream in, String charsetName) throws IOException { 220 StringBuffer licenseText = new StringBuffer (); 221 BufferedReader br = new BufferedReader (charsetName == null ? new InputStreamReader (in) : new InputStreamReader (in, 222 charsetName)); 223 try { 224 char[] buf = new char[65536]; 225 int r = 0; 226 while ((r = br.read(buf)) != -1) 227 licenseText.append(buf, 0, r); 228 } finally { 229 br.close(); 230 } 231 return licenseText.toString(); 232 } 233 234 239 public static void dumpSessionAttributes(HttpSession session) { 240 System.err.println("Session attributes for " + session.getId()); 241 for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { 242 String n = (String ) e.nextElement(); 243 System.err.println(" " + n + " = " + session.getAttribute(n)); 244 } 245 } 246 247 252 public static void dumpRequestAttributes(HttpServletRequest request) { 253 System.err.println("Request attributes for " + request.getPathTranslated()); 254 for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) { 255 String n = (String ) e.nextElement(); 256 System.err.println(" " + n + " = " + request.getAttribute(n)); 257 } 258 } 259 260 265 public static void dumpRequestHeaders(HttpServletRequest request) { 266 System.err.println("Request headers for " + request.getPathTranslated()); 267 for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { 268 String n = (String ) e.nextElement(); 269 for(Enumeration e2 = request.getHeaders(n); e2.hasMoreElements(); ) { 270 String v = (String )e2.nextElement(); 271 System.err.println(" " + n + " = " + v); 272 } 273 } 274 } 275 276 281 public static void dumpServletContextAttributes(ServletContext context) { 282 System.err.println("Servlet context attributes for"); 283 for (Enumeration e = context.getAttributeNames(); e.hasMoreElements();) { 284 String n = (String ) e.nextElement(); 285 System.err.println(" " + n + " = " + context.getAttribute(n)); 286 } 287 288 } 289 290 295 public static void dumpRequestParameters(HttpServletRequest request) { 296 System.err.println("Request parameters for session #" + request.getSession().getId()); 297 for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) { 298 String n = (String ) e.nextElement(); 299 String [] vals = request.getParameterValues(n); 300 for (int i = 0; i < vals.length; i++) { 301 System.err.println(" " + n + " = " + vals[i]); 302 } 303 } 304 305 } 306 307 313 public static void dumpRequest(HttpServletRequest request) { 314 System.err.println("Context Path " + request.getContextPath()); 315 System.err.println("Path Translated " + request.getPathTranslated()); 316 System.err.println("Path Info " + request.getPathInfo()); 317 System.err.println("Query: " + request.getQueryString()); 318 System.err.println("Request URI: " + request.getRequestURI()); 319 System.err.println("Request URL: " + request.getRequestURL()); 320 System.err.println("Is Secure: " + request.isSecure()); 321 System.err.println("Scheme: " + request.getScheme()); 322 dumpRequestParameters(request); 323 dumpRequestAttributes(request); 324 dumpRequestHeaders(request); 325 326 } 327 328 333 public static void dumpMap(Map map) { 334 System.err.println("Map dump"); 335 for (Iterator i = map.entrySet().iterator(); i.hasNext();) { 336 Map.Entry entry = (Map.Entry ) i.next(); 337 System.err.println(" Key = " + entry.getKey() + " Val = " + entry.getValue()); 338 } 339 340 } 341 342 347 public static void printStackTrace(Throwable exception) { 348 Exception e; 349 try { 350 throw new Exception (); 351 } catch (Exception ex) { 352 e = ex; 353 } 354 StackTraceElement [] trace = e.getStackTrace(); 355 System.err.println("[REMOVE-ME] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber()); 356 exception.printStackTrace(); 357 358 } 359 360 367 public static String getExceptionMessageChain(Throwable t) { 368 StringBuffer buf = new StringBuffer (); 369 while (t != null) { 370 if (buf.length() > 0 && !buf.toString().endsWith(".")) { 371 buf.append(". "); 372 } 373 if (t.getMessage() != null) { 374 buf.append(t.getMessage().trim()); 375 } 376 t = t.getCause(); 377 } 378 return buf.toString(); 379 } 380 381 390 public static void toDo(String message) { 391 Exception e; 392 try { 393 throw new Exception (); 394 } catch (Exception ex) { 395 e = ex; 396 } 397 StackTraceElement [] trace = e.getStackTrace(); 398 System.err.println("[***TODO***] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber() + " - " + message); 399 } 400 401 410 public static void removeMe(String message) { 411 Exception e; 412 try { 413 throw new Exception (); 414 } catch (Exception ex) { 415 e = ex; 416 } 417 StackTraceElement [] trace = e.getStackTrace(); 418 System.err.println("[REMOVE-ME] - " + trace[1].getClassName() + ":" + trace[1].getLineNumber() + " - " + message); 419 420 } 421 422 430 public static String encodeHTML(String html) { 431 StringBuffer buf = new StringBuffer (); 433 char ch; 434 for (int i = 0; i < html.length(); i++) { 435 ch = html.charAt(i); 436 switch (ch) { 437 case '&': 438 439 if (((i + 5) < html.length()) && html.substring(i + 1, i + 5).equals("amp;")) { 441 buf.append(ch); 442 } else { 443 buf.append("&"); 444 } 445 break; 446 case '"': 447 buf.append("""); 448 break; 449 case '<': 450 buf.append("<"); 451 break; 452 case '>': 453 buf.append(">"); 454 break; 455 default: 456 buf.append(ch); 457 } 458 } 459 return buf.toString(); 460 } 461 462 469 public static String decodeHTML(String html) { 470 StringBuffer buf = new StringBuffer (); 472 char ch; 473 for (int i = 0; i < html.length(); i++) { 474 ch = html.charAt(i); 475 switch (ch) { 476 case '&': 477 String s = html.substring(i); 478 if (s.startsWith("&")) { 479 buf.append("&"); 480 i += 4; 481 } else if (s.startsWith(""e;")) { 482 buf.append("\""); 483 i += 6; 484 } else if (s.startsWith("<")) { 485 buf.append("<"); 486 i += 3; 487 } else if (s.startsWith(">")) { 488 buf.append(">"); 489 i += 3; 490 } 491 break; 492 default: 493 buf.append(ch); 494 } 495 } 496 return buf.toString(); 497 } 498 499 507 public static String escapeForJavascriptString(String string, boolean doSingle, boolean doDouble) { 508 if(string == null) { 509 return ""; 510 } 511 string = trimBoth(string); 512 string = string.replaceAll("\\\\", "\\\\\\\\"); 513 if(doSingle) 514 string = string.replaceAll("'", "\\\\'"); 515 if(doDouble) 516 string = string.replaceAll("\"", "\\\\'"); 517 String [] lines = string.split("\n"); 518 StringBuffer buf = new StringBuffer (); 519 for (int i = 0; i < lines.length; i++) { 520 if (buf.length() > 0) { 521 buf.append("<br/>"); 522 } 523 buf.append(trimBoth(lines[i])); 524 } 525 return buf.toString(); 526 } 527 528 534 public static String escapeForJavascriptString(String string) { 535 return escapeForJavascriptString(string, true, true); 536 } 537 538 546 public static boolean delTree(File file) { 547 if (log.isDebugEnabled()) 548 log.debug("Deleting " + file.getAbsolutePath()); 549 if (file.isDirectory()) { 550 File [] f = file.listFiles(); 551 if (f != null) { 552 for (int i = 0; i < f.length; i++) { 553 if (!delTree(f[i])) { 554 return false; 555 } 556 } 557 } 558 } 559 if (!file.delete()) { 560 log.warn("Failed to remove " + file.getAbsolutePath()); 561 return false; 562 } 563 return true; 564 } 565 566 576 public static String trimToSize(String text, int size, boolean addElipses) { 577 return text.length() <= size ? text 578 : (text.substring(0, size - (addElipses ? (size > 3 ? 3 : size) : 0)) + (addElipses ? " .." : "")); 579 } 580 581 587 public static String urlEncode(String url) { 588 return urlEncode(url, System.getProperty("sslexplorer.urlencoding", "UTF-8")); 589 } 590 591 598 public static String urlEncode(String url, String charset) { 599 try { 600 return URLEncoder.encode(url, charset); 602 } catch (UnsupportedEncodingException uee) { 603 try { 604 return URLEncoder.encode(url, "us-ascii"); 606 } catch (UnsupportedEncodingException uee2) { 607 log.error("URL could not be encoded! This should NOT happen!!!"); 608 return url; 609 } 610 } 611 } 612 613 619 public static String urlDecode(String url) { 620 try { 621 return URLDecoder.decode(url, System.getProperty("sslexplorer.urlencoding", "UTF-8")); 623 } catch (UnsupportedEncodingException uee) { 624 try { 625 return URLDecoder.decode(url, "us-ascii"); 627 } catch (UnsupportedEncodingException uee2) { 628 log.error("URL could not be decoded! This should NOT happen!!!"); 629 return url; 630 } 631 } 632 } 633 634 640 public static void noCache(HttpServletResponse response) { 641 response.setHeader("Pragma", "no-cache"); 642 response.setHeader("Cache-Control", "no-cache"); 647 } 648 649 660 public static String decodeRequestString(HttpServletRequest request, String string) { 661 String enc = request.getParameter("_charset_"); 662 if (enc != null && !enc.equals("ISO-8859-1")) { 663 try { 664 return new String (string.getBytes("ISO-8859-1"), enc); 665 } catch (Exception e) { 666 } 667 } 668 enc = request.getCharacterEncoding(); 669 if (enc != null && !enc.equals("ISO-8859-1")) { 670 try { 671 return new String (string.getBytes("ISO-8859-1"), enc); 672 } catch (Exception e) { 673 } 674 675 } 676 return string; 677 } 678 679 686 public static Map listToHashMapKeys(List list) { 687 HashMap map = new HashMap (); 688 Object k; 689 for (Iterator i = list.iterator(); i.hasNext();) { 690 k = i.next(); 691 map.put(k, k); 692 } 693 return map; 694 } 695 696 704 public static void copy(InputStream in, OutputStream out) throws IOException { 705 copy(in, out, -1); 706 } 707 708 709 718 public static void copy(InputStream in, OutputStream out, long count) throws IOException { 719 copy(in, out, count, BUFFER_SIZE); 720 } 721 722 732 public static void copy(InputStream in, OutputStream out, long count, int bufferSize) throws IOException { 733 byte buffer[] = new byte[bufferSize]; 734 int i = bufferSize; 735 if (count >= 0) { 736 while (count > 0) { 737 if (count < bufferSize) 738 i = in.read(buffer, 0, (int) count); 739 else 740 i = in.read(buffer, 0, bufferSize); 741 742 if (i == -1) 743 break; 744 745 count -= i; 746 out.write(buffer, 0, i); 747 out.flush(); 749 } 750 } else { 751 while (true) { 752 i = in.read(buffer, 0, bufferSize); 753 if (i < 0) 754 break; 755 if (log.isDebugEnabled()) 756 log.debug("Transfered " + i + " bytes"); 757 out.write(buffer, 0, i); 758 out.flush(); 760 } 761 } 762 763 } 764 765 772 public static void copy(File f, File t) throws IOException { 773 copy(f, t, false); 774 } 775 776 784 public static void copy(File f, File t, boolean onlyIfNewer) throws IOException { 785 if (!onlyIfNewer || f.lastModified() > t.lastModified()) { 786 if (log.isDebugEnabled()) 787 log.debug("Copying " + f.getAbsolutePath() + " to " + t.getAbsolutePath()); 788 InputStream in = new FileInputStream (f); 789 try { 790 OutputStream out = new FileOutputStream (t); 791 try { 792 copy(in, out); 793 } finally { 794 out.close(); 795 } 796 } finally { 797 in.close(); 798 } 799 t.setLastModified(f.lastModified()); 800 } else { 801 if (log.isDebugEnabled()) 802 log.debug("Skipping copying of file " + f.getAbsolutePath() + " as the target is newer than the source."); 803 } 804 } 805 806 815 public static void copyToDir(File from, File toDir, boolean replace, boolean onlyIfNewer) throws IOException { 816 if (!toDir.exists()) { 817 throw new IOException ("Destination directory " + toDir.getAbsolutePath() + " doesn't exist."); 818 } 819 if (from.isDirectory()) { 820 File toDirDir = new File (toDir, from.getName()); 821 if (toDirDir.exists() && replace) { 822 delTree(toDirDir); 823 } 824 if (!toDirDir.exists()) { 825 if (log.isDebugEnabled()) 826 log.debug("Creating directory " + toDirDir.getAbsolutePath()); 827 if (!toDirDir.mkdirs()) { 828 throw new IOException ("Failed to create directory " + toDirDir.getAbsolutePath()); 829 } 830 } 831 File [] f = from.listFiles(); 832 if (f != null) { 833 for (int i = 0; i < f.length; i++) { 834 copyToDir(f[i], toDirDir, replace, onlyIfNewer); 835 } 836 } else { 837 throw new IOException ("Failed to list " + from.getAbsolutePath()); 838 } 839 } else if (from.isFile()) { 840 copy(from, new File (toDir, from.getName()), onlyIfNewer); 841 } else { 842 throw new IOException (from.getAbsolutePath() + " is not a plain file or directory."); 843 } 844 } 845 846 852 public static String emptyWhenNull(String string) { 853 return string == null ? "" : string; 854 } 855 856 863 public static String makeConstantReadable(String constant) { 864 StringBuffer buf = new StringBuffer (); 865 char ch; 866 boolean firstChar = true; 867 for (int i = 0; i < constant.length(); i++) { 868 ch = constant.charAt(i); 869 if (ch == '_') { 870 ch = ' '; 871 firstChar = true; 872 } else { 873 if (firstChar) { 874 ch = Character.toUpperCase(ch); 875 firstChar = false; 876 } else { 877 ch = Character.toLowerCase(ch); 878 } 879 } 880 buf.append(ch); 881 } 882 return buf.toString(); 883 } 884 885 892 public static String makeKeyReadable(String constant) { 893 StringBuffer buf = new StringBuffer (); 895 char ch; 896 char lastChar = 0; 897 for (int i = 0; i < constant.length(); i++) { 898 ch = constant.charAt(i); 899 if(i == 0) { 900 ch = Character.toUpperCase(ch); 901 } 902 else { 903 if(Character.isUpperCase(ch)) { 904 if(!Character.isUpperCase(lastChar)) { 905 buf.append(" "); 906 } 907 } 908 } 909 buf.append(ch); 910 lastChar = ch; 911 } 912 return buf.toString(); 913 } 914 915 922 public static String makeConstantKey(String constant) { 923 StringBuffer buf = new StringBuffer (); 924 char ch; 925 boolean firstChar = false; 926 for (int i = 0; i < constant.length(); i++) { 927 ch = constant.charAt(i); 928 if (ch == '_') { 929 firstChar = true; 930 } else { 931 if (firstChar) { 932 ch = Character.toUpperCase(ch); 933 firstChar = false; 934 } else { 935 ch = Character.toLowerCase(ch); 936 } 937 buf.append(ch); 938 } 939 } 940 return buf.toString(); 941 } 942 943 950 public static String reCase(String unCased) { 951 StringBuffer buf = new StringBuffer (); 952 char ch; 953 boolean wordNext = false; 954 for (int i = 0; i < unCased.length(); i++) { 955 ch = unCased.charAt(i); 956 if (ch == ' ') { 957 wordNext = true; 958 } else { 959 if (wordNext) { 960 ch = Character.toUpperCase(ch); 961 wordNext = false; 962 } else { 963 ch = Character.toLowerCase(ch); 964 } 965 buf.append(ch); 966 } 967 } 968 return buf.toString(); 969 } 970 971 980 public static int readFullyIntoBuffer(InputStream in, byte[] buf) throws IOException { 981 int read; 982 while ((read = in.read(buf)) > -1) { 983 ; 984 } 985 return read; 986 } 987 988 999 public static String parseSimplePatternToRegExp(String simplePattern) { 1000 if (simplePattern.startsWith("#")) { 1001 simplePattern = simplePattern.substring(1); 1002 } else if (simplePattern.startsWith("=")) { 1003 simplePattern = "^" + Util.simplePatternToRegExp(simplePattern.substring(1)) + "$"; 1004 } else { 1005 simplePattern = "^" + Util.simplePatternToRegExp(simplePattern) 1006 + (simplePattern.indexOf('*') == -1 && simplePattern.indexOf('?') == -1 ? ".*" : "") + "$"; 1007 } 1008 return simplePattern; 1009 } 1010 1011 1017 static String simplePatternToRegExp(String simplePattern) { 1018 int c = simplePattern.length(); 1019 char ch; 1020 StringBuffer buf = new StringBuffer (); 1021 for (int i = 0; i < c; i++) { 1022 ch = simplePattern.charAt(i); 1023 if (Character.isLetterOrDigit(ch)) { 1024 buf.append(ch); 1025 } else if (ch == '*') { 1026 buf.append(".*"); 1027 } else if (ch == '?') { 1028 buf.append(".?"); 1029 } else { 1030 buf.append("\\"); 1031 buf.append(ch); 1032 } 1033 } 1034 return buf.toString(); 1035 } 1036 1037 1044 public static String getClassPath(ClassLoader classLoader) { 1045 StringBuffer buf = new StringBuffer (); 1046 if(classLoader instanceof URLClassLoader ) { 1047 URLClassLoader urlc = (URLClassLoader )classLoader; 1048 URL [] urls = urlc.getURLs(); 1049 for(int i = 0 ; i < urls.length; i++) { 1050 if(urls[i].getProtocol().equals("file")) { 1051 File f = new File (Util.urlDecode(urls[i].getPath())); 1052 if(buf.length() > 0) { 1053 buf.append(File.pathSeparator); 1054 } 1055 buf.append(f.getPath()); 1056 } 1057 } 1058 } 1059 return buf.toString(); 1060 } 1061 1062 1071 public static String appendToCommaSeparatedList(String original, String value) { 1072 if(original == null || original.equals("")) { 1073 return value; 1074 } 1075 return original + "," + value; 1076 } 1077 1078 1087 public static void appendToCommaSeparatedSystemProperty(String systemPropertyName, String value) { 1088 System.setProperty(systemPropertyName, appendToCommaSeparatedList(System.getProperty(systemPropertyName), value)); 1089 } 1090 1091 1097 public static String getSimpleClassName(Class cls) { 1098 int idx = cls.getName().lastIndexOf("."); 1099 return idx == -1 ? cls.getName() : cls.getName().substring(idx + 1); 1100 } 1101 1102 1112 1113 public static String [] splitString(String str, char delim, char quote, char escape) { 1114 Vector v = new Vector (); 1115 StringBuffer str1 = new StringBuffer (); 1116 char ch = ' '; 1117 boolean inQuote = false; 1118 boolean escaped = false; 1119 1120 for (int i = 0; i < str.length(); i++) { 1121 ch = str.charAt(i); 1122 1123 if ((escape != -1) && (ch == escape) && !escaped) { 1124 escaped = true; 1125 } else { 1126 if ((quote != -1) && (ch == quote) && !escaped) { 1127 inQuote = !inQuote; 1128 } else if (!inQuote && (ch == delim && !escaped)) { 1129 v.addElement(str1.toString()); 1130 str1.setLength(0); 1131 } else { 1132 str1.append(ch); 1133 } 1134 if (escaped) { 1135 escaped = false; 1136 } 1137 } 1138 } 1139 1140 if (str.length() > 0) { 1141 v.addElement(str1.toString()); 1142 1143 } 1144 String [] array; 1145 array = new String [v.size()]; 1146 v.copyInto(array); 1147 1148 return array; 1149 } 1150 1151 1157 public static String escapeForDNString(String string) { 1158 char ch; 1159 StringBuffer b = new StringBuffer (string.length()); 1160 for(int i = 0 ; i < string.length(); i++) { 1161 ch = string.charAt(i); 1162 if(ch == ',' || ch == '+' || ch == '"' || ch == '<' || ch == '>' || ch == ';' || ch == '.') { 1163 b.append("\\"); 1164 b.append(Integer.toHexString(ch)); 1165 } 1166 else { 1167 b.append(ch); 1168 } 1169 } 1170 return b.toString(); 1171 } 1172 1173 1174 public static boolean checkVersion(String actual, String required) { 1175 1176 int[] applicationVersion = getVersion(actual); 1177 int[] installedJREVersion = getVersion(required); 1178 1179 for (int i = 0; i < applicationVersion.length && i < installedJREVersion.length; i++) { 1180 if (applicationVersion[i] < installedJREVersion[i]) 1181 return false; 1182 } 1183 1184 return true; 1185 } 1186 1187 public static int[] getVersion(String version) { 1188 1189 int idx = 0; 1190 int pos = 0; 1191 int[] result = new int[0]; 1192 do { 1193 1194 idx = version.indexOf('.', pos); 1195 int v; 1196 if (idx > -1) { 1197 v = Integer.parseInt(version.substring(pos, idx)); 1198 pos = idx + 1; 1199 } else { 1200 try { 1201 int sub = version.indexOf('_', pos); 1202 if (sub == -1) { 1203 sub = version.indexOf('-', pos); 1204 } 1205 if (sub > -1) { 1206 v = Integer.parseInt(version.substring(pos, sub)); 1207 } else { 1208 v = Integer.parseInt(version.substring(pos)); 1209 } 1210 } catch (NumberFormatException ex) { 1211 break; 1213 } 1214 } 1215 int[] tmp = new int[result.length + 1]; 1216 System.arraycopy(result, 0, tmp, 0, result.length); 1217 tmp[tmp.length - 1] = v; 1218 result = tmp; 1219 1220 } while (idx > -1); 1221 1222 return result; 1223 } 1224 1225 public static String escapeForRegexpReplacement(String repl) { 1226 StringBuffer buf = new StringBuffer (repl.length()); 1227 char ch; 1228 int len = repl.length(); 1229 for(int i = 0 ; i < len; i++) { 1230 ch = repl.charAt(i); 1231 if(ch == '\\') { 1232 buf.append(ch); 1233 } 1234 else if(ch == '$') { 1235 buf.append('\\'); 1236 } 1237 buf.append(ch); 1238 } 1239 return buf.toString(); 1240 } 1241 1242 1250 public static int getDayOfWeekForText(String text) { 1251 text = text.toLowerCase(); 1252 if(text.startsWith("sun")) { 1253 return Calendar.SUNDAY; 1254 } 1255 else if(text.startsWith("mon")) { 1256 return Calendar.MONDAY; 1257 } 1258 else if(text.startsWith("tue")) { 1259 return Calendar.TUESDAY; 1260 } 1261 else if(text.startsWith("wed")) { 1262 return Calendar.WEDNESDAY; 1263 } 1264 else if(text.startsWith("thu")) { 1265 return Calendar.THURSDAY; 1266 } 1267 else if(text.startsWith("fri")) { 1268 return Calendar.FRIDAY; 1269 } 1270 else if(text.startsWith("sat")) { 1271 return Calendar.SATURDAY; 1272 } 1273 return 0; 1274 } 1275 1276 1286 public static void setSystemProperty(String key, String value, String comment) throws IOException { 1287 InputStream in = null; 1288 OutputStream out = null; 1289 File f = new File (ContextHolder.getContext().getConfDirectory(), "system.properties"); 1290 File tf = new File (ContextHolder.getContext().getConfDirectory(), "system.properties.tmp"); 1291 File of = new File (ContextHolder.getContext().getConfDirectory(), "system.properties.old"); 1292 try { 1293 in = new FileInputStream (f); 1294 out = new FileOutputStream (tf); 1295 BufferedReader br = new BufferedReader (new InputStreamReader (in)); 1296 PrintWriter pw = new PrintWriter (out); 1297 String line = null; 1298 boolean found = false; 1299 while( ( line = br.readLine() ) != null ) { 1300 if(found) { 1301 pw.println(line); 1302 } 1303 else { 1304 String trimLine = Util.trimBoth(line); 1305 boolean commented = false; 1306 int idx = 0; 1307 while(idx < trimLine.length() && trimLine.charAt(idx) == '#') { 1308 commented = true; 1309 idx++; 1310 } 1311 String tVal = trimLine.substring(idx); 1312 if(tVal.startsWith(key + "=")) { 1313 found = true; 1314 if(commented) { 1315 if(value == null) { 1316 } 1318 else { 1319 pw.println(key + "=" + value); 1321 } 1322 } 1323 else { 1324 if(value == null) { 1325 pw.println("#" + line); 1327 } 1328 else { 1329 pw.println(key + "=" + value); 1331 } 1332 } 1333 } 1334 else { 1335 pw.println(line); 1336 } 1337 trimLine.startsWith("#"); 1338 } 1339 1340 } 1341 if(!found) { 1342 if(comment != null) { 1343 pw.println(); 1344 pw.println(comment); 1345 } 1346 pw.println(key + "=" + value); 1347 } 1348 pw.flush(); 1349 1350 } finally { 1351 Util.closeStream(in); 1352 Util.closeStream(out); 1353 } 1354 1355 if(of.exists() && !of.delete()) { 1357 log.warn("Failed to delete old backup system properties file"); 1358 } 1359 copy(f, of); 1360 copy(tf, f); 1361 if(!tf.delete()) { 1362 log.warn("Failed to delete temporary system properties file"); 1363 } 1364 1365 1366 } 1367 1368 1375 public static String arrayToCommaSeparatedList(Object [] elements) { 1376 StringBuffer buf = new StringBuffer (); 1377 for(int i = 0 ; i < elements.length; i++) { 1378 if(i > 0) 1379 buf.append(","); 1380 buf.append(elements[i].toString()); 1381 } 1382 return buf.toString(); 1383 } 1384 1385 1392 public static boolean isNullOrTrimmedBlank(String string) { 1393 return string == null || string.trim().length() == 0; 1394 } 1395 1396 1404 public static String trimmedOrBlank(String string) { 1405 return string == null ? "" : string.trim(); 1406 } 1407 1408 1416 public static String trimmedBothOrBlank(String string) { 1417 return trimBoth(string == null ? "" : string.trim()); 1418 } 1419 1420 1427 public static void makeExecutable(File binLocation) throws IOException { 1428 Process p = Runtime.getRuntime().exec(new String [] { "chmod", "ug+rx", binLocation.getAbsolutePath() }); 1429 try { 1430 copy(p.getErrorStream(), new ByteArrayOutputStream ()); 1431 } 1432 finally { 1433 try { 1434 if(p.waitFor() != 0) { 1435 throw new IOException ("Failed to set execute permission. Return code " + p.exitValue() + "."); 1436 } 1437 } catch (InterruptedException e) { 1438 } 1439 } 1440 1441 } 1442} | Popular Tags |