OSDN Git Service

Initial revision
[pf3gnuchains/gcc-fork.git] / libjava / classpath / gnu / java / io / PlatformHelper.java
1 /* PlatformHelper.java -- Isolate OS-specific IO helper methods and variables
2    Copyright (C) 1998, 2002 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10  
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING.  If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
20
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version. */
37
38 package gnu.java.io;
39
40 import java.util.StringTokenizer;
41
42 /**
43  * We had many changes in File.java, URLStreamHandler.java etc. to handle
44  * path representations on different platforms (Windows/Unix-family).
45  * Finally we'd like to collect all these ad hoc codes into this utility class.
46  *       --Gansha
47  */
48 public class PlatformHelper
49 {
50   public static final boolean isWindows = System.getProperty("os.name").indexOf("Windows") >= 0;
51   public static final String separator = System.getProperty("file.separator");
52   public static final char separatorChar = separator.charAt(0);
53   public static final String pathSeparator = System.getProperty("path.separator");
54   public static final char pathSeparatorChar = pathSeparator.charAt(0);
55
56   /**
57    * On most platforms 260 is equal or greater than a max path value, 
58    * so we can set the initial buffer size of StringBuffer to half of this value
59    * to improve performance.
60    */
61   public static final int INITIAL_MAX_PATH = 260/2;
62
63   /**
64    * This routine checks the input param "path" whether it begins with root path
65    * prefix.
66    * if not, return 0;
67    * if yes, return the len of root path prefix;
68    *   --for Unix-family platform, root path begins with "/" and len is 1
69    *   --for Windows platform, root path begins with "drive:\\" and len is 3
70    */
71   public static final int beginWithRootPathPrefix(String path)
72   {
73     if (path.startsWith("/") || path.startsWith("\\"))
74       return 1;
75
76     if (!isWindows)
77       return 0;
78
79     if (path.length() > 2
80         && Character.isLetter(path.charAt(0))
81         && path.charAt(1) == ':'
82         && (path.charAt(2) == '/' || path.charAt(2) == '\\'))
83       return 3;
84
85     return 0;
86   }
87
88   /**
89    * This routine checks the input param "path" whether it's root directory.
90    *  --for Unix-family platform, root directory is "/"
91    *  --for Windows platform, root directory is "\\" or "drive:\\".
92    */
93   public static final boolean isRootDirectory(String path)
94   {
95     int len = path.length();
96     return len > 0 && beginWithRootPathPrefix(path) == len;
97   }
98
99   /**
100    * This routine canonicalizes input param "path" to formal path representation
101    *  for current platform, including interpreting ".." and "." .
102    */
103   public static final String toCanonicalForm(String path)
104   {
105     /*??
106     if(path.indexOf('.') < 0 && path.indexOf("..") < 0)
107         return path; 
108     */
109     String tmppath = path.replace('/', separatorChar);
110     StringBuffer canonpath;
111
112     // We found it'll be more efficient and easy to handle to
113     // return a lowercased canonical path
114     if(isWindows)
115       tmppath = tmppath.toLowerCase();
116
117     int i;
118
119     if ((i = beginWithRootPathPrefix(tmppath)) == 0 )
120       return path;
121     
122     /* The original 
123            "canonpath = new StringBuffer(tmppath.substring(0, i))"
124        isn't very efficient because StringBuffer's 
125        ensureCapacity_unsynchronized will fail definitely each time 
126        and will enlarge buffer and copy contents.       .
127     */
128     canonpath = new StringBuffer(INITIAL_MAX_PATH);
129     canonpath.append(tmppath.substring(0, i));
130     tmppath = tmppath.substring(i);
131     // pathdepth==0 indicates there're only root path in the buffer
132     int pathdepth = 0;
133     
134     StringTokenizer st = new StringTokenizer(tmppath, separator);
135     
136     // Traverse each element of the path, handling "." and ".."
137     // Should handle "~" too?
138     if (st.hasMoreTokens())
139       do
140         {
141           String s = st.nextToken();
142         
143           // Handle "." or an empty element.  
144           if (s.equals(".") || s.equals(""))
145             continue;
146         
147           // Handle ".." by deleting the last element from the path
148           if (s.equals(".."))
149             {
150               if (pathdepth == 0)
151                 continue;
152
153               // Strip of trailing separator
154               canonpath.setLength(canonpath.length() - 1/*separator.length()*/);
155               String tmpstr = canonpath.toString();
156               int idx = tmpstr.lastIndexOf(separator); 
157
158               if ((idx == -1) || ((idx + 1/*separator.length()*/) > tmpstr.length()))
159                 //throw new IOException("Can't happen error"); 
160                 return path; // Shouldn't happen 
161         
162               canonpath.setLength(idx + 1/*separator.length()*/);
163               pathdepth--;
164               continue;
165             }
166         
167           canonpath.append(s);
168           pathdepth++; //now it's more than root path
169
170           if (st.hasMoreTokens())
171             canonpath.append(separator);
172         }
173       while (st.hasMoreTokens());
174     
175     if (endWithSeparator(path))
176       canonpath.append(separator);
177         
178     String tmpstr = canonpath.toString();
179     //if (pathdepth > 0 && endWithSeparator(tmpstr) )
180     //    tmpstr = tmpstr.substring(0, tmpstr.length() - 1/*separator.length()*/);
181     
182     return tmpstr;
183   }
184
185   /**
186    * This routine canonicalizes input param "path" to formal path representation
187    *  for current platform, and normalize all separators to "sepchar".
188    */
189   public static final String toCanonicalForm(String path, char sepchar)
190   {
191     String tmpstr = toCanonicalForm(path);
192     tmpstr = tmpstr.replace(separatorChar, sepchar);
193     return tmpstr;
194   }
195
196   /**
197    * This routine checks whether input param "path" ends with separator
198    */
199   public static final boolean endWithSeparator(String path)
200   {
201     if (path.endsWith("\\") || path.endsWith("/"))
202       return true;
203
204     return false;
205   }
206
207   /**
208    * This routine removes from input param "path" the tail separator if it exists, 
209    * and return the remain part.
210    */
211   public static final String removeTailSeparator(String path)
212   {
213     if (endWithSeparator(path) && !isRootDirectory(path))
214       return path.substring(0, path.length() - 1);
215
216     return path;
217   }
218
219   /**
220    * This routine returns last index of separator in input param "path", 
221    * and return it.
222    */
223   public static final int lastIndexOfSeparator(String path)
224   {
225     return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
226   }
227
228 }