javax.tools.JavaFileManager Java Examples

The following examples show how to use javax.tools.JavaFileManager. 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: T7190862.java    From openjdk-jdk8u with GNU General Public License v2.0 7 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 #2
Source File: JavacTrees.java    From openjdk-jdk9 with 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
Source File: JavapTask.java    From jdk8u60 with 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 #4
Source File: TypeAnnotationsPretty.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: JavapTaskCtorFailWithNPE.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source File: T7190862.java    From TencentKona-8 with 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 #7
Source File: JavacProcessingEnvironment.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: JavapTaskCtorFailWithNPE.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 File: JavacProcessingEnvironment.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: JavahTask.java    From openjdk-8-source with 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 #11
Source File: T7190862.java    From openjdk-jdk9 with 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 #12
Source File: DocEnv.java    From hottub with 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 #13
Source File: SourceAnalyzerFactory.java    From netbeans with 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 #14
Source File: ReusableContext.java    From openjdk-jdk9 with 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 #15
Source File: ConfigLoader.java    From deptective with 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 #16
Source File: ProxyFileManager.java    From netbeans with 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 #17
Source File: FormattingFiler.java    From google-java-format with 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 #18
Source File: JavahTool.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public NativeHeaderTask getTask(Writer out,
        JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener,
        Iterable<String> options,
        Iterable<String> classes) {
    return new JavahTask(out, fileManager, diagnosticListener, options, classes);
}
 
Example #19
Source File: ClasspathInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static 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 new ClasspathInfo(
            bootPath,
            moduleBootPath,
            classPath,
            moduleCompilePath,
            moduleClassPath,
            sourcePath,
            moduleSourcePath,
            filter,
            backgroundCompilation,
            ignoreExcludes,
            hasMemoryFileManager,
            useModifiedFiles,
            requiresSourceRoots,
            jfmProvider);
}
 
Example #20
Source File: JavacFileManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a Context.Factory to create a JavacFileManager.
 */
public static void preRegister(Context context) {
    context.put(JavaFileManager.class, new Context.Factory<JavaFileManager>() {
        public JavaFileManager make(Context c) {
            return new JavacFileManager(c, true, null);
        }
    });
}
 
Example #21
Source File: SingleBehaviorTester.java    From FreeBuilder with 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 #22
Source File: JsonSchemaType.java    From manifold with 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 File: TypesEclipseTest.java    From javapoet with 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 #24
Source File: SourceJavaFileObject.java    From manifold with 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;
}
 
Example #25
Source File: ClasspathInfo.java    From netbeans with 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 #26
Source File: TemplateManifold.java    From manifold with Apache License 2.0 5 votes vote down vote up
@Override
protected String contribute( JavaFileManager.Location location, String topLevelFqn, boolean genStubs, String existing, TemplateModel model, DiagnosticListener<JavaFileObject> errorHandler )
{
  String source = model.getSource();
  model.report( errorHandler );
  return source;
}
 
Example #27
Source File: FileManagerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected JavaFileManagerDescripton[] getDescriptions() throws IOException {

JavaFileManager tfm = createGoldenJFM( new File[] { rtFolder }, 
				       new File[] { srcFolder} );		    
JavaFileManager gfm = createGoldenJFM( new File[] { rtFile }, 
				       new File[] { srcFile } );	
return new JavaFileManagerDescripton[] {
    new JavaFileManagerDescripton( tfm, gfm, srcZipArchive ),
};
   }
 
Example #28
Source File: ClassFinder.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Construct a new class finder. */
protected ClassFinder(Context context) {
    context.put(classFinderKey, this);
    reader = ClassReader.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    fileManager = context.get(JavaFileManager.class);
    dependencies = Dependencies.instance(context);
    if (fileManager == null)
        throw new AssertionError("FileManager initialization error");
    diagFactory = JCDiagnostic.Factory.instance(context);

    log = Log.instance(context);
    annotate = Annotate.instance(context);

    Options options = Options.instance(context);
    verbose = options.isSet(Option.VERBOSE);
    cacheCompletionFailure = options.isUnset("dev");
    preferSource = "source".equals(options.get("-Xprefer"));
    userPathsFirst = options.isSet(Option.XXUSERPATHSFIRST);
    allowSigFiles = context.get(PlatformDescription.class) != null;

    completionFailureName =
        options.isSet("failcomplete")
        ? names.fromString(options.get("failcomplete"))
        : null;

    profile = Profile.instance(context);
}
 
Example #29
Source File: ManifoldJavaFileManager.java    From manifold with Apache License 2.0 5 votes vote down vote up
private /*Symbol.ModuleSymbol*/ Object inferModule( JavaFileManager.Location location )
{
  /*Modules*/ Object modules = ReflectUtil.method( "com.sun.tools.javac.comp.Modules", "instance", Context.class ).invokeStatic( _ctx );
  Object defaultModule = ReflectUtil.method( modules, "getDefaultModule" ).invoke();
  if( defaultModule == ReflectUtil.field( Symtab.instance( _ctx ), "noModule" ).get() )
  {
    return defaultModule;
  }
  Set<?>/*<Symbol.ModuleSymbol>*/ rootModules = (Set<?>)ReflectUtil.method( modules, "getRootModules" ).invoke();

  Object moduleSym = null;
  if( location instanceof ManPatchLocation )
  {
    String moduleName = ((ManPatchLocation)location).inferModuleName( _ctx );
    if( moduleName != null )
    {
      Name name = Names.instance( _ctx ).fromString( moduleName );
      moduleSym = ReflectUtil.method( modules, "getObservableModule", Name.class ).invoke( name );
      if( moduleSym == null )
      {
        throw new IllegalStateException( "null module symbol for module: '" + moduleName + "'" );
      }
    }
  }

  if( rootModules.size() == 1 )
  {
    return rootModules.iterator().next();
  }

  throw new IllegalStateException( "no module inferred" );
}
 
Example #30
Source File: PackageReferenceValidator.java    From deptective with Apache License 2.0 5 votes vote down vote up
public PackageReferenceValidator(JavaFileManager jfm, PackageDependencies packageDependencies,
        ReportingPolicy reportingPolicy, ReportingPolicy unconfiguredPackageReportingPolicy,
        ReportingPolicy cycleReportingPolicy, boolean createDotFile,
        Log log) {
    this.log = log;
    this.allowedPackageDependencies = packageDependencies;
    this.jfm = jfm;
    this.reportingPolicy = reportingPolicy;
    this.unconfiguredPackageReportingPolicy = unconfiguredPackageReportingPolicy;
    this.cycleReportingPolicy = cycleReportingPolicy;
    this.reportedUnconfiguredPackages = new HashMap<>();
    this.actualPackageDependencies = PackageDependencies.builder();
    this.createDotFile = createDotFile;
}