1 /*************************************************************************
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * Copyright 2000, 2010 Oracle and/or its affiliates.
6  *
7  * OpenOffice.org - a multi-platform office productivity suite
8  *
9  * This file is part of OpenOffice.org.
10  *
11  * OpenOffice.org is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License version 3
13  * only, as published by the Free Software Foundation.
14  *
15  * OpenOffice.org is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License version 3 for more details
19  * (a copy is included in the LICENSE file that accompanied this code).
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * version 3 along with OpenOffice.org.  If not, see
23  * <http://www.openoffice.org/license.html>
24  * for a copy of the LGPLv3 License.
25  *
26  ************************************************************************/
27 
28 package graphical;
29 
30 import java.io.File;
31 import java.io.FileFilter;
32 import java.io.FileInputStream;
33 import java.io.FileOutputStream;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.util.StringTokenizer;
37 import helper.OSHelper;
38 
39 import java.io.PrintStream;
40 import javax.swing.JOptionPane;
41 
42 public class FileHelper
43 {
44     public FileHelper()
45         {
46             // fs = System.getProperty("file.separator");
47 
48 
49             String sOSName = System.getProperty("os.name");
50             String sOSArch = System.getProperty("os.arch");
51             String sOSVersion = System.getProperty("os.version");
52 
53             GlobalLogWriter.println(sOSName);
54             GlobalLogWriter.println(sOSArch);
55             GlobalLogWriter.println(sOSVersion);
56 
57         }
58 
59     public static void MessageBox(String _sStr)
60         {
61             String sVersion = System.getProperty("java.version");
62             String sOSName  = System.getProperty("os.name");
63             JOptionPane.showMessageDialog( null, _sStr, sVersion + " " + sOSName + " Hello World Debugger", JOptionPane.INFORMATION_MESSAGE );
64         }
65 
66     public static boolean exists(String _sFile)
67         {
68             if (_sFile == null)
69             {
70                 return false;
71             }
72 
73             File aFile = new File(_sFile);
74             if (aFile.exists())
75             {
76                 return true;
77             }
78             // This is just nice for DEBUG behaviour
79             // due to the fact this is absolutly context dependency no one should use it.
80             // else
81             // {
82             //     System.out.println("FileHelper:exists() tell this path doesn't exists. Check it. path is:" );
83             //     System.out.println( _sFile );
84             //     System.out.println( aFile.getAbsolutePath() );
85             //     MessageBox("Der JavaProzess wartet auf eine interaktion ihrerseits.");
86             //
87             //     File aFile2 = new File(_sFile);
88             //     if (aFile2.exists())
89             //     {
90             //         System.out.println("Thanks, file exists." );
91             //         return true;
92             //     }
93             // }
94             return false;
95         }
96 
97     public static boolean isDir(String _sDir)
98         {
99             if (_sDir == null)
100             {
101                 return false;
102             }
103             try
104             {
105                 File aFile = new File(_sDir);
106                 if (aFile.exists() && aFile.isDirectory())
107                 {
108                     return true;
109                 }
110             }
111             catch (NullPointerException e)
112             {
113                 GlobalLogWriter.println("Exception caught. FileHelper.isDir('" + _sDir + "')");
114                 e.printStackTrace();
115             }
116             return false;
117         }
118 
119     public static String getBasename(String _sFilename)
120         {
121             if (_sFilename == null)
122             {
123                 return "";
124             }
125             // String fs = System.getProperty("file.separator");
126 
127             int nIdx = _sFilename.lastIndexOf("\\");
128             if (nIdx == -1)
129             {
130                 nIdx = _sFilename.lastIndexOf("/");
131             }
132             if (nIdx > 0)
133             {
134                 return _sFilename.substring(nIdx + 1);
135             }
136             return _sFilename;
137         }
138 
139     public static String getNameNoSuffix(String _sFilename)
140         {
141             if (_sFilename == null)
142             {
143                 return "";
144             }
145             int nIdx = _sFilename.lastIndexOf(".");
146             if (nIdx > 0)
147             {
148                 return _sFilename.substring(0, nIdx);
149             }
150             return _sFilename;
151         }
152 
153     public static String getSuffix(String _sFilename)
154         {
155             if (_sFilename == null)
156             {
157                 return "";
158             }
159             int nIdx = _sFilename.lastIndexOf(".");
160             if (nIdx > 0)
161             {
162                 return _sFilename.substring(nIdx );
163             }
164             return "";
165         }
166 
167     public static String getPath(String _sFilename)
168         {
169             if (_sFilename == null)
170             {
171                 return "";
172             }
173             // String fs = System.getProperty("file.separator");
174 
175             int nIdx = _sFilename.lastIndexOf("\\");
176             if (nIdx == -1)
177             {
178                 nIdx = _sFilename.lastIndexOf("/");
179             }
180             if (nIdx > 0)
181             {
182                 return _sFilename.substring(0, nIdx);
183             }
184             return "";
185         }
186 
187 /*
188     static ArrayList files = new ArrayList();
189     public static Object[] traverse( String afileDirectory )
190         {
191 
192             File fileDirectory = new File(afileDirectory);
193             // Testing, if the file is a directory, and if so, it throws an exception
194             if ( !fileDirectory.isDirectory() )
195             {
196                 throw new IllegalArgumentException( "not a directory: " + fileDirectory.getName() );
197             }
198 
199             // Getting all files and directories in the current directory
200             File[] entries = fileDirectory.listFiles();
201 
202             // Iterating for each file and directory
203             for ( int i = 0; i < entries.length; ++i )
204             {
205                 // adding file to List
206                 try
207                 {
208                     // Composing the URL by replacing all backslashs
209                     String stringUrl = "file:///"
210                         + entries[ i ].getAbsolutePath().replace( '\\', '/' );
211                     files.add(stringUrl);
212                 }
213                 catch( Exception exception )
214                 {
215                     exception.printStackTrace();
216                 }
217             }
218             return files.toArray();
219         }
220 */
221 
222     // makeDirectories("", "/tmp/a/b");
223     // creates all directories /tmp/a/b
224     //
225     public static void makeDirectories(String first, String path)
226         {
227             makeDirectories(first, path, "0777");
228         }
229 
230     public static void makeDirectories(String first, String path, String _sMode)
231         {
232             String fs = System.getProperty("file.separator");
233             if (path.startsWith(fs + fs)) // starts with UNC Path
234             {
235                 int n = path.indexOf(fs, 2);
236                 n = path.indexOf(fs, n + 1);
237                 first = path.substring(0, n);
238                 path = path.substring(n + 1);
239             }
240 
241             String already_done = null;
242             StringTokenizer path_tokenizer = new StringTokenizer(path,fs,false);
243             already_done = first;
244             while (path_tokenizer.hasMoreTokens())
245             {
246                 String part = path_tokenizer.nextToken();
247                 File new_dir = new File(already_done + File.separatorChar + part);
248                 already_done = new_dir.toString();
249                 // System.out.println(already_done);
250                 //create the directory
251                 new_dir.mkdirs();
252                 if (OSHelper.isUnix() &&
253                     _sMode.length() > 0)
254                 {
255                     try
256                     {
257                         chmod(new_dir, _sMode);
258                     }
259                     catch (java.io.IOException e)
260                     {
261                         GlobalLogWriter.println("Exception caught. FileHelper.makeDirectories('" + new_dir.getAbsolutePath() + "')");
262                     }
263                 }
264             }
265             // return;
266         }
267 
268     public static void chmod(File file, String mode) throws java.io.IOException
269         {
270             Runtime.getRuntime().exec
271                 (new String[]
272                     {"chmod", mode, file.getAbsolutePath()});
273         }
274 
275     public static String removeFirstDirectorysAndBasenameFrom(String _sName, String _sRemovePath)
276         {
277             // pre: _sName: /a/b/c/d/e/f.g _sRemovePath /a/b/c
278             // result: d/e
279             String fs = System.getProperty("file.separator");
280 
281             String sBasename = FileHelper.getBasename(_sName);
282             String sSubDirs = "";
283             if (_sName.startsWith(_sRemovePath))
284             {
285                 // if _sName starts with _sRemovePath
286                 int nRemovePathIndex = _sRemovePath.length();
287                 if (! _sRemovePath.endsWith(fs))
288                 {
289                     // add 1 if we not ends with file separator
290                     nRemovePathIndex ++;
291                 }
292                 int nBasenameIndex = _sName.length() - sBasename.length() - 1;
293                 if (nRemovePathIndex < nBasenameIndex)
294                 {
295                     sSubDirs = _sName.substring(nRemovePathIndex, nBasenameIndex);
296                 }
297             }
298             else
299             {
300                 // special case, the _sRemovePath is not part of _sName
301                 sSubDirs = FileHelper.getPath(_sName);
302                 if (sSubDirs.startsWith(fs))
303                 {
304                     // remove leading file separator
305                     sSubDirs = sSubDirs.substring(1);
306                 }
307             }
308 
309             return sSubDirs;
310         }
311 
312     public static void test_removeFirstDirectorysAndBasenameFrom()
313         {
314             String a = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/a/b/c");
315             // assure("", a.equals("d/e"));
316             String b = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/a/b/c/");
317             // assure("", b.equals("d/e"));
318             String c = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/b/c");
319             // assure("", c.equals("a/b/c/d/e"));
320         }
321 
322 
323     public static String getSystemPathFromFileURL( String _sFileURL )
324     {
325         String sSystemFile = null;
326 
327         if(_sFileURL.startsWith("file:///"))
328         {
329             if (OSHelper.isWindows())
330             {
331                 sSystemFile = _sFileURL.substring(8);
332             }
333             else
334             {
335                 sSystemFile = _sFileURL.substring(7);
336             }
337         }
338         else if (_sFileURL.startsWith("file://"))
339         {
340             sSystemFile = _sFileURL.substring(5);
341         }
342         String fs = System.getProperty("file.separator");
343         if (! fs.equals("/"))
344         {
345             sSystemFile = sSystemFile.replace ('/', fs.toCharArray ()[0]);
346         }
347 // FEATURE FOR UNC NEED!!!
348         return sSystemFile;
349     }
350 
351     private static boolean m_bDebugTextShown = false;
352     public static boolean isDebugEnabled()
353         {
354             boolean bDebug = false;
355             String sTmpPath = util.utils.getUsersTempDir();
356             //util.utils.getUsersTempDir();
357             String fs = System.getProperty("file.separator");
358             String sName = sTmpPath + fs + "DOC_COMPARATOR_DEBUG";
359             File aFile = new File(sName);
360             if (aFile.exists())
361             {
362                 if (m_bDebugTextShown == false)
363                 {
364                     GlobalLogWriter.println("Found file: " + sName);
365                     GlobalLogWriter.println("Activate debug mode.");
366                     GlobalLogWriter.println("If debug mode is no longer necessary, remove the above file.");
367                     m_bDebugTextShown = true;
368                 }
369                 bDebug = true;
370             }
371             return bDebug;
372         }
373 
374     private static void copyStream(InputStream _aIn, OutputStream _aOut) throws java.io.IOException
375     {
376         byte[] aBuffer = new byte[0xFFFF];
377         for (int len; (len = _aIn.read(aBuffer)) != -1; )
378         {
379             _aOut.write(aBuffer, 0, len);
380         }
381     }
382 
383     public static void copy(String _sSource, String _sDestination)
384         {
385             FileInputStream aFIS = null;
386             FileOutputStream aFOS = null;
387 
388             try
389             {
390                 aFIS = new FileInputStream(_sSource);
391                 aFOS = new FileOutputStream(_sDestination);
392                 copyStream(aFIS, aFOS);
393             }
394             catch (java.io.IOException e)
395             {
396                 System.out.println("Error: caught Exception: " + e.getMessage());
397             }
398             finally
399             {
400                 if (aFIS != null)
401                 {
402                     try
403                     {
404                         aFIS.close();
405                     }
406                     catch (java.io.IOException e)
407                     {
408                         System.out.println("Error: caught Exception: " + e.getMessage());
409                     }
410                 }
411                 if (aFOS != null)
412                 {
413                     try
414                     {
415                         aFOS.close();
416                     }
417                     catch (java.io.IOException e)
418                     {
419                         System.out.println("Error: caught Exception: " + e.getMessage());
420                     }
421                 }
422             }
423 
424 //            try
425 //            {
426 //                File inputFile = new File(_sSource);
427 //                File outputFile = new File(_sDestination);
428 //
429 //                java.io.FileReader in = new java.io.FileReader(inputFile);
430 //                java.io.FileWriter out = new java.io.FileWriter(outputFile);
431 //                int c;
432 //
433 //                while ((c = in.read()) != -1)
434 //                {
435 //                    out.write(c);
436 //                }
437 //
438 //                in.close();
439 //                out.close();
440 //            }
441 //            catch (java.io.IOException e)
442 //            {
443 //                GlobalLogWriter.get().println("Exception caught. FileHelper.copy('" + _sSource + ", " + _sDestination + "')");
444 //                GlobalLogWriter.get().println("Message: " + e.getMessage());
445 //            }
446         }
447 
448 
449     /**
450      * Within the directory run through, it's possible to say which file extension types should not
451      * consider like '*.prn' because it's not a document.
452      *
453      * @return a FileFilter function
454      */
455     public static FileFilter getFileFilter()
456         {
457             FileFilter aFileFilter = new FileFilter()
458                 {
459                     public boolean accept( File pathname )
460                         {
461                             // leave out files which started by '~$' these are Microsoft Office temp files
462                             if (pathname.getName().startsWith("~$"))
463                             {
464                                 return false;
465                             }
466                             // leave out files starts with '.~lock.' these are OpenOffice.org lock files
467                             if (pathname.getName().startsWith(".~lock."))
468                             {
469                                 return false;
470                             }
471                             // leave out files ends with '#' these could be temp files
472                             if (pathname.getName().endsWith("#"))
473                             {
474                                 return false;
475                             }
476                             if (pathname.getName().endsWith(".prn"))
477                             {
478                                 return false;
479                             }
480                             if (pathname.getName().endsWith(".ps"))
481                             {
482                                 return false;
483                             }
484                             // This type of document no one would like to load.
485                             if (pathname.getName().endsWith(".zip"))
486                             {
487                                 return false;
488                             }
489                             // just a hack
490                             if (pathname.getName().endsWith("_"))
491                             {
492                                 return false;
493                             }
494                             return true;
495                         }
496                 };
497             return aFileFilter;
498         }
499     /**
500      * Within the directory run through, it's possible to say which file extension types should not
501      * consider like '*.prn' because it's not a document.
502      *
503      * @return a FileFilter function
504      */
505     public static FileFilter getFileFilterPSorPDF()
506         {
507             FileFilter aFileFilter = new FileFilter()
508                 {
509                     public boolean accept( File pathname )
510                         {
511                             if (pathname.getName().endsWith(".ps"))
512                             {
513                                 return true;
514                             }
515                             if (pathname.getName().endsWith(".pdf"))
516                             {
517                                 return true;
518                             }
519                             return false;
520                         }
521                 };
522             return aFileFilter;
523         }
524     /**
525      * Within the directory run through, it's possible to say which file extension types should not
526      * consider like '*.prn' because it's not a document.
527      *
528      * @return a FileFilter function
529      */
530     public static FileFilter getFileFilterJPEG()
531         {
532             FileFilter aFileFilter = new FileFilter()
533                 {
534                     public boolean accept( File pathname )
535                         {
536                             if (pathname.getName().toLowerCase().endsWith(".jpg"))
537                             {
538                                 return true;
539                             }
540                             if (pathname.getName().toLowerCase().endsWith(".jpeg"))
541                             {
542                                 return true;
543                             }
544                             return false;
545                         }
546                 };
547             return aFileFilter;
548         }
549     /**
550      * Within the directory run through, it's possible to say which file extension types should not
551      * consider like '*.ini' because it's not a document.
552      *
553      * @return a FileFilter function
554      */
555     public static FileFilter getFileFilterINI()
556         {
557             FileFilter aFileFilter = new FileFilter()
558                 {
559                     public boolean accept( File pathname )
560                         {
561                             String sPathname = pathname.getName().toLowerCase();
562                             if (sPathname.endsWith("index.ini"))
563                             {
564                                 // don't consider the index.ini file
565                                 return false;
566                             }
567                             if (sPathname.endsWith(".ini"))
568                             {
569                                 return true;
570                             }
571                             return false;
572                         }
573                 };
574             return aFileFilter;
575         }
576 
577         public static String appendPath(String _sPath, String _sRelativePathToAdd)
578         {
579             String sNewPath = _sPath;
580             String fs = System.getProperty("file.separator");
581             if (_sPath.startsWith("file:"))
582             {
583                 fs = "/";                                  // we use a file URL so only '/' is allowed.
584             }
585             if (! (sNewPath.endsWith("/") || sNewPath.endsWith("\\") ) )
586             {
587                 sNewPath += fs;
588             }
589             sNewPath += _sRelativePathToAdd;
590             return sNewPath;
591         }
592 
593     // -----------------------------------------------------------------------------
594     public static void createInfoFile(String _sFile, ParameterHelper _aGTA)
595         {
596             createInfoFile(_sFile, _aGTA, "");
597         }
598 
599     public static void createInfoFile(String _sFile, ParameterHelper _aGTA, String _sSpecial)
600         {
601             String sFilename;
602             if (_sFile.startsWith("file://"))
603             {
604                 sFilename = FileHelper.getSystemPathFromFileURL(_sFile);
605                 GlobalLogWriter.println("CreateInfoFile: '" + sFilename + "'" );
606             }
607             else
608             {
609                 sFilename = _sFile;
610             }
611             String sFileDir = FileHelper.getPath(sFilename);
612             String sBasename = FileHelper.getBasename(sFilename);
613             String sNameNoSuffix = FileHelper.getNameNoSuffix(sBasename);
614 
615             String sIniFile = FileHelper.appendPath(sFileDir, sBasename + ".ini");
616             IniFile aIniFile = new IniFile(sIniFile);
617 
618             // OLD INFO FILE
619 
620             // String fs = System.getProperty("file.separator");
621             String ls = System.getProperty("line.separator");
622             String sInfoFilename = FileHelper.appendPath(sFileDir, sNameNoSuffix + ".info");
623             File aInfoFile = new File(sInfoFilename);
624 
625             String sBuildID = "";
626 
627             try
628             {
629                 FileOutputStream out2 = new FileOutputStream(aInfoFile.toString());
630                 PrintStream out = new PrintStream(out2);
631 
632                 out.println("# automatically created file by graphical compare");
633                 if (_aGTA != null)
634                 {
635                     if (_sSpecial != null && _sSpecial.equals("msoffice"))
636                     {
637                         out.println("# buildid from wordloadfile");
638                         sBuildID = _aGTA.getPerformance().getMSOfficeVersion();
639                         out.println("buildid=" + sBuildID);
640                     }
641                     else
642                     {
643                         out.println("# buildid is read out of the bootstrap file");
644                         sBuildID = _aGTA.getBuildID();
645                         out.println("buildid=" + sBuildID);
646                     }
647                     aIniFile.insertValue("global", "buildid", sBuildID);
648 
649                     // if (_sSpecial != null && _sSpecial.length() > 0)
650                     // {
651                     //    out.write("special=" + _sSpecial + ls);
652                     // }
653                     out.println();
654                     out.println("# resolution given in DPI");
655                     out.println("resolution=" + _aGTA.getResolutionInDPI());
656                     aIniFile.insertValue("global", "resolution", _aGTA.getResolutionInDPI());
657                 }
658                 else
659                 {
660                     out.println("buildid=" + _sSpecial);
661                     aIniFile.insertValue("global", "buildid", _sSpecial);
662                 }
663 
664                 // long nTime = stopTimer();
665                 // if (nTime != 0)
666                 // {
667                 //     out.write("# time is given in milli seconds" + ls);
668                 //     out.write("time=" + nTime + ls);
669                 // }
670 
671                 out.println();
672                 out.println("# Values out of System.getProperty(...)");
673                 out.println("os.name=" + System.getProperty("os.name"));
674                 out.println("os.arch=" + System.getProperty("os.arch"));
675                 out.println("os.version=" + System.getProperty("os.version"));
676 
677                 aIniFile.insertValue("global", "os.name", System.getProperty("os.name"));
678                 aIniFile.insertValue("global", "os.arch", System.getProperty("os.arch"));
679                 aIniFile.insertValue("global", "os.version", System.getProperty("os.version"));
680 
681                 if (_aGTA != null)
682                 {
683                     out.println();
684                     out.println("# Performance output, values are given in milli sec.");
685                     _aGTA.getPerformance().print(out);
686                     _aGTA.getPerformance().print(aIniFile, "global");
687                 }
688 
689                 out.flush();
690                 out.close();
691                 out2.close();
692             }
693             catch (java.io.IOException e)
694             {
695                 GlobalLogWriter.println("can't create Info file.");
696                 e.printStackTrace();
697             }
698             aIniFile.close();
699 
700 //            String sExtension = FileHelper.getSuffix(_aGTA.getInputFile());
701 //            if (sExtension.startsWith("."))
702 //            {
703 //                sExtension = sExtension.substring(1);
704 //            }
705 //
706 //            DB.writeToDB(_aGTA.getInputFile(),
707 //                         sNameNoSuffix,
708 //                         sExtension,
709 //                         sBuildID,
710 //                         _aGTA.getReferenceType(),
711 //                         _aGTA.getResolutionInDPI()
712 //                         );
713         }
714 
715         public static void addBasenameToFile(String _sIndexFilename, String _sBasename, String _sCreator, String _sType, String _sSource)
716         {
717             // String sOutputDir = FileHelper.getPath(_sOutputFilename);
718             String sPath;
719             if (_sIndexFilename.startsWith("file:"))
720             {
721                 sPath = FileHelper.getSystemPathFromFileURL(_sIndexFilename);
722             }
723             else
724             {
725                 sPath = _sIndexFilename;
726             }
727             String sIndexFilename = sPath; // FileHelper.appendPath(sPath, _sFilename);
728             IniFile aIniFile = new IniFile(sIndexFilename);
729             aIniFile.insertValue(_sBasename, "creator", _sCreator);
730             aIniFile.insertValue(_sBasename, "type", _sType);
731             aIniFile.insertValue(_sBasename, "source", _sSource);
732             aIniFile.close();
733 //            File aFile = new File(sIndexFilename);
734 //            try
735 //            {
736 //                RandomAccessFile aRandomAccess = new RandomAccessFile(aFile, "rw");
737 //                // String sBasename = FileHelper.getBasename(_sOutputFilename);
738 //                aRandomAccess.seek(aRandomAccess.length()); // jump to the end.
739 //// TODO: seems to be wrong, there exist no writeLine() with 'return' ending?
740 //                aRandomAccess.writeUTF(_sBasename);
741 //                aRandomAccess.close();
742 //            }
743 //            catch (java.io.FileNotFoundException e)
744 //            {
745 //            }
746 //            catch (java.io.IOException e)
747 //            {
748 //            }
749         }
750 
751         public static void addBasenameToPostscript(String _sOutputFilename)
752         {
753             String sIndexFilename = FileHelper.appendPath(_sOutputFilename, "postscript.ini");
754             // String sPath = FileHelper.getPath(sIndexFilename);
755             String sBasename = FileHelper.getBasename(_sOutputFilename);
756             addBasenameToFile(sIndexFilename, sBasename, "", "", "");
757         }
758         public static void addBasenameToIndex(String _sOutputFilename, String _sBasename, String _sCreator, String _sType, String _sSource)
759         {
760             String sIndexFilename = FileHelper.appendPath(_sOutputFilename, "index.ini");
761             // String sPath = FileHelper.getPath(sIndexFilename);
762             // String sBasename = FileHelper.getBasename(_sOutputFilename);
763             addBasenameToFile(sIndexFilename, _sBasename, _sCreator, _sType, _sSource);
764         }
765 
766 }
767 
768