javax.tools.JavaFileManager.Location Java Examples

The following examples show how to use javax.tools.JavaFileManager.Location. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavapTask.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Location findModule(String moduleName) throws IOException {
    Location[] locns = {
        StandardLocation.UPGRADE_MODULE_PATH,
        StandardLocation.SYSTEM_MODULES,
        StandardLocation.MODULE_PATH
    };
    for (Location segment: locns) {
        for (Set<Location> set: fileManager.listLocationsForModules(segment)) {
            Location result = null;
            for (Location l: set) {
                String name = fileManager.inferModuleName(l);
                if (name.equals(moduleName)) {
                    if (result == null)
                        result = l;
                    else
                        throw new IOException("multiple definitions found for " + moduleName);
                }
            }
            if (result != null)
                return result;
        }
    }
    return null;
}
 
Example #2
Source File: StandardDocFileFactory.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private File getDestDir() {
    if (destDir == null) {
        if (!configuration.destDirName.isEmpty()
                || !fileManager.hasLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT)) {
            try {
                String dirName = configuration.destDirName.isEmpty() ? "." : configuration.destDirName;
                File dir = new File(dirName);
                fileManager.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(dir));
            } catch (IOException e) {
                throw new DocletAbortException(e);
            }
        }

        destDir = fileManager.getLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT).iterator().next();
    }
    return destDir;
}
 
Example #3
Source File: Locations.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
void initHandlers() {
    handlersForLocation = new HashMap<Location, LocationHandler>();
    handlersForOption = new EnumMap<Option, LocationHandler>(Option.class);

    LocationHandler[] handlers = {
        new BootClassPathLocationHandler(),
        new ClassPathLocationHandler(),
        new SimpleLocationHandler(StandardLocation.SOURCE_PATH, Option.SOURCEPATH),
        new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_PATH, Option.PROCESSORPATH),
        new OutputLocationHandler((StandardLocation.CLASS_OUTPUT), Option.D),
        new OutputLocationHandler((StandardLocation.SOURCE_OUTPUT), Option.S),
        new OutputLocationHandler((StandardLocation.NATIVE_HEADER_OUTPUT), Option.H)
    };

    for (LocationHandler h: handlers) {
        handlersForLocation.put(h.location, h);
        for (Option o: h.options)
            handlersForOption.put(o, h);
    }
}
 
Example #4
Source File: ElementsTable.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void computeSubpackages() throws ToolException {
    ((List<String>) opts.computeIfAbsent(ToolOption.EXCLUDE, v -> Collections.EMPTY_LIST))
            .stream()
            .map(ModulePackage::new)
            .forEachOrdered((mpkg) -> excludePackages.add(mpkg));

    excludePackages.forEach((p) -> {
        getEntry(p).excluded = true;
    });

    for (ModulePackage modpkg : subPackages) {
        List<Location> locs = getLocation(modpkg);
        for (Location loc : locs) {
            addPackagesFromLocations(loc, modpkg);
        }
    }
}
 
Example #5
Source File: PathDocFileFactory.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
Iterable<DocFile> list(Location location, DocPath path) {
    if (location != StandardLocation.SOURCE_PATH)
        throw new IllegalArgumentException();

    Set<DocFile> files = new LinkedHashSet<DocFile>();
    if (fileManager.hasLocation(location)) {
        for (Path f: fileManager.getLocation(location)) {
            if (Files.isDirectory(f)) {
                f = f.resolve(path.getPath());
                if (Files.exists(f))
                    files.add(new StandardDocFile(f));
            }
        }
    }
    return files;
}
 
Example #6
Source File: ContainsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void checkContains(StandardJavaFileManager fm, Location l, FileObject fo, boolean expect) throws IOException {
    boolean found = fm.contains(l, fo);
    if (found) {
        if (expect) {
            out.println("file found, as expected: " + l + " " + fo.getName());
        } else {
            error("file not found: " + l + " " + fo.getName());
        }
    } else {
        if (expect) {
            error("file found unexpectedly: " + l + " " + fo.getName());
        } else {
            out.println("file not found, as expected: " + l + " " + fo.getName());
        }
    }
}
 
Example #7
Source File: ElementsTable.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Set<PackageElement> getAllModulePackages(ModuleElement mdle) throws ToolException {
    Set<PackageElement> result = new HashSet<>();
    ModuleSymbol msym = (ModuleSymbol) mdle;
    List<Location> msymlocs = getModuleLocation(locations, msym.name.toString());
    for (Location msymloc : msymlocs) {
        for (JavaFileObject fo : fmList(msymloc, "", sourceKinds, true)) {
            if (fo.getName().endsWith("module-info.java")) {
                continue;
            }
            String binaryName = fm.inferBinaryName(msymloc, fo);
            String pn = getPackageName(binaryName);
            PackageSymbol psym = syms.enterPackage(msym, names.fromString(pn));
            result.add((PackageElement) psym);
        }
    }
    return result;
}
 
Example #8
Source File: CompilationSubject.java    From compile-testing with Apache License 2.0 6 votes vote down vote up
private JavaFileObjectSubject checkGeneratedFile(
    Optional<JavaFileObject> generatedFile, Location location, String path) {
  if (!generatedFile.isPresent()) {
    // TODO(b/132162475): Use Facts if it becomes public API.
    ImmutableList.Builder<Fact> facts = ImmutableList.builder();
    facts.add(fact("in location", location.getName()));
    facts.add(simpleFact("it generated:"));
    for (JavaFileObject generated : actual.generatedFiles()) {
      if (generated.toUri().getPath().contains(location.getName())) {
        facts.add(simpleFact("  " + generated.toUri().getPath()));
      }
    }
    failWithoutActual(
        fact("expected to generate file", "/" + path), facts.build().toArray(new Fact[0]));
    return ignoreCheck().about(javaFileObjects()).that(ALREADY_FAILED);
  }
  return check("generatedFile(/%s)", path).about(javaFileObjects()).that(generatedFile.get());
}
 
Example #9
Source File: StandardDocFileFactory.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private File getDestDir() {
    if (destDir == null) {
        if (!configuration.destDirName.isEmpty()
                || !fileManager.hasLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT)) {
            try {
                String dirName = configuration.destDirName.isEmpty() ? "." : configuration.destDirName;
                File dir = new File(dirName);
                fileManager.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(dir));
            } catch (IOException e) {
                throw new DocletAbortException(e);
            }
        }

        destDir = fileManager.getLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT).iterator().next();
    }
    return destDir;
}
 
Example #10
Source File: SourceFileManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForInput (Location l, final String className, JavaFileObject.Kind kind) {
    String[] namePair = FileObjects.getParentRelativePathAndName (className);
    String ext = kind == JavaFileObject.Kind.CLASS ? FileObjects.SIG : kind.extension.substring(1);   //tzezula: Clearly wrong in compile on save, but "class" is also wrong
    for (ClassPath.Entry entry : this.sourceRoots.entries()) {
        FileObject root = entry.getRoot();
        if (root != null) {
            FileObject parent = root.getFileObject(namePair[0]);
            if (parent != null) {
                FileObject[] children = parent.getChildren();
                for (FileObject child : children) {
                    if (namePair[1].equals(child.getName()) && ext.equalsIgnoreCase(child.getExt()) && (ignoreExcludes || entry.includes(child))) {
                        return FileObjects.sourceFileObject(child, root);
                    }
                }
            }
        }
    }
    return null;
}
 
Example #11
Source File: JavacFiler.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public FileObject createResource(JavaFileManager.Location location,
                                 CharSequence pkg,
                                 CharSequence relativeName,
                                 Element... originatingElements) throws IOException {
    locationCheck(location);

    String strPkg = pkg.toString();
    if (strPkg.length() > 0)
        checkName(strPkg);

    FileObject fileObject =
        fileManager.getFileForOutput(location, strPkg,
                                     relativeName.toString(), null);
    checkFileReopening(fileObject, true);

    if (fileObject instanceof JavaFileObject)
        return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject);
    else
        return new FilerOutputFileObject(null, fileObject);
}
 
Example #12
Source File: ClassReader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void fillIn(PackageSymbol p,
                    Location location,
                    Iterable<JavaFileObject> files)
{
    currentLoc = location;
    for (JavaFileObject fo : files) {
        switch (fo.getKind()) {
        case CLASS:
        case SOURCE: {
            // TODO pass binaryName to includeClassFile
            String binaryName = fileManager.inferBinaryName(currentLoc, fo);
            String simpleName = binaryName.substring(binaryName.lastIndexOf(".") + 1);
            if (SourceVersion.isIdentifier(simpleName) ||
                simpleName.equals("package-info"))
                includeClassFile(p, fo);
            break;
        }
        default:
            extraFileActions(p, fo);
        }
    }
}
 
Example #13
Source File: JavacFiler.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public FileObject createResource(JavaFileManager.Location location,
                                 CharSequence pkg,
                                 CharSequence relativeName,
                                 Element... originatingElements) throws IOException {
    locationCheck(location);

    String strPkg = pkg.toString();
    if (strPkg.length() > 0)
        checkName(strPkg);

    FileObject fileObject =
        fileManager.getFileForOutput(location, strPkg,
                                     relativeName.toString(), null);
    checkFileReopening(fileObject, true);

    if (fileObject instanceof JavaFileObject)
        return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject);
    else
        return new FilerOutputFileObject(null, fileObject);
}
 
Example #14
Source File: PathDocFileFactory.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
Iterable<DocFile> list(Location location, DocPath path) {
    if (location != StandardLocation.SOURCE_PATH)
        throw new IllegalArgumentException();

    Set<DocFile> files = new LinkedHashSet<DocFile>();
    if (fileManager.hasLocation(location)) {
        for (Path f: fileManager.getLocation(location)) {
            if (Files.isDirectory(f)) {
                f = f.resolve(path.getPath());
                if (Files.exists(f))
                    files.add(new StandardDocFile(f));
            }
        }
    }
    return files;
}
 
Example #15
Source File: SetLocationForModule.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testBasic(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location[] locns = {
            StandardLocation.SOURCE_PATH,
            StandardLocation.CLASS_PATH,
            StandardLocation.PLATFORM_CLASS_PATH,
        };
        // set a value
        Path out = Files.createDirectories(base.resolve("out"));
        for (Location locn : locns) {
            checkException("unsupported for location",
                    IllegalArgumentException.class,
                    "location is not an output location or a module-oriented location: " + locn,
                    () -> fm.setLocationForModule(locn, "m", List.of(out)));
        }
    }
}
 
Example #16
Source File: WriteBackTransaction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private Collection<File> listDir(
        @NonNull final Location location,
        @NonNull final String dir) {
    final Map<String, Map<File, CachedFileObject>> cache = getCacheLine(location, true);
    Map<File, CachedFileObject> content = cache.get(dir);
    return content == null ? Collections.<File>emptyList() : content.keySet();
}
 
Example #17
Source File: JavacFiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void locationCheck(JavaFileManager.Location location) {
    if (location instanceof StandardLocation) {
        StandardLocation stdLoc = (StandardLocation) location;
        if (!stdLoc.isOutputLocation())
            throw new IllegalArgumentException("Resource creation not supported in location " +
                                               stdLoc);
    }
}
 
Example #18
Source File: JavacFiler.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private JavaFileObject createSourceOrClassFile(ModuleSymbol mod, boolean isSourceFile, String name) throws IOException {
    Assert.checkNonNull(mod);

    if (lint) {
        int periodIndex = name.lastIndexOf(".");
        if (periodIndex != -1) {
            String base = name.substring(periodIndex);
            String extn = (isSourceFile ? ".java" : ".class");
            if (base.equals(extn))
                log.warning(Warnings.ProcSuspiciousClassName(name, extn));
        }
    }
    checkNameAndExistence(mod, name, isSourceFile);
    Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);

    if (modules.multiModuleMode) {
        loc = this.fileManager.getLocationForModule(loc, mod.name.toString());
    }
    JavaFileObject.Kind kind = (isSourceFile ?
                                JavaFileObject.Kind.SOURCE :
                                JavaFileObject.Kind.CLASS);

    JavaFileObject fileObject =
        fileManager.getJavaFileForOutput(loc, name, kind, null);
    checkFileReopening(fileObject, true);

    if (lastRound)
        log.warning(Warnings.ProcFileCreateLastRound(name));

    if (isSourceFile)
        aggregateGeneratedSourceNames.add(Pair.of(mod, name));
    else
        aggregateGeneratedClassNames.add(Pair.of(mod, name));
    openTypeNames.add(name);

    return new FilerOutputJavaFileObject(mod, name, fileObject);
}
 
Example #19
Source File: PathDocFileFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open an output stream for the file.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public OutputStream openOutputStream() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    OutputStream out = getFileObjectForOutput(path).openOutputStream();
    return new BufferedOutputStream(out);
}
 
Example #20
Source File: T6420409.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
static void test(Iterable<? extends File> path, File file, Location location) {
    Iterator<? extends File> it = path.iterator();
    if (!it.next().equals(file))
        throw new AssertionError(file + " not in " + location);
    if (it.hasNext())
        throw new AssertionError("Unexpected element in "  + location + " : " + it.next());
    System.err.format((Locale)null, "OK: %s: %s%n", location, path);
}
 
Example #21
Source File: JavacFiler.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private JavaFileObject createSourceOrClassFile(boolean isSourceFile, String name) throws IOException {
    if (lint) {
        int periodIndex = name.lastIndexOf(".");
        if (periodIndex != -1) {
            String base = name.substring(periodIndex);
            String extn = (isSourceFile ? ".java" : ".class");
            if (base.equals(extn))
                log.warning("proc.suspicious.class.name", name, extn);
        }
    }
    checkNameAndExistence(name, isSourceFile);
    Location loc = (isSourceFile ? SOURCE_OUTPUT : CLASS_OUTPUT);
    JavaFileObject.Kind kind = (isSourceFile ?
                                JavaFileObject.Kind.SOURCE :
                                JavaFileObject.Kind.CLASS);

    JavaFileObject fileObject =
        fileManager.getJavaFileForOutput(loc, name, kind, null);
    checkFileReopening(fileObject, true);

    if (lastRound)
        log.warning("proc.file.create.last.round", name);

    if (isSourceFile)
        aggregateGeneratedSourceNames.add(name);
    else
        aggregateGeneratedClassNames.add(name);
    openTypeNames.add(name);

    return new FilerOutputJavaFileObject(name, fileObject);
}
 
Example #22
Source File: Locations.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a handler. The location and options provide a way to map
 * from a location or an option to the corresponding handler.
 * @see #initHandlers
 */
protected LocationHandler(Location location, Option... options) {
    this.location = location;
    this.options = options.length == 0 ?
        EnumSet.noneOf(Option.class):
        EnumSet.copyOf(Arrays.asList(options));
}
 
Example #23
Source File: SetLocationForModule.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testModulePath(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Path src = base.resolve("src");
        Path src_m = src.resolve("m");
        tb.writeJavaFiles(src_m, "module m { }");

        Location locn = StandardLocation.MODULE_PATH;

        Path modules1 = Files.createDirectories(base.resolve("modules1"));
        new JavacTask(tb)
                .outdir(modules1)
                .options("--module-source-path", src.toString())
                .files(tb.findJavaFiles(src))
                .run();
        fm.setLocationFromPaths(locn, List.of(modules1));

        Location m = fm.getLocationForModule(locn, "m");
        checkEqual("default setting",
                fm.getLocationAsPaths(m), modules1.resolve("m"));

        Path override1 = Files.createDirectories(base.resolve("override1"));
        fm.setLocationForModule(locn, "m", List.of(override1));
        checkEqual("override setting 1",
                fm.getLocationAsPaths(m), override1);

        Path override2 = Files.createDirectories(base.resolve("override2"));
        fm.setLocationFromPaths(m, List.of(override2));
        checkEqual("override setting 2",
                fm.getLocationAsPaths(m), override2);

        Path modules2 = Files.createDirectories(base.resolve("modules2"));
        fm.setLocationFromPaths(locn, List.of(modules2));

        checkEqual("updated setting",
                fm.getLocationAsPaths(m), modules2.resolve("m"));
    }
}
 
Example #24
Source File: SimpleDocFileFactory.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a relative file against the given output location.
 * @param locn Currently, only
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} is supported.
 */
public DocFile resolveAgainst(Location locn) {
    if (locn != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalArgumentException();
    return new SimpleDocFile(
            new File(configuration.destDirName, file.getPath()));
}
 
Example #25
Source File: StandardDocFileFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open an output stream for the file.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public OutputStream openOutputStream() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    OutputStream out = getFileObjectForOutput(path).openOutputStream();
    return new BufferedOutputStream(out);
}
 
Example #26
Source File: JavacFiler.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void locationCheck(JavaFileManager.Location location) {
    if (location instanceof StandardLocation) {
        StandardLocation stdLoc = (StandardLocation) location;
        if (!stdLoc.isOutputLocation())
            throw new IllegalArgumentException("Resource creation not supported in location " +
                                               stdLoc);
    }
}
 
Example #27
Source File: JavacFiler.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void locationCheck(JavaFileManager.Location location) {
    if (location instanceof StandardLocation) {
        StandardLocation stdLoc = (StandardLocation) location;
        if (!stdLoc.isOutputLocation())
            throw new IllegalArgumentException("Resource creation not supported in location " +
                                               stdLoc);
    }
}
 
Example #28
Source File: T6397104.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void test(boolean hasLocation, File siblingFile, String relName, String expectedPath)
    throws Exception
{
    StandardJavaFileManager fm;
    if (hasLocation) {
        for (Location location : StandardLocation.values()) {
            fm = tool.getStandardFileManager(null, null, null);
            fm.setLocation(location, Arrays.asList(new File(".")));
            test(fm, location, siblingFile, relName, expectedPath);
        }
    } else {
        fm = tool.getStandardFileManager(null, null, null);
        test(fm, CLASS_OUTPUT, siblingFile, relName, expectedPath);
    }
}
 
Example #29
Source File: PathDocFileFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public PathDocFileFactory(Configuration configuration) {
    super(configuration);
    fileManager = (PathFileManager) configuration.getFileManager();

    if (!configuration.destDirName.isEmpty()
            || !fileManager.hasLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT)) {
        try {
            String dirName = configuration.destDirName.isEmpty() ? "." : configuration.destDirName;
            Path dir = fileManager.getDefaultFileSystem().getPath(dirName);
            fileManager.setLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT, Arrays.asList(dir));
        } catch (IOException e) {
            throw new DocletAbortException(e);
        }
    }

    destDir = fileManager.getLocation(DocumentationTool.Location.DOCUMENTATION_OUTPUT).iterator().next();
}
 
Example #30
Source File: Locations.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a handler. The location and options provide a way to map
 * from a location or an option to the corresponding handler.
 * @see #initHandlers
 */
protected LocationHandler(Location location, Option... options) {
    this.location = location;
    this.options = options.length == 0 ?
        EnumSet.noneOf(Option.class):
        EnumSet.copyOf(Arrays.asList(options));
}