PathFileObject.java revision 4144:b8a35541a048
1/*
2 * Copyright (c) 2009, 2017, 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 */
25
26package com.sun.tools.javac.file;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.io.InputStreamReader;
31import java.io.OutputStream;
32import java.io.OutputStreamWriter;
33import java.io.Reader;
34import java.io.Writer;
35import java.net.URI;
36import java.net.URISyntaxException;
37import java.nio.ByteBuffer;
38import java.nio.CharBuffer;
39import java.nio.charset.CharsetDecoder;
40import java.nio.file.FileSystem;
41import java.nio.file.FileSystems;
42import java.nio.file.Files;
43import java.nio.file.LinkOption;
44import java.nio.file.Path;
45import java.text.Normalizer;
46import java.util.Objects;
47
48import javax.lang.model.element.Modifier;
49import javax.lang.model.element.NestingKind;
50import javax.tools.FileObject;
51import javax.tools.JavaFileObject;
52
53import com.sun.tools.javac.file.RelativePath.RelativeFile;
54import com.sun.tools.javac.util.DefinedBy;
55import com.sun.tools.javac.util.DefinedBy.Api;
56
57
58/**
59 *  Implementation of JavaFileObject using java.nio.file API.
60 *
61 *  <p>PathFileObjects are, for the most part, straightforward wrappers around
62 *  immutable absolute Path objects. Different subtypes are used to provide
63 *  specialized implementations of "inferBinaryName" and "getName" that capture
64 *  additional information available at the time the object is created.
65 *
66 *  <p>In general, {@link JavaFileManager#isSameFile} should be used to
67 *  determine whether two file objects refer to the same file on disk.
68 *  PathFileObject also supports the standard {@code equals} and {@code hashCode}
69 *  methods, primarily for convenience when working with collections.
70 *  All of these operations delegate to the equivalent operations on the
71 *  underlying Path object.
72 *
73 *  <p><b>This is NOT part of any supported API.
74 *  If you write code that depends on this, you do so at your own risk.
75 *  This code and its internal interfaces are subject to change or
76 *  deletion without notice.</b>
77 */
78public abstract class PathFileObject implements JavaFileObject {
79    private static final FileSystem defaultFileSystem = FileSystems.getDefault();
80    private static final boolean isMacOS = System.getProperty("os.name", "").contains("OS X");
81
82    protected final BaseFileManager fileManager;
83    protected final Path path;
84    private boolean hasParents;
85
86    /**
87     * Create a PathFileObject for a file within a directory, such that the
88     * binary name can be inferred from the relationship to an enclosing directory.
89     *
90     * The binary name is derived from {@code relativePath}.
91     * The name is derived from the composition of {@code userPackageRootDir}
92     * and {@code relativePath}.
93     *
94     * @param fileManager the file manager creating this file object
95     * @param path the absolute path referred to by this file object
96     * @param userPackageRootDir the path of the directory containing the
97     *          root of the package hierarchy
98     * @param relativePath the path of this file relative to {@code userPackageRootDir}
99     */
100    static PathFileObject forDirectoryPath(BaseFileManager fileManager, Path path,
101            Path userPackageRootDir, RelativePath relativePath) {
102        return new DirectoryFileObject(fileManager, path, userPackageRootDir, relativePath);
103    }
104
105    private static class DirectoryFileObject extends PathFileObject {
106        private final Path userPackageRootDir;
107        private final RelativePath relativePath;
108
109        private DirectoryFileObject(BaseFileManager fileManager, Path path,
110                Path userPackageRootDir, RelativePath relativePath) {
111            super(fileManager, path);
112            this.userPackageRootDir = Objects.requireNonNull(userPackageRootDir);
113            this.relativePath = relativePath;
114        }
115
116        @Override @DefinedBy(Api.COMPILER)
117        public String getName() {
118            return relativePath.resolveAgainst(userPackageRootDir).toString();
119        }
120
121        @Override
122        public String inferBinaryName(Iterable<? extends Path> paths) {
123            return toBinaryName(relativePath);
124        }
125
126        @Override
127        public String toString() {
128            return "DirectoryFileObject[" + userPackageRootDir + ":" + relativePath.path + "]";
129        }
130
131        @Override
132        PathFileObject getSibling(String baseName) {
133            return new DirectoryFileObject(fileManager,
134                    path.resolveSibling(baseName),
135                    userPackageRootDir,
136                    new RelativeFile(relativePath.dirname(), baseName)
137            );
138        }
139    }
140
141    /**
142     * Create a PathFileObject for a file in a file system such as a jar file,
143     * such that the binary name can be inferred from its position within the
144     * file system.
145     *
146     * The binary name is derived from {@code path}.
147     * The name is derived from the composition of {@code userJarPath}
148     * and {@code path}.
149     *
150     * @param fileManager the file manager creating this file object
151     * @param path the path referred to by this file object
152     * @param userJarPath the path of the jar file containing the file system.
153     * @return the file object
154     */
155    public static PathFileObject forJarPath(BaseFileManager fileManager,
156            Path path, Path userJarPath) {
157        return new JarFileObject(fileManager, path, userJarPath);
158    }
159
160    private static class JarFileObject extends PathFileObject {
161        private final Path userJarPath;
162
163        private JarFileObject(BaseFileManager fileManager, Path path, Path userJarPath) {
164            super(fileManager, path);
165            this.userJarPath = userJarPath;
166        }
167
168        @Override @DefinedBy(Api.COMPILER)
169        public String getName() {
170            // The use of ( ) to delimit the entry name is not ideal
171            // but it does match earlier behavior
172            return userJarPath + "(" + path + ")";
173        }
174
175        @Override
176        public String inferBinaryName(Iterable<? extends Path> paths) {
177            Path root = path.getFileSystem().getRootDirectories().iterator().next();
178            return toBinaryName(root.relativize(path));
179        }
180
181        @Override @DefinedBy(Api.COMPILER)
182        public URI toUri() {
183            // Work around bug JDK-8134451:
184            // path.toUri() returns double-encoded URIs, that cannot be opened by URLConnection
185            return createJarUri(userJarPath, path.toString());
186        }
187
188        @Override
189        public String toString() {
190            return "JarFileObject[" + userJarPath + ":" + path + "]";
191        }
192
193        @Override
194        PathFileObject getSibling(String baseName) {
195            return new JarFileObject(fileManager,
196                    path.resolveSibling(baseName),
197                    userJarPath
198            );
199        }
200
201        private static URI createJarUri(Path jarFile, String entryName) {
202            URI jarURI = jarFile.toUri().normalize();
203            String separator = entryName.startsWith("/") ? "!" : "!/";
204            try {
205                // The jar URI convention appears to be not to re-encode the jarURI
206                return new URI("jar:" + jarURI + separator + entryName);
207            } catch (URISyntaxException e) {
208                throw new CannotCreateUriError(jarURI + separator + entryName, e);
209            }
210        }
211    }
212
213    /**
214     * Create a PathFileObject for a file in a modular file system, such as jrt:,
215     * such that the binary name can be inferred from its position within the
216     * filesystem.
217     *
218     * The binary name is derived from {@code path}, ignoring the first two
219     * elements of the name (which are "modules" and a module name).
220     * The name is derived from {@code path}.
221     *
222     * @param fileManager the file manager creating this file object
223     * @param path the path referred to by this file object
224     * @return the file object
225     */
226    public static PathFileObject forJRTPath(BaseFileManager fileManager,
227            final Path path) {
228        return new JRTFileObject(fileManager, path);
229    }
230
231    private static class JRTFileObject extends PathFileObject {
232        // private final Path javaHome;
233        private JRTFileObject(BaseFileManager fileManager, Path path) {
234            super(fileManager, path);
235        }
236
237        @Override @DefinedBy(Api.COMPILER)
238        public String getName() {
239            return path.toString();
240        }
241
242        @Override
243        public String inferBinaryName(Iterable<? extends Path> paths) {
244            // use subpath to ignore the leading /modules/MODULE-NAME
245            return toBinaryName(path.subpath(2, path.getNameCount()));
246        }
247
248        @Override
249        public String toString() {
250            return "JRTFileObject[" + path + "]";
251        }
252
253        @Override
254        PathFileObject getSibling(String baseName) {
255            return new JRTFileObject(fileManager,
256                    path.resolveSibling(baseName)
257            );
258        }
259    }
260
261    /**
262     * Create a PathFileObject for a file whose binary name must be inferred
263     * from its position on a search path.
264     *
265     * The binary name is inferred by finding an enclosing directory in
266     * the sequence of paths associated with the location given to
267     * {@link JavaFileManager#inferBinaryName).
268     * The name is derived from {@code userPath}.
269     *
270     * @param fileManager the file manager creating this file object
271     * @param path the path referred to by this file object
272     * @param userPath the "user-friendly" name for this path.
273     */
274    static PathFileObject forSimplePath(BaseFileManager fileManager,
275            Path path, Path userPath) {
276        return new SimpleFileObject(fileManager, path, userPath);
277    }
278
279    private static class SimpleFileObject extends PathFileObject {
280        private final Path userPath;
281        private SimpleFileObject(BaseFileManager fileManager, Path path, Path userPath) {
282            super(fileManager, path);
283            this.userPath = userPath;
284        }
285
286        @Override @DefinedBy(Api.COMPILER)
287        public String getName() {
288            return userPath.toString();
289        }
290
291        @Override
292        public String inferBinaryName(Iterable<? extends Path> paths) {
293            Path absPath = path.toAbsolutePath();
294            for (Path p: paths) {
295                Path ap = p.toAbsolutePath();
296                if (absPath.startsWith(ap)) {
297                    try {
298                        Path rp = ap.relativize(absPath);
299                        if (rp != null) // maybe null if absPath same as ap
300                            return toBinaryName(rp);
301                    } catch (IllegalArgumentException e) {
302                        // ignore this p if cannot relativize path to p
303                    }
304                }
305            }
306            return null;
307        }
308
309        @Override @DefinedBy(Api.COMPILER)
310        public Kind getKind() {
311            return BaseFileManager.getKind(userPath);
312        }
313
314        @Override @DefinedBy(Api.COMPILER)
315        public boolean isNameCompatible(String simpleName, Kind kind) {
316            return isPathNameCompatible(userPath, simpleName, kind);
317        }
318
319        @Override
320        PathFileObject getSibling(String baseName) {
321            return new SimpleFileObject(fileManager,
322                    path.resolveSibling(baseName),
323                    userPath.resolveSibling(baseName)
324            );
325        }
326    }
327
328    /**
329     * Create a PathFileObject, for a specified path, in the context of
330     * a given file manager.
331     *
332     * In general, this path should be an
333     * {@link Path#toAbsolutePath absolute path}, if not a
334     * {@link Path#toRealPath} real path.
335     * It will be used as the basis of {@code equals}, {@code hashCode}
336     * and {@code isSameFile} methods on this file object.
337     *
338     * A PathFileObject should also have a "friendly name" per the
339     * specification for {@link FileObject#getName}. The friendly name
340     * is provided by the various subtypes of {@code PathFileObject}.
341     *
342     * @param fileManager the file manager creating this file object
343     * @param path the path contained in this file object.
344     */
345    protected PathFileObject(BaseFileManager fileManager, Path path) {
346        this.fileManager = Objects.requireNonNull(fileManager);
347        if (Files.isDirectory(path)) {
348            throw new IllegalArgumentException("directories not supported");
349        }
350        this.path = path;
351    }
352
353    /**
354     * See {@link JavacFileManager#inferBinaryName}.
355     */
356    abstract String inferBinaryName(Iterable<? extends Path> paths);
357
358    /**
359     * Return the file object for a sibling file with a given file name.
360     * See {@link JavacFileManager#getFileForOutput} and
361     * {@link JavacFileManager#getJavaFileForOutput}.
362     */
363    abstract PathFileObject getSibling(String basename);
364
365    /**
366     * Return the Path for this object.
367     * @return the Path for this object.
368     * @see StandardJavaFileManager#asPath
369     */
370    public Path getPath() {
371        return path;
372    }
373
374    /**
375     * The short name is used when generating raw diagnostics.
376     * @return the last component of the path
377     */
378    public String getShortName() {
379        return path.getFileName().toString();
380    }
381
382    @Override @DefinedBy(Api.COMPILER)
383    public Kind getKind() {
384        return BaseFileManager.getKind(path);
385    }
386
387    @Override @DefinedBy(Api.COMPILER)
388    public boolean isNameCompatible(String simpleName, Kind kind) {
389        return isPathNameCompatible(path, simpleName, kind);
390    }
391
392    protected boolean isPathNameCompatible(Path p, String simpleName, Kind kind) {
393        Objects.requireNonNull(simpleName);
394        Objects.requireNonNull(kind);
395
396        if (kind == Kind.OTHER && BaseFileManager.getKind(p) != kind) {
397            return false;
398        }
399
400        String sn = simpleName + kind.extension;
401        String pn = p.getFileName().toString();
402        if (pn.equals(sn)) {
403            return true;
404        }
405
406        if (p.getFileSystem() == defaultFileSystem) {
407            if (isMacOS) {
408                if (Normalizer.isNormalized(pn, Normalizer.Form.NFD)
409                        && Normalizer.isNormalized(sn, Normalizer.Form.NFC)) {
410                    // On Mac OS X it is quite possible to have the file name and the
411                    // given simple name normalized in different ways.
412                    // In that case we have to normalize file name to the
413                    // Normal Form Composed (NFC).
414                    String normName = Normalizer.normalize(pn, Normalizer.Form.NFC);
415                    if (normName.equals(sn)) {
416                        return true;
417                    }
418                }
419            }
420
421            if (pn.equalsIgnoreCase(sn)) {
422                try {
423                    // allow for Windows
424                    return p.toRealPath(LinkOption.NOFOLLOW_LINKS).getFileName().toString().equals(sn);
425                } catch (IOException e) {
426                }
427            }
428        }
429
430        return false;
431    }
432
433    @Override @DefinedBy(Api.COMPILER)
434    public NestingKind getNestingKind() {
435        return null;
436    }
437
438    @Override @DefinedBy(Api.COMPILER)
439    public Modifier getAccessLevel() {
440        return null;
441    }
442
443    @Override @DefinedBy(Api.COMPILER)
444    public URI toUri() {
445        return path.toUri();
446    }
447
448    @Override @DefinedBy(Api.COMPILER)
449    public InputStream openInputStream() throws IOException {
450        fileManager.updateLastUsedTime();
451        return Files.newInputStream(path);
452    }
453
454    @Override @DefinedBy(Api.COMPILER)
455    public OutputStream openOutputStream() throws IOException {
456        fileManager.updateLastUsedTime();
457        fileManager.flushCache(this);
458        ensureParentDirectoriesExist();
459        return Files.newOutputStream(path);
460    }
461
462    @Override @DefinedBy(Api.COMPILER)
463    public Reader openReader(boolean ignoreEncodingErrors) throws IOException {
464        CharsetDecoder decoder = fileManager.getDecoder(fileManager.getEncodingName(), ignoreEncodingErrors);
465        return new InputStreamReader(openInputStream(), decoder);
466    }
467
468    @Override @DefinedBy(Api.COMPILER)
469    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
470        CharBuffer cb = fileManager.getCachedContent(this);
471        if (cb == null) {
472            try (InputStream in = openInputStream()) {
473                ByteBuffer bb = fileManager.makeByteBuffer(in);
474                JavaFileObject prev = fileManager.log.useSource(this);
475                try {
476                    cb = fileManager.decode(bb, ignoreEncodingErrors);
477                } finally {
478                    fileManager.log.useSource(prev);
479                }
480                fileManager.recycleByteBuffer(bb);
481                if (!ignoreEncodingErrors) {
482                    fileManager.cache(this, cb);
483                }
484            }
485        }
486        return cb;
487    }
488
489    @Override @DefinedBy(Api.COMPILER)
490    public Writer openWriter() throws IOException {
491        fileManager.updateLastUsedTime();
492        fileManager.flushCache(this);
493        ensureParentDirectoriesExist();
494        return new OutputStreamWriter(Files.newOutputStream(path), fileManager.getEncodingName());
495    }
496
497    @Override @DefinedBy(Api.COMPILER)
498    public long getLastModified() {
499        try {
500            return Files.getLastModifiedTime(path).toMillis();
501        } catch (IOException e) {
502            return 0;
503        }
504    }
505
506    @Override @DefinedBy(Api.COMPILER)
507    public boolean delete() {
508        try {
509            Files.delete(path);
510            return true;
511        } catch (IOException e) {
512            return false;
513        }
514    }
515
516    boolean isSameFile(PathFileObject other) {
517        // By construction, the "path" field should be canonical in all likely, supported scenarios.
518        // (Any exceptions would involve the use of symlinks within a package hierarchy.)
519        // Therefore, it is sufficient to check that the paths are .equals.
520        return path.equals(other.path);
521    }
522
523    @Override
524    public boolean equals(Object other) {
525        return (other instanceof PathFileObject && path.equals(((PathFileObject) other).path));
526    }
527
528    @Override
529    public int hashCode() {
530        return path.hashCode();
531    }
532
533    @Override
534    public String toString() {
535        return getClass().getSimpleName() + "[" + path + "]";
536    }
537
538    private void ensureParentDirectoriesExist() throws IOException {
539        if (!hasParents) {
540            Path parent = path.getParent();
541            if (parent != null && !Files.isDirectory(parent)) {
542                try {
543                    Files.createDirectories(parent);
544                } catch (IOException e) {
545                    throw new IOException("could not create parent directories", e);
546                }
547            }
548            hasParents = true;
549        }
550    }
551
552    protected static String toBinaryName(RelativePath relativePath) {
553        return toBinaryName(relativePath.path, "/");
554    }
555
556    protected static String toBinaryName(Path relativePath) {
557        return toBinaryName(relativePath.toString(),
558                relativePath.getFileSystem().getSeparator());
559    }
560
561    private static String toBinaryName(String relativePath, String sep) {
562        return removeExtension(relativePath).replace(sep, ".");
563    }
564
565    private static String removeExtension(String fileName) {
566        int lastDot = fileName.lastIndexOf(".");
567        return (lastDot == -1 ? fileName : fileName.substring(0, lastDot));
568    }
569
570    /**
571     * Return the last component of a presumed hierarchical URI.
572     * From the scheme specific part of the URI, it returns the substring
573     * after the last "/" if any, or everything if no "/" is found.
574     * @param fo the file object
575     * @return the simple name of the file object
576     */
577    public static String getSimpleName(FileObject fo) {
578        URI uri = fo.toUri();
579        String s = uri.getSchemeSpecificPart();
580        return s.substring(s.lastIndexOf("/") + 1); // safe when / not found
581
582    }
583
584    /** Used when URLSyntaxException is thrown unexpectedly during
585     *  implementations of FileObject.toURI(). */
586    public static class CannotCreateUriError extends Error {
587        private static final long serialVersionUID = 9101708840997613546L;
588        public CannotCreateUriError(String value, Throwable cause) {
589            super(value, cause);
590        }
591    }
592}
593