Java 类java.util.spi.ToolProvider 实例源码

项目:openjdk-jdk10    文件:ModuleReaderTest.java   
/**
 * Test ModuleReader to JMOD
 */
public void testJMod() throws IOException {
    Path dir = Files.createTempDirectory(USER_DIR, "mlib");

    // jmod create --class-path mods/${TESTMODULE}  mlib/${TESTMODULE}.jmod
    String cp = MODS_DIR.resolve(TEST_MODULE).toString();
    String jmod = dir.resolve("m.jmod").toString();
    String[] args = { "create", "--class-path", cp, jmod };
    ToolProvider jmodTool = ToolProvider.findFirst("jmod")
        .orElseThrow(() ->
            new RuntimeException("jmod tool not found")
        );
    assertEquals(jmodTool.run(System.out, System.out, args), 0);

    test(dir);
}
项目:pro    文件:PackagerPlugin.java   
@Override
public int execute(Config config) throws IOException {
  Log log = Log.create(name(), config.getOrThrow("pro", ProConf.class).loglevel());
  log.debug(config, conf -> "config " + config);

  ToolProvider jarTool = ToolProvider.findFirst("jar")
      .orElseThrow(() -> new IllegalStateException("can not find jar"));
  PackagerConf packager = config.getOrThrow(name(), PackagerConf.class);

  List<Path> moduleExplodedSourcePath = FileHelper.pathFromFilesThatExist(packager.moduleExplodedSourcePath());
  Path moduleArtifactSourcePath = packager.moduleArtifactSourcePath();
  List<Path> moduleExplodedTestPath = FileHelper.pathFromFilesThatExist(packager.moduleExplodedTestPath());
  Path moduleArtifactTestPath = packager.moduleArtifactTestPath();

  Map<String, Metadata> metadataMap = packager.moduleMetadata().map(MetadataParser::parse).orElse(Map.of());

  int errorCode = packageModules(log, jarTool, moduleExplodedSourcePath, moduleArtifactSourcePath, packager, metadataMap, "");
  if (errorCode != 0) {
    return errorCode;
  }
  if (!moduleExplodedTestPath.stream().anyMatch(Files::exists)) {
    return 0;
  }
  return packageModules(log, jarTool, moduleExplodedTestPath, moduleArtifactTestPath, packager, metadataMap, "test-");
}
项目:pro    文件:PackagerPlugin.java   
private static int packageModules(Log log, ToolProvider jarTool, List<Path> moduleExplodedPath, Path moduleArtifactPath, PackagerConf packager, Map<String, Metadata> metadataMap, String prefix) throws IOException {
  FileHelper.deleteAllFiles(moduleArtifactPath, false);
  Files.createDirectories(moduleArtifactPath);

  for(Path explodedPath: moduleExplodedPath) {
    try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(explodedPath)) {
      for(Path moduleExploded: directoryStream) {
        int exitCode = packageModule(log, jarTool, moduleExploded, moduleArtifactPath, packager, metadataMap, prefix);
        if (exitCode != 0) {
          return exitCode;
        }
      }
    }
  }
  return 0;
}
项目:pro    文件:PackagerPlugin.java   
private static int packageModule(Log log, ToolProvider jarTool, Path moduleExploded,  Path moduleArtifact, PackagerConf packager, Map<String, Metadata> metadataMap, String prefix) {
  Set<ModuleReference> set = ModuleFinder.of(moduleExploded).findAll();
  if (set.size() != 1) {
    throw new IllegalStateException("more than one module packaged in the exploded module " + moduleExploded);
  }

  String moduleName = set.iterator().next().descriptor().name(); 

  Optional<Metadata> metadata = Optional.ofNullable(metadataMap.get(moduleName));
  String version = metadata.flatMap(Metadata::version).orElse("1.0");
  Jar jar = new Jar(moduleExploded, moduleArtifact.resolve(prefix + moduleName + "-" + version + ".jar"));
  jar.setModuleVersion(version);
  metadata.flatMap(Metadata::mainClass).ifPresent(jar::setMainClass);
  packager.rawArguments().ifPresent(jar::rawArguments);

  CmdLine cmdLine = new CmdLine().add("--create");
  cmdLine = OptionAction.gatherAll(JarOption.class, option -> option.action).apply(jar, cmdLine);
  String[] arguments = cmdLine.add(".").toArguments();

  log.verbose(jar, _jar -> OptionAction.toPrettyString(JarOption.class, option -> option.action).apply(_jar, "jar"));
  int exitCode = jarTool.run(System.out, System.err, arguments);
  return exitCode;
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
@Test
public void testProviders() throws Exception {
    Map<String, ToolProvider> providers = new LinkedHashMap<>();
    for (ToolProvider tp : ServiceLoader.load(ToolProvider.class,
            ClassLoader.getSystemClassLoader())) {
        System.out.println("Provider: " + tp.name() + ": " + tp.getClass().getName());
        providers.put(tp.name(), tp);
    }
    if (!providers.containsKey("javadoc")) {
        error("javadoc ToolProvider not found");
    }
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
@Test
public void testProviders() throws Exception {
    Map<String, ToolProvider> providers = new LinkedHashMap<>();
    for (ToolProvider tp : ServiceLoader.load(ToolProvider.class,
            ClassLoader.getSystemClassLoader())) {
        System.out.println("Provider: " + tp.name() + ": " + tp.getClass().getName());
        providers.put(tp.name(), tp);
    }
    if (!providers.containsKey("javac")) {
        error("javac ToolProvider not found");
    }
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
private void test() throws Exception {
    ToolProvider testProvider = ToolProvider.findFirst("test").get();
    int rc = testProvider.run(System.out, System.err, "hello test");
    if (rc != 0) {
        throw new Exception("unexpected exit code: " + rc);
    }
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
private void initServices() throws IOException {
    Path testClasses = Paths.get(System.getProperty("test.classes"));
    Path services = testClasses.resolve(Paths.get("META-INF", "services"));
    Files.createDirectories(services);
    Files.write(services.resolve(ToolProvider.class.getName()),
            Arrays.asList(TestProvider.class.getName()));
}
项目:openjdk-jdk10    文件:ImageModules.java   
static ToolResult execTool(ToolProvider tool, String... args) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    List<String> filteredArgs = Stream.of(args)
                                      .map(s -> s.split(" ")).flatMap(Stream::of)
                                      .filter(s -> !s.equals(""))
                                      .collect(Collectors.toList());
    System.out.println(tool + " " + filteredArgs);
    int ec = tool.run(ps, ps, filteredArgs.toArray(new String[] {}));
    return new ToolResult(ec, new String(baos.toByteArray(), UTF_8));
}
项目:openjdk-jdk10    文件:JavaClassPathTest.java   
@BeforeTest
public void setup() throws Exception {
    boolean compiled = CompilerUtils.compile(SRC_DIR.resolve(TEST_MODULE),
                                             MODS_DIR.resolve(TEST_MODULE));
    assertTrue(compiled, "module " + TEST_MODULE + " did not compile");

    // add the class and a resource to the current working directory
    Path file = Paths.get("jdk/test/Main.class");
    Files.createDirectories(file.getParent());
    Files.copy(MODS_DIR.resolve(TEST_MODULE).resolve(file), file);

    Path res = Paths.get("jdk/test/res.properties");
    Files.createFile(res);

    ToolProvider jartool = ToolProvider.findFirst("jar").orElseThrow(
        () -> new RuntimeException("jar tool not found")
    );

    Path jarfile = LIB_DIR.resolve("m.jar");
    Files.createDirectories(LIB_DIR);
    assertTrue(jartool.run(System.out, System.err, "cfe",
                           jarfile.toString(), TEST_MAIN,
                           file.toString()) == 0);

    Path manifest = LIB_DIR.resolve("manifest");
    try (BufferedWriter writer = Files.newBufferedWriter(manifest)) {
        writer.write("CLASS-PATH: lib/m.jar");
    }
    jarfile = LIB_DIR.resolve("m1.jar");
    assertTrue(jartool.run(System.out, System.err, "cfme",
                           jarfile.toString(), manifest.toString(), TEST_MAIN,
                           file.toString()) == 0);
}
项目:pro    文件:ModuleFixerPlugin.java   
private static int patchModularJar(ToolProvider jarTool, ModuleReference ref, Path generatedModuleInfo) {
  System.out.println("[modulefixer] fix " + ref.descriptor().name());
  return jarTool.run(System.out, System.err,
      "--update",
      "--file", Paths.get(ref.location().get()).toString(),
      "-C", generatedModuleInfo.getParent().toString(),
      generatedModuleInfo.getFileName().toString());
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
ToolProviderTest() {
    super(System.err);
    javadoc = ToolProvider.findFirst("javadoc").get();
}
项目:openjdk-jdk10    文件:ToolProviderTest.java   
ToolProviderTest() {
    super(System.err);
    javac = ToolProvider.findFirst("javac").get();
}
项目:pro    文件:CompilerPlugin.java   
@Override
public int execute(Config config) throws IOException {
  Log log = Log.create(name(), config.getOrThrow("pro", ProConf.class).loglevel());
  log.debug(config, conf -> "config " + config);

  ToolProvider javacTool = ToolProvider.findFirst("javac")
      .orElseThrow(() -> new IllegalStateException("can not find javac"));
  CompilerConf compiler = config.getOrThrow(name(), CompilerConf.class);


  ModuleFinder moduleSourceFinder = ModuleHelper.sourceModuleFinders(compiler.moduleSourcePath());
  int errorCode = compile(log, javacTool, compiler,
      compiler.moduleSourcePath(),
      moduleSourceFinder,
      List.of(),
      compiler.moduleSourceResourcesPath(),
      compiler.moduleExplodedSourcePath(),
      "source:");
  if (errorCode != 0) {
    return errorCode;
  }
  List<Path> moduleTestPath = FileHelper.pathFromFilesThatExist(compiler.moduleTestPath());
  if (moduleTestPath.isEmpty()) {
    return 0;
  }

  ModuleFinder moduleTestFinder = ModuleHelper.sourceModuleFinders(compiler.moduleTestPath());
  if (moduleTestFinder.findAll().isEmpty()) {  // there is no test module-info defined
    log.info(compiler.moduleTestPath(), testPath -> "test: can not find any test modules in " + testPath.stream().map(Path::toString).collect(Collectors.joining(", ")));
    return 0;
  }

  Path moduleMergedTestPath = compiler.moduleMergedTestPath();
  deleteAllFiles(moduleMergedTestPath, false);

  errorCode = merge(moduleSourceFinder, moduleTestFinder, moduleMergedTestPath);
  if (errorCode != 0) {
    return errorCode;
  }

  ModuleFinder moduleMergedTestFinder = ModuleHelper.sourceModuleFinder(compiler.moduleMergedTestPath());
  return compile(log, javacTool, compiler,
      List.of(moduleMergedTestPath),
      moduleMergedTestFinder,
      List.of(compiler.moduleExplodedSourcePath()),
      StableList.<Path>of().appendAll(compiler.moduleSourceResourcesPath()).appendAll(compiler.moduleTestResourcesPath()),
      compiler.moduleExplodedTestPath(),
      "test:");
}
项目:pro    文件:CompilerPlugin.java   
private static int compile(Log log, ToolProvider javacTool, CompilerConf compiler, List<Path> moduleSourcePath, ModuleFinder moduleFinder, List<Path> additionalSourcePath, List<Path> resourcesPath, Path destination, String pass) throws IOException {
  Optional<List<Path>> modulePath = modulePathOrDependencyPath(compiler.modulePath(),
      compiler.moduleDependencyPath(), additionalSourcePath);

  ModuleFinder dependencyFinder = ModuleFinder.compose(
      modulePath
          .stream()
          .flatMap(List::stream)
          .map(ModuleFinder::of)
          .toArray(ModuleFinder[]::new));
  List<String> rootSourceNames = moduleFinder.findAll().stream()
          .map(ref -> ref.descriptor().name())
          .collect(Collectors.toList());
  if (rootSourceNames.isEmpty()) {
    log.error(moduleSourcePath, sourcePath -> pass + " can not find any modules in " + sourcePath.stream().map(Path::toString).collect(Collectors.joining(", ")));
    return 1; //FIXME
  }

  ModuleFinder systemFinder = ModuleHelper.systemModulesFinder();

  log.debug(moduleFinder, finder -> pass + " modules " + finder.findAll().stream().map(ref -> ref.descriptor().name()).sorted().collect(Collectors.joining(", ")));
  log.debug(dependencyFinder, finder -> pass + " dependency modules " + finder.findAll().stream().map(ref -> ref.descriptor().name()).sorted().collect(Collectors.joining(", ")));
  log.debug(systemFinder, finder -> pass + " system modules " + finder.findAll().stream().map(ref -> ref.descriptor().name()).sorted().collect(Collectors.joining(", ")));

  /*
  Configuration.resolveRequires(ModuleFinder.compose(sourceModuleFinder, dependencyFinder),
      List.of(Layer.boot().configuration()), ModuleFinder.of(), rootNames);
  */
  boolean resolved = ModuleHelper.resolveOnlyRequires(
      ModuleFinder.compose(moduleFinder, dependencyFinder, systemFinder),
      rootSourceNames,
      (moduleName, dependencyChain) -> {
        log.error(null, __ -> pass + " can not resolve " + moduleName + " from " + dependencyChain);
      });
  if (!resolved) {
    return 1;  //FIXME
  }

  deleteAllFiles(destination, false);

  Javac javac = new Javac(compiler.release(), destination, moduleSourcePath);
  compiler.verbose().ifPresent(javac::verbose);
  compiler.lint().ifPresent(javac::lint);
  compiler.rawArguments().ifPresent(javac::rawArguments);
  modulePath.ifPresent(javac::modulePath);
  compiler.upgradeModulePath().ifPresent(javac::upgradeModulePath);
  compiler.rootModules().ifPresent(javac::rootModules);


  CmdLine cmdLine = gatherAll(JavacOption.class, option -> option.action).apply(javac, new CmdLine());
  List<Path> files = compiler.files().orElseGet(
      () -> walkIfNecessary(moduleSourcePath, pathFilenameEndsWith(".java")));  //FIXME, use rootNames ??
  files.forEach(cmdLine::add);
  String[] arguments = cmdLine.toArguments();
  log.verbose(files, fs -> OptionAction.toPrettyString(JavacOption.class, option -> option.action).apply(javac, "javac") + "\n" + fs.stream().map(Path::toString).collect(Collectors.joining(" ")));

  int errorCode = javacTool.run(System.out, System.err, arguments);
  if (errorCode != 0) {
    return errorCode;
  }

  //copy all resources
  for(Path resources: resourcesPath) {
    if (Files.exists(resources)) {
      log.debug(null, __ -> "copy " + resources + " to " + destination);
      FileHelper.walkAndFindCounterpart(resources, destination, Function.identity(), (src, dest) -> {
        if (Files.isDirectory(src) && Files.isDirectory(dest)) { // do not overwrite directory
          return;
        }
        Files.copy(src, dest); 
      });
    }
  }
  return 0;
}
项目:pro    文件:LinkerPlugin.java   
@Override
public int execute(Config config) throws IOException {
  Log log = Log.create(name(), config.getOrThrow("pro", ProConf.class).loglevel());
  log.debug(config, conf -> "config " + config);

  ToolProvider jlinkTool = ToolProvider.findFirst("jlink")
      .orElseThrow(() -> new IllegalStateException("can not find jlink"));
  LinkerConf linker = config.getOrThrow(name(), LinkerConf.class);

  Path systemModulePath = linker.systemModulePath();
  if (!(Files.exists(systemModulePath))) {
    throw new IOException("unable to find system modules at " + systemModulePath);
  }

  ModuleFinder moduleFinder = ModuleFinder.of(linker.moduleArtifactSourcePath());
  Set<String> rootModules = linker.rootModules().map(HashSet::new).orElseGet(() -> {
    return moduleFinder.findAll().stream()
        .map(reference -> reference.descriptor().name())
        .collect(Collectors.toCollection(HashSet::new));
  });
  linker.serviceNames().ifPresent(serviceNames -> {
    ModuleFinder rootFinder = ModuleFinder.compose(moduleFinder, ModuleHelper.systemModulesFinder());
    ModuleHelper.findAllModulesWhichProvideAService(serviceNames, rootFinder)
      .map(ref -> ref.descriptor().name())
      .forEach(rootModules::add);
  });

  // find launchers
  List<String> launchers = linker.launchers().orElseGet(() -> findLaunchersFromMainClasses(rootModules, moduleFinder));
  if (launchers.isEmpty()) {
    log.error(null, __ -> "no launcher found and no main classes defined in the root modules");
    return 1; //FIXME
  }

  List<Path> modulePath =
      linker.modulePath()
        .orElseGet(() -> StableList.of(linker.moduleArtifactSourcePath())
              .appendAll(FileHelper.pathFromFilesThatExist(linker.moduleDependencyPath()))
              .append(systemModulePath));

  log.debug(rootModules, roots -> "rootModules " + roots);
  log.debug(launchers, launcherMains -> "launchers " + launcherMains);
  Jlink jlink = new Jlink(linker, rootModules, launchers, modulePath);

  Path destination = linker.destination();
  FileHelper.deleteAllFiles(destination, true);

  String[] arguments = OptionAction.gatherAll(JlinkOption.class, option -> option.action).apply(jlink, new CmdLine()).toArguments();
  log.verbose(null, __ -> OptionAction.toPrettyString(JlinkOption.class, option -> option.action).apply(jlink, "jlink"));

  int errorCode = jlinkTool.run(System.out, System.err, arguments);
  if (errorCode != 0) {
    return errorCode; 
  }

  if (linker.includeSystemJMODs()) {
    Path jmods = destination.resolve("jmods");
    Files.createDirectories(jmods);
    try(DirectoryStream<Path> stream = Files.newDirectoryStream(systemModulePath)) {
      for(Path path: stream) {
        Files.copy(path, jmods.resolve(path.getFileName()));
      }
    }
  }
  return 0;
}