Path: blob/master/src/java.compiler/share/classes/javax/tools/StandardJavaFileManager.java
41152 views
/*1* Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.tools;2627import java.io.File;28import java.io.IOException;29import java.nio.file.Path;30import java.util.ArrayList;31import java.util.Arrays;32import java.util.Collection;33import java.util.Iterator;34import java.util.List;3536/**37* File manager based on {@link File java.io.File} and {@link Path java.nio.file.Path}.38*39* A common way to obtain an instance of this class is using40* {@linkplain JavaCompiler#getStandardFileManager getStandardFileManager}, for example:41*42* <pre>43* JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();44* {@code DiagnosticCollector<JavaFileObject>} diagnostics =45* new {@code DiagnosticCollector<JavaFileObject>()};46* StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostics, null, null);47* </pre>48*49* This file manager creates file objects representing regular50* {@linkplain File files},51* {@linkplain java.util.zip.ZipEntry zip file entries}, or entries in52* similar file system based containers. Any file object returned53* from a file manager implementing this interface must observe the54* following behavior:55*56* <ul>57* <li>58* File names need not be canonical.59* </li>60* <li>61* For file objects representing regular files62* <ul>63* <li>64* the method <code>{@linkplain FileObject#delete()}</code>65* is equivalent to <code>{@linkplain File#delete()}</code>,66* </li>67* <li>68* the method <code>{@linkplain FileObject#getLastModified()}</code>69* is equivalent to <code>{@linkplain File#lastModified()}</code>,70* </li>71* <li>72* the methods <code>{@linkplain FileObject#getCharContent(boolean)}</code>,73* <code>{@linkplain FileObject#openInputStream()}</code>, and74* <code>{@linkplain FileObject#openReader(boolean)}</code>75* must succeed if the following would succeed (ignoring76* encoding issues):77* <blockquote>78* <pre>new {@linkplain java.io.FileInputStream#FileInputStream(File) FileInputStream}(new {@linkplain File#File(java.net.URI) File}({@linkplain FileObject fileObject}.{@linkplain FileObject#toUri() toUri}()))</pre>79* </blockquote>80* </li>81* <li>82* and the methods83* <code>{@linkplain FileObject#openOutputStream()}</code>, and84* <code>{@linkplain FileObject#openWriter()}</code> must85* succeed if the following would succeed (ignoring encoding86* issues):87* <blockquote>88* <pre>new {@linkplain java.io.FileOutputStream#FileOutputStream(File) FileOutputStream}(new {@linkplain File#File(java.net.URI) File}({@linkplain FileObject fileObject}.{@linkplain FileObject#toUri() toUri}()))</pre>89* </blockquote>90* </li>91* </ul>92* </li>93* <li>94* The {@linkplain java.net.URI URI} returned from95* <code>{@linkplain FileObject#toUri()}</code>96* <ul>97* <li>98* must be {@linkplain java.net.URI#isAbsolute() absolute} (have a schema), and99* </li>100* <li>101* must have a {@linkplain java.net.URI#normalize() normalized}102* {@linkplain java.net.URI#getPath() path component} which103* can be resolved without any process-specific context such104* as the current directory (file names must be absolute).105* </li>106* </ul>107* </li>108* </ul>109*110* According to these rules, the following URIs, for example, are111* allowed:112* <ul>113* <li>114* <code>file:///C:/Documents%20and%20Settings/UncleBob/BobsApp/Test.java</code>115* </li>116* <li>117* <code>jar:///C:/Documents%20and%20Settings/UncleBob/lib/vendorA.jar!/com/vendora/LibraryClass.class</code>118* </li>119* </ul>120* Whereas these are not (reason in parentheses):121* <ul>122* <li>123* <code>file:BobsApp/Test.java</code> (the file name is relative124* and depend on the current directory)125* </li>126* <li>127* <code>jar:lib/vendorA.jar!/com/vendora/LibraryClass.class</code>128* (the first half of the path depends on the current directory,129* whereas the component after ! is legal)130* </li>131* <li>132* <code>Test.java</code> (this URI depends on the current133* directory and does not have a schema)134* </li>135* <li>136* <code>jar:///C:/Documents%20and%20Settings/UncleBob/BobsApp/../lib/vendorA.jar!com/vendora/LibraryClass.class</code>137* (the path is not normalized)138* </li>139* </ul>140*141* <p>All implementations of this interface must support Path objects representing142* files in the {@linkplain java.nio.file.FileSystems#getDefault() default file system.}143* It is recommended that implementations should support Path objects from any filesystem.</p>144*145*146* @apiNote147* Some methods on this interface take a {@code Collection<? extends Path>}148* instead of {@code Iterable<? extends Path>}.149* This is to prevent the possibility of accidentally calling the method150* with a single {@code Path} as such an argument, because although151* {@code Path} implements {@code Iterable<Path>}, it would almost never be152* correct to call these methods with a single {@code Path} and have it be treated as153* an {@code Iterable} of its components.154*155*156* @author Peter von der Ahé157* @since 1.6158*/159public interface StandardJavaFileManager extends JavaFileManager {160161/**162* Compares two file objects and return true if they represent the163* same canonical file, zip file entry, or entry in any file164* system based container.165*166* @param a a file object167* @param b a file object168* @return true if the given file objects represent the same169* canonical file, zip file entry or path; false otherwise170*171* @throws IllegalArgumentException if either of the arguments172* were created with another file manager implementation173*/174@Override175boolean isSameFile(FileObject a, FileObject b);176177/**178* Returns file objects representing the given files.179*180* @param files a list of files181* @return a list of file objects182* @throws IllegalArgumentException if the list of files includes183* a directory184*/185Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(186Iterable<? extends File> files);187188/**189* Returns file objects representing the given paths.190*191* @implSpec192* The default implementation converts each path to a file and calls193* {@link #getJavaFileObjectsFromFiles getJavaObjectsFromFiles}.194* IllegalArgumentException will be thrown if any of the paths195* cannot be converted to a file.196*197* @param paths a list of paths198* @return a list of file objects199* @throws IllegalArgumentException if the list of paths includes200* a directory or if this file manager does not support any of the201* given paths.202*203* @since 13204*/205default Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(206Collection<? extends Path> paths) {207return getJavaFileObjectsFromFiles(asFiles(paths));208}209210/**211* Returns file objects representing the given paths.212*213* @implSpec214* The default implementation converts each path to a file and calls215* {@link #getJavaFileObjectsFromFiles getJavaObjectsFromFiles}.216* IllegalArgumentException will be thrown if any of the paths217* cannot be converted to a file.218*219* @param paths a list of paths220* @return a list of file objects221* @throws IllegalArgumentException if the list of paths includes222* a directory or if this file manager does not support any of the223* given paths.224*225* @since 9226* @deprecated use {@link #getJavaFileObjectsFromPaths(Collection)} instead,227* to prevent the possibility of accidentally calling the method with a228* single {@code Path} as such an argument. Although {@code Path} implements229* {@code Iterable<Path>}, it would almost never be correct to pass a single230* {@code Path} and have it be treated as an {@code Iterable} of its231* components.232*/233@Deprecated(since = "13")234default Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(235Iterable<? extends Path> paths) {236return getJavaFileObjectsFromPaths(asCollection(paths));237}238239/**240* Returns file objects representing the given files.241* Convenience method equivalent to:242*243* <pre>244* getJavaFileObjectsFromFiles({@linkplain java.util.Arrays#asList Arrays.asList}(files))245* </pre>246*247* @param files an array of files248* @return a list of file objects249* @throws IllegalArgumentException if the array of files includes250* a directory251* @throws NullPointerException if the given array contains null252* elements253*/254Iterable<? extends JavaFileObject> getJavaFileObjects(File... files);255256/**257* Returns file objects representing the given paths.258* Convenience method equivalent to:259*260* <pre>261* getJavaFileObjectsFromPaths({@linkplain java.util.Arrays#asList Arrays.asList}(paths))262* </pre>263*264* @param paths an array of paths265* @return a list of file objects266* @throws IllegalArgumentException if the array of files includes267* a directory268* @throws NullPointerException if the given array contains null269* elements270*271* @since 9272*/273default Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {274return getJavaFileObjectsFromPaths(Arrays.asList(paths));275}276277/**278* Returns file objects representing the given file names.279*280* @param names a list of file names281* @return a list of file objects282* @throws IllegalArgumentException if the list of file names283* includes a directory284*/285Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(286Iterable<String> names);287288/**289* Returns file objects representing the given file names.290* Convenience method equivalent to:291*292* <pre>293* getJavaFileObjectsFromStrings({@linkplain java.util.Arrays#asList Arrays.asList}(names))294* </pre>295*296* @param names a list of file names297* @return a list of file objects298* @throws IllegalArgumentException if the array of file names299* includes a directory300* @throws NullPointerException if the given array contains null301* elements302*/303Iterable<? extends JavaFileObject> getJavaFileObjects(String... names);304305/**306* Associates the given search path with the given location. Any307* previous value will be discarded.308*309* If the location is a module-oriented or output location, any module-specific310* associations set up by {@linkplain #setLocationForModule setLocationForModule}311* will be cancelled.312*313* @param location a location314* @param files a list of files, if {@code null} use the default315* search path for this location316* @see #getLocation317* @throws IllegalArgumentException if {@code location} is an output318* location and {@code files} does not contain exactly one element319* @throws IOException if {@code location} is an output location and320* does not represent an existing directory321*/322void setLocation(Location location, Iterable<? extends File> files)323throws IOException;324325/**326* Associates the given search path with the given location.327* Any previous value will be discarded.328*329* If the location is a module-oriented or output location, any module-specific330* associations set up by {@linkplain #setLocationForModule setLocationForModule}331* will be cancelled.332*333* @implSpec334* The default implementation converts each path to a file and calls335* {@link #getJavaFileObjectsFromFiles getJavaObjectsFromFiles}.336* {@linkplain IllegalArgumentException IllegalArgumentException}337* will be thrown if any of the paths cannot be converted to a file.338*339* @param location a location340* @param paths a list of paths, if {@code null} use the default341* search path for this location342* @see #getLocation343* @throws IllegalArgumentException if {@code location} is an output344* location and {@code paths} does not contain exactly one element345* or if this file manager does not support any of the given paths346* @throws IOException if {@code location} is an output location and347* {@code paths} does not represent an existing directory348*349* @since 9350*/351default void setLocationFromPaths(Location location, Collection<? extends Path> paths)352throws IOException {353setLocation(location, asFiles(paths));354}355356/**357* Associates the given search path with the given module and location,358* which must be a module-oriented or output location.359* Any previous value will be discarded.360* This overrides any default association derived from the search path361* associated with the location itself.362*363* All such module-specific associations will be cancelled if a364* new search path is associated with the location by calling365* {@linkplain #setLocation setLocation} or366* {@linkplain #setLocationFromPaths setLocationFromPaths}.367*368* @throws IllegalStateException if the location is not a module-oriented369* or output location.370* @throws UnsupportedOperationException if this operation is not supported by371* this file manager.372* @throws IOException if {@code location} is an output location and373* {@code paths} does not represent an existing directory374*375* @param location the location376* @param moduleName the name of the module377* @param paths the search path to associate with the location and module.378*379* @see #setLocation380* @see #setLocationFromPaths381*382* @since 9383*/384default void setLocationForModule(Location location, String moduleName,385Collection<? extends Path> paths) throws IOException {386throw new UnsupportedOperationException();387}388389/**390* Returns the search path associated with the given location.391*392* @param location a location393* @return a list of files or {@code null} if this location has no394* associated search path395* @throws IllegalStateException if any element of the search path396* cannot be converted to a {@linkplain File}, or if the search path397* cannot be represented as a simple series of files.398*399* @see #setLocation400* @see Path#toFile401*/402Iterable<? extends File> getLocation(Location location);403404/**405* Returns the search path associated with the given location.406*407* @implSpec408* The default implementation calls {@link #getLocation getLocation}409* and then returns an {@code Iterable} formed by calling {@code toPath()}410* on each {@code File} returned from {@code getLocation}.411*412* @param location a location413* @return a list of paths or {@code null} if this location has no414* associated search path415* @throws IllegalStateException if the search path cannot be represented416* as a simple series of paths.417*418* @see #setLocationFromPaths419* @since 9420*/421default Iterable<? extends Path> getLocationAsPaths(Location location) {422return asPaths(getLocation(location));423}424425/**426* Returns the path, if any, underlying this file object (optional operation).427* File objects derived from a {@link java.nio.file.FileSystem FileSystem},428* including the default file system, typically have a corresponding underlying429* {@link java.nio.file.Path Path} object. In such cases, this method may be430* used to access that object.431*432* @implSpec433* The default implementation throws {@link UnsupportedOperationException}434* for all files.435*436* @param file a file object437* @return a path representing the same underlying file system artifact438* @throws IllegalArgumentException if the file object does not have an underlying path439* @throws UnsupportedOperationException if the operation is not supported by this file manager440*441* @since 9442*/443default Path asPath(FileObject file) {444throw new UnsupportedOperationException();445}446447/**448* Factory to create {@code Path} objects from strings.449*450* @since 9451*/452interface PathFactory {453/**454* Converts a path string, or a sequence of strings that when joined form a path string, to a Path.455*456* @param first the path string or initial part of the path string457* @param more additional strings to be joined to form the path string458* @return the resulting {@code Path}459*/460Path getPath(String first, String... more);461}462463/**464* Specify a factory that can be used to generate a path from a string, or series of strings.465*466* If this method is not called, a factory whose {@code getPath} method is467* equivalent to calling468* {@link java.nio.file.Paths#get(String, String...) java.nio.file.Paths.get(first, more)}469* will be used.470*471* @implSpec472* The default implementation of this method ignores the factory that is provided.473*474* @param f the factory475*476* @since 9477*/478default void setPathFactory(PathFactory f) { }479480481private static Iterable<Path> asPaths(final Iterable<? extends File> files) {482return () -> new Iterator<>() {483final Iterator<? extends File> iter = files.iterator();484485@Override486public boolean hasNext() {487return iter.hasNext();488}489490@Override491public Path next() {492return iter.next().toPath();493}494};495}496497private static Iterable<File> asFiles(final Iterable<? extends Path> paths) {498return () -> new Iterator<>() {499final Iterator<? extends Path> iter = paths.iterator();500501@Override502public boolean hasNext() {503return iter.hasNext();504}505506@Override507public File next() {508Path p = iter.next();509try {510return p.toFile();511} catch (UnsupportedOperationException e) {512throw new IllegalArgumentException(p.toString(), e);513}514}515};516}517518private static <T> Collection<T> asCollection(Iterable<T> iterable) {519if (iterable instanceof Collection) {520return (Collection<T>) iterable;521}522List<T> result = new ArrayList<>();523for (T item : iterable) result.add(item);524return result;525}526}527528529