001    package railo.loader.util;
002    
003    import java.io.BufferedInputStream;
004    import java.io.BufferedOutputStream;
005    import java.io.BufferedReader;
006    import java.io.File;
007    import java.io.IOException;
008    import java.io.InputStream;
009    import java.io.InputStreamReader;
010    import java.io.OutputStream;
011    import java.io.Reader;
012    import java.io.Writer;
013    import java.text.SimpleDateFormat;
014    import java.util.Date;
015    import java.util.Locale;
016    import java.util.StringTokenizer;
017    import java.util.TimeZone;
018    
019    import railo.commons.io.res.Resource;
020    
021    /**
022     * Util class for different little jobs
023     */
024    public class Util {
025        
026        private static File tempFile;
027        private static File homeFile;
028        
029        private final static SimpleDateFormat HTTP_TIME_STRING_FORMAT;
030            static {
031                    HTTP_TIME_STRING_FORMAT = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz",Locale.ENGLISH);
032                    HTTP_TIME_STRING_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
033            }
034        
035    
036        /**
037         * copy a inputstream to a outputstream
038         * @param in 
039         * @param out
040         * @throws IOException
041         */
042        public final static void copy(InputStream in, OutputStream out) throws IOException {
043            byte[] buffer = new byte[0xffff];
044            int len;
045            while((len = in.read(buffer)) !=-1)
046              out.write(buffer, 0, len);
047            
048            closeEL(in);
049            closeEL(out);
050        }
051        
052        /**
053         * read String data from a InputStream and returns it as String Object 
054         * @param is InputStream to read data from.
055         * @return readed data from InputStream
056         * @throws IOException
057         */
058        public static String toString(InputStream is) throws IOException {
059            BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
060            StringBuffer content=new StringBuffer();
061            
062            String line=br.readLine();
063            if(line!=null) {
064                content.append(line);
065                while((line=br.readLine())!=null)   {
066                    content.append("\n"+line);
067                }
068            }
069            br.close();
070            return content.toString();
071        }
072        
073    
074            public static boolean toBooleanValue(String str) throws IOException {
075                    str=str.trim().toLowerCase();
076    
077                    if("true".equals(str)) return true;
078                    if("false".equals(str)) return false;
079                    if("yes".equals(str)) return true;
080                    if("no".equals(str)) return false;
081                    throw new IOException("can't cast string to a boolean value");
082            }
083        
084    
085        /**
086         * close inputstream without a Exception
087         * @param is 
088         * @param os 
089         */
090         public static void closeEL(InputStream is,OutputStream os) {
091             closeEL(is);
092             closeEL(os);
093          }
094    
095         /**
096          * close inputstream without a Exception
097          * @param is 
098          */
099          public static void closeEL(InputStream is) {
100               try {
101                 if(is!=null)is.close();
102             } 
103             catch (Throwable e) {}
104           }
105    
106          /**
107           * close reader without a Exception
108           * @param is 
109           */
110           public static void closeEL(Reader r) {
111                try {
112                  if(r!=null)r.close();
113              } 
114              catch (Throwable e) {}
115            }
116    
117           /**
118            * close reader without a Exception
119            * @param is 
120            */
121            public static void closeEL(Writer w) {
122               try {
123                   if(w!=null)w.close();
124               } 
125               catch (Throwable e) {}
126             }
127    
128         
129         /**
130          * close outputstream without a Exception
131          * @param os 
132          */
133         public static void closeEL(OutputStream os) {
134               try {
135                   if(os!=null)os.close();
136             } 
137             catch (Throwable e) {}
138           }
139         
140        /**
141         * @param is inputStream to get content From
142         * @param charset
143         * @return returns content from a file inputed by input stream
144         * @throws IOException
145         */
146        public static String getContentAsString(InputStream is, String charset) throws IOException {
147        
148            BufferedReader br = (charset==null)?
149                    new BufferedReader(new InputStreamReader(is)):
150                    new BufferedReader(new InputStreamReader(is,charset)); 
151            StringBuffer content=new StringBuffer();
152            
153            String line=br.readLine();
154            if(line!=null) {
155                content.append(line);
156                while((line=br.readLine())!=null)   {
157                    content.append("\n"+line);
158                }
159            }
160            br.close();
161            return content.toString();
162         }
163    
164        /**
165         * check if string is empty (null or "")
166         * @param str
167         * @return is empty or not
168         */
169        public static boolean isEmpty(String str) {
170            return str==null || str.length()==0;
171        }
172    
173        /**
174         * check if string is empty (null or "")
175         * @param str
176         * @return is empty or not
177         */
178        public static boolean isEmpty(String str, boolean trim) {
179            if(!trim) return isEmpty(str);
180            return str==null || str.trim().length()==0;
181        }
182    
183    
184            public static int length(String str) {
185                    if(str==null) return 0;
186                    return str.length();
187            }
188            
189        /**
190         * cast a railo string version to a int version
191         * @param version
192         * @return int version
193         */
194        public static int toInVersion(String version) {
195            
196            int     rIndex = version.lastIndexOf(".rcs");
197            if(rIndex==-1)  rIndex = version.lastIndexOf(".rc");
198            
199            if(rIndex!=-1) {
200                version=version.substring(0,rIndex);
201            }
202            
203            //1.0.0.090
204            int beginIndex=0;
205            
206            //Major
207            int endIndex=version.indexOf('.',beginIndex);
208            int intVersion=0;
209            intVersion+=Integer.parseInt(version.substring(beginIndex,endIndex))*1000000; // FUTURE 10000000
210    
211            // Minor
212            beginIndex=endIndex+1;
213            endIndex=version.indexOf('.',beginIndex);
214            intVersion+=Integer.parseInt(version.substring(beginIndex,endIndex))*10000; // FUTURE 100000
215    
216            // releases
217            beginIndex=endIndex+1;
218            endIndex=version.indexOf('.',beginIndex);
219            intVersion+=Integer.parseInt(version.substring(beginIndex,endIndex))*100; // FUTURE 1000
220            
221            // patches
222            beginIndex=endIndex+1;
223            intVersion+=Integer.parseInt(version.substring(beginIndex));
224            
225            return intVersion;
226            
227            
228            //intVersion=(major*1000000)+(minor*10000)+(releases*100)+patches;
229            
230        }
231        
232        public static String toStringVersion(int version) {
233            
234            StringBuffer sb=new StringBuffer();
235    
236            // Major
237            int tmp=(version/1000000); // FUTURE 10000000
238            version-=tmp*1000000; // FUTURE 10000000
239            sb.append(String.valueOf(tmp));
240            sb.append(".");
241    
242            // Minor
243            tmp=(version/10000); // FUTURE 100000
244            version-=tmp*10000; // FUTURE 100000
245            sb.append(len(String.valueOf(tmp),2));
246            sb.append(".");
247    
248            // releases
249            tmp=(version/100); // FUTURE 1000
250            version-=tmp*100; // FUTURE 1000
251            sb.append(len(String.valueOf(tmp),2));
252            sb.append(".");
253            
254            // patches
255            sb.append(len(String.valueOf(version),3));
256            
257            return sb.toString();
258            
259        }
260        
261        
262        private static Object len(String str, int i) {
263                    while(str.length()<i)
264                            str="0"+str;
265                    return str;
266            }
267    
268            /**
269         * @param str String to work with
270         * @param sub1 value to replace
271         * @param sub2 replacement
272         * @param onlyFirst replace only first or all 
273         * @return new String
274         */
275        public static String replace(String str, String sub1, String sub2, boolean onlyFirst) {
276            if(sub1.equals(sub2)) return str;
277            
278            if(!onlyFirst && sub1.length()==1 && sub2.length()==1)return str.replace(sub1.charAt(0),sub2.charAt(0));
279            
280            
281            StringBuffer sb=new StringBuffer();
282            int start=0;
283            int pos;
284            int sub1Length=sub1.length();
285            
286            while((pos=str.indexOf(sub1,start))!=-1){
287                sb.append(str.substring(start,pos));
288                sb.append(sub2);
289                start=pos+sub1Length;
290                if(onlyFirst)break;
291            }
292            sb.append(str.substring(start));
293            
294            return sb.toString();
295        }
296        /**
297         * replace path placeholder with the real path, placeholders are [{temp-directory},{system-directory},{home-directory}]
298         * @param path
299         * @return updated path
300         */
301        public static String parsePlaceHolder(String path) {
302            if(path==null) return path;
303            // Temp
304            if(path.startsWith("{temp")) {
305                if(path.startsWith("}",5)) path=new File(getTempDirectory(),path.substring(6)).toString();
306                else if(path.startsWith("-dir}",5)) path=new File(getTempDirectory(),path.substring(10)).toString();
307                else if(path.startsWith("-directory}",5)) path=new File(getTempDirectory(),path.substring(16)).toString();
308            }
309            // System
310            else if(path.startsWith("{system")) {
311                if(path.startsWith("}",7)) path=new File(getSystemDirectory(),path.substring(8)).toString();
312                else if(path.startsWith("-dir}",7)) path=new File(getSystemDirectory(),path.substring(12)).toString();
313                else if(path.startsWith("-directory}",7)) path=new File(getSystemDirectory(),path.substring(18)).toString();
314            }
315            // Home
316            else if(path.startsWith("{home")) {
317                if(path.startsWith("}",5)) path=new File(getHomeDirectory(),path.substring(6)).toString();
318                else if(path.startsWith("-dir}",5)) path=new File(getHomeDirectory(),path.substring(10)).toString();
319                else if(path.startsWith("-directory}",5)) path=new File(getHomeDirectory(),path.substring(16)).toString();
320            }
321            return path;
322        }
323        
324        /**
325         * returns the Temp Directory of the System
326         * @return temp directory
327         */
328        public static File getTempDirectory() {
329            if(tempFile!=null) return tempFile;
330            
331            String tmpStr = System.getProperty("java.io.tmpdir");
332            if(tmpStr!=null) {
333                tempFile=new File(tmpStr);
334                if(tempFile.exists()) {
335                    tempFile=getCanonicalFileEL(tempFile);
336                    return tempFile;
337                }
338            }
339            try {
340                File tmp = File.createTempFile("a","a");
341                tempFile=tmp.getParentFile();
342                tempFile=getCanonicalFileEL(tempFile);
343                tmp.delete();
344            }
345            catch(IOException ioe) {}
346            
347            return tempFile;
348        }
349        
350        /**
351         * returns the Hoome Directory of the System
352         * @return home directory
353         */
354        public static File getHomeDirectory() {
355            if(homeFile!=null) return homeFile;
356            
357            String homeStr = System.getProperty("user.home");
358            if(homeStr!=null) {
359                homeFile=new File(homeStr);
360                homeFile=getCanonicalFileEL(homeFile);
361            }
362            return homeFile;
363        }
364        
365    
366        /**
367         * @return return System directory
368         */
369        public static File getSystemDirectory() {
370            String pathes=System.getProperty("java.library.path");
371            if(pathes!=null) {
372                String[] arr=pathes.split(File.pathSeparator);
373                //String[] arr=List.toStringArrayEL(List.listToArray(pathes,File.pathSeparatorChar));
374                for(int i=0;i<arr.length;i++) {    
375                    if(arr[i].toLowerCase().indexOf("windows\\system")!=-1) {
376                        File file = new File(arr[i]);
377                        if(file.exists() && file.isDirectory() && file.canWrite()) return getCanonicalFileEL(file);
378                        
379                    }
380                }
381                for(int i=0;i<arr.length;i++) {    
382                    if(arr[i].toLowerCase().indexOf("windows")!=-1) {
383                        File file = new File(arr[i]);
384                        if(file.exists() && file.isDirectory() && file.canWrite()) return getCanonicalFileEL(file);
385                        
386                    }
387                }
388                for(int i=0;i<arr.length;i++) {    
389                    if(arr[i].toLowerCase().indexOf("winnt")!=-1) {
390                        File file = new File(arr[i]);
391                        if(file.exists() && file.isDirectory() && file.canWrite()) return getCanonicalFileEL(file);
392                        
393                    }
394                }
395                for(int i=0;i<arr.length;i++) {    
396                    if(arr[i].toLowerCase().indexOf("win")!=-1) {
397                        File file = new File(arr[i]);
398                        if(file.exists() && file.isDirectory() && file.canWrite()) return getCanonicalFileEL(file);
399                        
400                    }
401                }
402                for(int i=0;i<arr.length;i++) {
403                    File file = new File(arr[i]);
404                    if(file.exists() && file.isDirectory() && file.canWrite()) return getCanonicalFileEL(file);
405                }
406            }
407            return null;
408        }
409        
410        /**
411         * Returns the canonical form of this abstract pathname.
412         * @param file file to get canoncial form from it
413         *
414         * @return  The canonical pathname string denoting the same file or
415         *          directory as this abstract pathname
416         *
417         * @throws  SecurityException
418         *          If a required system property value cannot be accessed.
419         */
420        public static File getCanonicalFileEL(File file) {
421            try {
422                return file.getCanonicalFile();
423            } catch (IOException e) {
424                return file;
425            }
426        }
427            
428            public static String toHTTPTimeString(Date date) {
429                    return replace(HTTP_TIME_STRING_FORMAT.format(date),"+00:00","",true);
430            }
431            
432            public static String toHTTPTimeString() {
433                    return replace(HTTP_TIME_STRING_FORMAT.format(new Date()),"+00:00","",true);
434            }
435            
436            public static boolean hasUpperCase(String str) {
437                    if(isEmpty(str)) return false;
438                    return !str.equals(str.toLowerCase());
439            }
440    
441            public static BufferedInputStream toBufferedInputStream(InputStream is) {
442                    if(is instanceof BufferedInputStream) return (BufferedInputStream) is;
443                    return new BufferedInputStream(is);
444            }
445        
446        public static BufferedOutputStream toBufferedOutputStream(OutputStream os) {
447                    if(os instanceof BufferedOutputStream) return (BufferedOutputStream) os;
448                    return new BufferedOutputStream(os);
449            }
450    
451        public static void copy(Resource in, Resource out) throws IOException {
452                    InputStream is=null;
453                    OutputStream os=null;
454                    try {
455                            is=toBufferedInputStream(in.getInputStream());
456                            os=toBufferedOutputStream(out.getOutputStream());
457                    }
458                    catch(IOException ioe) {
459                            closeEL(os);
460                            closeEL(is);
461                            throw ioe;
462                    }
463                    copy(is,os);
464            }
465        
466        public static String toVariableName(String str, boolean addIdentityNumber) {
467                    StringBuffer rtn=new StringBuffer();
468                    char[] chars=str.toCharArray();
469                    long changes=0;
470                    for(int i=0;i<chars.length;i++) {
471                            char c=chars[i];
472                            if(i==0 && (c>='0' && c<='9'))rtn.append("_"+c);
473                            else if((c>='a' && c<='z') ||(c>='A' && c<='Z') ||(c>='0' && c<='9') || c=='_' || c=='$')
474                                    rtn.append(c);
475                            else {  
476                                rtn.append('_');
477                                    changes+=(c*(i+1));
478                            }
479                    }
480                    if(addIdentityNumber && changes>0)rtn.append(changes);
481                    return rtn.toString();
482            }
483        
484        public static String first(String str,String delimeter){
485                    StringTokenizer st=new StringTokenizer(str,delimeter);
486                    return st.nextToken();
487            }
488            
489            public static String last(String str,String delimeter){
490                    StringTokenizer st=new StringTokenizer(str,delimeter);
491                    String rtn=null;
492                    while(st.hasMoreTokens())
493                            rtn= st.nextToken();
494                    return rtn;
495            }
496        
497    }