KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > filesys > server > filesys > FileName


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.filesys.server.filesys;
18
19 import java.io.File JavaDoc;
20 import java.io.FileNotFoundException JavaDoc;
21 import java.util.StringTokenizer JavaDoc;
22
23 /**
24  * <p>
25  * Provides utility methods for manipulating file names.
26  */

27 public final class FileName
28 {
29
30     // DOS file name seperator
31

32     public static final char DOS_SEPERATOR = '\\';
33     public static final String JavaDoc DOS_SEPERATOR_STR = "\\";
34
35     // NTFS Stream seperator
36

37     public static final String JavaDoc NTFSStreamSeperator = ":";
38
39     /**
40      * Build a path using the specified components.
41      *
42      * @param dev java.lang.String
43      * @param path java.lang.String
44      * @param filename java.lang.String
45      * @param sep char
46      * @return java.lang.String
47      */

48     public static String JavaDoc buildPath(String JavaDoc dev, String JavaDoc path, String JavaDoc filename, char sep)
49     {
50
51         // Build the path string
52

53         StringBuffer JavaDoc fullPath = new StringBuffer JavaDoc();
54
55         // Check for a device name
56

57         if (dev != null)
58         {
59
60             // Add the device name
61

62             fullPath.append(dev);
63
64             // Check if the device name has a file seperator
65

66             if (dev.length() > 0 && dev.charAt(dev.length() - 1) != sep)
67                 fullPath.append(sep);
68         }
69
70         // Check for a path
71

72         if (path != null)
73         {
74
75             // Add the path
76

77             if (fullPath.length() > 0 && path.length() > 0
78                     && (path.charAt(0) == sep || path.charAt(0) == DOS_SEPERATOR))
79                 fullPath.append(path.substring(1));
80             else
81                 fullPath.append(path);
82
83             // Add a trailing seperator, if required
84

85             if (path.length() > 0 && path.charAt(path.length() - 1) != sep && filename != null)
86                 fullPath.append(sep);
87         }
88
89         // Check for a file name
90

91         if (filename != null)
92         {
93
94             // Add the file name
95

96             if (fullPath.length() > 0 && filename.length() > 0
97                     && (filename.charAt(0) == sep || filename.charAt(0) == DOS_SEPERATOR))
98                 fullPath.append(filename.substring(1));
99             else
100                 fullPath.append(filename);
101         }
102
103         // Convert the file seperator characters in the path if we are not using the normal
104
// DOS file seperator character.
105

106         if (sep != DOS_SEPERATOR)
107             return convertSeperators(fullPath.toString(), sep);
108         return fullPath.toString();
109     }
110
111     /**
112      * Convert the file seperators in a path to the specified path seperator character.
113      *
114      * @param path java.lang.String
115      * @param sep char
116      * @return java.lang.String
117      */

118     public static String JavaDoc convertSeperators(String JavaDoc path, char sep)
119     {
120
121         // Check if the path contains any DOS seperators
122

123         if (path.indexOf(DOS_SEPERATOR) == -1)
124             return path;
125
126         // Convert DOS path seperators to the specified seperator
127

128         StringBuffer JavaDoc newPath = new StringBuffer JavaDoc();
129         int idx = 0;
130
131         while (idx < path.length())
132         {
133
134             // Get the current character from the path and check if it is a DOS path
135
// seperator character.
136

137             char ch = path.charAt(idx++);
138             if (ch == DOS_SEPERATOR)
139                 newPath.append(sep);
140             else
141                 newPath.append(ch);
142         }
143
144         // Return the new path string
145

146         return newPath.toString();
147     }
148
149     /**
150      * Map the input path to a real path, this may require changing the case of various parts of the
151      * path. The base path is not checked, it is assumed to exist.
152      *
153      * @param base java.lang.String
154      * @param path java.lang.String
155      * @return java.lang.String
156      * @exception java.io.FileNotFoundException The path could not be mapped to a real path.
157      */

158     public static final String JavaDoc mapPath(String JavaDoc base, String JavaDoc path) throws java.io.FileNotFoundException JavaDoc
159     {
160
161         // Split the path string into seperate directory components
162

163         String JavaDoc pathCopy = path;
164         if (pathCopy.length() > 0 && pathCopy.startsWith(DOS_SEPERATOR_STR))
165             pathCopy = pathCopy.substring(1);
166
167         StringTokenizer JavaDoc token = new StringTokenizer JavaDoc(pathCopy, "\\/");
168         int tokCnt = token.countTokens();
169
170         // The mapped path string, if it can be mapped
171

172         String JavaDoc mappedPath = null;
173
174         if (tokCnt > 0)
175         {
176
177             // Allocate an array to hold the directory names
178

179             String JavaDoc[] dirs = new String JavaDoc[token.countTokens()];
180
181             // Get the directory names
182

183             int idx = 0;
184             while (token.hasMoreTokens())
185                 dirs[idx++] = token.nextToken();
186
187             // Check if the path ends with a directory or file name, ie. has a trailing '\' or not
188

189             int maxDir = dirs.length;
190
191             if (path.endsWith(DOS_SEPERATOR_STR) == false)
192             {
193
194                 // Ignore the last token as it is a file name
195

196                 maxDir--;
197             }
198
199             // Build up the path string and validate that the path exists at each stage.
200

201             StringBuffer JavaDoc pathStr = new StringBuffer JavaDoc(base);
202             if (base.endsWith(java.io.File.separator) == false)
203                 pathStr.append(java.io.File.separator);
204
205             int lastPos = pathStr.length();
206             idx = 0;
207             File JavaDoc lastDir = null;
208             if (base != null && base.length() > 0)
209                 lastDir = new File JavaDoc(base);
210             File JavaDoc curDir = null;
211
212             while (idx < maxDir)
213             {
214
215                 // Append the current directory to the path
216

217                 pathStr.append(dirs[idx]);
218                 pathStr.append(java.io.File.separator);
219
220                 // Check if the current path exists
221

222                 curDir = new File JavaDoc(pathStr.toString());
223
224                 if (curDir.exists() == false)
225                 {
226
227                     // Check if there is a previous directory to search
228

229                     if (lastDir == null)
230                         throw new FileNotFoundException JavaDoc();
231
232                     // Search the current path for a matching directory, the case may be different
233

234                     String JavaDoc[] fileList = lastDir.list();
235                     if (fileList == null || fileList.length == 0)
236                         throw new FileNotFoundException JavaDoc();
237
238                     int fidx = 0;
239                     boolean foundPath = false;
240
241                     while (fidx < fileList.length && foundPath == false)
242                     {
243
244                         // Check if the current file name matches the required directory name
245

246                         if (fileList[fidx].equalsIgnoreCase(dirs[idx]))
247                         {
248
249                             // Use the current directory name
250

251                             pathStr.setLength(lastPos);
252                             pathStr.append(fileList[fidx]);
253                             pathStr.append(java.io.File.separator);
254
255                             // Check if the path is valid
256

257                             curDir = new File JavaDoc(pathStr.toString());
258                             if (curDir.exists())
259                             {
260                                 foundPath = true;
261                                 break;
262                             }
263                         }
264
265                         // Update the file name index
266

267                         fidx++;
268                     }
269
270                     // Check if we found the required directory
271

272                     if (foundPath == false)
273                         throw new FileNotFoundException JavaDoc();
274                 }
275
276                 // Set the last valid directory file
277

278                 lastDir = curDir;
279
280                 // Update the end of valid path location
281

282                 lastPos = pathStr.length();
283
284                 // Update the current directory index
285

286                 idx++;
287             }
288
289             // Check if there is a file name to be added to the mapped path
290

291             if (path.endsWith(DOS_SEPERATOR_STR) == false)
292             {
293
294                 // Map the file name
295

296                 String JavaDoc[] fileList = lastDir.list();
297                 String JavaDoc fileName = dirs[dirs.length - 1];
298
299                 // Check if the file list is valid, if not then the path is not valid
300

301                 if (fileList == null)
302                     throw new FileNotFoundException JavaDoc(path);
303
304                 // Search for the required file
305

306                 idx = 0;
307                 boolean foundFile = false;
308
309                 while (idx < fileList.length && foundFile == false)
310                 {
311                     if (fileList[idx].compareTo(fileName) == 0)
312                         foundFile = true;
313                     else
314                         idx++;
315                 }
316
317                 // Check if we found the file name, if not then do a case insensitive search
318

319                 if (foundFile == false)
320                 {
321
322                     // Search again using a case insensitive search
323

324                     idx = 0;
325
326                     while (idx < fileList.length && foundFile == false)
327                     {
328                         if (fileList[idx].equalsIgnoreCase(fileName))
329                         {
330                             foundFile = true;
331                             fileName = fileList[idx];
332                         }
333                         else
334                             idx++;
335                     }
336                 }
337
338                 // Append the file name
339

340                 pathStr.append(fileName);
341             }
342
343             // Set the new path string
344

345             mappedPath = pathStr.toString();
346         }
347
348         // Return the mapped path string, if successful.
349

350         return mappedPath;
351     }
352
353     /**
354      * Remove the file name from the specified path string.
355      *
356      * @param path java.lang.String
357      * @return java.lang.String
358      */

359     public final static String JavaDoc removeFileName(String JavaDoc path)
360     {
361
362         // Find the last path seperator
363

364         int pos = path.lastIndexOf(DOS_SEPERATOR);
365         if (pos != -1)
366             return path.substring(0, pos);
367
368         // Return an empty string, no path seperators
369

370         return "";
371     }
372
373     /**
374      * Split the path into seperate directory path and file name strings.
375      *
376      * @param path Full path string.
377      * @param sep Path seperator character.
378      * @return java.lang.String[]
379      */

380     public static String JavaDoc[] splitPath(String JavaDoc path)
381     {
382         return splitPath(path, DOS_SEPERATOR, null);
383     }
384
385     /**
386      * Split the path into seperate directory path and file name strings.
387      *
388      * @param path Full path string.
389      * @param sep Path seperator character.
390      * @return java.lang.String[]
391      */

392     public static String JavaDoc[] splitPath(String JavaDoc path, char sep)
393     {
394         return splitPath(path, sep, null);
395     }
396
397     /**
398      * Split the path into seperate directory path and file name strings.
399      *
400      * @param path Full path string.
401      * @param sep Path seperator character.
402      * @param list String list to return values in, or null to allocate
403      * @return java.lang.String[]
404      */

405     public static String JavaDoc[] splitPath(String JavaDoc path, char sep, String JavaDoc[] list)
406     {
407         if (path == null)
408             throw new IllegalArgumentException JavaDoc("Path may not be null");
409
410         // Create an array of strings to hold the path and file name strings
411
String JavaDoc[] pathStr = list;
412         if (pathStr == null)
413             pathStr = new String JavaDoc[] {"", ""};
414
415         // Check if the path is valid
416
if (path.length() > 0)
417         {
418             // Check if the path has a trailing seperator, if so then there is no file name.
419
int pos = path.lastIndexOf(sep);
420             if (pos == -1 || pos == (path.length() - 1))
421             {
422                 // Set the path string in the returned string array
423
pathStr[0] = path;
424             }
425             else
426             {
427                 // Split the path into directory list and file name strings
428
pathStr[1] = path.substring(pos + 1);
429
430                 if (pos == 0)
431                     pathStr[0] = path.substring(0, pos + 1);
432                 else
433                     pathStr[0] = path.substring(0, pos);
434             }
435         }
436
437         // Return the path strings
438
return pathStr;
439     }
440
441     /**
442      * Split the path into all the component directories and filename
443      *
444      * @param path String
445      * @return String[]
446      */

447     public static String JavaDoc[] splitAllPaths(String JavaDoc path)
448     {
449
450         // Check if the path is valid
451

452         if (path == null || path.length() == 0)
453             return null;
454
455         // Determine the number of components in the path
456

457         StringTokenizer JavaDoc token = new StringTokenizer JavaDoc(path, DOS_SEPERATOR_STR);
458         String JavaDoc[] names = new String JavaDoc[token.countTokens()];
459
460         // Split the path
461

462         int i = 0;
463
464         while (i < names.length && token.hasMoreTokens())
465             names[i++] = token.nextToken();
466
467         // Return the path components
468

469         return names;
470     }
471
472     /**
473      * Split a path string into directory path, file name and stream name components
474      *
475      * @param path Full path string.
476      * @return java.lang.String[]
477      */

478     public static String JavaDoc[] splitPathStream(String JavaDoc path)
479     {
480
481         // Allocate the return list
482

483         String JavaDoc[] pathStr = new String JavaDoc[3];
484
485         // Split the path into directory path and file/stream name
486

487         FileName.splitPath(path, DOS_SEPERATOR, pathStr);
488         if (pathStr[1] == null)
489             return pathStr;
490
491         // Split the file name into file and stream names
492

493         int pos = pathStr[1].indexOf(NTFSStreamSeperator);
494
495         if (pos != -1)
496         {
497
498             // Split the file/stream name
499

500             pathStr[2] = pathStr[1].substring(pos);
501             pathStr[1] = pathStr[1].substring(0, pos);
502         }
503
504         // Return the path components list
505

506         return pathStr;
507     }
508
509     /**
510      * Test if a file name contains an NTFS stream name
511      *
512      * @param path String
513      * @return boolean
514      */

515     public static boolean containsStreamName(String JavaDoc path)
516     {
517
518         // Check if the path contains the stream name seperator character
519

520         if (path.indexOf(NTFSStreamSeperator) != -1)
521             return true;
522         return false;
523     }
524
525     /**
526      * Normalize the path to uppercase the directory names and keep the case of the file name.
527      *
528      * @param path String
529      * @return String
530      */

531     public final static String JavaDoc normalizePath(String JavaDoc path)
532     {
533
534         // Split the path into directories and file name, only uppercase the directories to
535
// normalize
536
// the path.
537

538         String JavaDoc normPath = path;
539
540         if (path.length() > 3)
541         {
542
543             // Split the path to seperate the folders/file name
544

545             int pos = path.lastIndexOf(DOS_SEPERATOR);
546             if (pos != -1)
547             {
548
549                 // Get the path and file name parts, normalize the path
550

551                 String JavaDoc pathPart = path.substring(0, pos).toUpperCase();
552                 String JavaDoc namePart = path.substring(pos);
553
554                 // Rebuild the path string
555

556                 normPath = pathPart + namePart;
557             }
558         }
559
560         // Return the normalized path
561

562         return normPath;
563     }
564
565     /**
566      * Make a path relative to the base path for the specified path.
567      *
568      * @param basePath String
569      * @param fullPath String
570      * @return String
571      */

572     public final static String JavaDoc makeRelativePath(String JavaDoc basePath, String JavaDoc fullPath)
573     {
574
575         // Check if the base path is the root path
576

577         if (basePath.length() == 0 || basePath.equals(DOS_SEPERATOR_STR))
578         {
579
580             // Return the full path, strip any leading seperator
581

582             if (fullPath.length() > 0 && fullPath.charAt(0) == DOS_SEPERATOR)
583                 return fullPath.substring(1);
584             return fullPath;
585         }
586
587         // Split the base and full paths into seperate components
588

589         String JavaDoc[] baseNames = splitAllPaths(basePath);
590         String JavaDoc[] fullNames = splitAllPaths(fullPath);
591
592         // Check that the full path is actually within the base path tree
593

594         if (baseNames != null && baseNames.length > 0 && fullNames != null && fullNames.length > 0
595                 && baseNames[0].equalsIgnoreCase(fullNames[0]) == false)
596             return null;
597
598         // Match the path names
599

600         int idx = 0;
601
602         while (idx < baseNames.length && idx < fullNames.length && baseNames[idx].equalsIgnoreCase(fullNames[idx]))
603             idx++;
604
605         // Build the relative path
606

607         StringBuffer JavaDoc relPath = new StringBuffer JavaDoc(128);
608
609         while (idx < fullNames.length)
610         {
611             relPath.append(fullNames[idx++]);
612             if (idx < fullNames.length)
613                 relPath.append(DOS_SEPERATOR);
614         }
615
616         // Return the relative path
617

618         return relPath.toString();
619     }
620 }
Popular Tags