1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 package com.sun.star.wizards.common;
24 
25 // import com.sun.star.wizards.common.NoValidPathException;
26 import java.io.File;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Vector;
30 
31 import com.sun.star.awt.VclWindowPeerAttribute;
32 import com.sun.star.beans.PropertyValue;
33 import com.sun.star.beans.XPropertySet;
34 import com.sun.star.document.XDocumentProperties;
35 import com.sun.star.io.XActiveDataSink;
36 import com.sun.star.io.XInputStream;
37 // import com.sun.star.io.XStream;
38 import com.sun.star.io.XTextInputStream;
39 import com.sun.star.lang.Locale;
40 import com.sun.star.lang.XMultiServiceFactory;
41 import com.sun.star.ucb.CommandAbortedException;
42 import com.sun.star.ucb.XFileIdentifierConverter;
43 import com.sun.star.ucb.XSimpleFileAccess;
44 import com.sun.star.ucb.XSimpleFileAccess2;
45 import com.sun.star.uno.Exception;
46 import com.sun.star.uno.UnoRuntime;
47 import com.sun.star.uno.XInterface;
48 import com.sun.star.util.DateTime;
49 import com.sun.star.util.XMacroExpander;
50 import com.sun.star.wizards.ui.UIConsts;
51 
52 /**
53  * This class delivers static convenience methods
54  * to use with ucb SimpleFileAccess service.
55  * You can also instanciate the class, to encapsulate
56  * some functionality of SimpleFileAccess. The instance
57  * keeps a reference to an XSimpleFileAccess and an
58  * XFileIdentifierConverter, saves the permanent
59  * overhead of quering for those interfaces, and delivers
60  * conveneince methods for using them.
61  * These Convenince methods include mainly Exception-handling.
62  */
63 public class FileAccess
64 {
65 
66     /**
67      *
68      * @param xMSF
69      * @param sPath
70      * @param sAddPath
71      */
addOfficePath(XMultiServiceFactory xMSF, String sPath, String sAddPath)72     public static void addOfficePath(XMultiServiceFactory xMSF, String sPath, String sAddPath)
73     {
74         XSimpleFileAccess xSimpleFileAccess = null;
75         String ResultPath = getOfficePath(xMSF, sPath, xSimpleFileAccess);
76         // As there are several conventions about the look of Url  (e.g. with " " or with "%20") you cannot make a
77         // simple String comparison to find out, if a path is already in "ResultPath"
78         String[] PathList = JavaTools.ArrayoutofString(ResultPath, PropertyNames.SEMI_COLON);
79         int MaxIndex = PathList.length - 1;
80         String CompCurPath;
81         //  sAddPath.replace(null, (char) 47);
82         String CompAddPath = JavaTools.replaceSubString(sAddPath, PropertyNames.EMPTY_STRING, "/");
83         String CurPath;
84         for (int i = 0; i <= MaxIndex; i++)
85         {
86             CurPath = JavaTools.convertfromURLNotation(PathList[i]);
87             CompCurPath = JavaTools.replaceSubString(CurPath, PropertyNames.EMPTY_STRING, "/");
88             if (CompCurPath.equals(CompAddPath))
89             {
90                 return;
91             }
92         }
93         ResultPath += PropertyNames.SEMI_COLON + sAddPath;
94         }
95 
deleteLastSlashfromUrl(String _sPath)96     public static String deleteLastSlashfromUrl(String _sPath)
97     {
98         if (_sPath.endsWith("/"))
99         {
100             return _sPath.substring(0, _sPath.length() - 1);
101         }
102         else
103         {
104             return _sPath;
105         }
106     }
107 
108     /**
109      * Further information on arguments value see in OO Developer Guide,
110      * chapter 6.2.7
111      * @param xMSF
112      * @param sPath
113      * @param xSimpleFileAccess
114      * @return the respective path of the office application. A probable following "/" at the end is trimmed.
115      */
getOfficePath(XMultiServiceFactory xMSF, String sPath, XSimpleFileAccess xSimpleFileAccess)116     public static String getOfficePath(XMultiServiceFactory xMSF, String sPath, XSimpleFileAccess xSimpleFileAccess)
117     {
118         try
119         {
120             String ResultPath = PropertyNames.EMPTY_STRING;
121             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.util.PathSettings");
122             ResultPath = com.sun.star.uno.AnyConverter.toString(Helper.getUnoPropertyValue(xInterface, sPath));
123             ResultPath = deleteLastSlashfromUrl(ResultPath);
124             return ResultPath;
125         }
126         catch (Exception exception)
127         {
128             exception.printStackTrace(System.out);
129             return PropertyNames.EMPTY_STRING;
130         }
131     }
132 
133     /**
134      * Further information on arguments value see in OO Developer Guide,
135      * chapter 6.2.7
136      * @param xMSF
137      * @param sPath
138      * @param sType use "share" or "user". Set to PropertyNames.EMPTY_STRING if not needed eg for the WorkPath;
139      * In the return Officepath a possible slash at the end is cut off
140      * @param sSearchDir
141      * @return
142      * @throws NoValidPathException
143      */
getOfficePath(XMultiServiceFactory xMSF, String sPath, String sType, String sSearchDir)144     public static String getOfficePath(XMultiServiceFactory xMSF, String sPath, String sType, String sSearchDir) throws NoValidPathException
145     {
146         //This method currently only works with sPath="Template"
147 
148         String ResultPath = PropertyNames.EMPTY_STRING;
149 
150         String Template_writable = PropertyNames.EMPTY_STRING;
151         String[] Template_internal;
152         String[] Template_user;
153 
154         boolean bexists = false;
155         try
156         {
157             XInterface xPathInterface = (XInterface) xMSF.createInstance("com.sun.star.util.PathSettings");
158             XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xPathInterface);
159             String WritePath = PropertyNames.EMPTY_STRING;
160             String[] ReadPaths = null;
161             XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
162             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
163 
164             Template_writable = (String) xPropertySet.getPropertyValue(sPath + "_writable");
165             Template_internal = (String[]) xPropertySet.getPropertyValue(sPath + "_internal");
166             Template_user = (String[]) xPropertySet.getPropertyValue(sPath + "_user");
167             int iNumEntries = Template_user.length + Template_internal.length + 1;
168             ReadPaths = new String[iNumEntries];
169             int t = 0;
170             for (int i = 0; i < Template_internal.length; i++)
171             {
172                 ReadPaths[t] = Template_internal[i];
173                 t++;
174             }
175             for (int i = 0; i < Template_user.length; i++)
176             {
177                 ReadPaths[t] = Template_user[i];
178                 t++;
179             }
180             ReadPaths[t] = Template_writable;
181             WritePath = Template_writable;
182 
183             if (sType.equalsIgnoreCase("user"))
184             {
185                 ResultPath = WritePath;
186                 bexists = true;
187             }
188             else
189             {
190                 //find right path using the search sub path
191                 for (int i = 0; i < ReadPaths.length; i++)
192                 {
193                     String tmpPath = ReadPaths[i] + sSearchDir;
194                     if (xSimpleFileAccess.exists(tmpPath))
195                     {
196                         ResultPath = ReadPaths[i];
197                         bexists = true;
198                         break;
199                     }
200                 }
201             }
202             ResultPath = deleteLastSlashfromUrl(ResultPath);
203         }
204         catch (Exception exception)
205         {
206             exception.printStackTrace(System.out);
207             ResultPath = PropertyNames.EMPTY_STRING;
208         }
209         if (!bexists)
210         {
211             throw new NoValidPathException(xMSF, PropertyNames.EMPTY_STRING);
212         }
213         return ResultPath;
214     }
215 
getOfficePaths(XMultiServiceFactory xMSF, String _sPath, String sType, String sSearchDir)216     public static ArrayList<String> getOfficePaths(XMultiServiceFactory xMSF, String _sPath, String sType, String sSearchDir) throws NoValidPathException
217     {
218         //This method currently only works with sPath="Template"
219 
220         // String ResultPath = PropertyNames.EMPTY_STRING;
221         ArrayList<String> aPathList = new ArrayList<String>();
222         String Template_writable = PropertyNames.EMPTY_STRING;
223         String[] Template_internal;
224         String[] Template_user;
225 
226         // String [] ReadPaths = null;
227 
228         // boolean bexists = false;
229         try
230         {
231             XInterface xPathInterface = (XInterface) xMSF.createInstance("com.sun.star.util.PathSettings");
232             XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xPathInterface);
233             // String WritePath = PropertyNames.EMPTY_STRING;
234             // XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
235             // XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) com.sun.star.uno.UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
236 
237             Template_writable = (String) xPropertySet.getPropertyValue(_sPath + "_writable");
238             Template_internal = (String[]) xPropertySet.getPropertyValue(_sPath + "_internal");
239             Template_user = (String[]) xPropertySet.getPropertyValue(_sPath + "_user");
240 
241             // int iNumEntries = Template_user.length + Template_internal.length + 1;
242             for (int i = 0; i < Template_internal.length; i++)
243             {
244                 String sPath = Template_internal[i];
245                 if (sPath.startsWith("vnd."))
246                 {
247                     String sPathToExpand = sPath.substring("vnd.sun.star.Expand:".length());
248 
249                     XMacroExpander xExpander = Helper.getMacroExpander(xMSF);
250                     sPath = xExpander.expandMacros(sPathToExpand);
251                 }
252 
253                 // if there exists a language in the directory, we try to add the right language
254                 sPath = checkIfLanguagePathExists(xMSF, sPath);
255 
256                 aPathList.add(sPath);
257             }
258             aPathList.addAll(Arrays.asList(Template_user));
259             aPathList.add(Template_writable);
260         // WritePath = Template_writable;
261 
262 //            if (sType.equalsIgnoreCase("user"))
263 //            {
264 //                ResultPath = WritePath;
265 //                bexists = true;
266 //            }
267 
268         // There was a bug here, because we have to search through the whole list of paths
269 //            else
270 //            {
271 //                //find right path using the search sub path
272 //                for (int i = 0; i<ReadPaths.length; i++)
273 //                {
274 //                    String tmpPath = ReadPaths[i]+sSearchDir;
275 //                    if (xSimpleFileAccess.exists(tmpPath))
276 //                    {
277 //                        ResultPath = ReadPaths[i];
278 //                        bexists = true;
279 //                        break;
280 //                    }
281 //                }
282 //            }
283 //            ResultPath = deleteLastSlashfromUrl(ResultPath);
284         }
285         catch (Exception exception)
286         {
287             exception.printStackTrace(System.out);
288         // ResultPath = PropertyNames.EMPTY_STRING;
289         }
290 //        if (bexists == false)
291 //        {
292 //            throw new NoValidPathException(xMSF, PropertyNames.EMPTY_STRING);
293 //        }
294 //        return ResultPath;
295         return aPathList;
296     }
297 
checkIfLanguagePathExists(XMultiServiceFactory _xMSF, String _sPath)298     private static String checkIfLanguagePathExists(XMultiServiceFactory _xMSF, String _sPath)
299     {
300         try
301         {
302             Object defaults = _xMSF.createInstance("com.sun.star.text.Defaults");
303             Locale aLocale = (Locale) Helper.getUnoStructValue(defaults, "CharLocale");
304             if (aLocale == null)
305             {
306                 java.util.Locale.getDefault();
307                 aLocale = new com.sun.star.lang.Locale();
308                 aLocale.Country = java.util.Locale.getDefault().getCountry();
309                 aLocale.Language = java.util.Locale.getDefault().getLanguage();
310                 aLocale.Variant = java.util.Locale.getDefault().getVariant();
311             }
312 
313             String sLanguage = aLocale.Language;
314             String sCountry = aLocale.Country;
315             String sVariant = aLocale.Variant;
316 
317             // de-DE-Bayrisch
318             StringBuffer aLocaleAll = new StringBuffer();
319             aLocaleAll.append(sLanguage).append('-').append(sCountry).append('-').append(sVariant);
320             String sPath = _sPath + "/" + aLocaleAll.toString();
321 
322             XInterface xInterface = (XInterface) _xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
323             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
324             if (xSimpleFileAccess.exists(sPath))
325             {
326                 return sPath;
327             }
328 
329             // de-DE
330             StringBuffer aLocaleLang_Country = new StringBuffer();
331             aLocaleLang_Country.append(sLanguage).append('-').append(sCountry);
332             sPath = _sPath + "/" + aLocaleLang_Country.toString();
333 
334             if (xSimpleFileAccess.exists(sPath))
335             {
336                 return sPath;
337             }
338 
339             // de
340             StringBuffer aLocaleLang = new StringBuffer();
341             aLocaleLang.append(sLanguage);
342             sPath = _sPath + "/" + aLocaleLang.toString();
343 
344             if (xSimpleFileAccess.exists(sPath))
345             {
346                 return sPath;
347             }
348 
349             // the absolute default is en-US or en
350             sPath = _sPath + "/en-US";
351             if (xSimpleFileAccess.exists(sPath))
352             {
353                 return sPath;
354             }
355 
356             sPath = _sPath + "/en";
357             if (xSimpleFileAccess.exists(sPath))
358             {
359                 return sPath;
360             }
361 
362         // java.util.Locale jl = new java.util.Locale(
363         //        l.Language , l.Country, l.Variant );
364         }
365         catch (com.sun.star.uno.Exception e)
366         {
367         }
368 
369         return _sPath;
370     }
371 
372     /*
373     public static String getOfficePath(XMultiServiceFactory xMSF, String sPath, String sType) throws NoValidPathException {
374     String ResultPath = PropertyNames.EMPTY_STRING;
375     Object oPathSettings;
376     int iPathCount;
377     String[] PathList;
378     boolean bexists = false;
379     try {
380     XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
381     XSimpleFileAccess xSimpleFileAccess = (XSimpleFileAccess) com.sun.star.uno.UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
382     ResultPath = getOfficePath(xMSF, sPath, xSimpleFileAccess);
383     PathList = JavaTools.ArrayoutofString(ResultPath, PropertyNames.SEMI_COLON);
384     if (!sType.equals(PropertyNames.EMPTY_STRING)) {
385     ResultPath = PropertyNames.EMPTY_STRING;
386     String CurPath = PropertyNames.EMPTY_STRING;
387     String EndString = "/" + sType;
388     int EndLength = EndString.length();
389     sType = "/" + sType + "/";
390     int MaxIndex = PathList.length - 1;
391     int iPos;
392     for (int i = 0; i <= MaxIndex; i++) {
393     CurPath = PathList[i];
394     iPos = CurPath.length() - EndLength;
395     if ((CurPath.indexOf(sType) > 0) || (CurPath.indexOf(EndString) == iPos)) {
396     ResultPath = deleteLastSlashfromUrl(CurPath);
397     if (xSimpleFileAccess.exists(ResultPath))
398     break;
399     }
400     }
401     } else
402     ResultPath = PathList[0];
403     if (ResultPath.equals(PropertyNames.EMPTY_STRING) == false)
404     bexists = xSimpleFileAccess.exists(ResultPath);
405     } catch (Exception exception) {
406     exception.printStackTrace(System.out);
407     ResultPath = PropertyNames.EMPTY_STRING;
408     }
409     if (bexists == false)
410     throw new NoValidPathException(xMSF);
411     return ResultPath;
412     }
413      **/
combinePaths(XMultiServiceFactory xMSF, ArrayList _aFirstPath, String _sSecondPath)414     public static void combinePaths(XMultiServiceFactory xMSF, ArrayList _aFirstPath, String _sSecondPath) throws NoValidPathException
415     {
416         for (int i = 0; i < _aFirstPath.size(); ++i)
417         {
418             String sOnePath = (String) _aFirstPath.get(i);
419             sOnePath = addPath(sOnePath, _sSecondPath);
420             if (isPathValid(xMSF, sOnePath))
421             {
422                 _aFirstPath.add(i, sOnePath);
423                 _aFirstPath.remove(i + 1);
424             }
425             else
426             {
427                 _aFirstPath.remove(i);
428                 --i;
429             }
430         }
431     }
432 
isPathValid(XMultiServiceFactory xMSF, String _sPath)433     public static boolean isPathValid(XMultiServiceFactory xMSF, String _sPath)
434     {
435         boolean bExists = false;
436         try
437         {
438             XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
439             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
440             bExists = xSimpleFileAccess.exists(_sPath);
441         }
442         catch (Exception exception)
443         {
444             exception.printStackTrace(System.out);
445         }
446         return bExists;
447     }
448 
combinePaths(XMultiServiceFactory xMSF, String _sFirstPath, String _sSecondPath)449     public static String combinePaths(XMultiServiceFactory xMSF, String _sFirstPath, String _sSecondPath) throws NoValidPathException
450     {
451         boolean bexists = false;
452         String ReturnPath = PropertyNames.EMPTY_STRING;
453         try
454         {
455             XInterface xUcbInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
456             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xUcbInterface);
457             ReturnPath = _sFirstPath + _sSecondPath;
458             bexists = xSimpleFileAccess.exists(ReturnPath);
459         }
460         catch (Exception exception)
461         {
462             exception.printStackTrace(System.out);
463             return PropertyNames.EMPTY_STRING;
464         }
465         if (!bexists)
466         {
467             throw new NoValidPathException(xMSF, PropertyNames.EMPTY_STRING);
468         }
469         return ReturnPath;
470     }
471 
createSubDirectory(XMultiServiceFactory xMSF, XSimpleFileAccess xSimpleFileAccess, String Path)472     public static boolean createSubDirectory(XMultiServiceFactory xMSF, XSimpleFileAccess xSimpleFileAccess, String Path)
473     {
474         String sNoDirCreation = PropertyNames.EMPTY_STRING;
475         try
476         {
477             Resource oResource = new Resource(xMSF, "ImportWizard", "imp");
478             sNoDirCreation = oResource.getResText(UIConsts.RID_DB_COMMON + 50);
479             String sMsgDirNotThere = oResource.getResText(UIConsts.RID_DB_COMMON + 51);
480             String sQueryForNewCreation = oResource.getResText(UIConsts.RID_DB_COMMON + 52);
481             String OSPath = JavaTools.convertfromURLNotation(Path);
482             String sQueryMessage = JavaTools.replaceSubString(sMsgDirNotThere, OSPath, "%1");
483             sQueryMessage = sQueryMessage + (char) 13 + sQueryForNewCreation;
484             int icreate = SystemDialog.showMessageBox(xMSF, "QueryBox", VclWindowPeerAttribute.YES_NO, sQueryMessage);
485             if (icreate == 2)
486             {
487                 xSimpleFileAccess.createFolder(Path);
488                 return true;
489             }
490             return false;
491         }
492         catch (com.sun.star.ucb.CommandAbortedException exception)
493         {
494             String sMsgNoDir = JavaTools.replaceSubString(sNoDirCreation, Path, "%1");
495             SystemDialog.showMessageBox(xMSF, "ErrorBox", VclWindowPeerAttribute.OK, sMsgNoDir);
496             return false;
497         }
498         catch (com.sun.star.uno.Exception unoexception)
499         {
500             String sMsgNoDir = JavaTools.replaceSubString(sNoDirCreation, Path, "%1");
501             SystemDialog.showMessageBox(xMSF, "ErrorBox", VclWindowPeerAttribute.OK, sMsgNoDir);
502             return false;
503         }
504     }
505 
506     // checks if the root of a path exists. if the parameter xWindowPeer is not null then also the directory is
507     // created when it does not exists and the user
PathisValid(XMultiServiceFactory xMSF, String Path, String sMsgFilePathInvalid, boolean baskbeforeOverwrite)508     public static boolean PathisValid(XMultiServiceFactory xMSF, String Path, String sMsgFilePathInvalid, boolean baskbeforeOverwrite)
509     {
510         try
511         {
512             String SubDir;
513             String SubDirPath = PropertyNames.EMPTY_STRING;
514             int SubLen;
515             int NewLen;
516             int RestLen;
517             boolean bexists;
518             boolean bSubDirexists = true;
519             String LowerCasePath;
520             String NewPath = Path;
521             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
522             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
523             if (baskbeforeOverwrite)
524             {
525                 if (xSimpleFileAccess.exists(Path))
526                 {
527                     Resource oResource = new Resource(xMSF, "ImportWizard", "imp");
528                     String sFileexists = oResource.getResText(1053);
529                     String NewString = JavaTools.convertfromURLNotation(Path);
530                     sFileexists = JavaTools.replaceSubString(sFileexists, NewString, "<1>");
531                     sFileexists = JavaTools.replaceSubString(sFileexists, String.valueOf((char) 13), "<CR>");
532                     int iLeave = SystemDialog.showMessageBox(xMSF, "QueryBox", VclWindowPeerAttribute.YES_NO, sFileexists);
533                     if (iLeave == 3)
534                     {
535                         return false;
536                     }
537                 }
538             }
539             String[] DirArray = JavaTools.ArrayoutofString(Path, "/");
540             int MaxIndex = DirArray.length - 1;
541             if (MaxIndex > 0)
542             {
543                 for (int i = MaxIndex; i >= 0; i--)
544                 {
545                     SubDir = DirArray[i];
546                     SubLen = SubDir.length();
547                     NewLen = NewPath.length();
548                     RestLen = NewLen - SubLen;
549                     if (RestLen > 0)
550                     {
551                         NewPath = NewPath.substring(0, NewLen - SubLen - 1);
552                         if (i == MaxIndex)
553                         {
554                             SubDirPath = NewPath;
555                         }
556                         bexists = xSimpleFileAccess.exists(NewPath);
557                         if (bexists)
558                         {
559                             LowerCasePath = NewPath.toLowerCase();
560                             bexists = (!((LowerCasePath.equals("file:///")) || (LowerCasePath.equals("file://")) || (LowerCasePath.equals("file:/")) || (LowerCasePath.equals("file:"))));
561                         }
562                         if (bexists)
563                         {
564                             if (!bSubDirexists)
565                             {
566                                 return createSubDirectory(xMSF, xSimpleFileAccess, SubDirPath);
567                             }
568                             return true;
569                         }
570                         else
571                         {
572                             bSubDirexists = false;
573                         }
574                     }
575                 }
576             }
577             SystemDialog.showMessageBox(xMSF, "ErrorBox", VclWindowPeerAttribute.OK, sMsgFilePathInvalid);
578             return false;
579         }
580         catch (com.sun.star.uno.Exception exception)
581         {
582             exception.printStackTrace(System.out);
583             SystemDialog.showMessageBox(xMSF, "ErrorBox", VclWindowPeerAttribute.OK, sMsgFilePathInvalid);
584             return false;
585         }
586     }
587 
588     /**
589      * searches a directory for files which start with a certain
590      * prefix, and returns their URLs and document-titles.
591      * @param xMSF
592      * @param FilterName the prefix of the filename. a "-" is added to the prefix !
593      * @param FolderName the folder (URL) to look for files...
594      * @return an array with two array members. The first one, with document titles,
595      * the second with the corresponding URLs.
596      * @deprecated please use the getFolderTitles() with ArrayList
597      */
getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String FilterName, String FolderName)598     public static String[][] getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String FilterName, String FolderName)
599     {
600         String[][] LocLayoutFiles = new String[2][]; //{PropertyNames.EMPTY_STRING,PropertyNames.EMPTY_STRING}{PropertyNames.EMPTY_STRING};
601         try
602         {
603             java.util.Vector<String> TitleVector = null;
604             java.util.Vector<String> NameVector = null;
605 
606             XInterface xDocInterface = (XInterface) xMSF.createInstance("com.sun.star.document.DocumentProperties");
607             XDocumentProperties xDocProps = UnoRuntime.queryInterface(XDocumentProperties.class, xDocInterface);
608 
609             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
610             com.sun.star.ucb.XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
611 
612             String[] nameList = xSimpleFileAccess.getFolderContents(FolderName, false);
613 
614             TitleVector = new java.util.Vector<String>(/*nameList.length*/);
615             NameVector = new java.util.Vector<String>(nameList.length);
616 
617             FilterName = FilterName == null || FilterName.equals(PropertyNames.EMPTY_STRING) ? null : FilterName + "-";
618 
619             String fileName = PropertyNames.EMPTY_STRING;
620             PropertyValue[] noArgs = { };
621             for (int i = 0; i < nameList.length; i++)
622             {
623                 fileName = getFilename(nameList[i]);
624 
625                 if (FilterName == null || fileName.startsWith(FilterName))
626                 {
627                     xDocProps.loadFromMedium(nameList[i], noArgs);
628                     NameVector.addElement(nameList[i]);
629                     TitleVector.addElement(xDocProps.getTitle());
630                 }
631             }
632             String[] LocNameList = new String[NameVector.size()];
633             String[] LocTitleList = new String[TitleVector.size()];
634 
635             NameVector.copyInto(LocNameList);
636             TitleVector.copyInto(LocTitleList);
637             LocLayoutFiles[1] = LocNameList;
638             LocLayoutFiles[0] = LocTitleList;
639 
640             JavaTools.bubblesortList(LocLayoutFiles);
641         }
642         catch (Exception exception)
643         {
644             exception.printStackTrace(System.out);
645         }
646         return LocLayoutFiles;
647     }
648 
649     /**
650      * We search in all given path for a given file
651      * @param _sPath
652      * @param _sPath2
653      * @return
654      */
addPath(String _sPath, String _sPath2)655     public static String addPath(String _sPath, String _sPath2)
656     {
657         String sNewPath;
658         if (!_sPath.endsWith("/"))
659         {
660             _sPath += "/";
661         }
662         if (_sPath2.startsWith("/"))
663         {
664             _sPath2 = _sPath2.substring(1);
665         }
666         sNewPath = _sPath + _sPath2;
667         return sNewPath;
668     }
669 
getPathFromList(XMultiServiceFactory xMSF, ArrayList _aList, String _sFile)670     public static String getPathFromList(XMultiServiceFactory xMSF, ArrayList _aList, String _sFile)
671     {
672         String sFoundFile = PropertyNames.EMPTY_STRING;
673         try
674         {
675             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
676             com.sun.star.ucb.XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
677 
678             for (int i = 0; i < _aList.size(); i++)
679             {
680                 String sPath = (String) _aList.get(i);
681                 sPath = addPath(sPath, _sFile);
682                 if (xSimpleFileAccess.exists(sPath))
683                 {
684                     sFoundFile = sPath;
685                 }
686             }
687         }
688         catch (com.sun.star.uno.Exception e)
689         {
690         }
691         return sFoundFile;
692     }
693 
694     /**
695      *
696      * @param xMSF
697      * @param _sStartFilterName
698      * @param FolderNames
699      * @return
700      * @throws com.sun.star.wizards.common.NoValidPathException
701      */
getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String _sStartFilterName, ArrayList FolderNames)702     public static String[][] getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String _sStartFilterName, ArrayList FolderNames)
703             throws NoValidPathException
704     {
705         return getFolderTitles(xMSF, _sStartFilterName, FolderNames, PropertyNames.EMPTY_STRING);
706     }
707 
getTitle(XMultiServiceFactory xMSF, String _sFile)708     private static String getTitle(XMultiServiceFactory xMSF, String _sFile)
709     {
710         String sTitle = PropertyNames.EMPTY_STRING;
711         try
712         {
713             XInterface xDocInterface = (XInterface) xMSF.createInstance("com.sun.star.document.DocumentProperties");
714             XDocumentProperties xDocProps = UnoRuntime.queryInterface(XDocumentProperties.class, xDocInterface);
715             PropertyValue[] noArgs = { };
716             xDocProps.loadFromMedium(_sFile, noArgs);
717             sTitle = xDocProps.getTitle();
718         }
719         catch (Exception e)
720         {
721         }
722         return sTitle;
723     }
724 
getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String _sStartFilterName, ArrayList FolderName, String _sEndFilterName)725     public static String[][] getFolderTitles(com.sun.star.lang.XMultiServiceFactory xMSF, String _sStartFilterName, ArrayList FolderName, String _sEndFilterName)
726             throws NoValidPathException
727     {
728         String[][] LocLayoutFiles = new String[2][]; //{PropertyNames.EMPTY_STRING,PropertyNames.EMPTY_STRING}{PropertyNames.EMPTY_STRING};
729         if (FolderName.size() == 0)
730         {
731             throw new NoValidPathException(null, "Path not given.");
732         }
733         ArrayList<String> TitleVector = new ArrayList<String>();
734         ArrayList<String> URLVector = new ArrayList<String>();
735 
736         com.sun.star.ucb.XSimpleFileAccess xSimpleFileAccess = null;
737         try
738         {
739             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
740             xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, xInterface);
741         }
742         catch (com.sun.star.uno.Exception e)
743         {
744             e.printStackTrace();
745             throw new NoValidPathException(null, "Internal error.");
746         }
747 
748         for (int j = 0; j < FolderName.size(); j++)
749         {
750             String sFolderName = (String) FolderName.get(j);
751 
752             try
753             {
754                 String[] nameList = xSimpleFileAccess.getFolderContents(sFolderName, false);
755                 _sStartFilterName = _sStartFilterName == null || _sStartFilterName.equals(PropertyNames.EMPTY_STRING) ? null : _sStartFilterName + "-";
756 
757                 String fileName = PropertyNames.EMPTY_STRING;
758                 for (int i = 0; i < nameList.length; i++)
759                 {
760                     fileName = getFilename(nameList[i]);
761                     String sTitle;
762 
763                     if (_sStartFilterName == null || fileName.startsWith(_sStartFilterName))
764                     {
765                         if (_sEndFilterName.equals(PropertyNames.EMPTY_STRING))
766                         {
767                             sTitle = getTitle(xMSF, nameList[i]);
768                         }
769                         else if (fileName.endsWith(_sEndFilterName))
770                         {
771                             fileName = fileName.replaceAll(_sEndFilterName + "$", PropertyNames.EMPTY_STRING);
772                             sTitle = fileName;
773                         }
774                         else
775                         {
776                             // no or wrong (start|end) filter
777                             continue;
778                         }
779                         URLVector.add(nameList[i]);
780                         TitleVector.add(sTitle);
781                     }
782                 }
783             }
784             catch (com.sun.star.ucb.CommandAbortedException exception)
785             {
786                 exception.printStackTrace(System.out);
787             }
788             catch (com.sun.star.uno.Exception e)
789             {
790             }
791         }
792 
793         String[] LocNameList = new String[URLVector.size()];
794         String[] LocTitleList = new String[TitleVector.size()];
795 
796         // LLA: we have to check if this works
797         URLVector.toArray(LocNameList);
798         TitleVector.toArray(LocTitleList);
799 
800         LocLayoutFiles[1] = LocNameList;
801         LocLayoutFiles[0] = LocTitleList;
802 
803         JavaTools.bubblesortList(LocLayoutFiles);
804 
805         return LocLayoutFiles;
806     }
807     public XSimpleFileAccess2 fileAccess;
808     public XFileIdentifierConverter filenameConverter;
809 
FileAccess(XMultiServiceFactory xmsf)810     public FileAccess(XMultiServiceFactory xmsf) throws com.sun.star.uno.Exception
811     {
812         //get a simple file access...
813         Object fa = xmsf.createInstance("com.sun.star.ucb.SimpleFileAccess");
814         fileAccess = UnoRuntime.queryInterface(XSimpleFileAccess2.class, fa);
815         //get the file identifier converter
816         Object fcv = xmsf.createInstance("com.sun.star.ucb.FileContentProvider");
817         filenameConverter = UnoRuntime.queryInterface(XFileIdentifierConverter.class, fcv);
818     }
819 
getURL(String parentPath, String childPath)820     public String getURL(String parentPath, String childPath)
821     {
822         String parent = filenameConverter.getSystemPathFromFileURL(parentPath);
823         File f = new File(parent, childPath);
824         return filenameConverter.getFileURLFromSystemPath(parentPath, f.getAbsolutePath());
825     }
826 
getURL(String path)827     public String getURL(String path)
828     {
829         File f = new File(path);
830         return filenameConverter.getFileURLFromSystemPath(path, f.getAbsolutePath());
831     }
832 
getPath(String parentURL, String childURL)833     public String getPath(String parentURL, String childURL)
834     {
835         return filenameConverter.getSystemPathFromFileURL(parentURL + (((childURL == null || childURL.equals(PropertyNames.EMPTY_STRING)) ? PropertyNames.EMPTY_STRING : "/" + childURL)));
836     }
837 
838     /**
839      * @author rpiterman
840      * @param filename
841      * @return the extension of the given filename.
842      */
getExtension(String filename)843     public static String getExtension(String filename)
844     {
845         int p = filename.indexOf(".");
846         if (p == -1)
847         {
848             return PropertyNames.EMPTY_STRING;
849         }
850         else
851         {
852             do
853             {
854                 filename = filename.substring(p + 1);
855             }
856             while ((p = filename.indexOf(".")) > -1);
857         }
858         return filename;
859     }
860 
861     /**
862      * @author rpiterman
863      * @param s
864      * @return
865      */
mkdir(String s)866     public boolean mkdir(String s)
867     {
868         try
869         {
870             fileAccess.createFolder(s);
871             return true;
872         }
873         catch (CommandAbortedException cax)
874         {
875             cax.printStackTrace();
876         }
877         catch (com.sun.star.uno.Exception ex)
878         {
879             ex.printStackTrace();
880         }
881         return false;
882     }
883 
884     /**
885      * @author rpiterman
886      * @param filename
887      * @param def what to return in case of an exception
888      * @return true if the given file exists or not.
889      * if an exception accures, returns the def value.
890      */
exists(String filename, boolean def)891     public boolean exists(String filename, boolean def)
892     {
893         try
894         {
895             return fileAccess.exists(filename);
896         }
897         catch (CommandAbortedException e)
898         {
899         }
900         catch (Exception e)
901         {
902         }
903 
904         return def;
905     }
906 
907     /**
908      * @author rpiterman
909      * @param filename
910      * @return
911      */
isDirectory(String filename)912     public boolean isDirectory(String filename)
913     {
914         try
915         {
916             return fileAccess.isFolder(filename);
917         }
918         catch (CommandAbortedException e)
919         {
920         }
921         catch (Exception e)
922         {
923         }
924 
925         return false;
926     }
927 
928     /**
929      * lists the files in a given directory
930      * @author rpiterman
931      * @param dir
932      * @param includeFolders
933      * @return
934      */
listFiles(String dir, boolean includeFolders)935     public String[] listFiles(String dir, boolean includeFolders)
936     {
937         try
938         {
939             return fileAccess.getFolderContents(dir, includeFolders);
940         }
941         catch (CommandAbortedException e)
942         {
943         }
944         catch (Exception e)
945         {
946         }
947 
948         return new String[0];
949     }
950 
951     /**
952      * @author rpiterman
953      * @param file
954      * @return
955      */
delete(String file)956     public boolean delete(String file)
957     {
958         try
959         {
960             fileAccess.kill(file);
961             return true;
962         }
963         catch (CommandAbortedException e)
964         {
965             e.printStackTrace(System.out);
966         }
967         catch (Exception e)
968         {
969             e.printStackTrace(System.out);
970         }
971 
972         return false;
973     }
974 
975     /**
976      * @author rpiterman
977      * @param path
978      * @return
979      */
getFilename(String path)980     public static String getFilename(String path)
981     {
982         return getFilename(path, "/");
983     }
984 
985     /**
986      * return the filename out of a system-dependent path
987      * @param path
988      * @return
989      */
getPathFilename(String path)990     public static String getPathFilename(String path)
991     {
992         return getFilename(path, File.separator);
993     }
994 
995     /**
996      * @author rpiterman
997      * @param path
998      * @param pathSeparator
999      * @return
1000      */
getFilename(String path, String pathSeparator)1001     public static String getFilename(String path, String pathSeparator)
1002     {
1003         String[] s = JavaTools.ArrayoutofString(path, pathSeparator);
1004         return s[s.length - 1];
1005     }
1006 
getBasename(String path, String pathSeparator)1007     public static String getBasename(String path, String pathSeparator)
1008     {
1009         String filename = getFilename(path, pathSeparator);
1010         String sExtension = getExtension(filename);
1011         return filename.substring(0, filename.length() - (sExtension.length() + 1));
1012     }
1013 
1014     /**
1015      * @author rpiterman
1016      * @param source
1017      * @param target
1018      * @return
1019      */
copy(String source, String target)1020     public boolean copy(String source, String target)
1021     {
1022         try
1023         {
1024             fileAccess.copy(source, target);
1025             return true;
1026         }
1027         catch (CommandAbortedException e)
1028         {
1029         }
1030         catch (Exception e)
1031         {
1032         }
1033 
1034         return false;
1035     }
1036 
getLastModified(String url)1037     public DateTime getLastModified(String url)
1038     {
1039         try
1040         {
1041             return fileAccess.getDateTimeModified(url);
1042         }
1043         catch (CommandAbortedException e)
1044         {
1045         }
1046         catch (Exception e)
1047         {
1048         }
1049         return null;
1050     }
1051 
1052     /**
1053      *
1054      * @param url
1055      * @return the parent dir of the given url.
1056      * if the path points to file, gives the directory in which the file is.
1057      */
getParentDir(String url)1058     public static String getParentDir(String url)
1059     {
1060         if (url.endsWith("/"))
1061         {
1062             return getParentDir(url.substring(0, url.length() - 1));
1063         }
1064         int pos = -1;
1065         int lastPos = 0;
1066         while ((pos = url.indexOf("/", pos + 1)) > -1)
1067         {
1068             lastPos = pos;
1069         }
1070         return url.substring(0, lastPos);
1071     }
1072 
createNewDir(String parentDir, String name)1073     public String createNewDir(String parentDir, String name)
1074     {
1075         String s = getNewFile(parentDir, name, PropertyNames.EMPTY_STRING);
1076         if (mkdir(s))
1077         {
1078             return s;
1079         }
1080         else
1081         {
1082             return null;
1083         }
1084     }
1085 
getNewFile(String parentDir, String name, String extension)1086     public String getNewFile(String parentDir, String name, String extension)
1087     {
1088 
1089         int i = 0;
1090         String url;
1091         do
1092         {
1093             String filename = filename(name, extension, i++);
1094             url = getURL(parentDir, filename);
1095         }
1096         while (exists(url, true));
1097 
1098         return url;
1099     }
1100 
filename(String name, String ext, int i)1101     private static String filename(String name, String ext, int i)
1102     {
1103         return name + (i == 0 ? PropertyNames.EMPTY_STRING : String.valueOf(i)) + (ext.equals(PropertyNames.EMPTY_STRING) ? PropertyNames.EMPTY_STRING : "." + ext);
1104     }
1105 
getSize(String url)1106     public int getSize(String url)
1107     {
1108         try
1109         {
1110             return fileAccess.getSize(url);
1111         }
1112         catch (Exception ex)
1113         {
1114             return -1;
1115         }
1116     }
1117 
connectURLs(String urlFolder, String urlFilename)1118     public static String connectURLs(String urlFolder, String urlFilename)
1119     {
1120         return urlFolder + (urlFolder.endsWith("/") ? PropertyNames.EMPTY_STRING : "/") +
1121                 (urlFilename.startsWith("/") ? urlFilename.substring(1) : urlFilename);
1122     }
1123 
getDataFromTextFile(XMultiServiceFactory _xMSF, String _filepath)1124     public static String[] getDataFromTextFile(XMultiServiceFactory _xMSF, String _filepath)
1125     {
1126         String[] sFileData = null;
1127         try
1128         {
1129             Vector<String> oDataVector = new Vector<String>();
1130             Object oSimpleFileAccess = _xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
1131             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, oSimpleFileAccess);
1132             if (xSimpleFileAccess.exists(_filepath))
1133             {
1134                 XInputStream xInputStream = xSimpleFileAccess.openFileRead(_filepath);
1135                 Object oTextInputStream = _xMSF.createInstance("com.sun.star.io.TextInputStream");
1136                 XTextInputStream xTextInputStream = UnoRuntime.queryInterface(XTextInputStream.class, oTextInputStream);
1137                 XActiveDataSink xActiveDataSink = UnoRuntime.queryInterface(XActiveDataSink.class, oTextInputStream);
1138                 xActiveDataSink.setInputStream(xInputStream);
1139                 while (!xTextInputStream.isEOF())
1140                 {
1141                     oDataVector.addElement( xTextInputStream.readLine());
1142                 }
1143                 xTextInputStream.closeInput();
1144                 sFileData = new String[oDataVector.size()];
1145                 oDataVector.toArray(sFileData);
1146 
1147             }
1148         }
1149         catch (Exception e)
1150         {
1151             e.printStackTrace(System.out);
1152         }
1153         return sFileData;
1154     }
1155 
1156     /**
1157      * shortens a filename to a user displayable representation.
1158      * @param path
1159      * @param maxLength
1160      * @return
1161      */
getShortFilename(String path, int maxLength)1162     public static String getShortFilename(String path, int maxLength)
1163     {
1164         int firstPart = 0;
1165 
1166         if (path.length() > maxLength)
1167         {
1168             if (path.startsWith("/"))
1169             { // unix
1170                 int nextSlash = path.indexOf("/", 1) + 1;
1171                 firstPart = Math.min(nextSlash, (maxLength - 3) / 2);
1172             }
1173             else
1174             { //windows
1175                 firstPart = Math.min(10, (maxLength - 3) / 2);
1176             }
1177 
1178             String s1 = path.substring(0, firstPart);
1179             String s2 = path.substring(path.length() - (maxLength - (3 + firstPart)));
1180 
1181             return s1 + "..." + s2;
1182         }
1183         else
1184         {
1185             return path;
1186         }
1187     }
1188 }
1189