1 21 package org.jahia.utils; 22 23 import java.io.BufferedInputStream ; 24 import java.io.BufferedOutputStream ; 25 import java.io.BufferedReader ; 26 import java.io.File ; 27 import java.io.FileInputStream ; 28 import java.io.FileOutputStream ; 29 import java.io.FileReader ; 30 import java.io.FileWriter ; 31 import java.io.IOException ; 32 import java.io.InputStream ; 33 import java.io.OutputStream ; 34 import java.io.StringReader ; 35 import java.net.URL ; 36 import java.text.SimpleDateFormat ; 37 import java.util.Calendar ; 38 import java.util.Date ; 39 import java.util.Enumeration ; 40 import java.util.Locale ; 41 import java.util.StringTokenizer ; 42 import java.util.Vector ; 43 44 import javax.servlet.ServletContext ; 45 import javax.servlet.http.HttpServletRequest ; 46 47 import org.jahia.utils.keygenerator.JahiaKeyGen; 48 import org.apache.commons.jexl.Expression; 49 import org.apache.commons.jexl.ExpressionFactory; 50 import org.apache.commons.jexl.JexlContext; 51 import org.apache.commons.jexl.JexlHelper; 52 import java.util.Map ; 53 54 70 public class JahiaTools 71 { 72 73 private static final char[] AUTHORIZED_CHARS = 75 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.-".toCharArray(); 76 77 82 83 90 static public void toConsole(String localisation, String msg) 91 { 92 System.out.println(">> " + localisation + "(): " + msg); 93 } 94 95 101 static public void toConsole(String msg) 102 { 103 System.out.println(">> " + msg); 104 } 105 106 107 108 113 114 private static String mask = "EEE, MMM d, yyyy"; 116 117 118 124 static public String getDisplayedDate() 125 { 126 Date today = new Date (); 127 SimpleDateFormat formatter = new SimpleDateFormat (mask,Locale.US); 128 String datenewformat = formatter.format(today); 129 return datenewformat; 130 } 131 132 133 139 static public String getDisplayedDate(long time) 140 { 141 Date today = new Date (time); 142 SimpleDateFormat formatter = new SimpleDateFormat (mask,Locale.US); 143 String datenewformat = formatter.format(today); 144 return datenewformat; 145 } 146 147 154 static public String getDisplayedDate(String time) 155 { 156 Long tmpLong = new Long ( time ); 157 Date today = new Date (tmpLong.longValue()); 158 SimpleDateFormat formatter = new SimpleDateFormat (mask,Locale.US); 159 String datenewformat = formatter.format(today); 160 return datenewformat; 161 } 162 163 164 170 static public long getCurrentDateInMs() 171 { 172 return System.currentTimeMillis(); 173 } 174 175 176 186 static public long getDateInMs(int year,int month,int day) 187 { 188 Calendar c = Calendar.getInstance(); 189 c.set(year,month-1,day); 191 Date d = c.getTime(); 192 return d.getTime(); 193 } 194 195 196 203 static public int getDayFromMs(long time) 204 { 205 Calendar c = Calendar.getInstance(); 206 c.setTime(new Date (time)); 207 return c.get(Calendar.DAY_OF_MONTH); 208 } 209 210 211 218 static public int getMonthFromMs(long time) 219 { 220 Calendar c = Calendar.getInstance(); 221 c.setTime(new Date (time)); 222 return c.get(Calendar.MONTH); 223 } 224 225 226 233 static public int getYearFromMs(long time) 234 { 235 Calendar c = Calendar.getInstance(); 236 c.setTime(new Date (time)); 237 return c.get(Calendar.YEAR); 238 } 239 240 241 247 public static String formatDateFromEpoch( String epochString ) 248 { 249 250 long longTime = Long.parseLong(epochString); 252 java.util.Date normalDate = new java.util.Date (longTime); 253 254 return java.text.DateFormat.getDateTimeInstance(3,3).format(normalDate); 255 } 256 257 258 259 264 265 275 static public String replacePattern(String str, String oldToken, String newToken) { 276 if (str==null){ 277 return str; 278 } 279 StringBuffer result = new StringBuffer (str.length() + 100); 280 int i = str.indexOf(oldToken); 281 int startOfIndex = 0; 282 while (i != -1) { 283 result.append(str.substring(startOfIndex,i)); 284 result.append(newToken); 285 startOfIndex = i + oldToken.length(); 286 i = str.indexOf(oldToken,startOfIndex); 287 } 288 result.append(str.substring(startOfIndex,str.length())); 289 return result.toString(); 290 } 291 292 303 static public String replacePatternIgnoreCase(String str, String oldToken, String newToken) { 304 if (str==null){ 305 return str; 306 } 307 308 StringBuffer result = new StringBuffer (str.length() + 100); 309 String strLower = str.toLowerCase(); 310 311 int i = strLower.indexOf(oldToken); 312 int startOfIndex = 0; 313 while (i != -1) { 314 result.append(str.substring(startOfIndex,i)); 315 result.append(newToken); 316 startOfIndex = i + oldToken.length(); 317 i = strLower.indexOf(oldToken,startOfIndex); 318 } 319 result.append(str.substring(startOfIndex,str.length())); 320 return result.toString(); 321 } 322 323 static public String replacePattern(String str, String newToken, String oldToken, int invert ) { 325 if (invert==0){ 326 return replacePattern(str, newToken, oldToken); 327 } else { 328 return replacePattern(str, oldToken, newToken); 330 } 331 } 332 333 342 static public String [] getTokens(String str, String sep) { 343 if (str==null){ 344 return null; 345 } 346 347 StringTokenizer st = new StringTokenizer (str,sep); 348 String [] result = new String [st.countTokens()]; 349 int count = 0; 350 while ( st.hasMoreTokens() ){ 351 result[count] = st.nextToken(); 352 count++; 353 } 354 355 return result; 356 } 357 358 359 369 public static String convertContexted( String convert, 370 PathResolver pathResolver ) 371 { 372 if(convert.startsWith("$context/")) { 373 convert = pathResolver.resolvePath( convert.substring(8, convert.length()) ); 374 } 375 return convert; 376 } 378 379 387 public static String string2Property( String originalValue ) 388 { 389 StringBuffer convertedValue = new StringBuffer (); 390 for(int i=0; i < originalValue.length(); i++) { 391 if(originalValue.substring(i, i+1).equals(":")) { 392 convertedValue.append( "\\:" ); 393 } else if(originalValue.substring(i, i+1).equals("\\")) { 394 convertedValue.append( "\\\\" ); 395 } else { 396 convertedValue.append( originalValue.substring(i, i+1) ); 397 } 398 } 399 return convertedValue.toString(); 400 } 402 403 415 public static Enumeration string2Enumeration( String decompose, boolean isFile ) 416 throws IOException 417 { 418 Vector stringLines = new Vector (); 419 String buffer = ""; 420 BufferedReader buffered; 421 422 if(isFile) { 423 buffered = new BufferedReader ( new FileReader ( decompose ) ); 424 } else { 425 buffered = new BufferedReader ( new StringReader ( decompose ) ); 426 } 427 428 while((buffer = buffered.readLine()) != null) 429 { 430 if(buffer.trim().length() > 0) { 431 stringLines.add(buffer); 432 } 433 } 434 buffered.close(); 435 436 return stringLines.elements(); 437 } 439 440 441 447 public static boolean isAlphaValid(String name) 448 { 449 if (name == null) { 450 return false; 451 } 452 if (name.length() == 0) { 453 return false; 454 } 455 456 char[] chars = AUTHORIZED_CHARS; 457 char[] nameBuffer = name.toCharArray(); 458 459 boolean badCharFound = false; 460 int i = 0; 461 while ((i < nameBuffer.length) && (!badCharFound)) 462 { 463 int j = 0; 464 boolean ok = false; 465 while ((j < chars.length) && (!ok)) { 466 if (chars[j] == nameBuffer[i]) { 467 ok = true; 468 } 469 j++; 470 } 471 badCharFound = (!ok); 472 if (badCharFound) { 473 JahiaConsole.println("JahiaTools.isAlphaValid","--/ Bad character found in ["+name+"] at position "+Integer.toString(i)); 474 } 475 i++; 476 } 477 return (!badCharFound); 478 } 480 481 482 490 public static void writeStringInFile( String fileName, 491 String output ) 492 { 493 try 495 { 496 File fileObject = new File ( fileName ); 497 FileWriter fileWriter = new FileWriter ( fileObject ); 498 499 fileWriter.write( output ); 500 fileWriter.close(); 501 } catch (IOException ioe) { 502 } 503 } 505 506 507 512 513 514 520 public static void copyFolderContent( String origin, 521 String destination ) 522 throws IOException 523 { 524 File originFolder = new File (origin); 525 File destinationFolder = new File (destination); 526 527 if(!destinationFolder.exists()) { 529 destinationFolder.mkdirs(); 530 } 531 532 if(originFolder.isDirectory()) 534 { 535 File [] filesInThisDirectory = originFolder.listFiles(); 536 StringBuffer destinationFile = null; 537 for(int i=0; i<filesInThisDirectory.length; i++) { 538 String originFile = filesInThisDirectory[i].getPath(); 539 String originFileName = filesInThisDirectory[i].getName(); 540 destinationFile = new StringBuffer (destination); 541 destinationFile.append(File.separator); 542 destinationFile.append(originFileName); 543 if(filesInThisDirectory[i].isFile()) { 544 FileInputStream fileInput = new FileInputStream ( originFile ); 545 FileOutputStream fileOutput = new FileOutputStream ( destinationFile.toString() ); 546 copyStream( fileInput, fileOutput ); 547 } else { 548 copyFolderContent( originFile, destinationFile.toString() ); 549 } 550 } 551 } 552 } 554 555 561 public static void copyStream( InputStream inputStream, 562 OutputStream outputStream ) 563 throws IOException 564 { 565 int bufferRead; 566 int bufferSize = 65536; 567 byte[] writeBuffer = new byte[bufferSize]; 568 569 BufferedInputStream bufInStream = new BufferedInputStream (inputStream, bufferSize); 570 BufferedOutputStream bufOutStream = new BufferedOutputStream (outputStream, bufferSize); 571 while((bufferRead = bufInStream.read(writeBuffer)) != -1) 572 573 bufOutStream.write(writeBuffer, 0, bufferRead); 574 bufOutStream.flush(); 575 bufOutStream.close(); 576 577 inputStream.close(); 578 579 outputStream.flush(); 580 outputStream.close(); 581 } 583 584 public static boolean checkFileExists( String fileName ) 586 { 587 try { 588 File fileObject = new File ( fileName ); 589 return fileObject.exists(); 590 } catch (NullPointerException npe) { 591 return false; 592 } 593 } 595 596 604 static public boolean checkFileNameCaseSensitive(String path){ 605 606 File tmpFile = new File (path); 607 if ( tmpFile != null && ( tmpFile.isFile() || tmpFile.isDirectory() ) ){ 608 String name = tmpFile.getName(); 609 if ( tmpFile.getParentFile() != null ){ 610 File [] files = tmpFile.getParentFile().listFiles(); 611 int nbFiles = files.length; 612 for (int i=0 ; i<nbFiles ; i++){ 613 if ( files[i].getName().equals(name) ){ 614 return true; 615 } 616 } 617 } 618 } 619 return false; 620 } 621 622 623 630 public static boolean deleteFile(File f){ 631 return deleteFile(f,false); 632 633 } 634 635 636 644 public static boolean deleteFile(File f, boolean contentOnly){ 645 646 if ( f == null ){ 647 return false; 648 } 649 650 if ( f.isDirectory() ){ 651 652 File [] files = f.listFiles(); 653 654 for ( int i=0 ; i<files.length ; i++ ){ 655 if ( files[i].isFile() ){ 656 files[i].delete(); 657 } else { 658 deleteFile(files[i],false); 659 } 660 } 661 if ( !contentOnly ){ 662 return f.delete(); 663 } 664 } 665 return true; 666 667 } 668 669 670 679 public static String removeFileExtension(String filename, String ext){ 680 681 String name = filename.toLowerCase(); 682 if ( name.endsWith( ext.toLowerCase() ) ){ 683 return ( filename.substring(0,name.lastIndexOf(ext.toLowerCase())) ); 684 } 685 return filename; 686 } 687 688 689 697 public static String getUniqueDirName() { 698 699 return ( JahiaKeyGen.getKey(10) ); 700 } 701 702 703 704 709 710 718 static public String quote(String input) 719 { 720 721 if ( input != null ){ 722 StringBuffer sb = new StringBuffer (input); 723 for (int i = 0; i < sb.length(); i++) 724 { 725 char c = sb.charAt(i); 726 if (c == '\'') 727 { 728 sb.insert(i++, '\''); 729 } 730 } 731 return sb.toString(); 732 } 733 return input; 734 } 735 736 743 static public String escapeString(String input) 744 { 745 if ( input != null ){ 746 StringBuffer sb = new StringBuffer (input); 747 for (int i = 0; i < sb.length(); i++) 748 { 749 char c = sb.charAt(i); 750 if (c == '"') 751 { 752 sb.insert(i++, '\"'); 753 } 754 } 755 return sb.toString(); 756 } 757 return input; 758 } 759 760 761 766 767 768 777 static public boolean inValues(String aValue, String [] values){ 778 if ( values != null ){ 779 for (int i=0 ; i<values.length ; i++){ 780 if (aValue.equals(values[i])){ 781 return true; 782 } 783 } 784 } 785 return false; 786 } 787 788 789 790 800 static public String replaceNullString(String data, String newValue){ 801 if ( data != null ){ 802 return data; 803 } 804 return newValue; 805 } 806 807 808 818 static public Integer replaceNullInteger(Integer data, Integer newValue){ 819 if ( data != null ){ 820 return data; 821 } 822 return newValue; 823 } 824 825 826 835 public static String nnString( String inputString ) 836 { 837 String outputString = (inputString != null) ? inputString : ""; 838 return outputString; 839 } 841 842 849 static public boolean int2boolean(int value) 850 { 851 return value != 0; 852 } 853 854 855 862 static public int boolean2int(boolean value) 863 { 864 return value ? 1 : 0; 865 } 866 867 868 875 static public Vector inverseVector(Vector myVector) { 876 877 Vector temp = new Vector (); 878 for(int i = myVector.size()-1; i >= 0; i--) { 879 880 temp.addElement(myVector.get(i)); 881 } 882 return temp; 883 } 884 885 886 897 public static void updatepropvalue( String propertyName, 898 String propvalue, 899 String path ) 900 { 901 Vector bufferVector = new Vector (); 902 String lineReaded = null; 903 int position = 0; 904 boolean lineFound = false; 905 boolean success = false; 906 907 try 908 { 909 BufferedReader buffered = new BufferedReader ( new FileReader (path) ); 911 while((lineReaded = buffered.readLine()) != null) { 912 if(lineReaded.indexOf(propertyName) >= 0) { 913 position = lineReaded.lastIndexOf("="); 914 if(position >= 0) { 915 bufferVector.add( lineReaded.substring(0,position+1) + " " + propvalue ); 916 lineFound = true; 917 } 918 } else { 919 bufferVector.add(lineReaded); 920 } 921 } 922 buffered.close(); 923 924 if(!lineFound) 926 { 927 bufferVector.add( propertyName + " = " + propvalue ); 928 } 929 930 File thisFile = new File (path); 932 FileWriter fileWriter = new FileWriter ( thisFile ); 933 StringBuffer outputBuffer = new StringBuffer (); 934 935 for(int i=0; i < bufferVector.size(); i++) { 936 outputBuffer.append((String ) bufferVector.get(i)); 937 } 938 939 fileWriter.write( outputBuffer.toString() ); 940 fileWriter.close(); 941 } catch (java.io.IOException ioe) { 942 } 943 } 945 946 947 951 952 public static boolean isMSIExplorer(HttpServletRequest req){ 954 return ( req.getHeader("user-agent") != null && req.getHeader("user-agent").indexOf("MSIE") != -1 ); 955 } 956 957 public static boolean isLynx(HttpServletRequest req){ 959 return ( req.getHeader("user-agent") != null && req.getHeader("user-agent").indexOf("Lynx") != -1 ); 960 } 961 962 963 964 968 969 979 public static String getStrParameter(HttpServletRequest req, String paramName, String nullVal){ 980 981 String val = (String )req.getParameter(paramName); 982 if ( val == null ){ 983 return nullVal; 984 } 985 return val; 986 } 987 988 989 999 public static Integer getIntParameter(HttpServletRequest req, String paramName, Integer nullVal){ 1000 1001 String strVal = (String )req.getParameter(paramName); 1002 Integer val = null; 1003 if ( strVal == null ){ 1004 return nullVal; 1005 } else { 1006 try { 1007 val = new Integer (strVal); 1008 } catch ( Throwable t ){ 1009 val = nullVal; 1010 } 1011 } 1012 return val; 1013 } 1014 1015 1016 1017 1030 public static void removeContextAttributes( ServletContext context, 1031 String startString ) 1032 { 1033 Enumeration contextAttributeNames = context.getAttributeNames(); 1034 Vector attributesToRemove = new Vector (); 1035 String attributeName; 1036 1037 while(contextAttributeNames.hasMoreElements()) { 1038 attributeName = (String ) contextAttributeNames.nextElement(); 1039 if(attributeName.length() >= 36) { 1040 if((attributeName.substring(0,36).equals(startString)) && (attributeName.indexOf("accessGranted") == -1)) { 1041 attributesToRemove.add( attributeName ); 1042 } 1043 } 1044 } 1045 1046 Enumeration attributesListToRemove = attributesToRemove.elements(); 1047 while(attributesListToRemove.hasMoreElements()) { 1048 attributeName = (String ) attributesListToRemove.nextElement(); 1049 context.removeAttribute( attributeName ); 1050 } 1051 } 1053 1054 1059 1060 1069 public static String text2html( String str ) 1070 { 1071 return TextHtml.text2html(str); } 1073 1074 1083 public static String html2text(String str) 1084 { 1085 str = replacePattern(str,"&","&"); 1087 return TextHtml.html2text(str); } 1089 1090 1091 1100 public static String text2XMLEntityRef(String str, int invert) 1101 { 1102 if ( str == null || str.trim().equals("") ){ 1103 return str; 1104 } 1105 if (invert == 0) { str = TextHtml.text2html(str); 1107 } 1108 else { 1109 str = TextHtml.html2text(str); 1110 } 1111 str = replacePattern(str,"&","&",invert); 1112 str = replacePattern(str,"<","<",invert); 1113 str = replacePattern(str,">",">",invert); 1114 str = replacePattern(str,"\"",""",invert); 1115 str = replacePattern(str,"'","'",invert); 1116 return str; 1117 } 1118 1119 1120 1128 public static boolean isValidURL(String URLString) { 1129 try { 1130 URL testURL = new URL (URLString); 1131 testURL.openConnection(); 1132 return true; 1133 } catch (Exception e) { 1134 return false; 1135 } 1136 } 1137 1138 1143 public static String javaSpecialChars(String text) 1144 { 1145 if ( text == null ){ 1146 return text; 1147 } 1148 text = replacePattern(text,"\n","\\n"); 1149 text = replacePattern(text,"\r","\\r"); 1150 text = replacePattern(text,"\t","\\t"); 1151 text = replacePattern(text,"\\","\\\\"); 1152 return text; 1153 } 1154 1155 public static String htmlSpecialChars(String text) 1156 { 1157 if ( text == null ){ 1158 return text; 1159 } 1160 text = replacePattern(text,"&","&"); 1161 text = replacePattern(text,"<","<"); 1162 text = replacePattern(text,">",">"); 1163 text = replacePattern(text,"\"","""); 1164 1170 1171 return text; 1172 1173 } 1174 1175 1188 public static String evaluateExpressions(String expr, Map contextVars) 1189 throws Exception { 1190 1191 final String START_EXPR_MARKER = "${"; 1192 final String END_EXPR_MARKER = "}"; 1193 1194 StringBuffer result = new StringBuffer (); 1195 1196 int startExprMarkerPos = expr.indexOf(START_EXPR_MARKER); 1197 int endExprMarkerPos = -1; 1198 int curParsingPos = 0; 1199 while (startExprMarkerPos != -1) { 1200 1201 result.append(expr.substring(curParsingPos, startExprMarkerPos)); 1202 1203 curParsingPos = startExprMarkerPos + START_EXPR_MARKER.length(); 1204 1205 endExprMarkerPos = expr.indexOf(END_EXPR_MARKER, curParsingPos); 1206 if (endExprMarkerPos == -1) { 1207 throw new Exception ( 1208 "Parsing exception, missing end-of-expression marker " + 1209 END_EXPR_MARKER + " for expression at column " + 1210 curParsingPos); 1211 } 1212 String curExpr = expr.substring(curParsingPos, endExprMarkerPos); 1213 1214 Expression e = ExpressionFactory.createExpression(curExpr); 1215 1216 JexlContext jc = JexlHelper.createContext(); 1217 jc.getVars().putAll(contextVars); 1218 1219 Object o = e.evaluate(jc); 1220 String s = null; 1221 if (o instanceof String ) { 1222 s = (String ) o; 1223 } else { 1224 s = o.toString(); 1225 } 1226 1227 result.append(s); 1228 curParsingPos = endExprMarkerPos + END_EXPR_MARKER.length(); 1229 1230 startExprMarkerPos = expr.indexOf(START_EXPR_MARKER, curParsingPos); 1231 } 1232 result.append(expr.substring(curParsingPos)); 1233 1234 return result.toString(); 1235 } 1236 1237 1238} | Popular Tags |