Java Code Examples for javax.tools.JavaFileManager

The following examples show how to use javax.tools.JavaFileManager. 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-jdk9   Source File: ReusableContext.java    License: GNU General Public License v2.0 6 votes vote down vote up
void clear() {
    drop(Arguments.argsKey);
    drop(DiagnosticListener.class);
    drop(Log.outKey);
    drop(Log.errKey);
    drop(JavaFileManager.class);
    drop(JavacTask.class);

    if (ht.get(Log.logKey) instanceof ReusableLog) {
        //log already inited - not first round
        ((ReusableLog)Log.instance(this)).clear();
        Enter.instance(this).newRound();
        ((ReusableJavaCompiler)ReusableJavaCompiler.instance(this)).clear();
        Types.instance(this).newRound();
        Check.instance(this).newRound();
        Modules.instance(this).newRound();
        Annotate.instance(this).newRound();
        CompileStates.instance(this).clear();
        MultiTaskListener.instance(this).clear();

        //find if any of the roots have redefined java.* classes
        Symtab syms = Symtab.instance(this);
        pollutionScanner.scan(roots, syms);
        roots.clear();
    }
}
 
Example 2
Source Project: openjdk-jdk9   Source File: JavacTrees.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void init(Context context) {
    modules = Modules.instance(context);
    attr = Attr.instance(context);
    enter = Enter.instance(context);
    elements = JavacElements.instance(context);
    log = Log.instance(context);
    resolve = Resolve.instance(context);
    treeMaker = TreeMaker.instance(context);
    memberEnter = MemberEnter.instance(context);
    names = Names.instance(context);
    types = Types.instance(context);
    docTreeMaker = DocTreeMaker.instance(context);
    parser = ParserFactory.instance(context);
    syms = Symtab.instance(context);
    fileManager = context.get(JavaFileManager.class);
    JavacTask t = context.get(JavacTask.class);
    if (t instanceof JavacTaskImpl)
        javacTaskImpl = (JavacTaskImpl) t;
}
 
Example 3
private void initProcessorClassLoader() {
    JavaFileManager fileManager = context.get(JavaFileManager.class);
    try {
        // If processorpath is not explicitly set, use the classpath.
        processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
            : fileManager.getClassLoader(CLASS_PATH);

        if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
            JavaCompiler compiler = JavaCompiler.instance(context);
            compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
        }
    } catch (SecurityException e) {
        processorClassLoaderException = e;
    }
}
 
Example 4
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
                null, Arrays.asList(new MyFileObject(src)));


        for (CompilationUnitTree cut : ct.parse()) {
            JCTree.JCMethodDecl meth =
                    (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
            checkMatch(code, meth);
        }
    }
}
 
Example 5
/**
 * Returns an empty processor iterator if no processors are on the
 * relevant path, otherwise if processors are present, logs an
 * error.  Called when a service loader is unavailable for some
 * reason, either because a service loader class cannot be found
 * or because a security policy prevents class loaders from being
 * created.
 *
 * @param key The resource key to use to log an error message
 * @param e   If non-null, pass this exception to Abort
 */
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
        StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
        Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
            : standardFileManager.getLocation(CLASS_PATH);

        if (needClassLoader(options.get(PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
 
Example 6
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 7
Source Project: TencentKona-8   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 8
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    DiagnosticCollector<JavaFileObject> dc =
            new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, null,
            Arrays.asList(classToCheck.getPath()));
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 9
Source Project: openjdk-8-source   Source File: JavahTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
JavahTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this();
    this.log = getPrintWriterForWriter(out);
    this.fileManager = fileManager;
    this.diagnosticListener = diagnosticListener;

    try {
        handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }

    this.classes = new ArrayList<String>();
    if (classes != null) {
        for (String classname: classes) {
            classname.getClass(); // null-check
            this.classes.add(classname);
        }
    }
}
 
Example 10
Source Project: netbeans   Source File: SourceAnalyzerFactory.java    License: Apache License 2.0 6 votes vote down vote up
public UsagesVisitor (
        @NonNull final JavacTaskImpl jt,
        @NonNull final CompilationUnitTree cu,
        @NonNull final JavaFileManager manager,
        @NonNull final javax.tools.JavaFileObject sibling,
        @NullAllowed final Set<? super ElementHandle<TypeElement>> newTypes,
        @NullAllowed final Set<? super ElementHandle<ModuleElement>> newModules,
        final JavaCustomIndexer.CompileTuple tuple) throws MalformedURLException, IllegalArgumentException {
    this(
            jt,
            cu,
            inferBinaryName(manager, sibling),
            tuple.virtual ? tuple.indexable.getURL() : sibling.toUri().toURL(),
            true,
            tuple.virtual,
            newTypes,
            newModules,
            null);
}
 
Example 11
Source Project: deptective   Source File: ConfigLoader.java    License: Apache License 2.0 6 votes vote down vote up
private InputStream getConfigStream(Optional<Path> configFile, JavaFileManager jfm) {
    try {
        if (configFile.isPresent()) {
            return Files.newInputStream(configFile.get());
        }
        else {
            FileObject file = jfm.getFileForInput(StandardLocation.SOURCE_PATH, "", "deptective.json");

            if (file != null) {
                return file.openInputStream();
            }

            file = jfm.getFileForInput(StandardLocation.CLASS_PATH, "", "META-INF/deptective.json");

            if (file != null) {
                return file.openInputStream();
            }
        }
    }
    catch (IOException e) {
        throw new RuntimeException("Failed to load Deptective configuration file", e);
    }

    return null;
}
 
Example 12
Source Project: jdk8u60   Source File: JavapTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
public JavapTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    this(out, fileManager, diagnosticListener);

    this.classes = new ArrayList<String>();
    for (String classname: classes) {
        classname.getClass(); // null-check
        this.classes.add(classname);
    }

    try {
        if (options != null)
            handleOptions(options, false);
    } catch (BadArgs e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 13
Source Project: netbeans   Source File: ProxyFileManager.java    License: Apache License 2.0 6 votes vote down vote up
@NonNull
JavaFileManager[] get() {
    JavaFileManager[] res;
     if (fileManagers != null) {
        res = fileManagers;
    } else {
        fileManagers = factory.get();
        assert fileManagers != null;
        factory = null;
        res = fileManagers;
    }
    if (filter != null) {
        res = filter.apply(res);
    }
    return res;
}
 
Example 14
Source Project: openjdk-jdk8u   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 15
Source Project: openjdk-jdk9   Source File: T7190862.java    License: GNU General Public License v2.0 6 votes vote down vote up
private String javap(List<String> args, List<String> classes) {
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileManager fm = JavapFileManager.create(dc, pw);
    JavapTask t = new JavapTask(pw, fm, dc, args, classes);
    if (t.run() != 0)
        throw new Error("javap failed unexpectedly");

    List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> d: diags) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new Error(d.getMessage(Locale.ENGLISH));
    }
    return sw.toString();

}
 
Example 16
Source Project: hottub   Source File: DocEnv.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param context      Context for this javadoc instance.
 */
protected DocEnv(Context context) {
    context.put(docEnvKey, this);
    this.context = context;

    messager = Messager.instance0(context);
    syms = Symtab.instance(context);
    reader = JavadocClassReader.instance0(context);
    enter = JavadocEnter.instance0(context);
    names = Names.instance(context);
    externalizableSym = reader.enterClass(names.fromString("java.io.Externalizable"));
    chk = Check.instance(context);
    types = Types.instance(context);
    fileManager = context.get(JavaFileManager.class);
    if (fileManager instanceof JavacFileManager) {
        ((JavacFileManager)fileManager).setSymbolFileEnabled(false);
    }

    // Default.  Should normally be reset with setLocale.
    this.doclocale = new DocLocale(this, "", breakiterator);
    source = Source.instance(context);
}
 
Example 17
Source Project: netbeans   Source File: SourceAnalyzerFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes given compilation unit and returns the result of analyzes.
 * @param cu the java compilation unit to be analyzed
 * @param jt the {@link JavacTaskImpl} providing the context
 * @param manager the {@link JavaFileManager} used to infer binary names
 * @return the result of analyzes encoded as list of tuples {{fqn,relative_source_path_or_null},usages_data}
 * @throws IOException in case of IO error
 */
@CheckForNull
public List<Pair<Pair<BinaryName, String>, Object[]>> analyseUnit (
        @NonNull final CompilationUnitTree cu,
        @NonNull final JavacTaskImpl jt) throws IOException {
    if (used) {
        throw new IllegalStateException("Trying to reuse SimpleAnalyzer");  //NOI18N
    }
    used = true;
    try {
        final Map<Pair<BinaryName,String>,UsagesData<String>> usages = new HashMap<> ();
        final Set<Pair<String,String>> topLevels = new HashSet<>();
        final JavaFileManager jfm = jt.getContext().get(JavaFileManager.class);
        final UsagesVisitor uv = new UsagesVisitor (jt, cu, jfm, cu.getSourceFile(), topLevels);
        uv.scan(cu,usages);
        for (Map.Entry<Pair<BinaryName,String>,UsagesData<String>> oe : usages.entrySet()) {
            final Pair<BinaryName,String> key = oe.getKey();
            final UsagesData<String> data = oe.getValue();
            addClassReferences (key,data);
        }
        //this.writer.deleteEnclosedAndStore(this.references, topLevels);
        return this.references;
    } catch (IllegalArgumentException iae) {
        Exceptions.printStackTrace(iae);
        return null;
    }catch (OutputFileManager.InvalidSourcePath e) {
        return null;
    }
}
 
Example 18
Source Project: openjdk-jdk9   Source File: SJFM_Locations.java    License: GNU General Public License v2.0 5 votes vote down vote up
void test_setPaths_getPaths(StandardJavaFileManager fm, List<Path> inPaths) throws IOException {
    System.err.println("test_setPaths_getPaths");
    JavaFileManager.Location l = newLocation();
    fm.setLocationFromPaths(l, inPaths);
    Iterable<? extends Path> outPaths = fm.getLocationAsPaths(l);
    compare(inPaths, outPaths);
}
 
Example 19
Source Project: openjdk-jdk9   Source File: DocFileFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the appropriate factory, based on the file manager given in the
 * configuration.
 *
 * @param configuration the configuration for this doclet
 * @return the factory associated with this configuration
 */
public static synchronized DocFileFactory getFactory(Configuration configuration) {
    DocFileFactory f = configuration.docFileFactory;
    if (f == null) {
        JavaFileManager fm = configuration.getFileManager();
        if (fm instanceof StandardJavaFileManager) {
            f = new StandardDocFileFactory(configuration);
        } else {
            throw new IllegalStateException();
        }
        configuration.docFileFactory = f;
    }
    return f;
}
 
Example 20
/**
 * Create a JavacPathFileManager using a given context, optionally registering
 * it as the JavaFileManager for that context.
 */
public JavacPathFileManager(Context context, boolean register, Charset charset) {
    super(charset);
    if (register)
        context.put(JavaFileManager.class, this);
    pathsForLocation = new HashMap<Location, PathsForLocation>();
    fileSystems = new HashMap<Path,FileSystem>();
    setContext(context);
}
 
Example 21
Source Project: openjdk-8   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public DocumentationTask getTask(
        Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Class<?> docletClass,
        Iterable<String> options,
        Iterable<? extends JavaFileObject> compilationUnits) {
    Context context = new Context();
    return getTask(out, fileManager, diagnosticListener,
            docletClass, options, compilationUnits, context);
}
 
Example 22
Source Project: manifold   Source File: JsonSchemaType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * exclusive to top-level types (facilitates inner class extensions)
 */
@Override
public void prepareToRender( JavaFileManager.Location location, IModule module, DiagnosticListener<JavaFileObject> errorHandler )
{
  _state._location = location;
  _state._module = module;
  _state._errorHandler = errorHandler;
}
 
Example 23
Source Project: openjdk-8   Source File: CompilerThread.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepare the compiler thread for use. It is not yet started.
 * It will be started by the executor service.
 */
public synchronized void use() {
    assert(!inUse);
    inUse = true;
    compiler = com.sun.tools.javac.api.JavacTool.create();
    fileManager = compiler.getStandardFileManager(null, null, null);
    fileManagerBase = (BaseFileManager)fileManager;
    smartFileManager = new SmartFileManager(fileManager);
    context = new Context();
    context.put(JavaFileManager.class, smartFileManager);
    ResolveWithDeps.preRegister(context);
    JavaCompilerWithDeps.preRegister(context, this);
    subTasks = new ArrayList<Future<?>>();
}
 
Example 24
/**
 * Prepare the compiler thread for use. It is not yet started.
 * It will be started by the executor service.
 */
public synchronized void use() {
    assert(!inUse);
    inUse = true;
    compiler = com.sun.tools.javac.api.JavacTool.create();
    fileManager = compiler.getStandardFileManager(null, null, null);
    fileManagerBase = (BaseFileManager)fileManager;
    smartFileManager = new SmartFileManager(fileManager);
    context = new Context();
    context.put(JavaFileManager.class, smartFileManager);
    ResolveWithDeps.preRegister(context);
    JavaCompilerWithDeps.preRegister(context, this);
    subTasks = new ArrayList<Future<?>>();
}
 
Example 25
Source Project: jdk8u60   Source File: CompilerThread.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepare the compiler thread for use. It is not yet started.
 * It will be started by the executor service.
 */
public synchronized void use() {
    assert(!inUse);
    inUse = true;
    compiler = com.sun.tools.javac.api.JavacTool.create();
    fileManager = compiler.getStandardFileManager(null, null, null);
    fileManagerBase = (BaseFileManager)fileManager;
    smartFileManager = new SmartFileManager(fileManager);
    context = new Context();
    context.put(JavaFileManager.class, smartFileManager);
    ResolveWithDeps.preRegister(context);
    JavaCompilerWithDeps.preRegister(context, this);
    subTasks = new ArrayList<Future<?>>();
}
 
Example 26
Source Project: netbeans   Source File: ClasspathInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClasspathInfo create (
        @NonNull final ClassPath bootPath,
        @NonNull final ClassPath moduleBootPath,
        @NonNull final ClassPath classPath,
        @NonNull final ClassPath moduleCompilePath,
        @NonNull final ClassPath moduleClassPath,
        @NullAllowed final ClassPath sourcePath,
        @NullAllowed final ClassPath moduleSourcePath,
        @NullAllowed final JavaFileFilterImplementation filter,
        final boolean backgroundCompilation,
        final boolean ignoreExcludes,
        final boolean hasMemoryFileManager,
        final boolean useModifiedFiles,
        final boolean requiresSourceRoots,
        @NullAllowed final Function<JavaFileManager.Location, JavaFileManager> jfmProvider) {
    return ClasspathInfo.create(
            bootPath,
            moduleBootPath,
            classPath,
            moduleCompilePath,
            moduleClassPath,
            sourcePath,
            moduleSourcePath,
            filter,
            backgroundCompilation,
            ignoreExcludes,
            hasMemoryFileManager,
            useModifiedFiles,
            requiresSourceRoots,
            jfmProvider);
}
 
Example 27
Source Project: google-java-format   Source File: FormattingFiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FileObject createResource(
    JavaFileManager.Location location,
    CharSequence pkg,
    CharSequence relativeName,
    Element... originatingElements)
    throws IOException {
  return delegate.createResource(location, pkg, relativeName, originatingElements);
}
 
Example 28
Source Project: FreeBuilder   Source File: SingleBehaviorTester.java    License: Apache License 2.0 5 votes vote down vote up
SourceClassLoader(
    ClassLoader parent,
    JavaFileManager fileManager,
    Set<String> testFiles) {
  super(parent);
  this.fileManager = fileManager;
  this.testFiles = testFiles;
}
 
Example 29
Source Project: javapoet   Source File: TypesEclipseTest.java    License: Apache License 2.0 5 votes vote down vote up
static private boolean compile(Iterable<? extends Processor> processors) {
  JavaCompiler compiler = new EclipseCompiler();
  DiagnosticCollector<JavaFileObject> diagnosticCollector =
      new DiagnosticCollector<>();
  JavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Locale.getDefault(), UTF_8);
  JavaCompiler.CompilationTask task = compiler.getTask(
      null,
      fileManager,
      diagnosticCollector,
      ImmutableSet.of(),
      ImmutableSet.of(TypesEclipseTest.class.getCanonicalName()),
      ImmutableSet.of());
  task.setProcessors(processors);
  return task.call();
}
 
Example 30
Source Project: manifold   Source File: SourceJavaFileObject.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public String inferBinaryName( JavaFileManager.Location location )
{
  if( _fqn == null )
  {
    throw new IllegalStateException( "Null class name" );
  }
  return _fqn;
}