javax.tools.JavaFileObject.Kind Java Examples

The following examples show how to use javax.tools.JavaFileObject.Kind. 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: SmartFileManager.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    // Acquire the list of files.
    Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
    if (visibleSources.isEmpty()) {
        return files;
    }
    // Now filter!
    ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
    for (JavaFileObject f : files) {
        URI uri = f.toUri();
        String t = uri.toString();
        if (t.startsWith("jar:")
            || t.endsWith(".class")
            || visibleSources.contains(uri))
        {
            filteredFiles.add(f);
        }
    }
    return filteredFiles;
}
 
Example #2
Source File: ElementStructureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException {
    if (location != StandardLocation.PLATFORM_CLASS_PATH || !kinds.contains(Kind.CLASS))
        return Collections.emptyList();

    if (!packageName.isEmpty())
        packageName += ".";

    List<JavaFileObject> result = new ArrayList<>();

    for (Entry<String, JavaFileObject> e : className2File.entrySet()) {
        String currentPackage = e.getKey().substring(0, e.getKey().lastIndexOf(".") + 1);
        if (recurse ? currentPackage.startsWith(packageName) : packageName.equals(currentPackage))
            result.add(e.getValue());
    }

    return result;
}
 
Example #3
Source File: EclipseFileManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse)
		throws IOException {
	
	Iterable<? extends File> allFilesInLocations = getLocation(location);
	if (allFilesInLocations == null) {
		throw new IllegalArgumentException("Unknown location : " + location);//$NON-NLS-1$
	}
	
	ArrayList<JavaFileObject> collector = new ArrayList<JavaFileObject>();
	String normalizedPackageName = normalized(packageName);
	for (File file : allFilesInLocations) {
		collectAllMatchingFiles(file, normalizedPackageName, kinds, recurse, collector);
	}
	return collector;
}
 
Example #4
Source File: JavacPathFileManager.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location,
        String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example #5
Source File: SmartFileManager.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    // Acquire the list of files.
    Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
    if (visibleSources.isEmpty()) {
        return files;
    }
    // Now filter!
    ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
    for (JavaFileObject f : files) {
        URI uri = f.toUri();
        String t = uri.toString();
        if (t.startsWith("jar:")
            || t.endsWith(".class")
            || visibleSources.contains(uri))
        {
            filteredFiles.add(f);
        }
    }
    return filteredFiles;
}
 
Example #6
Source File: TestClassCompilers.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
 
Example #7
Source File: JavacPathFileManager.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location,
        String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example #8
Source File: JavacPathFileManager.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location,
        String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example #9
Source File: JavaFile.java    From JReFrameworker with MIT License 6 votes vote down vote up
public JavaFileObject toJavaFileObject() {
  URI uri = URI.create((packageName.isEmpty()
      ? typeSpec.name
      : packageName.replace('.', '/') + '/' + typeSpec.name)
      + Kind.SOURCE.extension);
  return new SimpleJavaFileObject(uri, Kind.SOURCE) {
    private final long lastModified = System.currentTimeMillis();
    @Override public String getCharContent(boolean ignoreEncodingErrors) {
      return JavaFile.this.toString();
    }
    @Override public InputStream openInputStream() throws IOException {
      return new ByteArrayInputStream(getCharContent(true).getBytes(UTF_8));
    }
    @Override public long getLastModified() {
      return lastModified;
    }
  };
}
 
Example #10
Source File: JavaCompiler.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Emit plain Java source for a class.
 *  @param env    The attribution environment of the outermost class
 *                containing this class.
 *  @param cdef   The class definition to be printed.
 */
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
    JavaFileObject outFile
       = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
                                           cdef.sym.flatname.toString(),
                                           JavaFileObject.Kind.SOURCE,
                                           null);
    if (inputFiles.contains(outFile)) {
        log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
        return null;
    } else {
        try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
            new Pretty(out, true).printUnit(env.toplevel, cdef);
            if (verbose)
                log.printVerbose("wrote.file", outFile);
        }
        return outFile;
    }
}
 
Example #11
Source File: TestNonSerializableLambdaNameStability.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example #12
Source File: DynaFileManager.java    From kan-java with Eclipse Public License 1.0 6 votes vote down vote up
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    if (Kind.CLASS != kind && Kind.SOURCE != kind)
        throw new IOException("Unsupported output kind: " + kind);
    if (!(location instanceof StandardLocation))
        throw new IOException("Unsupported output location: " + location);
    switch ((StandardLocation) location) {
    case CLASS_OUTPUT:
        return getOrCreateMemFileByClassName(className, this.classes, JavaClassFile.class);
    case SOURCE_OUTPUT:
        return getOrCreateMemFileByClassName(className, this.srcs, JavaSourceFile.class);
    case CLASS_PATH:
    case SOURCE_PATH:
    case ANNOTATION_PROCESSOR_PATH:
    case PLATFORM_CLASS_PATH:
    default:
        throw new IOException("Unsupported output location: " + location);
    }
}
 
Example #13
Source File: SmartFileManager.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
    if (file == null) return file;
    int dp = className.lastIndexOf('.');
    String pkg_name = "";
    if (dp != -1) {
        pkg_name = className.substring(0, dp);
    }
    // When modules are in use, then the mod_name might be something like "jdk_base"
    String mod_name = "";
    addArtifact(mod_name+":"+pkg_name, file.toUri());
    return file;
}
 
Example #14
Source File: SimpleJavaFileObject.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a SimpleJavaFileObject of the given kind and with the
 * given URI.
 *
 * @param uri  the URI for this file object
 * @param kind the kind of this file object
 */
protected SimpleJavaFileObject(URI uri, Kind kind) {
    // null checks
    uri.getClass();
    kind.getClass();
    if (uri.getPath() == null)
        throw new IllegalArgumentException("URI must have a path: " + uri);
    this.uri = uri;
    this.kind = kind;
}
 
Example #15
Source File: JavaCompiler.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform dataflow checks on an attributed parse tree.
 */
protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
    if (compileStates.isDone(env, CompileState.FLOW)) {
        results.add(env);
        return;
    }

    try {
        if (shouldStop(CompileState.FLOW))
            return;

        if (verboseCompilePolicy)
            printNote("[flow " + env.enclClass.sym + "]");
        JavaFileObject prev = log.useSource(
                                            env.enclClass.sym.sourcefile != null ?
                                            env.enclClass.sym.sourcefile :
                                            env.toplevel.sourcefile);
        try {
            make.at(Position.FIRSTPOS);
            TreeMaker localMake = make.forToplevel(env.toplevel);
            flow.analyzeTree(env, localMake);
            compileStates.put(env, CompileState.FLOW);

            if (shouldStop(CompileState.FLOW))
                return;

            results.add(env);
        }
        finally {
            log.useSource(prev);
        }
    }
    finally {
        if (!taskListener.isEmpty()) {
            TaskEvent e = new TaskEvent(TaskEvent.Kind.ANALYZE, env.toplevel, env.enclClass.sym);
            taskListener.finished(e);
        }
    }
}
 
Example #16
Source File: BaseFileManager.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static Kind getKind(String name) {
    if (name.endsWith(Kind.CLASS.extension))
        return Kind.CLASS;
    else if (name.endsWith(Kind.SOURCE.extension))
        return Kind.SOURCE;
    else if (name.endsWith(Kind.HTML.extension))
        return Kind.HTML;
    else
        return Kind.OTHER;
}
 
Example #17
Source File: Modules.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void visitExports(JCExports tree) {
    Iterable<Symbol> packageContent = tree.directive.packge.members().getSymbols();
    List<JavaFileObject> filesToCheck = List.nil();
    boolean packageNotEmpty = false;
    for (Symbol sym : packageContent) {
        if (sym.kind != Kinds.Kind.TYP)
            continue;
        ClassSymbol csym = (ClassSymbol) sym;
        if (sym.completer.isTerminal() ||
            csym.classfile.getKind() == Kind.CLASS) {
            packageNotEmpty = true;
            filesToCheck = List.nil();
            break;
        }
        if (csym.classfile.getKind() == Kind.SOURCE) {
            filesToCheck = filesToCheck.prepend(csym.classfile);
        }
    }
    for (JavaFileObject jfo : filesToCheck) {
        if (findPackageInFile.findPackageNameOf(jfo) == tree.directive.packge.fullname) {
            packageNotEmpty = true;
            break;
        }
    }
    if (!packageNotEmpty) {
        log.error(tree.qualid.pos(), Errors.PackageEmptyOrNotFound(tree.directive.packge));
    }
    msym.directives = msym.directives.prepend(tree.directive);
}
 
Example #18
Source File: ForwardingJavaFileManager.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * @throws IllegalArgumentException {@inheritDoc}
 * @throws IllegalStateException {@inheritDoc}
 */
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    return fileManager.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #19
Source File: TurbineFiler.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject createClassFile(CharSequence n, Element... originatingElements)
    throws IOException {
  String name = n.toString();
  checkArgument(!name.contains("/"), "invalid type name: %s", name);
  return create(StandardLocation.CLASS_OUTPUT, Kind.CLASS, name.replace('.', '/') + ".class");
}
 
Example #20
Source File: InMemoryJavaCompiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
                                           Kind kind, FileObject sibling)
    throws IOException {
    if (!file.getClassName().equals(className)) {
        throw new IOException("Expected class with name " + file.getClassName() +
                              ", but got " + className);
    }
    return file;
}
 
Example #21
Source File: InMemoryJavaCompiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
                                           Kind kind, FileObject sibling)
    throws IOException {
    if (!file.getClassName().equals(className)) {
        throw new IOException("Expected class with name " + file.getClassName() +
                              ", but got " + className);
    }
    return file;
}
 
Example #22
Source File: WrappingJavaFileManager.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws IllegalStateException {@inheritDoc}
 */
@DefinedBy(Api.COMPILER)
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    return wrap(super.list(location, packageName, kinds, recurse));
}
 
Example #23
Source File: SimpleJavaFileObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a SimpleJavaFileObject of the given kind and with the
 * given URI.
 *
 * @param uri  the URI for this file object
 * @param kind the kind of this file object
 */
protected SimpleJavaFileObject(URI uri, Kind kind) {
    // null checks
    uri.getClass();
    kind.getClass();
    if (uri.getPath() == null)
        throw new IllegalArgumentException("URI must have a path: " + uri);
    this.uri = uri;
    this.kind = kind;
}
 
Example #24
Source File: ScopeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #25
Source File: MemoryOutputJavaFileManager.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling)
        throws IOException {
    if (kind != Kind.CLASS) {
        throw new IOException("Only class output supported, kind=" + kind);
    }
    try {
        MemoryOutputJavaFileObject output = new MemoryOutputJavaFileObject(new URI(className), kind);
        outputMap.put(className, output);
        return output;
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}
 
Example #26
Source File: ForwardingJavaFileManager.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws IllegalArgumentException {@inheritDoc}
 * @throws IllegalStateException {@inheritDoc}
 */
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    return fileManager.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example #27
Source File: WrappingJavaFileManager.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * @throws IllegalStateException {@inheritDoc}
 */
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    return wrap(super.list(location, packageName, kinds, recurse));
}
 
Example #28
Source File: WrappingJavaFileManager.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws IllegalStateException {@inheritDoc}
 */
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    return wrap(super.list(location, packageName, kinds, recurse));
}
 
Example #29
Source File: InMemoryJavaCompiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
                                           Kind kind, FileObject sibling)
    throws IOException {
    if (!file.getClassName().equals(className)) {
        throw new IOException("Expected class with name " + file.getClassName() +
                              ", but got " + className);
    }
    return file;
}
 
Example #30
Source File: MemoryBasedJavaFileManager.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public Key(Location location, String classpath, String packageName, Set<Kind> kinds, boolean recurse) {
	this.location = location;
	this.classpath = classpath;
	this.packageName = packageName;
	this.kinds = kinds;
	this.recurse = recurse;
}