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