Java Code Examples for javax.tools.JavaFileManager.Location

The following examples show how to use javax.tools.JavaFileManager.Location. These examples are extracted from open source projects. 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 Project: openjdk-jdk8u   Source File: Locations.java    License: 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 2
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 Project: openjdk-jdk9   Source File: ElementsTable.java    License: 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 4
@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 5
Source Project: openjdk-jdk9   Source File: ContainsTest.java    License: 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 6
Source Project: openjdk-jdk9   Source File: ElementsTable.java    License: 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 7
Source Project: compile-testing   Source File: CompilationSubject.java    License: 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 8
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 9
Source Project: netbeans   Source File: SourceFileManager.java    License: 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 10
Source Project: openjdk-jdk8u   Source File: JavacFiler.java    License: 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 11
Source Project: jdk8u60   Source File: ClassReader.java    License: 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 12
Source Project: jdk8u60   Source File: JavacFiler.java    License: 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 13
Source Project: hottub   Source File: PathDocFileFactory.java    License: 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 14
Source Project: jdk8u60   Source File: PathDocFileFactory.java    License: GNU General Public License v2.0 6 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 15
@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 Project: openjdk-jdk9   Source File: JavapTask.java    License: 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 17
/**
 * 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 18
Source Project: openjdk-jdk8u   Source File: JavacFiler.java    License: 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 19
Source Project: TencentKona-8   Source File: JavacFiler.java    License: 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 20
Source Project: hottub   Source File: Locations.java    License: 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 21
/**
 * Open an writer for the file, using the encoding (if any) given in the
 * doclet configuration.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public Writer openWriter() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    createDirectoryForFile(file);
    FileOutputStream fos = new FileOutputStream(file);
    if (configuration.docencoding == null) {
        return new BufferedWriter(new OutputStreamWriter(fos));
    } else {
        return new BufferedWriter(new OutputStreamWriter(fos, configuration.docencoding));
    }
}
 
Example 22
Source Project: takari-lifecycle   Source File: FilerImpl.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public FileObject getResource(Location location, CharSequence pkg, CharSequence relativeName) throws IOException {
  FileObject file = fileManager.getFileForInput(location, pkg.toString(), relativeName.toString());
  if (file == null) {
    throw new FileNotFoundException("Resource does not exist " + location + '/' + pkg + '/' + relativeName);
  }
  if (createdResources.contains(file.toUri())) {
    throw new FilerException("Resource already created " + pkg + "." + relativeName);
  }
  return file;
}
 
Example 23
/**
 * 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 24
Source Project: openjdk-jdk9   Source File: ElementsTable.java    License: GNU General Public License v2.0 5 votes vote down vote up
private List<Location> getLocation(ModulePackage modpkg) throws ToolException {
    if (locations.size() == 1 && !locations.contains(StandardLocation.MODULE_SOURCE_PATH)) {
        return Collections.singletonList(locations.get(0));
    }

    if (modpkg.hasModule()) {
        return getModuleLocation(locations, modpkg.moduleName);
    }
    // TODO: handle invalid results better.
    ModuleSymbol msym = findModuleOfPackageName(modpkg.packageName);
    if (msym == null) {
        return Collections.emptyList();
    }
    return getModuleLocation(locations, msym.name.toString());
}
 
Example 25
Source Project: openjdk-8-source   Source File: Locations.java    License: GNU General Public License v2.0 5 votes vote down vote up
void setLocation(Location location, Iterable<? extends File> files) throws IOException {
    LocationHandler h = getHandler(location);
    if (h == null) {
        if (location.isOutputLocation())
            h = new OutputLocationHandler(location);
        else
            h = new SimpleLocationHandler(location);
        handlersForLocation.put(location, h);
    }
    h.setLocation(files);
}
 
Example 26
/** Create a DocFile for a given location and relative path. */
private SimpleDocFile(Location location, DocPath path) {
    super(configuration, location, path);
    String destDirName = configuration.destDirName;
    this.file = destDirName.isEmpty() ? new File(path.getPath())
            : new File(destDirName, path.getPath());
}
 
Example 27
Source Project: jdk8u60   Source File: T6397104.java    License: 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 28
Source Project: openjdk-8   Source File: JavacFiler.java    License: 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 29
Source Project: hottub   Source File: SimpleDocFileFactory.java    License: 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 30
@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"));
    }
}