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 
24 package helper;
25 
26 // __________ Imports __________
27 
28 // exceptions
29 import java.net.MalformedURLException;
30 
31 // interfaces
32 import com.sun.star.util.XURLTransformer;
33 
34 // others
35 import java.io.File;
36 import java.util.Vector;
37 import java.util.Enumeration;
38 
39 
40 /**
41  * It collects some static helper functons to handle URLs.
42  * Sometimes it's necessary to convert URL from/to system paths.
43  * Or from string to strutural notations (e.g. com.sun.star.util.URL).
44  * And sometimes java had another notation then the office it has.
45  *
46  */
47 public class URLHelper
48 {
49     // ____________________
50 
51     /**
52      * Because the office need URLs for loading/saving documents
53      * we must convert used system paths.
54      * And java use another notation for file URLs ... correct it.
55      *
56      * @param aSystemPath
57      *          represent the file in system notation
58      *
59      * @return [String]
60      *          a file url which represent the given system path
61      */
getFileURLFromSystemPath( File aSystemPath )62     public static String getFileURLFromSystemPath( File aSystemPath )
63     {
64         String sFileURL = null;
65         try
66         {
67             //sFileURL = aSystemPath.toURI().toURL().toString();
68             sFileURL = aSystemPath.toURL().toString();
69         }
70         catch( MalformedURLException exWrong )
71         {
72             sFileURL = null;
73         }
74 
75         // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones!
76         // => correct this problem first, otherwise office can't use these URL's
77         if(
78             (sFileURL                       != null ) &&
79             (sFileURL.startsWith("file:/")  == true ) &&
80             (sFileURL.startsWith("file://") == false)
81           )
82         {
83             StringBuffer sWorkBuffer = new StringBuffer(sFileURL);
84             sWorkBuffer.insert(6,"//");
85             sFileURL = sWorkBuffer.toString();
86         }
87 
88         return sFileURL;
89     }
90 
91     // ____________________
92 
93     /**
94      * The same as getFileURLFromSystemPath() before but uses string parameter instead
95      * of a File type. It exists to suppress converting of necessary parameters in the
96      * outside code. But of course getFileURLFromSystemPath(File) will be a little bit faster
97      * then this method ...
98      *
99      * @param sSystemPath
100      *          represent the file in system notation
101      *
102      * @return [String]
103      *          a file url which represent the given system path
104      */
getFileURLFromSystemPath( String sSystemPath )105     public static String getFileURLFromSystemPath( String sSystemPath )
106     {
107         return getFileURLFromSystemPath(new File(sSystemPath));
108     }
109 
110     // ____________________
111 
112     /**
113      * Does the same as getFileURLFromSystemPath() before ... but uses
114      * the given protocol string (e.g."http://") instead of "file:///".
115      *
116      * @param aSystemPath
117      *          represent the file in system notation
118      *
119      * @param aBasePath
120      *          define the base path of the aSystemPath value,
121      *          which must be replaced with the value of "sServerPath".
122      *
123      * @param sServerURL
124      *          Will be used to replace sBasePath.
125      *
126      * @example
127      *          System Path = "d:\test\file.txt"
128      *          Base Path   = "d:\test"
129      *          Server Path = "http://alaska:8000"
130      *          => "http://alaska:8000/file.txt"
131      *
132      * @return [String]
133      *          an url which represent the given system path
134      *          and uses the given protocol
135      */
getURLWithProtocolFromSystemPath( File aSystemPath, File aBasePath, String sServerURL )136     public static String getURLWithProtocolFromSystemPath( File aSystemPath, File aBasePath, String sServerURL )
137     {
138         String sFileURL = URLHelper.getFileURLFromSystemPath(aSystemPath);
139         String sBaseURL = URLHelper.getFileURLFromSystemPath(aBasePath  );
140 
141         // cut last '/'!
142         if (sBaseURL.lastIndexOf('/')==(sBaseURL.length()-1))
143             sBaseURL = sBaseURL.substring(0,sBaseURL.length()-1);
144 
145         // cut last '/'!
146         if (sServerURL.lastIndexOf('/')==(sServerURL.length()-1))
147             sServerURL = sServerURL.substring(0,sServerURL.length()-1);
148 
149         int index = sFileURL.indexOf(sBaseURL);
150         String sURL = sFileURL.substring(0,index) + sServerURL +
151                                 sFileURL.substring(index+sBaseURL.length());
152         //String sURL = sFileURL.replaceFirst(sBaseURL,sServerURL);
153         return sURL;
154     }
155 
156     // ____________________
157 
158     /**
159      * The same as getURLWithProtocolFromSystemPath() before but uses string parameter instead
160      * of a File types. It exists to suppress converting of necessary parameters in the
161      * outside code. But of course getURLWithProtocolFromSystemPath(File,File,String) will be
162      * a little bit faster then this method ...
163      *
164      * @param sSystemPath
165      *          represent the file in system notation
166      *
167      * @param sBasePath
168      *          define the base path of the aSystemPath value,
169      *          which must be replaced with the value of "sServerPath".
170      *
171      * @param sServerPath
172      *          Will be used to replace sBasePath.
173      *
174      * @example
175      *          System Path = "d:\test\file.txt"
176      *          Base Path   = "d:\test"
177      *          Server Path = "http://alaska:8000"
178      *          => "http://alaska:8000/file.txt"
179      *
180      * @return [String]
181      *          an url which represent the given system path
182      *          and uses the given protocol
183      */
getURLWithProtocolFromSystemPath( String sSystemPath, String sBasePath, String sServerPath )184     public static String getURLWithProtocolFromSystemPath( String sSystemPath, String sBasePath, String sServerPath )
185     {
186         return getURLWithProtocolFromSystemPath(new File(sSystemPath), new File(sBasePath), sServerPath);
187     }
188 
189     // ____________________
190 
191     /**
192      * This convert an URL (formatted as a string) to a struct com.sun.star.util.URL.
193      * It use a special service to do that: the URLTransformer.
194      * Because some API calls need it and it's not allowed to set "Complete"
195      * part of the util struct only. The URL must be parsed.
196      *
197      * @param sURL
198      *          URL for parsing in string notation
199      *
200      * @return [com.sun.star.util.URL]
201      *              URL in UNO struct notation
202      */
parseURL(XURLTransformer xParser, String sURL)203     public static com.sun.star.util.URL parseURL(XURLTransformer xParser, String sURL)
204     {
205         com.sun.star.util.URL aURL = null;
206 
207         if (sURL==null || sURL.equals(""))
208             return null;
209 
210         try
211         {
212             // Create special service for parsing of given URL.
213 /*            com.sun.star.util.XURLTransformer xParser = (com.sun.star.util.XURLTransformer)OfficeConnect.createRemoteInstance(
214                                                             com.sun.star.util.XURLTransformer.class,
215                                                             "com.sun.star.util.URLTransformer");
216 */
217             // Because it's an in/out parameter we must use an array of URL objects.
218             com.sun.star.util.URL[] aParseURL = new com.sun.star.util.URL[1];
219             aParseURL[0]          = new com.sun.star.util.URL();
220             aParseURL[0].Complete = sURL;
221 
222             // Parse the URL
223             xParser.parseStrict(aParseURL);
224 
225             aURL = aParseURL[0];
226         }
227         catch(com.sun.star.uno.RuntimeException exRuntime)
228         {
229             // Any UNO method of this scope can throw this exception.
230             // Reset the return value only.
231             aURL = null;
232         }
233 
234         return aURL;
235     }
236 
237     //_________________________________
238     /**
239      * Return a name list of all available files of a directory.
240      * We filter pure sub directories names. All other files
241      * are returned as full qualified URL strings. So they can be
242      * used for further purposes. One parameter define the start directory,
243      * another one describe the url protocol, which the return URL names should have.
244      *
245      * @param   sStartDir
246      *              the start directory, which should include all test files
247      *
248      * @return  [Vector]
249      *              a filtered list of java File objects of all available files of the start dir
250      *              and all accessible subdirectories.
251      */
getSystemFilesFromDir(String sStartDir)252     public static Vector getSystemFilesFromDir(String sStartDir)
253     {
254         File aRoot = new File(sStartDir);
255 
256         if (! aRoot.exists())
257             return null;
258 
259         if (! aRoot.isDirectory())
260             return null;
261 
262         File[] lAllFiles = aRoot.listFiles();
263         if (lAllFiles == null )
264             return null;
265 
266         Vector lFilteredFiles = new Vector(lAllFiles.length);
267 
268         for (int i=0; i<lAllFiles.length; ++i)
269         {
270             if (lAllFiles[i].isFile())
271                 lFilteredFiles.add(lAllFiles[i]);
272             else
273             if (lAllFiles[i].isDirectory())
274             {
275                 // recursion!
276                 Vector lSubFiles = URLHelper.getSystemFilesFromDir(lAllFiles[i].getPath());
277                 if (lSubFiles != null)
278                 {
279                     Enumeration aSnapshot = lSubFiles.elements();
280                     while (aSnapshot.hasMoreElements())
281                         lFilteredFiles.add(aSnapshot.nextElement());
282                 }
283             }
284         }
285 
286         return lFilteredFiles;
287     }
288 }
289