src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java

Tue, 25 Oct 2011 10:48:05 -0700

author
jjg
date
Tue, 25 Oct 2011 10:48:05 -0700
changeset 1116
d830d28fc72e
parent 1111
d2cbb77469ed
child 1157
3809292620c9
permissions
-rw-r--r--

7104039: refactor/cleanup javac Paths class
Reviewed-by: mcimadamore

     1 /*
     2  * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.nio;
    28 import java.io.File;
    29 import java.io.IOException;
    30 import java.net.MalformedURLException;
    31 import java.net.URL;
    32 import java.nio.charset.Charset;
    33 import java.nio.file.Files;
    34 import java.nio.file.FileSystem;
    35 import java.nio.file.FileSystems;
    36 import java.nio.file.FileVisitOption;
    37 import java.nio.file.FileVisitResult;
    38 import java.nio.file.Path;
    39 import java.nio.file.SimpleFileVisitor;
    40 import java.nio.file.attribute.BasicFileAttributes;
    41 import java.util.ArrayList;
    42 import java.util.Arrays;
    43 import java.util.Collection;
    44 import java.util.Collections;
    45 import java.util.EnumSet;
    46 import java.util.HashMap;
    47 import java.util.Iterator;
    48 import java.util.LinkedHashSet;
    49 import java.util.Map;
    50 import java.util.Set;
    51 import javax.lang.model.SourceVersion;
    52 import javax.tools.FileObject;
    53 import javax.tools.JavaFileManager;
    54 import javax.tools.JavaFileObject;
    55 import javax.tools.JavaFileObject.Kind;
    56 import javax.tools.StandardLocation;
    58 import static java.nio.file.FileVisitOption.*;
    59 import static javax.tools.StandardLocation.*;
    61 import com.sun.tools.javac.util.BaseFileManager;
    62 import com.sun.tools.javac.util.Context;
    63 import com.sun.tools.javac.util.List;
    64 import com.sun.tools.javac.util.ListBuffer;
    66 import static com.sun.tools.javac.main.OptionName.*;
    69 // NOTE the imports carefully for this compilation unit.
    70 //
    71 // Path:  java.nio.file.Path -- the new NIO type for which this file manager exists
    72 //
    73 // Paths: com.sun.tools.javac.file.Paths -- legacy javac type for handling path options
    74 //      The other Paths (java.nio.file.Paths) is not used
    76 // NOTE this and related classes depend on new API in JDK 7.
    77 // This requires special handling while bootstrapping the JDK build,
    78 // when these classes might not yet have been compiled. To workaround
    79 // this, the build arranges to make stubs of these classes available
    80 // when compiling this and related classes. The set of stub files
    81 // is specified in make/build.properties.
    83 /**
    84  *  Implementation of PathFileManager: a JavaFileManager based on the use
    85  *  of java.nio.file.Path.
    86  *
    87  *  <p>Just as a Path is somewhat analagous to a File, so too is this
    88  *  JavacPathFileManager analogous to JavacFileManager, as it relates to the
    89  *  support of FileObjects based on File objects (i.e. just RegularFileObject,
    90  *  not ZipFileObject and its variants.)
    91  *
    92  *  <p>The default values for the standard locations supported by this file
    93  *  manager are the same as the default values provided by JavacFileManager --
    94  *  i.e. as determined by the javac.file.Paths class. To override these values,
    95  *  call {@link #setLocation}.
    96  *
    97  *  <p>To reduce confusion with Path objects, the locations such as "class path",
    98  *  "source path", etc, are generically referred to here as "search paths".
    99  *
   100  *  <p><b>This is NOT part of any supported API.
   101  *  If you write code that depends on this, you do so at your own risk.
   102  *  This code and its internal interfaces are subject to change or
   103  *  deletion without notice.</b>
   104  */
   105 public class JavacPathFileManager extends BaseFileManager implements PathFileManager {
   106     protected FileSystem defaultFileSystem;
   108     /**
   109      * Create a JavacPathFileManager using a given context, optionally registering
   110      * it as the JavaFileManager for that context.
   111      */
   112     public JavacPathFileManager(Context context, boolean register, Charset charset) {
   113         super(charset);
   114         if (register)
   115             context.put(JavaFileManager.class, this);
   116         pathsForLocation = new HashMap<Location, PathsForLocation>();
   117         fileSystems = new HashMap<Path,FileSystem>();
   118         setContext(context);
   119     }
   121     /**
   122      * Set the context for JavacPathFileManager.
   123      */
   124     @Override
   125     public void setContext(Context context) {
   126         super.setContext(context);
   127     }
   129     @Override
   130     public FileSystem getDefaultFileSystem() {
   131         if (defaultFileSystem == null)
   132             defaultFileSystem = FileSystems.getDefault();
   133         return defaultFileSystem;
   134     }
   136     @Override
   137     public void setDefaultFileSystem(FileSystem fs) {
   138         defaultFileSystem = fs;
   139     }
   141     @Override
   142     public void flush() throws IOException {
   143         contentCache.clear();
   144     }
   146     @Override
   147     public void close() throws IOException {
   148         for (FileSystem fs: fileSystems.values())
   149             fs.close();
   150     }
   152     @Override
   153     public ClassLoader getClassLoader(Location location) {
   154         nullCheck(location);
   155         Iterable<? extends Path> path = getLocation(location);
   156         if (path == null)
   157             return null;
   158         ListBuffer<URL> lb = new ListBuffer<URL>();
   159         for (Path p: path) {
   160             try {
   161                 lb.append(p.toUri().toURL());
   162             } catch (MalformedURLException e) {
   163                 throw new AssertionError(e);
   164             }
   165         }
   167         return getClassLoader(lb.toArray(new URL[lb.size()]));
   168     }
   170     @Override
   171     public boolean isDefaultBootClassPath() {
   172         return locations.isDefaultBootClassPath();
   173     }
   175     // <editor-fold defaultstate="collapsed" desc="Location handling">
   177     public boolean hasLocation(Location location) {
   178         return (getLocation(location) != null);
   179     }
   181     public Iterable<? extends Path> getLocation(Location location) {
   182         nullCheck(location);
   183         lazyInitSearchPaths();
   184         PathsForLocation path = pathsForLocation.get(location);
   185         if (path == null && !pathsForLocation.containsKey(location)) {
   186             setDefaultForLocation(location);
   187             path = pathsForLocation.get(location);
   188         }
   189         return path;
   190     }
   192     private Path getOutputLocation(Location location) {
   193         Iterable<? extends Path> paths = getLocation(location);
   194         return (paths == null ? null : paths.iterator().next());
   195     }
   197     public void setLocation(Location location, Iterable<? extends Path> searchPath)
   198             throws IOException
   199     {
   200         nullCheck(location);
   201         lazyInitSearchPaths();
   202         if (searchPath == null) {
   203             setDefaultForLocation(location);
   204         } else {
   205             if (location.isOutputLocation())
   206                 checkOutputPath(searchPath);
   207             PathsForLocation pl = new PathsForLocation();
   208             for (Path p: searchPath)
   209                 pl.add(p);  // TODO -Xlint:path warn if path not found
   210             pathsForLocation.put(location, pl);
   211         }
   212     }
   214     private void checkOutputPath(Iterable<? extends Path> searchPath) throws IOException {
   215         Iterator<? extends Path> pathIter = searchPath.iterator();
   216         if (!pathIter.hasNext())
   217             throw new IllegalArgumentException("empty path for directory");
   218         Path path = pathIter.next();
   219         if (pathIter.hasNext())
   220             throw new IllegalArgumentException("path too long for directory");
   221         if (!isDirectory(path))
   222             throw new IOException(path + ": not a directory");
   223     }
   225     private void setDefaultForLocation(Location locn) {
   226         Collection<File> files = null;
   227         if (locn instanceof StandardLocation) {
   228             switch ((StandardLocation) locn) {
   229                 case CLASS_PATH:
   230                     files = locations.userClassPath();
   231                     break;
   232                 case PLATFORM_CLASS_PATH:
   233                     files = locations.bootClassPath();
   234                     break;
   235                 case SOURCE_PATH:
   236                     files = locations.sourcePath();
   237                     break;
   238                 case CLASS_OUTPUT: {
   239                     String arg = options.get(D);
   240                     files = (arg == null ? null : Collections.singleton(new File(arg)));
   241                     break;
   242                 }
   243                 case SOURCE_OUTPUT: {
   244                     String arg = options.get(S);
   245                     files = (arg == null ? null : Collections.singleton(new File(arg)));
   246                     break;
   247                 }
   248             }
   249         }
   251         PathsForLocation pl = new PathsForLocation();
   252         if (files != null) {
   253             for (File f: files)
   254                 pl.add(f.toPath());
   255         }
   256         pathsForLocation.put(locn, pl);
   257     }
   259     private void lazyInitSearchPaths() {
   260         if (!inited) {
   261             setDefaultForLocation(PLATFORM_CLASS_PATH);
   262             setDefaultForLocation(CLASS_PATH);
   263             setDefaultForLocation(SOURCE_PATH);
   264             inited = true;
   265         }
   266     }
   267     // where
   268         private boolean inited = false;
   270     private Map<Location, PathsForLocation> pathsForLocation;
   272     private static class PathsForLocation extends LinkedHashSet<Path> {
   273         private static final long serialVersionUID = 6788510222394486733L;
   274     }
   276     // </editor-fold>
   278     // <editor-fold defaultstate="collapsed" desc="FileObject handling">
   280     @Override
   281     public Path getPath(FileObject fo) {
   282         nullCheck(fo);
   283         if (!(fo instanceof PathFileObject))
   284             throw new IllegalArgumentException();
   285         return ((PathFileObject) fo).getPath();
   286     }
   288     @Override
   289     public boolean isSameFile(FileObject a, FileObject b) {
   290         nullCheck(a);
   291         nullCheck(b);
   292         if (!(a instanceof PathFileObject))
   293             throw new IllegalArgumentException("Not supported: " + a);
   294         if (!(b instanceof PathFileObject))
   295             throw new IllegalArgumentException("Not supported: " + b);
   296         return ((PathFileObject) a).isSameFile((PathFileObject) b);
   297     }
   299     @Override
   300     public Iterable<JavaFileObject> list(Location location,
   301             String packageName, Set<Kind> kinds, boolean recurse)
   302             throws IOException {
   303         // validatePackageName(packageName);
   304         nullCheck(packageName);
   305         nullCheck(kinds);
   307         Iterable<? extends Path> paths = getLocation(location);
   308         if (paths == null)
   309             return List.nil();
   310         ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();
   312         for (Path path : paths)
   313             list(path, packageName, kinds, recurse, results);
   315         return results.toList();
   316     }
   318     private void list(Path path, String packageName, final Set<Kind> kinds,
   319             boolean recurse, final ListBuffer<JavaFileObject> results)
   320             throws IOException {
   321         if (!Files.exists(path))
   322             return;
   324         final Path pathDir;
   325         if (isDirectory(path))
   326             pathDir = path;
   327         else {
   328             FileSystem fs = getFileSystem(path);
   329             if (fs == null)
   330                 return;
   331             pathDir = fs.getRootDirectories().iterator().next();
   332         }
   333         String sep = path.getFileSystem().getSeparator();
   334         Path packageDir = packageName.isEmpty() ? pathDir
   335                 : pathDir.resolve(packageName.replace(".", sep));
   336         if (!Files.exists(packageDir))
   337             return;
   339 /* Alternate impl of list, superceded by use of Files.walkFileTree */
   340 //        Deque<Path> queue = new LinkedList<Path>();
   341 //        queue.add(packageDir);
   342 //
   343 //        Path dir;
   344 //        while ((dir = queue.poll()) != null) {
   345 //            DirectoryStream<Path> ds = dir.newDirectoryStream();
   346 //            try {
   347 //                for (Path p: ds) {
   348 //                    String name = p.getFileName().toString();
   349 //                    if (isDirectory(p)) {
   350 //                        if (recurse && SourceVersion.isIdentifier(name)) {
   351 //                            queue.add(p);
   352 //                        }
   353 //                    } else {
   354 //                        if (kinds.contains(getKind(name))) {
   355 //                            JavaFileObject fe =
   356 //                                PathFileObject.createDirectoryPathFileObject(this, p, pathDir);
   357 //                            results.append(fe);
   358 //                        }
   359 //                    }
   360 //                }
   361 //            } finally {
   362 //                ds.close();
   363 //            }
   364 //        }
   365         int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
   366         Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
   367         Files.walkFileTree(packageDir, opts, maxDepth,
   368                 new SimpleFileVisitor<Path>() {
   369             @Override
   370             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
   371                 Path name = dir.getFileName();
   372                 if (name == null || SourceVersion.isIdentifier(name.toString())) // JSR 292?
   373                     return FileVisitResult.CONTINUE;
   374                 else
   375                     return FileVisitResult.SKIP_SUBTREE;
   376             }
   378             @Override
   379             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
   380                 if (attrs.isRegularFile() && kinds.contains(getKind(file.getFileName().toString()))) {
   381                     JavaFileObject fe =
   382                         PathFileObject.createDirectoryPathFileObject(
   383                             JavacPathFileManager.this, file, pathDir);
   384                     results.append(fe);
   385                 }
   386                 return FileVisitResult.CONTINUE;
   387             }
   388         });
   389     }
   391     @Override
   392     public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(
   393         Iterable<? extends Path> paths) {
   394         ArrayList<PathFileObject> result;
   395         if (paths instanceof Collection<?>)
   396             result = new ArrayList<PathFileObject>(((Collection<?>)paths).size());
   397         else
   398             result = new ArrayList<PathFileObject>();
   399         for (Path p: paths)
   400             result.add(PathFileObject.createSimplePathFileObject(this, nullCheck(p)));
   401         return result;
   402     }
   404     @Override
   405     public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {
   406         return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths)));
   407     }
   409     @Override
   410     public JavaFileObject getJavaFileForInput(Location location,
   411             String className, Kind kind) throws IOException {
   412         return getFileForInput(location, getRelativePath(className, kind));
   413     }
   415     @Override
   416     public FileObject getFileForInput(Location location,
   417             String packageName, String relativeName) throws IOException {
   418         return getFileForInput(location, getRelativePath(packageName, relativeName));
   419     }
   421     private JavaFileObject getFileForInput(Location location, String relativePath)
   422             throws IOException {
   423         for (Path p: getLocation(location)) {
   424             if (isDirectory(p)) {
   425                 Path f = resolve(p, relativePath);
   426                 if (Files.exists(f))
   427                     return PathFileObject.createDirectoryPathFileObject(this, f, p);
   428             } else {
   429                 FileSystem fs = getFileSystem(p);
   430                 if (fs != null) {
   431                     Path file = getPath(fs, relativePath);
   432                     if (Files.exists(file))
   433                         return PathFileObject.createJarPathFileObject(this, file);
   434                 }
   435             }
   436         }
   437         return null;
   438     }
   440     @Override
   441     public JavaFileObject getJavaFileForOutput(Location location,
   442             String className, Kind kind, FileObject sibling) throws IOException {
   443         return getFileForOutput(location, getRelativePath(className, kind), sibling);
   444     }
   446     @Override
   447     public FileObject getFileForOutput(Location location, String packageName,
   448             String relativeName, FileObject sibling)
   449             throws IOException {
   450         return getFileForOutput(location, getRelativePath(packageName, relativeName), sibling);
   451     }
   453     private JavaFileObject getFileForOutput(Location location,
   454             String relativePath, FileObject sibling) {
   455         Path dir = getOutputLocation(location);
   456         if (dir == null) {
   457             if (location == CLASS_OUTPUT) {
   458                 Path siblingDir = null;
   459                 if (sibling != null && sibling instanceof PathFileObject) {
   460                     siblingDir = ((PathFileObject) sibling).getPath().getParent();
   461                 }
   462                 return PathFileObject.createSiblingPathFileObject(this,
   463                         siblingDir.resolve(getBaseName(relativePath)),
   464                         relativePath);
   465             } else if (location == SOURCE_OUTPUT) {
   466                 dir = getOutputLocation(CLASS_OUTPUT);
   467             }
   468         }
   470         Path file;
   471         if (dir != null) {
   472             file = resolve(dir, relativePath);
   473             return PathFileObject.createDirectoryPathFileObject(this, file, dir);
   474         } else {
   475             file = getPath(getDefaultFileSystem(), relativePath);
   476             return PathFileObject.createSimplePathFileObject(this, file);
   477         }
   479     }
   481     @Override
   482     public String inferBinaryName(Location location, JavaFileObject fo) {
   483         nullCheck(fo);
   484         // Need to match the path semantics of list(location, ...)
   485         Iterable<? extends Path> paths = getLocation(location);
   486         if (paths == null) {
   487             return null;
   488         }
   490         if (!(fo instanceof PathFileObject))
   491             throw new IllegalArgumentException(fo.getClass().getName());
   493         return ((PathFileObject) fo).inferBinaryName(paths);
   494     }
   496     private FileSystem getFileSystem(Path p) throws IOException {
   497         FileSystem fs = fileSystems.get(p);
   498         if (fs == null) {
   499             fs = FileSystems.newFileSystem(p, null);
   500             fileSystems.put(p, fs);
   501         }
   502         return fs;
   503     }
   505     private Map<Path,FileSystem> fileSystems;
   507     // </editor-fold>
   509     // <editor-fold defaultstate="collapsed" desc="Utility methods">
   511     private static String getRelativePath(String className, Kind kind) {
   512         return className.replace(".", "/") + kind.extension;
   513     }
   515     private static String getRelativePath(String packageName, String relativeName) {
   516         return packageName.replace(".", "/") + relativeName;
   517     }
   519     private static String getBaseName(String relativePath) {
   520         int lastSep = relativePath.lastIndexOf("/");
   521         return relativePath.substring(lastSep + 1); // safe if "/" not found
   522     }
   524     private static boolean isDirectory(Path path) throws IOException {
   525         BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
   526         return attrs.isDirectory();
   527     }
   529     private static Path getPath(FileSystem fs, String relativePath) {
   530         return fs.getPath(relativePath.replace("/", fs.getSeparator()));
   531     }
   533     private static Path resolve(Path base, String relativePath) {
   534         FileSystem fs = base.getFileSystem();
   535         Path rp = fs.getPath(relativePath.replace("/", fs.getSeparator()));
   536         return base.resolve(rp);
   537     }
   539     // </editor-fold>
   541 }

mercurial