Java Code Examples for javax.tools.StandardJavaFileManager#list()

The following examples show how to use javax.tools.StandardJavaFileManager#list() . 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
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 2
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 3
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 4
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
 
Example 5
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 6
void analyzeModule(StandardJavaFileManager fm, String moduleName)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaFileManager.Location location =
            fm.getLocationForModule(StandardLocation.SYSTEM_MODULES, moduleName);
    if (location == null)
        throw new AssertionError("can't find module " + moduleName);

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 7
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 8
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 9
void analyzeResource(URI resource)
    throws
        IOException,
        ConstantPoolException,
        InvalidDescriptor {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    JavaFileManager.Location location =
            StandardLocation.locationFor(resource.getPath());
    fm.setLocation(location, com.sun.tools.javac.util.List.of(
            new File(resource.getPath())));

    for (JavaFileObject file : fm.list(location, "", EnumSet.of(CLASS), true)) {
        String className = fm.inferBinaryName(location, file);
        int index = className.lastIndexOf('.');
        String pckName = index == -1 ? "" : className.substring(0, index);
        if (shouldAnalyzePackage(pckName)) {
            analyzeClassFile(ClassFile.read(file.openInputStream()));
        }
    }
}
 
Example 10
Source Project: openjdk-jdk9   File: Probe.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    if (args.length != 1) {
        System.err.println("Not enough arguments.");
        System.err.println("Usage:");
        System.err.println("    java " + Probe.class.getName() + " <output-file>");
        return ;
    }

    File outFile = new File(args[0]);
    Charset cs = Charset.forName("UTF-8");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    OutputStream out = new FileOutputStream(outFile);

    try {
        Iterable<JavaFileObject> bcpFiles =
                fm.list(StandardLocation.PLATFORM_CLASS_PATH, "", EnumSet.of(Kind.CLASS), true);

        for (JavaFileObject jfo : bcpFiles) {
            InputStream in = new BufferedInputStream(jfo.openInputStream());
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                StringBuilder textual = new StringBuilder();
                int read;

                while ((read = in.read()) != (-1)) {
                    baos.write(read);
                    textual.append(String.format("%02x", read));
                }

                textual.append("\n");
                out.write(textual.toString().getBytes(cs));
            } finally {
                in.close();
            }
        }
    } finally {
        out.close();
    }
}
 
Example 11
public boolean buildAllTable() throws Exception {
	boolean result = false;
	File dir = new File(Config.dir_local_temp_dynamic(true), StringTools.uniqueToken());
	FileUtils.forceMkdir(dir);
	File src = new File(dir, "src");
	FileUtils.forceMkdir(src);
	File target = new File(dir, "target");
	FileUtils.forceMkdir(target);
	File resources = new File(dir, "resources");
	FileUtils.forceMkdir(resources);
	List<Table> tables = emc.listEqual(Table.class, Table.status_FIELDNAME, Table.STATUS_build);
	/* 产生用于创建persistence.xml */
	List<String> classNames = new ArrayList<>();
	for (Table table : tables) {
		try {
			emc.beginTransaction(Table.class);
			if (StringUtils.isNotEmpty(table.getData())) {
				DynamicEntity dynamicEntity = XGsonBuilder.instance().fromJson(table.getData(),
						DynamicEntity.class);
				dynamicEntity.setName(table.getName());
				DynamicEntityBuilder builder = new DynamicEntityBuilder(dynamicEntity, src);
				builder.build();
				classNames.add(dynamicEntity.className());
			}
			table.setBuildSuccess(true);
			emc.commit();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	if (!classNames.isEmpty()) {

		PersistenceXmlHelper.directWrite(new File(resources, "META-INF/persistence.xml").getAbsolutePath(),
				classNames);

		List<File> classPath = new ArrayList<>();
		classPath.addAll(FileUtils.listFiles(Config.dir_commons_ext(), FileFilterUtils.suffixFileFilter(DOT_JAR),
				DirectoryFileFilter.INSTANCE));
		classPath.addAll(FileUtils.listFiles(Config.dir_store_jars(), FileFilterUtils.suffixFileFilter(DOT_JAR),
				DirectoryFileFilter.INSTANCE));

		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null,
				DefaultCharset.charset_utf_8);

		fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(target));
		fileManager.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(src, resources));
		fileManager.setLocation(StandardLocation.CLASS_PATH, classPath);

		Iterable<JavaFileObject> res = fileManager.list(StandardLocation.SOURCE_PATH, DynamicEntity.CLASS_PACKAGE,
				EnumSet.of(JavaFileObject.Kind.SOURCE), true);

		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

		StringWriter out = new StringWriter();

		if (!compiler.getTask(out, fileManager, diagnostics, null, null, res).call()) {
			for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
				out.append("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic).append('\n');
			}
			throw new ExceptionCompileError(out.toString());
		}

		result = true;

		fileManager.close();

		this.enhance(target, resources);

		File jar = new File(Config.dir_dynamic_jars(true), DynamicEntity.JAR_NAME + DOT_JAR);

		JarTools.jar(target, jar);
	}
	return result;
}
 
Example 12
Source Project: bazel   File: DumpPlatformClassPath.java    License: Apache License 2.0 4 votes vote down vote up
static boolean dumpJDK9AndNewerBootClassPath(
    int hostMajorVersion, Path output, Path targetJavabase) throws IOException {

  // JDK 9 and newer support cross-compiling to older platform versions using the --system
  // and --release flags.
  // * --system takes the path to a JDK root for JDK 9 and up, and causes the compilation
  //     to target the APIs from that JDK.
  // * --release takes a language level (e.g. '9') and uses the API information baked in to
  //     the host JDK (in lib/ct.sym).

  // Since --system only supports JDK >= 9, first check of the target JDK defines a JDK 8
  // bootclasspath.
  List<Path> bootClassPathJars = getBootClassPathJars(targetJavabase);
  if (!bootClassPathJars.isEmpty()) {
    writeClassPathJars(output, bootClassPathJars);
    return true;
  }

  // Initialize a FileManager to process the --system argument, and then read the
  // initialized bootclasspath data back out.

  Context context = new Context();
  JavacTool.create()
      .getTask(
          /* out = */ null,
          /* fileManager = */ null,
          /* diagnosticListener = */ null,
          /* options = */ Arrays.asList("--system", String.valueOf(targetJavabase)),
          /* classes = */ null,
          /* compilationUnits = */ null,
          context);
  StandardJavaFileManager fileManager =
      (StandardJavaFileManager) context.get(JavaFileManager.class);

  SortedMap<String, InputStream> entries = new TreeMap<>();
  for (JavaFileObject fileObject :
      fileManager.list(
          StandardLocation.PLATFORM_CLASS_PATH,
          "",
          EnumSet.of(Kind.CLASS),
          /* recurse= */ true)) {
    String binaryName =
        fileManager.inferBinaryName(StandardLocation.PLATFORM_CLASS_PATH, fileObject);
    entries.put(binaryName.replace('.', '/') + ".class", fileObject.openInputStream());
  }
  writeEntries(output, entries);
  return true;
}