KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > utils > JahiaTools


1 // $Id: JahiaTools.java 10570 2005-09-13 09:35:40Z pvollenweider $
2
//
3
// ____.
4
// __/\ ______| |__/\. _______
5
// __ .____| | \ | +----+ \
6
// _______| /--| | | - \ _ | : - \_________
7
// \\______: :---| : : | : | \________>
8
// |__\---\_____________:______: :____|____:_____\
9
// /_____|
10
//
11
// . . . i n j a h i a w e t r u s t . . .
12
//
13
//
14
// JahiaTools
15
//
16
// 26.02.2001 NK added in Jahia.
17
// 27.03.2001 AK changes in updatepropvalue().
18
// 25.07.2001 SB added isValidURL()
19
//
20

21 package org.jahia.utils;
22
23 import java.io.BufferedInputStream JavaDoc;
24 import java.io.BufferedOutputStream JavaDoc;
25 import java.io.BufferedReader JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.FileReader JavaDoc;
30 import java.io.FileWriter JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.OutputStream JavaDoc;
34 import java.io.StringReader JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.text.SimpleDateFormat JavaDoc;
37 import java.util.Calendar JavaDoc;
38 import java.util.Date JavaDoc;
39 import java.util.Enumeration JavaDoc;
40 import java.util.Locale JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42 import java.util.Vector JavaDoc;
43
44 import javax.servlet.ServletContext JavaDoc;
45 import javax.servlet.http.HttpServletRequest JavaDoc;
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 JavaDoc;
53
54 /**
55  * @author Jerome Tamiotti
56  *
57  *
58  * Class Tools:
59  *
60  * # Debugging tools
61  * # Date tools
62  * # String tools
63  * # Sql tools
64  * # Files tools
65  * # Comparison tools
66  * # General Purpose tools
67  * # Client Browser tools
68  *
69  */

70 public class JahiaTools
71 {
72
73     // authorized chars
74
private static final char[] AUTHORIZED_CHARS =
75         "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789.-".toCharArray();
76
77     /**************************************************************************
78      * Debugging Tools
79      *
80      *
81      *************************************************************************/

82
83     //-------------------------------------------------------------------------
84
/**
85      * Method toConsole: print a debug message into server console
86      *
87      * @param localisation the current class name followed by the method name
88      * @param msg the msg to print
89      */

90     static public void toConsole(String JavaDoc localisation, String JavaDoc msg)
91     {
92         System.out.println(">> " + localisation + "(): " + msg);
93     }
94
95     //-------------------------------------------------------------------------
96
/**
97      * Method toConsole: print a debug message into server console
98      *
99      * @param msg the msg to print
100      */

101     static public void toConsole(String JavaDoc msg)
102     {
103         System.out.println(">> " + msg);
104     }
105
106
107
108     /**************************************************************************
109      * Dates Tools
110      *
111      *
112      *************************************************************************/

113
114     // the mask used for date display
115
private static String JavaDoc mask = "EEE, MMM d, yyyy";
116
117
118     //-------------------------------------------------------------------------
119
/**
120      * Method getDisplayedDate: return the date of today as a string
121      *
122      * @return the string value of today
123      */

124     static public String JavaDoc getDisplayedDate()
125     {
126         Date JavaDoc today = new Date JavaDoc();
127         SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc(mask,Locale.US);
128         String JavaDoc datenewformat = formatter.format(today);
129         return datenewformat;
130     }
131
132
133     //-------------------------------------------------------------------------
134
/**
135      * Method getDisplayedDate: return the date represented by time as a string
136      *
137      * @return the string value of today
138      */

139     static public String JavaDoc getDisplayedDate(long time)
140     {
141         Date JavaDoc today = new Date JavaDoc(time);
142         SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc(mask,Locale.US);
143         String JavaDoc datenewformat = formatter.format(today);
144         return datenewformat;
145     }
146
147     //-------------------------------------------------------------------------
148
/**
149      * Method getDisplayedDate: return the date represented by time as a string
150      *
151      * @author AK
152      * @return the string value of today
153      */

154     static public String JavaDoc getDisplayedDate(String JavaDoc time)
155     {
156         Long JavaDoc tmpLong = new Long JavaDoc( time );
157         Date JavaDoc today = new Date JavaDoc(tmpLong.longValue());
158         SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc(mask,Locale.US);
159         String JavaDoc datenewformat = formatter.format(today);
160         return datenewformat;
161     }
162
163
164     //-------------------------------------------------------------------------
165
/**
166      * Method getCurrentDateInMs: return the date of today as a long value
167      *
168      * @return the long value of today
169      */

170     static public long getCurrentDateInMs()
171     {
172         return System.currentTimeMillis();
173     }
174
175
176     //-------------------------------------------------------------------------
177
/**
178      * Method getDateInMs: return a long value for the time represented by the
179      * given year, month and day
180      * @param year
181      * @param month (1 to 12)
182      * @param day
183      *
184      * @return the long value of time
185      */

186     static public long getDateInMs(int year,int month,int day)
187     {
188         Calendar JavaDoc c = Calendar.getInstance();
189         // class calendar use monthes from 0 to 11, so decrement
190
c.set(year,month-1,day);
191         Date JavaDoc d = c.getTime();
192         return d.getTime();
193     }
194
195
196     //-------------------------------------------------------------------------
197
/**
198      * Method getDayFromMs: from a date in ms from 1970, January 1st, return the day
199      * @param time
200      *
201      * @return the day value
202      */

203     static public int getDayFromMs(long time)
204     {
205         Calendar JavaDoc c = Calendar.getInstance();
206         c.setTime(new Date JavaDoc(time));
207         return c.get(Calendar.DAY_OF_MONTH);
208     }
209
210
211     //-------------------------------------------------------------------------
212
/**
213      * Method getMonthFromMs: from a date in ms from 1970, January 1st, return the month
214      * @param time
215      *
216      * @return the month value
217      */

218     static public int getMonthFromMs(long time)
219     {
220         Calendar JavaDoc c = Calendar.getInstance();
221         c.setTime(new Date JavaDoc(time));
222         return c.get(Calendar.MONTH);
223     }
224
225
226     //-------------------------------------------------------------------------
227
/**
228      * Method getYearFromMs: from a date in ms from 1970, January 1st, return the year
229      * @param time
230      *
231      * @return the year value
232      */

233     static public int getYearFromMs(long time)
234     {
235         Calendar JavaDoc c = Calendar.getInstance();
236         c.setTime(new Date JavaDoc(time));
237         return c.get(Calendar.YEAR);
238     }
239
240
241     //-------------------------------------------------------------------------
242
/**
243      * Format a epoch time (string) to human readable date.
244      *
245      * @author AK
246      */

247     public static String JavaDoc formatDateFromEpoch( String JavaDoc epochString )
248     {
249
250         // get a human-readable data format
251
long longTime = Long.parseLong(epochString);
252         java.util.Date JavaDoc normalDate = new java.util.Date JavaDoc(longTime);
253
254         return java.text.DateFormat.getDateTimeInstance(3,3).format(normalDate);
255     }
256
257
258
259     /**************************************************************************
260      * String Tools
261      *
262      *
263      *************************************************************************/

264
265     //-------------------------------------------------------------------------
266
/**
267      * Method replacePattern : replace a pattern in a text with another one
268      *
269      * @param str the text to alter
270      * @param oldToken the token to replace
271      * @param newToken the new text
272      *
273      * @return the altered text
274      */

275     static public String JavaDoc replacePattern(String JavaDoc str, String JavaDoc oldToken, String JavaDoc newToken) {
276         if (str==null){
277             return str;
278         }
279         StringBuffer JavaDoc result = new StringBuffer JavaDoc(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     //-------------------------------------------------------------------------
293
/**
294      * Method replacePattern : replace a pattern in a text with another one
295      * ignore oldToken case.
296      *
297      * @param str the text to alter
298      * @param oldToken the token to replace
299      * @param newToken the new text
300      *
301      * @return the altered text
302      */

303     static public String JavaDoc replacePatternIgnoreCase(String JavaDoc str, String JavaDoc oldToken, String JavaDoc newToken) {
304         if (str==null){
305             return str;
306         }
307
308         StringBuffer JavaDoc result = new StringBuffer JavaDoc(str.length() + 100);
309         String JavaDoc 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     // if invert == 1 -> inverse oldTocken with newTocken
324
static public String JavaDoc replacePattern(String JavaDoc str, String JavaDoc newToken, String JavaDoc oldToken, int invert ) {
325         if (invert==0){
326             return replacePattern(str, newToken, oldToken);
327         } else {
328             // inverse arguments
329
return replacePattern(str, oldToken, newToken);
330         }
331     }
332
333     //-------------------------------------------------------------------------
334
/**
335      * Method getTokens : return an arrays of String tokens
336      *
337      * @param str the string to parse
338      * @param sep the separator
339      * @return an array of string values
340      * @author NK
341      */

342     static public String JavaDoc[] getTokens(String JavaDoc str, String JavaDoc sep) {
343         if (str==null){
344             return null;
345         }
346
347         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str,sep);
348         String JavaDoc[] result = new String JavaDoc[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     //-------------------------------------------------------------------------
360
/**
361      * Convert a String starting with the word "$context" into a real filesystem
362      * path. This method is principally used by JahiaPrivateSettings and to
363      * convert jahia.properties settings.
364      * @author Alexandre Kraft
365      *
366      * @param convert The string to convert.
367      * @param pathResolver The path resolver used to get the real path.
368      */

369     public static String JavaDoc convertContexted( String JavaDoc convert,
370                                            PathResolver pathResolver )
371     {
372         if(convert.startsWith("$context/")) {
373             convert = pathResolver.resolvePath( convert.substring(8, convert.length()) );
374         }
375         return convert;
376     } // end convertContexted
377

378
379     //-------------------------------------------------------------------------
380
/**
381      * Convert a standard string to a property-compatible string.
382      * @author Alexandre Kraft
383      *
384      * @param originalValue The string that you want to convert.
385      * @return The string converted.
386      */

387     public static String JavaDoc string2Property( String JavaDoc originalValue )
388     {
389         StringBuffer JavaDoc convertedValue = new StringBuffer JavaDoc();
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     } // end string2Property
401

402
403     //-------------------------------------------------------------------------
404
/**
405      * Get each line from a string or a file and set it to an enumeration.
406      * @author Alexandre Kraft
407      *
408      * @param decompose The string that you want to convert if <code>isFile</code>
409      * is <code>false</code>. Otherwise, it's the path to
410      * the file you want to read.
411      * @boolean isFile <code>true</code> is the source is a File or
412      * <code>false</code> if the source is a String.
413      * @return Enumeration containing all lines of the string passed in parameter.
414      */

415     public static Enumeration JavaDoc string2Enumeration( String JavaDoc decompose, boolean isFile )
416     throws IOException JavaDoc
417     {
418         Vector JavaDoc stringLines = new Vector JavaDoc();
419         String JavaDoc buffer = "";
420         BufferedReader JavaDoc buffered;
421
422         if(isFile) {
423             buffered = new BufferedReader JavaDoc( new FileReader JavaDoc( decompose ) );
424         } else {
425             buffered = new BufferedReader JavaDoc( new StringReader JavaDoc( 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     } // end string2Enumeration
438

439
440
441     //-------------------------------------------------------------------------
442
/**
443      * Check if the String passed in parameter is Alpha valid.
444      *
445      * @author FH
446      */

447     public static boolean isAlphaValid(String JavaDoc 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     } // end isAlphaValid
479

480
481
482     //-------------------------------------------------------------------------
483
/**
484      * Write a string in a file.
485      *
486      * @author AK
487      * @param fileName File name.
488      * @param output String output.
489      */

490     public static void writeStringInFile( String JavaDoc fileName,
491                                           String JavaDoc output )
492     {
493         // try to write the file...
494
try
495         {
496             File JavaDoc fileObject = new File JavaDoc( fileName );
497             FileWriter JavaDoc fileWriter = new FileWriter JavaDoc( fileObject );
498
499             fileWriter.write( output );
500             fileWriter.close();
501         } catch (IOException JavaDoc ioe) {
502         }
503     } // end writeStringInFile
504

505
506
507     /**************************************************************************
508      * Files Tools
509      *
510      *
511      **************************************************************************/

512
513
514     //-------------------------------------------------------------------------
515
/**
516      * Copy files from String origin to String destination.
517      *
518      * @author AK
519      */

520     public static void copyFolderContent( String JavaDoc origin,
521                                           String JavaDoc destination )
522     throws IOException JavaDoc
523     {
524         File JavaDoc originFolder = new File JavaDoc(origin);
525         File JavaDoc destinationFolder = new File JavaDoc(destination);
526
527         // create the destination folder if necessary...
528
if(!destinationFolder.exists()) {
529             destinationFolder.mkdirs();
530         }
531
532         // copy recursive...
533
if(originFolder.isDirectory())
534         {
535             File JavaDoc[] filesInThisDirectory = originFolder.listFiles();
536             StringBuffer JavaDoc destinationFile = null;
537             for(int i=0; i<filesInThisDirectory.length; i++) {
538                 String JavaDoc originFile = filesInThisDirectory[i].getPath();
539                 String JavaDoc originFileName = filesInThisDirectory[i].getName();
540                 destinationFile = new StringBuffer JavaDoc(destination);
541                 destinationFile.append(File.separator);
542                 destinationFile.append(originFileName);
543                 if(filesInThisDirectory[i].isFile()) {
544                     FileInputStream JavaDoc fileInput = new FileInputStream JavaDoc( originFile );
545                     FileOutputStream JavaDoc fileOutput = new FileOutputStream JavaDoc( destinationFile.toString() );
546                     copyStream( fileInput, fileOutput );
547                 } else {
548                     copyFolderContent( originFile, destinationFile.toString() );
549                 }
550             }
551         }
552     } // end copyFiles
553

554
555     //-------------------------------------------------------------------------
556
/**
557      * Copy an InputStream to an OutputStream
558      *
559      * @author AK
560      */

561     public static void copyStream( InputStream JavaDoc inputStream,
562                                     OutputStream JavaDoc outputStream )
563     throws IOException JavaDoc
564     {
565         int bufferRead;
566         int bufferSize = 65536;
567         byte[] writeBuffer = new byte[bufferSize];
568
569         BufferedInputStream JavaDoc bufInStream = new BufferedInputStream JavaDoc(inputStream, bufferSize);
570         BufferedOutputStream JavaDoc bufOutStream = new BufferedOutputStream JavaDoc(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     } // end copyStream
582

583
584     //-------------------------------------------------------------------------
585
public static boolean checkFileExists( String JavaDoc fileName )
586     {
587         try {
588             File JavaDoc fileObject = new File JavaDoc( fileName );
589             return fileObject.exists();
590         } catch (NullPointerException JavaDoc npe) {
591             return false;
592         }
593     } // end checkFileExists
594

595
596     //-------------------------------------------------------------------------
597
/**
598      * check if a file or directory exists on disk. The check is case sensitive
599      *
600      * @author NK
601      * @param String the absolute path
602      * @return boolean true if comparison is success
603      */

604     static public boolean checkFileNameCaseSensitive(String JavaDoc path){
605
606         File JavaDoc tmpFile = new File JavaDoc(path);
607         if ( tmpFile != null && ( tmpFile.isFile() || tmpFile.isDirectory() ) ){
608             String JavaDoc name = tmpFile.getName();
609             if ( tmpFile.getParentFile() != null ){
610                 File JavaDoc[] 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     //-------------------------------------------------------------------------
624
/**
625      * delete a file or directory (and all its content)
626      *
627      * @author NK
628      * @param (File) the abstract file object
629      */

630     public static boolean deleteFile(File JavaDoc f){
631         return deleteFile(f,false);
632
633     }
634
635
636     //-------------------------------------------------------------------------
637
/**
638      * delete a file or directory ( and all its contains )
639      *
640      * @author NK
641      * @param (File) the abstract file object
642      * @param (boolean) contentOnly id true, delete only the folder content
643      */

644     public static boolean deleteFile(File JavaDoc f, boolean contentOnly){
645
646         if ( f == null ){
647             return false;
648         }
649
650         if ( f.isDirectory() ){
651
652             File JavaDoc[] 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     //-------------------------------------------------------------------------
671
/**
672      * Return the file name but without the extension
673      *
674      * @author NK
675      * @param (String) filename , the complete file name with extension
676      * @param (String) ext , the extension to remove
677      * @return(String) the filename without a gived extension
678      */

679     public static String JavaDoc removeFileExtension(String JavaDoc filename, String JavaDoc ext){
680
681         String JavaDoc 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     //-------------------------------------------------------------------------
690
/**
691      * Method getUniqueDirName
692      * Return a random and unique String that can be used
693      * as directory name
694      *
695      * @return a unique directory name
696      */

697     public static String JavaDoc getUniqueDirName() {
698
699          return ( JahiaKeyGen.getKey(10) );
700     }
701
702
703
704     /**************************************************************************
705      * Sql Tools
706      *
707      *
708      *************************************************************************/

709
710     //-------------------------------------------------------------------------
711
/**
712      * Method Quote
713      * Double the quotes in order to be SQL compliant
714      *
715      * @param input String to filter
716      * @return a filtered string
717      */

718     static public String JavaDoc quote(String JavaDoc input)
719     {
720
721         if ( input != null ){
722             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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     //-------------------------------------------------------------------------
737
/**
738      * Method escape double quote " with \"
739      *
740      * @param input String
741      * @return a filtered string
742      */

743     static public String JavaDoc escapeString(String JavaDoc input)
744     {
745         if ( input != null ){
746             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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     /**************************************************************************
762      * General purposes Tools
763      *
764      *
765      **************************************************************************/

766
767
768     //-------------------------------------------------------------------------
769
/**
770      * Check if a string value is in an array of string
771      *
772      * @param aValue a string value
773      * @param values an array of String
774      * @return true if value found in array
775      * @author NK
776      */

777      static public boolean inValues(String JavaDoc aValue, String JavaDoc[] 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     //-------------------------------------------------------------------------
791
/**
792      * Return a substitute String value if the source is null otherwise
793      * return the source value
794      *
795      * @param String the data
796      * @param String the subsitute value
797      * @return String
798      * @author NK
799      */

800      static public String JavaDoc replaceNullString(String JavaDoc data, String JavaDoc newValue){
801         if ( data != null ){
802             return data;
803         }
804         return newValue;
805      }
806
807
808     //-------------------------------------------------------------------------
809
/**
810      * Return a substitute Integer object if the source is null otherwise
811      * return the source integer object
812      *
813      * @param Integer data
814      * @param Integer newValue
815      * @return String
816      * @author NK
817      */

818      static public Integer JavaDoc replaceNullInteger(Integer JavaDoc data, Integer JavaDoc newValue){
819         if ( data != null ){
820             return data;
821         }
822         return newValue;
823      }
824
825
826     //-------------------------------------------------------------------------
827
/**
828      * Guarantee a String not to be null, giving it an empty value if needed.
829      *
830      * @author Mikha�l Janson
831      * @param inputString A <code>String</code> value, that may be null
832      *
833      * @return a <code>String</code> value, guaranteed not to be null.
834      */

835     public static String JavaDoc nnString( String JavaDoc inputString )
836     {
837         String JavaDoc outputString = (inputString != null) ? inputString : "";
838         return outputString;
839     } // end nnString
840

841
842     //-------------------------------------------------------------------------
843
/**
844      * Simple <code>int</code> to <code>boolean</code> converter
845      *
846      * @param value an integer value
847      * @return <code>false</code> if <code>0</code>, <code>1</code> if not <code>0</code>
848      */

849     static public boolean int2boolean(int value)
850     {
851         return value != 0;
852     }
853
854
855     //-------------------------------------------------------------------------
856
/**
857      * Simple <code>boolean</code> to <code>int</code> converter
858      *
859      * @param value a <code>boolean</code> value
860      * @return <code>0</code> if <code>false</code>, <code>1</code> if <code>true</code>
861      */

862     static public int boolean2int(boolean value)
863     {
864         return value ? 1 : 0;
865     }
866
867
868     //-------------------------------------------------------------------------
869
/**
870      * Method inverseVector : inverse the elements contained in a vector
871      *
872      * @param myVector the vector to inverse
873      * @return the inversed vector
874      */

875     static public Vector JavaDoc inverseVector(Vector JavaDoc myVector) {
876
877         Vector JavaDoc temp = new Vector JavaDoc();
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     //-------------------------------------------------------------------------
887
/**
888      * Update a property's value in a properties file.
889      *
890      * @author Khue N'Guyen
891      * @author Alexandre Kraft
892      *
893      * @param name the property name
894      * @param val the property value
895      * @param path the full filesystem path to the properties file
896      */

897     public static void updatepropvalue( String JavaDoc propertyName,
898                                             String JavaDoc propvalue,
899                                             String JavaDoc path )
900     {
901         Vector JavaDoc bufferVector = new Vector JavaDoc();
902         String JavaDoc lineReaded = null;
903         int position = 0;
904         boolean lineFound = false;
905         boolean success = false;
906
907         try
908         {
909             // parse the file...
910
BufferedReader JavaDoc buffered = new BufferedReader JavaDoc( new FileReader JavaDoc(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             // add property if it don't exists before...
925
if(!lineFound)
926             {
927                 bufferVector.add( propertyName + " = " + propvalue );
928             }
929
930             // rewrite the file...
931
File JavaDoc thisFile = new File JavaDoc(path);
932             FileWriter JavaDoc fileWriter = new FileWriter JavaDoc( thisFile );
933             StringBuffer JavaDoc outputBuffer = new StringBuffer JavaDoc();
934
935             for(int i=0; i < bufferVector.size(); i++) {
936                 outputBuffer.append((String JavaDoc) bufferVector.get(i));
937             }
938
939             fileWriter.write( outputBuffer.toString() );
940             fileWriter.close();
941         } catch (java.io.IOException JavaDoc ioe) {
942         }
943     } // end updatepropvalue
944

945
946
947     /**************************************************************************
948      * Client Browser Check Tools
949      *
950      **************************************************************************/

951
952     //-------------------------------------------------------------------------
953
public static boolean isMSIExplorer(HttpServletRequest JavaDoc req){
954         return ( req.getHeader("user-agent") != null && req.getHeader("user-agent").indexOf("MSIE") != -1 );
955     }
956
957     //-------------------------------------------------------------------------
958
public static boolean isLynx(HttpServletRequest JavaDoc req){
959         return ( req.getHeader("user-agent") != null && req.getHeader("user-agent").indexOf("Lynx") != -1 );
960     }
961
962
963
964     /**************************************************************************
965      * Servlet Request Parameters handling
966      *
967      **************************************************************************/

968
969     //-------------------------------------------------------------------------
970
/**
971      * return a parameter of String type if not null or return the subsitute value
972      *
973      * @param HttpServletRequest req the request object
974      * @param String the param name
975      * @param String the subsitute value to return if the parameter is null
976      * @return String the parameter value
977      * @author NK
978      */

979     public static String JavaDoc getStrParameter(HttpServletRequest JavaDoc req, String JavaDoc paramName, String JavaDoc nullVal){
980
981         String JavaDoc val = (String JavaDoc)req.getParameter(paramName);
982         if ( val == null ){
983             return nullVal;
984         }
985         return val;
986     }
987
988
989     //-------------------------------------------------------------------------
990
/**
991      * return a parameter of Integer type if not null or return the subsitute value
992      *
993      * @param HttpServletRequest req the request object
994      * @param String the param name
995      * @param Integer the subsitute value to return if the parameter is null
996      * @return Integer the parameter value
997      * @author NK
998      */

999     public static Integer JavaDoc getIntParameter(HttpServletRequest JavaDoc req, String JavaDoc paramName, Integer JavaDoc nullVal){
1000
1001        String JavaDoc strVal = (String JavaDoc)req.getParameter(paramName);
1002        Integer JavaDoc val = null;
1003        if ( strVal == null ){
1004            return nullVal;
1005        } else {
1006            try {
1007                val = new Integer JavaDoc(strVal);
1008            } catch ( Throwable JavaDoc t ){
1009                val = nullVal;
1010            }
1011        }
1012        return val;
1013    }
1014
1015
1016
1017    //-------------------------------------------------------------------------
1018
/**
1019     * Remove context attribute they names start with the string passed in
1020     * parameter. In details, this method select which attribute he wants to
1021     * remove and compose a temporary vector with it. Next step is to delete
1022     * all attributes contains in this vector, via an enumeration. The reason
1023     * of this is that you can't remove a context attribute while you use the
1024     * getAttributeNames method to get the list of context attribute names.
1025     * @author Alexandre Kraft
1026     *
1027     * @param context The context where do you want to remove attributes
1028     * @param startString The string for select the attributes by they names.
1029     */

1030    public static void removeContextAttributes( ServletContext JavaDoc context,
1031                                                String JavaDoc startString )
1032    {
1033        Enumeration JavaDoc contextAttributeNames = context.getAttributeNames();
1034        Vector JavaDoc attributesToRemove = new Vector JavaDoc();
1035        String JavaDoc attributeName;
1036
1037        while(contextAttributeNames.hasMoreElements()) {
1038            attributeName = (String JavaDoc) 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 JavaDoc attributesListToRemove = attributesToRemove.elements();
1047        while(attributesListToRemove.hasMoreElements()) {
1048            attributeName = (String JavaDoc) attributesListToRemove.nextElement();
1049            context.removeAttribute( attributeName );
1050        }
1051    } // end removeContextAttributes
1052

1053
1054    /**************************************************************************
1055     * HTML Tools
1056     *
1057     *
1058     *************************************************************************/

1059
1060    //-------------------------------------------------------------------------
1061
/***
1062      * Return text with HTML entities (text2html)
1063      * @author POL
1064      * @version 1.0 POL 14/06/2001
1065      * @version 1.1 MAP 23.10.2001
1066      * @param str Input String
1067      * @return str HtmlEntities output
1068      */

1069    public static String JavaDoc text2html( String JavaDoc str )
1070    {
1071        return TextHtml.text2html(str); // Changed by MAP
1072
}
1073
1074    //-------------------------------------------------------------------------
1075
/***
1076      * Return text without HTML entities (html2text)
1077      * @author POL
1078      * @version 1.0 POL 18/06/2001
1079      * @version 1.1 MAP 23.10.2001
1080      * @param str Input String
1081      * @return str Text output
1082      */

1083    public static String JavaDoc html2text(String JavaDoc str)
1084    {
1085        //str = replacePattern(str,"X-AND-X","&amp;");
1086
str = replacePattern(str,"&amp;","&");
1087        return TextHtml.html2text(str); // Changed by MAP
1088
}
1089
1090
1091    //-------------------------------------------------------------------------
1092
/***
1093      * text2XMLEntityRef
1094      * Parse a text and replace XML specific characters to their XML Entity Reference value.
1095      * @author Khue Nguyen
1096      * @param str Input String
1097      * @param invert int (0/1) 0 : text to XML Entity Reference / 1 : XML Entity Reference to text
1098      * @return str Text output
1099      */

1100    public static String JavaDoc text2XMLEntityRef(String JavaDoc str, int invert)
1101    {
1102        if ( str == null || str.trim().equals("") ){
1103            return str;
1104        }
1105        if (invert == 0) { // Change by MAP
1106
str = TextHtml.text2html(str);
1107        }
1108        else {
1109            str = TextHtml.html2text(str);
1110        }
1111        str = replacePattern(str,"&","&amp;",invert);
1112        str = replacePattern(str,"<","&lt;",invert);
1113        str = replacePattern(str,">","&gt;",invert);
1114        str = replacePattern(str,"\"","&quot;",invert);
1115        str = replacePattern(str,"'","&apos;",invert);
1116        return str;
1117    }
1118
1119
1120    //-------------------------------------------------------------------------
1121
/**
1122     * Tests whether an URL is valid or not.
1123     *
1124     * @param URLString the String representation of the URL to test
1125     * @return <code>true</code> if the URL could be accessed; <code>false</code>
1126     * otherwise
1127     */

1128    public static boolean isValidURL(String JavaDoc URLString) {
1129        try {
1130            URL JavaDoc testURL = new URL JavaDoc(URLString);
1131            testURL.openConnection();
1132            return true;
1133        } catch (Exception JavaDoc e) {
1134            return false;
1135        }
1136    }
1137
1138    /**
1139     * Converts whitespace characters no longer supported by
1140     * JRE 1.3.1_01a or later to character codes that Editize
1141     * will understand.
1142     */

1143    public static String JavaDoc javaSpecialChars(String JavaDoc 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 JavaDoc htmlSpecialChars(String JavaDoc text)
1156    {
1157        if ( text == null ){
1158            return text;
1159        }
1160        text = replacePattern(text,"&","&amp;");
1161        text = replacePattern(text,"<","&lt;");
1162        text = replacePattern(text,">","&gt;");
1163        text = replacePattern(text,"\"","&quot;");
1164        /*
1165        text = replacePattern(text,"&","&#60;");
1166        text = replacePattern(text,"<","&#34;");
1167        text = replacePattern(text,">","&#38;");
1168        text = replacePattern(text,"\"","&#62;");
1169        */

1170
1171        return text;
1172
1173    }
1174
1175    /**
1176     * This is a powerful expression evaluator that allows to evaluate a String
1177     * that has the following format :
1178     * "text${jexlExpr1}text${jexlExpr2}"
1179     * So the string passed may contain multiple JEXL expressions, which can
1180     * themselves be quite complex.
1181     * @param expr String a String containing one or multiple JEXL expressions
1182     * @param contextVars Map a map containing String keyed variables to be
1183     * used as the environment for the JEXL expressions.
1184     * @return String the resulting string from all the expression evaluations
1185     * @throws Exception if an error happened during parsing or expression
1186     * evaluation.
1187     */

1188    public static String JavaDoc evaluateExpressions(String JavaDoc expr, Map JavaDoc contextVars)
1189        throws Exception JavaDoc {
1190
1191        final String JavaDoc START_EXPR_MARKER = "${";
1192        final String JavaDoc END_EXPR_MARKER = "}";
1193
1194        StringBuffer JavaDoc result = new StringBuffer JavaDoc();
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 JavaDoc(
1208                    "Parsing exception, missing end-of-expression marker " +
1209                    END_EXPR_MARKER + " for expression at column " +
1210                    curParsingPos);
1211            }
1212            String JavaDoc 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 JavaDoc o = e.evaluate(jc);
1220            String JavaDoc s = null;
1221            if (o instanceof String JavaDoc) {
1222                s = (String JavaDoc) 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} // end JahiaTools
1239
Popular Tags