001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    
019    package org.apache.hadoop.fs;
020    
021    import java.io.IOException;
022    import java.net.URI;
023    import java.net.URISyntaxException;
024    import java.util.regex.Pattern;
025    
026    import org.apache.avro.reflect.Stringable;
027    import org.apache.commons.lang.StringUtils;
028    import org.apache.hadoop.HadoopIllegalArgumentException;
029    import org.apache.hadoop.classification.InterfaceAudience;
030    import org.apache.hadoop.classification.InterfaceStability;
031    import org.apache.hadoop.conf.Configuration;
032    
033    /** Names a file or directory in a {@link FileSystem}.
034     * Path strings use slash as the directory separator.  A path string is
035     * absolute if it begins with a slash.
036     */
037    @Stringable
038    @InterfaceAudience.Public
039    @InterfaceStability.Stable
040    public class Path implements Comparable {
041    
042      /** The directory separator, a slash. */
043      public static final String SEPARATOR = "/";
044      public static final char SEPARATOR_CHAR = '/';
045      
046      public static final String CUR_DIR = ".";
047      
048      public static final boolean WINDOWS
049        = System.getProperty("os.name").startsWith("Windows");
050    
051      /**
052       *  Pre-compiled regular expressions to detect path formats.
053       */
054      private static final Pattern hasUriScheme =
055          Pattern.compile("^[a-zA-Z][a-zA-Z0-9+-.]+:");
056      private static final Pattern hasDriveLetterSpecifier =
057          Pattern.compile("^/?[a-zA-Z]:");
058    
059      private URI uri;                                // a hierarchical uri
060    
061      /**
062       * Pathnames with scheme and relative path are illegal.
063       * @param path to be checked
064       */
065      void checkNotSchemeWithRelative() {
066        if (toUri().isAbsolute() && !isUriPathAbsolute()) {
067          throw new HadoopIllegalArgumentException(
068              "Unsupported name: has scheme but relative path-part");
069        }
070      }
071    
072      void checkNotRelative() {
073        if (!isAbsolute() && toUri().getScheme() == null) {
074          throw new HadoopIllegalArgumentException("Path is relative");
075        }
076      }
077    
078      public static Path getPathWithoutSchemeAndAuthority(Path path) {
079        // This code depends on Path.toString() to remove the leading slash before
080        // the drive specification on Windows.
081        Path newPath = path.isUriPathAbsolute() ?
082          new Path(null, null, path.toUri().getPath()) :
083          path;
084        return newPath;
085      }
086    
087      /** Resolve a child path against a parent path. */
088      public Path(String parent, String child) {
089        this(new Path(parent), new Path(child));
090      }
091    
092      /** Resolve a child path against a parent path. */
093      public Path(Path parent, String child) {
094        this(parent, new Path(child));
095      }
096    
097      /** Resolve a child path against a parent path. */
098      public Path(String parent, Path child) {
099        this(new Path(parent), child);
100      }
101    
102      /** Resolve a child path against a parent path. */
103      public Path(Path parent, Path child) {
104        // Add a slash to parent's path so resolution is compatible with URI's
105        URI parentUri = parent.uri;
106        String parentPath = parentUri.getPath();
107        if (!(parentPath.equals("/") || parentPath.equals(""))) {
108          try {
109            parentUri = new URI(parentUri.getScheme(), parentUri.getAuthority(),
110                          parentUri.getPath()+"/", null, parentUri.getFragment());
111          } catch (URISyntaxException e) {
112            throw new IllegalArgumentException(e);
113          }
114        }
115        URI resolved = parentUri.resolve(child.uri);
116        initialize(resolved.getScheme(), resolved.getAuthority(),
117                   resolved.getPath(), resolved.getFragment());
118      }
119    
120      private void checkPathArg( String path ) throws IllegalArgumentException {
121        // disallow construction of a Path from an empty string
122        if ( path == null ) {
123          throw new IllegalArgumentException(
124              "Can not create a Path from a null string");
125        }
126        if( path.length() == 0 ) {
127           throw new IllegalArgumentException(
128               "Can not create a Path from an empty string");
129        }   
130      }
131      
132      /** Construct a path from a String.  Path strings are URIs, but with
133       * unescaped elements and some additional normalization. */
134      public Path(String pathString) throws IllegalArgumentException {
135        checkPathArg( pathString );
136        
137        // We can't use 'new URI(String)' directly, since it assumes things are
138        // escaped, which we don't require of Paths. 
139        
140        // add a slash in front of paths with Windows drive letters
141        if (hasWindowsDrive(pathString) && pathString.charAt(0) != '/') {
142          pathString = "/" + pathString;
143        }
144    
145        // parse uri components
146        String scheme = null;
147        String authority = null;
148    
149        int start = 0;
150    
151        // parse uri scheme, if any
152        int colon = pathString.indexOf(':');
153        int slash = pathString.indexOf('/');
154        if ((colon != -1) &&
155            ((slash == -1) || (colon < slash))) {     // has a scheme
156          scheme = pathString.substring(0, colon);
157          start = colon+1;
158        }
159    
160        // parse uri authority, if any
161        if (pathString.startsWith("//", start) &&
162            (pathString.length()-start > 2)) {       // has authority
163          int nextSlash = pathString.indexOf('/', start+2);
164          int authEnd = nextSlash > 0 ? nextSlash : pathString.length();
165          authority = pathString.substring(start+2, authEnd);
166          start = authEnd;
167        }
168    
169        // uri path is the rest of the string -- query & fragment not supported
170        String path = pathString.substring(start, pathString.length());
171    
172        initialize(scheme, authority, path, null);
173      }
174    
175      /**
176       * Construct a path from a URI
177       */
178      public Path(URI aUri) {
179        uri = aUri.normalize();
180      }
181      
182      /** Construct a Path from components. */
183      public Path(String scheme, String authority, String path) {
184        checkPathArg( path );
185        initialize(scheme, authority, path, null);
186      }
187    
188      private void initialize(String scheme, String authority, String path,
189          String fragment) {
190        try {
191          this.uri = new URI(scheme, authority, normalizePath(scheme, path), null, fragment)
192            .normalize();
193        } catch (URISyntaxException e) {
194          throw new IllegalArgumentException(e);
195        }
196      }
197    
198      /**
199       * Merge 2 paths such that the second path is appended relative to the first.
200       * The returned path has the scheme and authority of the first path.  On
201       * Windows, the drive specification in the second path is discarded.
202       * 
203       * @param path1 Path first path
204       * @param path2 Path second path, to be appended relative to path1
205       * @return Path merged path
206       */
207      public static Path mergePaths(Path path1, Path path2) {
208        String path2Str = path2.toUri().getPath();
209        if(hasWindowsDrive(path2Str)) {
210          path2Str = path2Str.substring(path2Str.indexOf(':')+1);
211        }
212        return new Path(path1 + path2Str);
213      }
214    
215      /**
216       * Normalize a path string to use non-duplicated forward slashes as
217       * the path separator and remove any trailing path separators.
218       * @param scheme Supplies the URI scheme. Used to deduce whether we
219       *               should replace backslashes or not.
220       * @param path Supplies the scheme-specific part
221       * @return Normalized path string.
222       */
223      private static String normalizePath(String scheme, String path) {
224        // Remove double forward slashes.
225        path = StringUtils.replace(path, "//", "/");
226    
227        // Remove backslashes if this looks like a Windows path. Avoid
228        // the substitution if it looks like a non-local URI.
229        if (WINDOWS &&
230            (hasWindowsDrive(path) ||
231             (scheme == null) ||
232             (scheme.isEmpty()) ||
233             (scheme.equals("file")))) {
234          path = StringUtils.replace(path, "\\", "/");
235        }
236        
237        // trim trailing slash from non-root path (ignoring windows drive)
238        int minLength = hasWindowsDrive(path) ? 4 : 1;
239        if (path.length() > minLength && path.endsWith("/")) {
240          path = path.substring(0, path.length()-1);
241        }
242        
243        return path;
244      }
245    
246      private static boolean hasWindowsDrive(String path) {
247        return (WINDOWS && hasDriveLetterSpecifier.matcher(path).find());
248      }
249    
250      /**
251       * Determine whether a given path string represents an absolute path on
252       * Windows. e.g. "C:/a/b" is an absolute path. "C:a/b" is not.
253       *
254       * @param pathString Supplies the path string to evaluate.
255       * @param slashed true if the given path is prefixed with "/".
256       * @return true if the supplied path looks like an absolute path with a Windows
257       * drive-specifier.
258       */
259      public static boolean isWindowsAbsolutePath(final String pathString,
260                                                  final boolean slashed) {
261        int start = (slashed ? 1 : 0);
262    
263        return
264            hasWindowsDrive(pathString) &&
265            pathString.length() >= (start + 3) &&
266            ((pathString.charAt(start + 2) == SEPARATOR_CHAR) ||
267              (pathString.charAt(start + 2) == '\\'));
268      }
269    
270      /** Convert this to a URI. */
271      public URI toUri() { return uri; }
272    
273      /** Return the FileSystem that owns this Path. */
274      public FileSystem getFileSystem(Configuration conf) throws IOException {
275        return FileSystem.get(this.toUri(), conf);
276      }
277    
278      /**
279       * Is an absolute path (ie a slash relative path part)
280       *  AND  a scheme is null AND  authority is null.
281       */
282      public boolean isAbsoluteAndSchemeAuthorityNull() {
283        return  (isUriPathAbsolute() && 
284            uri.getScheme() == null && uri.getAuthority() == null);
285      }
286      
287      /**
288       *  True if the path component (i.e. directory) of this URI is absolute.
289       */
290      public boolean isUriPathAbsolute() {
291        int start = hasWindowsDrive(uri.getPath()) ? 3 : 0;
292        return uri.getPath().startsWith(SEPARATOR, start);
293       }
294      
295      /** True if the path component of this URI is absolute. */
296      /**
297       * There is some ambiguity here. An absolute path is a slash
298       * relative name without a scheme or an authority.
299       * So either this method was incorrectly named or its
300       * implementation is incorrect. This method returns true
301       * even if there is a scheme and authority.
302       */
303      public boolean isAbsolute() {
304         return isUriPathAbsolute();
305      }
306    
307      /**
308       * @return true if and only if this path represents the root of a file system
309       */
310      public boolean isRoot() {
311        return getParent() == null;
312      }
313    
314      /** Returns the final component of this path.*/
315      public String getName() {
316        String path = uri.getPath();
317        int slash = path.lastIndexOf(SEPARATOR);
318        return path.substring(slash+1);
319      }
320    
321      /** Returns the parent of a path or null if at root. */
322      public Path getParent() {
323        String path = uri.getPath();
324        int lastSlash = path.lastIndexOf('/');
325        int start = hasWindowsDrive(path) ? 3 : 0;
326        if ((path.length() == start) ||               // empty path
327            (lastSlash == start && path.length() == start+1)) { // at root
328          return null;
329        }
330        String parent;
331        if (lastSlash==-1) {
332          parent = CUR_DIR;
333        } else {
334          int end = hasWindowsDrive(path) ? 3 : 0;
335          parent = path.substring(0, lastSlash==end?end+1:lastSlash);
336        }
337        return new Path(uri.getScheme(), uri.getAuthority(), parent);
338      }
339    
340      /** Adds a suffix to the final name in the path.*/
341      public Path suffix(String suffix) {
342        return new Path(getParent(), getName()+suffix);
343      }
344    
345      @Override
346      public String toString() {
347        // we can't use uri.toString(), which escapes everything, because we want
348        // illegal characters unescaped in the string, for glob processing, etc.
349        StringBuilder buffer = new StringBuilder();
350        if (uri.getScheme() != null) {
351          buffer.append(uri.getScheme());
352          buffer.append(":");
353        }
354        if (uri.getAuthority() != null) {
355          buffer.append("//");
356          buffer.append(uri.getAuthority());
357        }
358        if (uri.getPath() != null) {
359          String path = uri.getPath();
360          if (path.indexOf('/')==0 &&
361              hasWindowsDrive(path) &&                // has windows drive
362              uri.getScheme() == null &&              // but no scheme
363              uri.getAuthority() == null)             // or authority
364            path = path.substring(1);                 // remove slash before drive
365          buffer.append(path);
366        }
367        if (uri.getFragment() != null) {
368          buffer.append("#");
369          buffer.append(uri.getFragment());
370        }
371        return buffer.toString();
372      }
373    
374      @Override
375      public boolean equals(Object o) {
376        if (!(o instanceof Path)) {
377          return false;
378        }
379        Path that = (Path)o;
380        return this.uri.equals(that.uri);
381      }
382    
383      @Override
384      public int hashCode() {
385        return uri.hashCode();
386      }
387    
388      @Override
389      public int compareTo(Object o) {
390        Path that = (Path)o;
391        return this.uri.compareTo(that.uri);
392      }
393      
394      /** Return the number of elements in this path. */
395      public int depth() {
396        String path = uri.getPath();
397        int depth = 0;
398        int slash = path.length()==1 && path.charAt(0)=='/' ? -1 : 0;
399        while (slash != -1) {
400          depth++;
401          slash = path.indexOf(SEPARATOR, slash+1);
402        }
403        return depth;
404      }
405    
406      /**
407       *  Returns a qualified path object.
408       *  
409       *  Deprecated - use {@link #makeQualified(URI, Path)}
410       */
411      @Deprecated
412      public Path makeQualified(FileSystem fs) {
413        return makeQualified(fs.getUri(), fs.getWorkingDirectory());
414      }
415      
416      /** Returns a qualified path object. */
417      @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
418      public Path makeQualified(URI defaultUri, Path workingDir ) {
419        Path path = this;
420        if (!isAbsolute()) {
421          path = new Path(workingDir, this);
422        }
423    
424        URI pathUri = path.toUri();
425          
426        String scheme = pathUri.getScheme();
427        String authority = pathUri.getAuthority();
428        String fragment = pathUri.getFragment();
429    
430        if (scheme != null &&
431            (authority != null || defaultUri.getAuthority() == null))
432          return path;
433    
434        if (scheme == null) {
435          scheme = defaultUri.getScheme();
436        }
437    
438        if (authority == null) {
439          authority = defaultUri.getAuthority();
440          if (authority == null) {
441            authority = "";
442          }
443        }
444        
445        URI newUri = null;
446        try {
447          newUri = new URI(scheme, authority , 
448            normalizePath(scheme, pathUri.getPath()), null, fragment);
449        } catch (URISyntaxException e) {
450          throw new IllegalArgumentException(e);
451        }
452        return new Path(newUri);
453      }
454    }