8171005: Fix JavaFileManager.getLocationForModule(Location location, JavaFileObject fo, String pkgName) to work with location == CLASS_OUTPUT
authorjlahoda
Tue, 13 Dec 2016 10:48:18 +0100
changeset 42814 058fc03646d9
parent 42813 5161872bab6b
child 42815 050370edaade
8171005: Fix JavaFileManager.getLocationForModule(Location location, JavaFileObject fo, String pkgName) to work with location == CLASS_OUTPUT Summary: JavaFileManager operations that allow module-oriented locations should also allow output locations. Reviewed-by: jjg
langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java
langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java
langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java
langtools/test/tools/javac/file/ModuleAndPackageLocations.java
--- a/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java	Mon Dec 12 18:56:45 2016 -0800
+++ b/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java	Tue Dec 13 10:48:18 2016 +0100
@@ -479,8 +479,10 @@
 
     /**
      * Gets a location for the module containing a specific file representing a Java
-     * source or class, to be found in a module-oriented location.
-     * The result will be a package-oriented location.
+     * source or class, to be found within a location, which may be either
+     * a module-oriented location or an output location.
+     * The result will be an output location if the given location is
+     * an output location, or it will be a package-oriented location.
      *
      * @apiNote the package name is used to identify the position of the file object
      * within the <em>module/package/class</em> hierarchy identified by by the location.
@@ -494,7 +496,8 @@
      *
      * @throws IOException if an I/O error occurred
      * @throws UnsupportedOperationException if this operation if not supported by this file manager
-     * @throws IllegalArgumentException if the location is not a module-oriented location
+     * @throws IllegalArgumentException if the location is neither an output location nor a
+     * module-oriented location
      * @since 9
      */
     default Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
@@ -543,8 +546,9 @@
     }
 
     /**
-     * Lists the locations for all the modules in a module-oriented location.
-     * The locations that are returned will be package-oriented locations.
+     * Lists the locations for all the modules in a module-oriented location or an output location.
+     * The locations that are returned will be output locations if the given location is an output,
+     * or it will be a package-oriented locations.
      *
      * @implSpec This implementation throws {@code UnsupportedOperationException}.
      *
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java	Mon Dec 12 18:56:45 2016 -0800
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java	Tue Dec 13 10:48:18 2016 +0100
@@ -950,11 +950,7 @@
 
     @Override @DefinedBy(Api.COMPILER)
     public Location getLocationForModule(Location location, String moduleName) throws IOException {
-        Objects.requireNonNull(location);
-        if (!location.isOutputLocation() && !location.isModuleOrientedLocation())
-            throw new IllegalArgumentException(
-                    "location is not an output location or a module-oriented location: "
-                            + location.getName());
+        checkModuleOrientedOrOutputLocation(location);
         nullCheck(moduleName);
         return locations.getLocationForModule(location, moduleName);
     }
@@ -978,7 +974,7 @@
 
     @Override @DefinedBy(Api.COMPILER)
     public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
-        checkModuleOrientedLocation(location);
+        checkModuleOrientedOrOutputLocation(location);
         if (!(fo instanceof PathFileObject))
             throw new IllegalArgumentException(fo.getName());
         int depth = 1; // allow 1 for filename
@@ -1012,7 +1008,7 @@
 
     @Override @DefinedBy(Api.COMPILER)
     public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
-        checkModuleOrientedLocation(location);
+        checkModuleOrientedOrOutputLocation(location);
         return locations.listLocationsForModules(location);
     }
 
@@ -1098,10 +1094,12 @@
             throw new IllegalArgumentException("location is not an output location: " + location.getName());
     }
 
-    private void checkModuleOrientedLocation(Location location) {
+    private void checkModuleOrientedOrOutputLocation(Location location) {
         Objects.requireNonNull(location);
-        if (!location.isModuleOrientedLocation())
-            throw new IllegalArgumentException("location is not module-oriented: " + location.getName());
+        if (!location.isModuleOrientedLocation() && !location.isOutputLocation())
+            throw new IllegalArgumentException(
+                    "location is not an output location or a module-oriented location: "
+                            + location.getName());
     }
 
     private void checkNotModuleOrientedLocation(Location location) {
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java	Mon Dec 12 18:56:45 2016 -0800
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java	Tue Dec 13 10:48:18 2016 +0100
@@ -476,6 +476,7 @@
 
         private Path outputDir;
         private Map<String, Location> moduleLocations;
+        private Map<Path, Location> pathLocations;
 
         OutputLocationHandler(Location location, Option... options) {
             super(location, options);
@@ -521,21 +522,50 @@
                 outputDir = dir;
             }
             moduleLocations = null;
+            pathLocations = null;
         }
 
         @Override
         Location getLocationForModule(String name) {
-            if (moduleLocations == null)
+            if (moduleLocations == null) {
                 moduleLocations = new HashMap<>();
+                pathLocations = new HashMap<>();
+            }
             Location l = moduleLocations.get(name);
             if (l == null) {
+                Path out = outputDir.resolve(name);
                 l = new ModuleLocationHandler(location.getName() + "[" + name + "]",
                         name,
-                        Collections.singleton(outputDir.resolve(name)),
+                        Collections.singleton(out),
                         true, false);
                 moduleLocations.put(name, l);
+                pathLocations.put(out.toAbsolutePath(), l);
+           }
+            return l;
+        }
+
+        @Override
+        Location getLocationForModule(Path dir) {
+            return pathLocations.get(dir);
+        }
+
+        private boolean listed;
+
+        @Override
+        Iterable<Set<Location>> listLocationsForModules() throws IOException {
+            if (!listed && outputDir != null) {
+                try (DirectoryStream<Path> stream = Files.newDirectoryStream(outputDir)) {
+                    for (Path p : stream) {
+                        getLocationForModule(p.getFileName().toString());
+                    }
+                }
+                listed = true;
             }
-            return l;
+            if (moduleLocations == null)
+                return Collections.emptySet();
+            Set<Location> locns = new LinkedHashSet<>();
+            moduleLocations.forEach((k, v) -> locns.add(v));
+            return Collections.singleton(locns);
         }
     }
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/file/ModuleAndPackageLocations.java	Tue Dec 13 10:48:18 2016 +0100
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8171005
+ * @summary Verify behavior of JavaFileManager methods w.r.t. module/package oriented locations
+ * @library /tools/lib
+ * @modules java.compiler
+ * @build toolbox.TestRunner ModuleAndPackageLocations
+ * @run main ModuleAndPackageLocations
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileManager.Location;
+import javax.tools.JavaFileObject;
+import javax.tools.JavaFileObject.Kind;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
+import toolbox.TestRunner;
+import toolbox.TestRunner.Test;
+
+public class ModuleAndPackageLocations extends TestRunner {
+
+    public static void main(String... args) throws Exception {
+        new ModuleAndPackageLocations().runTests(m -> new Object[] { Paths.get(m.getName()) });
+    }
+
+    public ModuleAndPackageLocations() {
+        super(System.err);
+    }
+
+    @Test
+    public void testListLocations(Path outerBase) throws Exception {
+        doRunTest(outerBase, (base, fm) -> {
+            assertLocations(fm.listLocationsForModules(StandardLocation.MODULE_SOURCE_PATH),
+                            toSet("MODULE_SOURCE_PATH[a]:false:false",
+                                  "MODULE_SOURCE_PATH[b]:false:false",
+                                  "MODULE_SOURCE_PATH[c]:false:false"));
+            assertLocations(fm.listLocationsForModules(StandardLocation.MODULE_PATH),
+                            toSet("MODULE_PATH[0.X,a]:false:false",
+                                  "MODULE_PATH[0.X,b]:false:false"),
+                            toSet("MODULE_PATH[1.X,c]:false:false",
+                                  "MODULE_PATH[1.X,b]:false:false"));
+            assertLocations(fm.listLocationsForModules(StandardLocation.SOURCE_OUTPUT),
+                            toSet("SOURCE_OUTPUT[a]:false:true",
+                                  "SOURCE_OUTPUT[b]:false:true"));
+
+            fm.getLocationForModule(StandardLocation.SOURCE_OUTPUT, "c");
+
+            assertLocations(fm.listLocationsForModules(StandardLocation.SOURCE_OUTPUT),
+                            toSet("SOURCE_OUTPUT[a]:false:true",
+                                  "SOURCE_OUTPUT[b]:false:true",
+                                  "SOURCE_OUTPUT[c]:false:true"));
+        });
+    }
+
+    @Test
+    public void testGetModuleForPath(Path outerBase) throws Exception {
+        doRunTest(outerBase, (base, fm) -> {
+            Location cOutput = fm.getLocationForModule(StandardLocation.SOURCE_OUTPUT, "c");
+            JavaFileObject testFO = fm.getJavaFileForOutput(cOutput, "test.Test", Kind.CLASS, null);
+            testFO.openOutputStream().close();
+            Location cOutput2 = fm.getLocationForModule(StandardLocation.SOURCE_OUTPUT, testFO, "test");
+
+            if (cOutput != cOutput2) {
+                throw new AssertionError("Unexpected location: " + cOutput2 + ", expected: " +cOutput);
+            }
+        });
+    }
+
+    @Test
+    public void testRejects(Path outerBase) throws Exception {
+        doRunTest(outerBase, (base, fm) -> {
+            assertRefused(() -> fm.getClassLoader(StandardLocation.MODULE_SOURCE_PATH));
+            assertRefused(() -> fm.getFileForInput(StandardLocation.MODULE_SOURCE_PATH, "", ""));
+            assertRefused(() -> fm.getFileForOutput(StandardLocation.MODULE_SOURCE_PATH, "", "", null));
+            assertRefused(() -> fm.getJavaFileForInput(StandardLocation.MODULE_SOURCE_PATH, "", Kind.SOURCE));
+            assertRefused(() -> fm.getJavaFileForOutput(StandardLocation.MODULE_SOURCE_PATH, "", Kind.SOURCE, null));
+            assertRefused(() -> fm.getLocationForModule(StandardLocation.SOURCE_PATH, "test"));
+            JavaFileObject out = fm.getJavaFileForInput(StandardLocation.CLASS_OUTPUT, "test.Test", Kind.CLASS);
+            assertRefused(() -> fm.getLocationForModule(StandardLocation.SOURCE_PATH, out, "test"));
+            assertRefused(() -> fm.inferBinaryName(StandardLocation.MODULE_PATH, out));
+            assertRefused(() -> fm.inferModuleName(StandardLocation.MODULE_SOURCE_PATH));
+            assertRefused(() -> fm.list(StandardLocation.MODULE_SOURCE_PATH, "test", EnumSet.allOf(Kind.class), false));
+            assertRefused(() -> fm.listLocationsForModules(StandardLocation.SOURCE_PATH));
+        });
+    }
+
+    void doRunTest(Path base, TestExec test) throws Exception {
+        try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
+            Path msp  = base.resolve("msp");
+            Path msp1 = msp.resolve("1");
+            Path msp2 = msp.resolve("2");
+
+            Files.createDirectories(msp1.resolve("a"));
+            Files.createDirectories(msp1.resolve("b"));
+            Files.createDirectories(msp2.resolve("b"));
+            Files.createDirectories(msp2.resolve("c"));
+
+            Path mp  = base.resolve("mp");
+            Path mp1 = mp.resolve("1");
+            Path mp2 = mp.resolve("2");
+
+            touch(mp1.resolve("a/module-info.class"),
+                  mp1.resolve("b/module-info.class"),
+                  mp2.resolve("b/module-info.class"),
+                  mp2.resolve("c/module-info.class"));
+
+            Path so  = base.resolve("so");
+
+            Files.createDirectories(so.resolve("a"));
+            Files.createDirectories(so.resolve("b"));
+
+            List<String> mspOpt = Arrays.asList(msp1.toAbsolutePath().toString() +
+                                                File.pathSeparatorChar +
+                                                msp2.toAbsolutePath().toString());
+
+            List<String> mpOpt = Arrays.asList(mp1.toAbsolutePath().toString() +
+                                               File.pathSeparatorChar +
+                                               mp2.toAbsolutePath().toString());
+
+            fm.handleOption("--module-source-path", mspOpt.iterator());
+            fm.handleOption("--module-path", mpOpt.iterator());
+            fm.handleOption("-s", Arrays.asList(so.toString()).iterator());
+
+            test.run(base, fm);
+        }
+    }
+
+    private Set<String> toSet(String... values) {
+        return new HashSet<>(Arrays.asList(values));
+    }
+
+    private void touch(Path... paths) throws IOException {
+        for (Path p : paths) {
+            Files.createDirectories(p.getParent());
+            Files.newOutputStream(p).close();
+        }
+    }
+
+    @SafeVarargs
+    private void assertLocations(Iterable<Set<Location>> locations, Set<String>... expected) {
+        List<Set<String>> actual =
+                StreamSupport.stream(locations.spliterator(), true)
+                             .map(locs -> locs.stream()
+                                              .map(l -> toString(l))
+                                              .collect(Collectors.toSet()))
+                             .collect(Collectors.toList());
+
+        if (!Objects.equals(actual, Arrays.asList(expected))) {
+            throw new AssertionError("Unexpected output: " + actual);
+        }
+    }
+
+    private void assertRefused(Callable r) throws Exception {
+        try {
+            r.call();
+            throw new AssertionError("Expected exception did not occur");
+        } catch (IllegalArgumentException ex) {
+            //ok
+        }
+    }
+
+    private static String toString(Location l) {
+        return l.getName().replaceAll("\\[([0-9])\\.[0-9]:", "[$1.X,") + ":" +
+               l.isModuleOrientedLocation() + ":" + l.isOutputLocation();
+    }
+
+    static interface TestExec {
+        public void run(Path base, JavaFileManager fm) throws Exception;
+    }
+
+    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+}
\ No newline at end of file