KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > PathUtilities


1 /*
2 Copyright (c) 2003 eInnovation Inc. All rights reserved
3
4 This library is free software; you can redistribute it and/or modify it under the terms
5 of the GNU Lesser General Public License as published by the Free Software Foundation;
6 either version 2.1 of the License, or (at your option) any later version.
7
8 This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
9 without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the GNU Lesser General Public License for more details.
11 */

12
13 /*--
14
15  Copyright (C) 2001-2002 Anthony Eden.
16  All rights reserved.
17
18  Redistribution and use in source and binary forms, with or without
19  modification, are permitted provided that the following conditions
20  are met:
21
22  1. Redistributions of source code must retain the above copyright
23     notice, this list of conditions, and the following disclaimer.
24
25  2. Redistributions in binary form must reproduce the above copyright
26     notice, this list of conditions, and the disclaimer that follows
27     these conditions in the documentation and/or other materials
28     provided with the distribution.
29
30  3. The name "JPublish" must not be used to endorse or promote products
31     derived from this software without prior written permission. For
32     written permission, please contact me@anthonyeden.com.
33
34  4. Products derived from this software may not be called "JPublish", nor
35     may "JPublish" appear in their name, without prior written permission
36     from Anthony Eden (me@anthonyeden.com).
37
38  In addition, I request (but do not require) that you include in the
39  end-user documentation provided with the redistribution and/or in the
40  software itself an acknowledgement equivalent to the following:
41      "This product includes software developed by
42       Anthony Eden (http://www.anthonyeden.com/)."
43
44  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
45  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
46  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
48  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
53  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
54  POSSIBILITY OF SUCH DAMAGE.
55
56  For more information on JPublish, please see <http://www.jpublish.org/>.
57
58  */

59 package com.openedit.util;
60
61 import org.apache.commons.logging.Log;
62 import org.apache.commons.logging.LogFactory;
63
64
65 /**
66  * Utility class for working with request paths.
67  *
68  * @author Anthony Eden
69  */

70 public final class PathUtilities
71 {
72     private static final Log log = LogFactory.getLog(PathUtilities.class);
73     private static final String JavaDoc WILDCARD = "*";
74
75     /**
76      * Internal constructor.
77      */

78     public PathUtilities()
79     {
80         // no op
81
}
82
83     /**
84      * Get the parent of the given path.
85      *
86      * @param path The path for which to retrieve the parent
87      *
88      * @return The parent path. If the given path is the root path ("/" or ""), return a blank string.
89      */

90     public static String JavaDoc extractDirectoryPath(String JavaDoc path)
91     {
92         if ((path == null) || path.equals("") || path.equals("/"))
93         {
94             return "";
95         }
96
97         int lastSlashPos = path.lastIndexOf('/');
98
99         if (lastSlashPos >= 0)
100         {
101             return path.substring(0, lastSlashPos); //strip off the slash
102
}
103         else
104         {
105             return ""; //we expect people to add + "/somedir on their own
106
}
107     }
108
109     /**
110      * Builds a path that might be within or one above a parent path String ret =
111      * buildRelative("../junk.txt","/a/b/c/something.html") Will return /a/b/junk.txt This code
112      * only returns a changed endPart if it starts with a dot .
113      *
114      * @param endPart
115      * @param fullParentPath
116      *
117      * @return
118      */

119     public static String JavaDoc buildRelative(String JavaDoc endPart, String JavaDoc fullParentPath)
120     {
121         String JavaDoc basepath = null;
122         if ( fullParentPath != null)
123         {
124             fullParentPath = fullParentPath.replace('\\','/');
125         }
126         //TODO: Make this work with random number of dots
127

128         //if we are dealing with relative path then we need to make sure the basepath ends with a /
129
if (endPart.startsWith(".") && (fullParentPath != null) && !fullParentPath.endsWith("/"))
130         {
131             //so with this function /examples/benchmark -> /examples/benchmark/
132
//is this parent a directory or a file, lets check for a .
133
int lastslash = fullParentPath.lastIndexOf("/");
134             int lastperiod = fullParentPath.lastIndexOf(".");
135
136             if (lastslash > lastperiod)
137             {
138                 //must be a directory
139
basepath = fullParentPath;
140             }
141         }
142
143         if (basepath == null)
144         {
145             basepath = PathUtilities.extractDirectoryPath(fullParentPath);
146         }
147         if ( basepath == null )
148         {
149             basepath = "";
150         }
151
152         String JavaDoc relative = endPart;
153
154         if (endPart.startsWith(".."))
155         {
156             //strip the filename
157
if (basepath.endsWith("/"))
158             {
159                 basepath = basepath.substring(0, basepath.length() - 1);
160             }
161
162             basepath = basepath.substring(0, basepath.lastIndexOf("/"));
163             relative = basepath + endPart.substring(2);
164         }
165         else if (endPart.startsWith("."))
166         {
167             relative = basepath + endPart.substring(1);
168         }
169         if ( !relative.startsWith("/"))
170         {
171             relative = "/" + relative;
172         }
173         return relative;
174     }
175
176     /**
177      * Extract the page name from the given path. The page name is the name of the file in the
178      * path without its suffix.
179      * i.e. /subpath/index.html -> index
180      *
181      * @param path The request path
182      *
183      * @return The page name
184      */

185     public static String JavaDoc extractPageName(String JavaDoc path)
186     {
187         if ( path == null)
188         {
189             return null;
190         }
191         String JavaDoc newpath = path.replace('\\','/');
192         int start = newpath.lastIndexOf("/");
193         if ( start == -1)
194         {
195             start = 0;
196         }
197         else
198         {
199             start++; //to remove slash
200
}
201         int dotIndex = newpath.lastIndexOf(".");
202
203         if (dotIndex == -1 || start > dotIndex )
204         {
205             return null;
206         }
207         String JavaDoc pageName = newpath.substring(start, dotIndex);
208
209         return pageName;
210     }
211
212     /**
213      * Extract the page path from the given request path. This method will return the path from
214      * the page root to the page descriptor file.
215      *
216      * /some/sub/dir/test.html -> /some/sub/dir/test
217      *
218      * @param path The request path
219      * @see extractDirectory
220      * @return The page path
221      */

222     public static String JavaDoc extractPagePath(String JavaDoc path)
223     {
224         if ( path != null && path.length() > 0)
225         {
226             int lastDot = path.lastIndexOf(".");
227             if( lastDot > 1)
228             {
229                 String JavaDoc pagePath = path.substring(0,lastDot);
230                 return pagePath;
231             }
232         }
233         return path;
234     }
235
236     /**
237      * Return the page type extracting it from the path. For example: index.html would return
238      * "html" as the page type. If the type cannot be determined then this method returns null.
239      *
240      * @param path The path
241      *
242      * @return The page type
243      */

244     public static String JavaDoc extractPageType(String JavaDoc path)
245     {
246         int dotIndex = path.lastIndexOf(".");
247
248         if (dotIndex == -1)
249         {
250             return null;
251         }
252
253         String JavaDoc pageType = path.substring(dotIndex + 1);
254
255         return pageType;
256     }
257
258     /**
259      * Match a path which may contain a wildcard.
260      *
261      * @param requestPath The request path submitted by the client
262      * @param exPath The match path with * wildcard
263      *
264      * @return DOCME
265      */

266     public static boolean match(String JavaDoc requestPath, String JavaDoc wildcardPath)
267     {
268         //log.debug("match(" + requestPath + "," + exPath + ")");
269
int wildcardIndex = wildcardPath.indexOf(WILDCARD);
270
271         if (wildcardIndex == -1)
272         {
273             return requestPath.equalsIgnoreCase(wildcardPath);
274         }
275         else if( wildcardPath.charAt(0) == '*' && wildcardPath.charAt(wildcardPath.length()-1) == '*' )
276         {
277             String JavaDoc path = wildcardPath.substring(1,wildcardPath.length()-1);
278             return requestPath.indexOf(path) > -1;
279         }
280         else if (wildcardIndex == (wildcardPath.length() - 1)) //ends with
281
{
282                 //log.debug("Wildcard appears at end of match path.");
283
String JavaDoc checkString = wildcardPath.substring(0, wildcardPath.length() - 1);
284
285                 //log.debug("String after wildcard removed: " + checkString);
286
boolean answer = requestPath.startsWith(checkString);
287
288                 //log.debug("Does " + requestPath + " start with " + checkString + "? " + answer);
289
return answer;
290         }
291         else if( wildcardPath.charAt(0) == '*')
292         {
293             String JavaDoc checkString = wildcardPath.substring(1);
294
295             //log.debug("String after wildcard removed: " + checkString);
296
boolean answer = requestPath.endsWith(checkString);
297             return answer;
298         }
299         else
300         {
301             //log.debug("Wildcard appears in the middle of the string");
302
String JavaDoc preMatch = wildcardPath.substring(0, wildcardIndex);
303             String JavaDoc postMatch = wildcardPath.substring(wildcardIndex + 1);
304
305             return requestPath.startsWith(preMatch) && requestPath.endsWith(postMatch);
306         }
307     }
308
309     /**
310      * resolve a relative URL string against an absolute URL string.
311      *
312      * This method was adapted from the CalCom library at http://www.calcom.de
313      *
314      * <p>the absolute URL string is the start point for the
315      * relative path.</p>
316      *
317      * <p><b>Example:</b></p>
318      * <pre>
319      * relative path: ../images/test.jpg
320      * absolute path: file:/d:/eigene dateien/eigene bilder/
321      * result: file:/d:/eigene dateien/images/test.jpg
322      * </pre>
323      *
324      * @param relPath The relative URL string to resolve. Unlike the Calcom version, this may be
325      * an absolute path, if it starts with "/".
326      * @param absPath The absolute URL string to start at. Unlike the CalCom version, this may be a filename
327      * rather than just a path.
328      *
329      * @return the absolute URL string resulting from resolving relPath against absPath
330      *
331      * @author Ulrich Hilger
332      * @author CalCom
333      * @author <a HREF="http://www.calcom.de">http://www.calcom.de</a>
334      * @author <a HREF="mailto:info@calcom.de">info@calcom.de</a>
335      * @author Dennis Brown (eInnovation)
336      */

337     public static String JavaDoc resolveRelativePath(String JavaDoc relPath, String JavaDoc absPath)
338     {
339         // if relative path is really absolute, then ignore absPath (eInnovation change)
340
if ( relPath.startsWith( "/" ) )
341         {
342             absPath = "";
343         }
344
345         String JavaDoc newAbsPath = absPath;
346         String JavaDoc newRelPath = relPath;
347         if( relPath.startsWith("$"))
348         {
349             return relPath;
350         }
351         else if (absPath.endsWith("/"))
352         {
353             newAbsPath = absPath.substring(0, absPath.length() - 1);
354         }
355         else
356         {
357             // absPath ends with a filename, remove it (eInnovation change)
358
int lastSlashIndex = absPath.lastIndexOf('/');
359             if ( lastSlashIndex >= 0 )
360             {
361                 newAbsPath = absPath.substring( 0, lastSlashIndex );
362             }
363             else
364             {
365                 newAbsPath = "";
366             }
367         }
368
369         int relPos = newRelPath.indexOf("../");
370         while (relPos > -1)
371         {
372             newRelPath = newRelPath.substring(relPos + 3);
373             int lastSlashInAbsPath = newAbsPath.lastIndexOf( "/" );
374             if ( lastSlashInAbsPath >= 0 )
375             {
376                 newAbsPath = newAbsPath.substring(0, newAbsPath.lastIndexOf("/"));
377             }
378             else
379             {
380                 // eInnovation change: fix potential exception
381
newAbsPath = "";
382             }
383             relPos = newRelPath.indexOf("../");
384         }
385         String JavaDoc returnedPath;
386         if (newRelPath.startsWith("/"))
387         {
388             returnedPath = newAbsPath + newRelPath;
389         }
390         else
391         {
392             returnedPath = newAbsPath + "/" + newRelPath;
393         }
394
395
396         // remove any "." references to current directory (eInnovation change)
397
// For example:
398
// "./junk" becomes "junk"
399
// "/./junk" becomes "/junk"
400
// "junk/." becomes "junk"
401
while ( returnedPath.endsWith( "/." ) )
402         {
403             returnedPath = returnedPath.substring( 0, returnedPath.length() - 2 );
404         }
405         do
406         {
407             int dotSlashIndex = returnedPath.lastIndexOf( "./" );
408             if ( dotSlashIndex < 0 )
409             {
410                 break;
411             }
412             else if ( dotSlashIndex == 0 || returnedPath.charAt( dotSlashIndex - 1 ) != '.' )
413             {
414                 String JavaDoc firstSubstring;
415                 if ( dotSlashIndex > 0 )
416                 {
417                     firstSubstring = returnedPath.substring( 0, dotSlashIndex );
418                 }
419                 else
420                 {
421                     firstSubstring = "";
422                 }
423                 String JavaDoc secondSubstring;
424                 if ( dotSlashIndex + 2 < returnedPath.length() )
425                 {
426                     secondSubstring = returnedPath.substring( dotSlashIndex + 2, returnedPath.length() );
427                 }
428                 else
429                 {
430                     secondSubstring = "";
431                 }
432                 returnedPath = firstSubstring + secondSubstring;
433             }
434         } while ( true );
435
436         return returnedPath;
437     }
438
439     /**
440      * Pass in /sub/dir/path.html returns path.html
441      * @param inPath
442      * @return
443      */

444     public static String JavaDoc extractFileName(String JavaDoc path) {
445
446         if ( path == null)
447         {
448             return null;
449         }
450         String JavaDoc newpath = path.replace('\\','/');
451         int start = newpath.lastIndexOf("/");
452         if ( start == -1)
453         {
454             start = 0;
455         }
456         else
457         {
458             start = start + 1;
459         }
460         String JavaDoc pageName = newpath.substring(start, newpath.length());
461
462         return pageName;
463     }
464
465     public static String JavaDoc createDraftPath(String JavaDoc inPath)
466     {
467         if ( inPath != null)
468         {
469             if( !inPath.contains(".draft."))
470             {
471                 String JavaDoc root = PathUtilities.extractPagePath(inPath);
472                 String JavaDoc p = root + ".draft." + PathUtilities.extractPageType(inPath);
473                 return p;
474             }
475         }
476         return inPath;
477     }
478     
479     public static String JavaDoc createLivePath(String JavaDoc inDraftPath)
480     {
481         if ( inDraftPath != null)
482         {
483             if( inDraftPath.contains(".draft."))
484             {
485                 return inDraftPath.replace(".draft", "");
486             }
487         }
488         return inDraftPath;
489     }
490     
491     public static String JavaDoc makeId(String JavaDoc inText)
492     {
493         String JavaDoc id = inText;
494         id = id.replace("\\/","_");
495         id = id.replace(".","_");
496         id = id.replace(" ","_");
497         if( id.charAt(0) == '_')
498         {
499             id = id.substring(1,id.length());
500         }
501         return id;
502     }
503 }
504
Popular Tags