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 convwatch;
29 
30 import java.io.File;
31 import java.io.FileFilter;
32 import java.util.StringTokenizer;
33 import helper.OSHelper;
34 
35 import javax.swing.JOptionPane;
36 
37 public class FileHelper
38 {
39     public FileHelper()
40         {
41             // fs = System.getProperty("file.separator");
42 
43 
44             String sOSName = System.getProperty("os.name");
45             String sOSArch = System.getProperty("os.arch");
46             String sOSVersion = System.getProperty("os.version");
47 
48             GlobalLogWriter.get().println(sOSName);
49             GlobalLogWriter.get().println(sOSArch);
50             GlobalLogWriter.get().println(sOSVersion);
51 
52         }
53 
54     public static void MessageBox(String _sStr)
55         {
56             String sVersion = System.getProperty("java.version");
57             String sOSName  = System.getProperty("os.name");
58             JOptionPane.showMessageDialog( null, _sStr, sVersion + " " + sOSName + " Hello World Debugger", JOptionPane.INFORMATION_MESSAGE );
59         }
60 
61     public static boolean exists(String _sFile)
62         {
63             if (_sFile == null) return false;
64 
65             File aFile = new File(_sFile);
66             if (aFile.exists())
67             {
68                 return true;
69             }
70             // This is just nice for DEBUG behaviour
71             // due to the fact this is absolutly context dependency no one should use it.
72             // else
73             // {
74             //     System.out.println("FileHelper:exists() tell this path doesn't exists. Check it. path is:" );
75             //     System.out.println( _sFile );
76             //     System.out.println( aFile.getAbsolutePath() );
77             //     MessageBox("Der JavaProzess wartet auf eine interaktion ihrerseits.");
78             //
79             //     File aFile2 = new File(_sFile);
80             //     if (aFile2.exists())
81             //     {
82             //         System.out.println("Thanks, file exists." );
83             //         return true;
84             //     }
85             // }
86             return false;
87         }
88 
89     public static boolean isDir(String _sDir)
90         {
91             if (_sDir == null) return false;
92             try
93             {
94                 File aFile = new File(_sDir);
95                 if (aFile.exists() && aFile.isDirectory())
96                 {
97                     return true;
98                 }
99             }
100             catch (NullPointerException e)
101             {
102                 GlobalLogWriter.get().println("Exception caught. FileHelper.isDir('" + _sDir + "')");
103                 e.printStackTrace();
104             }
105             return false;
106         }
107 
108     public static String getBasename(String _sFilename)
109         {
110             if (_sFilename == null) return "";
111             String fs = System.getProperty("file.separator");
112 
113             int nIdx = _sFilename.lastIndexOf(fs);
114             if (nIdx > 0)
115             {
116                 return _sFilename.substring(nIdx + 1);
117             }
118             return _sFilename;
119         }
120 
121     public static String getNameNoSuffix(String _sFilename)
122         {
123             if (_sFilename == null) return "";
124             int nIdx = _sFilename.lastIndexOf(".");
125             if (nIdx > 0)
126             {
127                 return _sFilename.substring(0, nIdx);
128             }
129             return _sFilename;
130         }
131 
132     public static String getSuffix(String _sFilename)
133         {
134             if (_sFilename == null) return "";
135             int nIdx = _sFilename.lastIndexOf(".");
136             if (nIdx > 0)
137             {
138                 return _sFilename.substring(nIdx );
139             }
140             return "";
141         }
142 
143     public static String getPath(String _sFilename)
144         {
145             if (_sFilename == null) return "";
146             String fs = System.getProperty("file.separator");
147 
148             int nIdx = _sFilename.lastIndexOf(fs);
149             if (nIdx > 0)
150             {
151                 return _sFilename.substring(0, nIdx);
152             }
153             return "";
154         }
155 
156 /*
157     static ArrayList files = new ArrayList();
158     public static Object[] traverse( String afileDirectory )
159         {
160 
161             File fileDirectory = new File(afileDirectory);
162             // Testing, if the file is a directory, and if so, it throws an exception
163             if ( !fileDirectory.isDirectory() )
164             {
165                 throw new IllegalArgumentException( "not a directory: " + fileDirectory.getName() );
166             }
167 
168             // Getting all files and directories in the current directory
169             File[] entries = fileDirectory.listFiles();
170 
171             // Iterating for each file and directory
172             for ( int i = 0; i < entries.length; ++i )
173             {
174                 // adding file to List
175                 try
176                 {
177                     // Composing the URL by replacing all backslashs
178                     String stringUrl = "file:///"
179                         + entries[ i ].getAbsolutePath().replace( '\\', '/' );
180                     files.add(stringUrl);
181                 }
182                 catch( Exception exception )
183                 {
184                     exception.printStackTrace();
185                 }
186             }
187             return files.toArray();
188         }
189 */
190 
191     // makeDirectories("", "/tmp/a/b");
192     // creates all directories /tmp/a/b
193     //
194     public static void makeDirectories(String first, String path)
195         {
196             makeDirectories(first, path, "0777");
197         }
198 
199     public static void makeDirectories(String first, String path, String _sMode)
200         {
201             String fs = System.getProperty("file.separator");
202             if (path.startsWith(fs + fs)) // starts with UNC Path
203             {
204                 int n = path.indexOf(fs, 2);
205                 n = path.indexOf(fs, n + 1);
206                 first = path.substring(0, n);
207                 path = path.substring(n + 1);
208             }
209 
210             String already_done = null;
211             StringTokenizer path_tokenizer = new StringTokenizer(path,fs,false);
212             already_done = first;
213             while (path_tokenizer.hasMoreTokens())
214             {
215                 String part = path_tokenizer.nextToken();
216                 File new_dir = new File(already_done + File.separatorChar + part);
217                 already_done = new_dir.toString();
218                 // System.out.println(already_done);
219                 //create the directory
220                 new_dir.mkdirs();
221                 if (OSHelper.isUnix() &&
222                     _sMode.length() > 0)
223                 {
224                     try
225                     {
226                         chmod(new_dir, _sMode);
227                     }
228                     catch (java.io.IOException e)
229                     {
230                         GlobalLogWriter.get().println("Exception caught. FileHelper.makeDirectories('" + new_dir.getAbsolutePath() + "')");
231                     }
232                 }
233             }
234             // return;
235         }
236 
237     public static void chmod(File file, String mode) throws java.io.IOException
238         {
239             Runtime.getRuntime().exec
240                 (new String[]
241                     {"chmod", mode, file.getAbsolutePath()});
242         }
243 
244     public static String removeFirstDirectorysAndBasenameFrom(String _sName, String _sRemovePath)
245         {
246             // pre: _sName: /a/b/c/d/e/f.g _sRemovePath /a/b/c
247             // result: d/e
248             String fs = System.getProperty("file.separator");
249 
250             String sBasename = FileHelper.getBasename(_sName);
251             String sSubDirs = "";
252             if (_sName.startsWith(_sRemovePath))
253             {
254                 // if _sName starts with _sRemovePath
255                 int nRemovePathIndex = _sRemovePath.length();
256                 if (! _sRemovePath.endsWith(fs))
257                 {
258                     // add 1 if we not ends with file separator
259                     nRemovePathIndex ++;
260                 }
261                 int nBasenameIndex = _sName.length() - sBasename.length() - 1;
262                 if (nRemovePathIndex < nBasenameIndex)
263                 {
264                     sSubDirs = _sName.substring(nRemovePathIndex, nBasenameIndex);
265                 }
266             }
267             else
268             {
269                 // special case, the _sRemovePath is not part of _sName
270                 sSubDirs = FileHelper.getPath(_sName);
271                 if (sSubDirs.startsWith(fs))
272                 {
273                     // remove leading file separator
274                     sSubDirs = sSubDirs.substring(1);
275                 }
276             }
277 
278             return sSubDirs;
279         }
280 
281     public static void test_removeFirstDirectorysAndBasenameFrom()
282         {
283             String a = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/a/b/c");
284             // assure("", a.equals("d/e"));
285             String b = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/a/b/c/");
286             // assure("", b.equals("d/e"));
287             String c = removeFirstDirectorysAndBasenameFrom("/a/b/c/d/e/f.g", "/b/c");
288             // assure("", c.equals("a/b/c/d/e"));
289         }
290 
291 
292     public static String getSystemPathFromFileURL( String _sFileURL )
293     {
294         String sSystemFile = null;
295 
296         if(_sFileURL.startsWith("file:///"))
297         {
298             if (OSHelper.isWindows())
299             {
300                 sSystemFile = _sFileURL.substring(8);
301             }
302             else
303             {
304                 sSystemFile = _sFileURL.substring(7);
305             }
306         }
307         else if (_sFileURL.startsWith("file://"))
308         {
309             sSystemFile = _sFileURL.substring(5);
310         }
311         String fs = System.getProperty("file.separator");
312         if (! fs.equals("/"))
313         {
314             sSystemFile = sSystemFile.replace ('/', fs.toCharArray ()[0]);
315         }
316 // FEATURE FOR UNC NEED!!!
317         return sSystemFile;
318     }
319 
320     private static boolean m_bDebugTextShown = false;
321     public static boolean isDebugEnabled()
322         {
323             boolean bDebug = false;
324             String sTmpPath = util.utils.getUsersTempDir();
325             //util.utils.getUsersTempDir();
326             String fs = System.getProperty("file.separator");
327             String sName = sTmpPath + fs + "DOC_COMPARATOR_DEBUG";
328             File aFile = new File(sName);
329             if (aFile.exists())
330             {
331                 if (m_bDebugTextShown == false)
332                 {
333                     GlobalLogWriter.get().println("Found file: " + sName);
334                     GlobalLogWriter.get().println("Activate debug mode.");
335                     GlobalLogWriter.get().println("If debug mode is no longer necessary, remove the above file.");
336                     m_bDebugTextShown = true;
337                 }
338                 bDebug = true;
339             }
340             return bDebug;
341         }
342 
343     public static void copy(String _sSource, String _sDestination)
344         {
345             try
346             {
347                 File inputFile = new File(_sSource);
348                 File outputFile = new File(_sDestination);
349 
350                 java.io.FileReader in = new java.io.FileReader(inputFile);
351                 java.io.FileWriter out = new java.io.FileWriter(outputFile);
352                 int c;
353 
354                 while ((c = in.read()) != -1)
355                     out.write(c);
356 
357                 in.close();
358                 out.close();
359             }
360             catch (java.io.IOException e)
361             {
362                 GlobalLogWriter.get().println("Exception caught. FileHelper.copy('" + _sSource + ", " + _sDestination + "')");
363                 GlobalLogWriter.get().println("Message: " + e.getMessage());
364             }
365         }
366 
367     /**
368      * Within the directory run through, it's possible to say which file extension types should not
369      * consider like '*.prn' because it's not a document.
370      *
371      * @return a FileFilter function
372      */
373     public static FileFilter getFileFilter()
374         {
375             FileFilter aFileFilter = new FileFilter()
376                 {
377                     public boolean accept( File pathname )
378                         {
379                             // leave out files which started by '~$' these are Microsoft Office temp files
380                             if (pathname.getName().startsWith("~$"))
381                             {
382                                 return false;
383                             }
384 
385                             if (pathname.getName().endsWith(".prn"))
386                             {
387                                 return false;
388                             }
389                             // This type of document no one would like to load.
390                             if (pathname.getName().endsWith(".zip"))
391                             {
392                                 return false;
393                             }
394                             // just a hack
395                             if (pathname.getName().endsWith("_"))
396                             {
397                                 return false;
398                             }
399                             return true;
400                         }
401                 };
402             return aFileFilter;
403         }
404 }
405 
406