Java Code Examples for java.nio.file.Path.resolve()

The following are Jave code examples for showing how to use resolve() of the java.nio.file.Path class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: SymLinkTest.java   View Source Code Vote up 7 votes
void test(Path base, String name) throws IOException {
    Path file = base.resolve(name);
    Path javaFile = base.resolve("HelloWorld.java");
    tb.writeFile(file,
            "public class HelloWorld {\n"
            + "    public static void main(String... args) {\n"
            + "        System.err.println(\"Hello World!\");\n"
            + "    }\n"
            + "}");

    try {
        Files.createSymbolicLink(javaFile, file.getFileName());
    } catch (FileSystemException fse) {
        System.err.println("warning: test passes vacuously, sym-link could not be created");
        System.err.println(fse.getMessage());
        return;
    }

    Path classes = Files.createDirectories(base.resolve("classes"));
    new JavacTask(tb)
        .outdir(classes)
        .files(javaFile)
        .run()
        .writeAll();
}
 
Example 2
Project: openjdk-jdk10   File: ProvidesTest.java   View Source Code Vote up 6 votes
@Test
public void testMissingService(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src,
            "module m { provides p.Missing with p.C; }",
            "package p; public class C extends p.Missing { }");

    List<String> output = new JavacTask(tb)
            .options("-XDrawDiagnostics")
            .outdir(Files.createDirectories(base.resolve("classes")))
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutputLines(Task.OutputKind.DIRECT);

    List<String> expected = Arrays.asList(
            "C.java:1:36: compiler.err.cant.resolve.location: kindname.class, Missing, , , (compiler.misc.location: kindname.package, p, null)",
            "module-info.java:1:22: compiler.err.cant.resolve.location: kindname.class, Missing, , , (compiler.misc.location: kindname.package, p, null)",
            "2 errors");
    if (!output.containsAll(expected)) {
        throw new Exception("Expected output not found");
    }
}
 
Example 3
Project: launcher-backend   File: GitHubServiceIT.java   View Source Code Vote up 6 votes
@Test
public void createGitHubRepositoryWithContent() throws Exception {
    // given
    final String repositoryName = generateRepositoryName();
    Path tempDirectory = Files.createTempDirectory("test");
    Path file = tempDirectory.resolve("README.md");
    Files.write(file, Collections.singletonList("Read me to know more"), Charset.forName("UTF-8"));

    // when
    final GitRepository targetRepo = getGitHubService().createRepository(repositoryName, MY_GITHUB_REPO_DESCRIPTION);
    getGitHubService().push(targetRepo, tempDirectory.toFile());

    // then
    Assert.assertEquals(GitHubTestCredentials.getUsername() + "/" + repositoryName, targetRepo.getFullName());
    URI readmeUri = UriBuilder.fromUri("https://raw.githubusercontent.com/")
            .path(GitHubTestCredentials.getUsername())
            .path(repositoryName)
            .path("/master/README.md").build();
    HttpURLConnection connection = (HttpURLConnection) readmeUri.toURL().openConnection();
    Assert.assertEquals("README.md should have been pushed to the repo", 200, connection.getResponseCode());

    FileUtils.forceDelete(tempDirectory.toFile());
}
 
Example 4
Project: openjdk-jdk10   File: ConfigurationTest.java   View Source Code Vote up 6 votes
/**
 * Writes a module-info.class. If {@code targetPlatform} is not null then
 * it includes the ModuleTarget class file attribute with the target platform.
 */
static Path writeModule(ModuleDescriptor descriptor, String targetPlatform)
    throws IOException
{
    ModuleTarget target;
    if (targetPlatform != null) {
        target = new ModuleTarget(targetPlatform);
    } else {
        target = null;
    }
    String name = descriptor.name();
    Path dir = Files.createTempDirectory(Paths.get(""), name);
    Path mi = dir.resolve("module-info.class");
    try (OutputStream out = Files.newOutputStream(mi)) {
        ModuleInfoWriter.write(descriptor, target, out);
    }
    return dir;
}
 
Example 5
Project: openjdk-jdk10   File: ModulePathTest.java   View Source Code Vote up 6 votes
@Test
public void testNotADirOnPath_1(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "class C { }");
    tb.writeFile("dummy.txt", "");

    String log = new JavacTask(tb, Task.Mode.CMDLINE)
            .options("-XDrawDiagnostics",
                    "--module-path", "dummy.txt")
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.contains("- compiler.err.illegal.argument.for.option: --module-path, dummy.txt"))
        throw new Exception("expected output not found");
}
 
Example 6
Project: r8   File: RequireNonNullRewriteTest.java   View Source Code Vote up 6 votes
private void runTest(CompilationMode mode)
    throws IOException, CompilationException, ExecutionException {
  final Path inputPath = Paths.get(ToolHelper.EXAMPLES_BUILD_DIR + "/rewrite.jar");
  Path outputPath = tmpOutputDir.newFolder().toPath();

  compileWithD8(inputPath, outputPath, mode);

  Path dexPath = outputPath.resolve("classes.dex");

  DexInspector dexInspector = new DexInspector(dexPath);
  ClassSubject classSubject = dexInspector.clazz("rewrite.RequireNonNull");
  MethodSubject methodSubject = classSubject
      .method("java.lang.Object", "nonnullRemove", Collections.emptyList());

  Iterator<InvokeInstructionSubject> iterator =
      methodSubject.iterateInstructions(InstructionSubject::isInvoke);
  Assert.assertTrue(iterator.hasNext());
  Assert.assertEquals("getClass", iterator.next().invokedMethod().name.toString());
  Assert.assertFalse(iterator.hasNext());

  runTest(inputPath, dexPath);
}
 
Example 7
Project: openjdk-jdk10   File: ModuleInfoTest.java   View Source Code Vote up 6 votes
/**
 * Verify that duplicate requires are detected.
 */
@Test
public void testDuplicateRequires(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1x");
    tb.writeFile(src_m1.resolve("module-info.java"), "module m1x { }");
    Path src_m2 = src.resolve("m2x");
    tb.writeFile(src_m2.resolve("module-info.java"), "module m2x { requires m1x; requires m1x; }");

    Path classes = base.resolve("classes");
    Files.createDirectories(classes);

    String log = new JavacTask(tb)
            .options("-XDrawDiagnostics", "--module-source-path", src.toString())
            .outdir(classes)
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.contains("module-info.java:1:37: compiler.err.duplicate.requires: m1x"))
        throw new Exception("expected output not found");
}
 
Example 8
Project: openjdk-jdk10   File: Modules.java   View Source Code Vote up 6 votes
@Test
public void testMissingModuleWithSourcePath(Path base) throws Exception {
    Path src = base.resolve("src");
    Path mod = src.resolve("m1");

    ModuleBuilder mb1 = new ModuleBuilder(tb, "m1");
    mb1.comment("The first module.")
            .exports("m1pub")
            .requires("m2")
            .classes("package m1pub; /** Class A */ public class A {}")
            .classes("package m1pro; /** Class B */ public class B {}")
            .write(src);

    Path javafile = Paths.get(mod.toString(), "m1pub/A.java");

    execNegativeTask("--source-path", mod.toString(),
            javafile.toString());

    assertMessagePresent("error: cannot access module-info");
    assertMessageNotPresent("error - fatal error encountered");

}
 
Example 9
Project: elasticsearch_my   File: InstallPluginCommand.java   View Source Code Vote up 5 votes
/** Load information about the plugin, and verify it can be installed with no errors. */
private PluginInfo verify(Terminal terminal, Path pluginRoot, boolean isBatch, Environment env) throws Exception {
    // read and validate the plugin descriptor
    PluginInfo info = PluginInfo.readFromProperties(pluginRoot);

    // checking for existing version of the plugin
    final Path destination = env.pluginsFile().resolve(info.getName());
    if (Files.exists(destination)) {
        final String message = String.format(
            Locale.ROOT,
            "plugin directory [%s] already exists; if you need to update the plugin, uninstall it first using command 'remove %s'",
            destination.toAbsolutePath(),
            info.getName());
        throw new UserException(ExitCodes.CONFIG, message);
    }

    terminal.println(VERBOSE, info.toString());

    // don't let user install plugin as a module...
    // they might be unavoidably in maven central and are packaged up the same way)
    if (MODULES.contains(info.getName())) {
        throw new UserException(
                ExitCodes.USAGE, "plugin '" + info.getName() + "' cannot be installed like this, it is a system module");
    }

    // check for jar hell before any copying
    jarHellCheck(pluginRoot, env.pluginsFile());

    // read optional security policy (extra permissions)
    // if it exists, confirm or warn the user
    Path policy = pluginRoot.resolve(PluginInfo.ES_PLUGIN_POLICY);
    if (Files.exists(policy)) {
        PluginSecurity.readPolicy(policy, terminal, env, isBatch);
    }

    return info;
}
 
Example 10
Project: openjdk-jdk10   File: IncCompInheritance.java   View Source Code Vote up 5 votes
public static void main(String... args) throws Exception {

        Path root = Paths.get(IncCompInheritance.class.getSimpleName() + "Test");
        Path src = root.resolve("src");
        Path classes = root.resolve("classes");

        // Prep source files: A <- B <- C
        String a = "package pkga; public class A { public void m() {} }";
        String b = "package pkgb; public class B extends pkga.A {}";
        String c = "package pkgc; public class C extends pkgb.B {{ new pkgb.B().m(); }}";
        toolbox.writeFile(src.resolve("pkga/A.java"), a);
        toolbox.writeFile(src.resolve("pkgb/B.java"), b);
        toolbox.writeFile(src.resolve("pkgc/C.java"), c);

        // Initial compile (should succeed)
        int rc1 = compile("-d", classes, "--state-dir=" + classes, src);
        if (rc1 != 0)
            throw new AssertionError("Compilation failed unexpectedly");

        // Remove method A.m
        Thread.sleep(2500); // Make sure we get a new timestamp
        String aModified = "package pkga; public class A { }";
        toolbox.writeFile(src.resolve("pkga/A.java"), aModified);

        // Incremental compile (C should now be recompiled even though it
        // depends on A only through inheritance via B).
        // Since A.m is removed, this should fail.
        int rc2 = compile("-d", classes, "--state-dir=" + classes, src);
        if (rc2 == 0)
            throw new AssertionError("Compilation succeeded unexpectedly");
    }
 
Example 11
Project: openjdk-jdk10   File: TestDriver.java   View Source Code Vote up 5 votes
private static void setup(Path userDir) throws IOException {
    Path src = Paths.get(System.getProperty("test.src"));
    Path testJar = src.resolve(ARCHIVE_NAME);
    Path policy = src.resolve(POLICY_FILE);
    Path testClass = Paths.get(System.getProperty("test.classes"),
                               TEST_NAME + ".class");
    Files.copy(testJar, userDir.resolve(ARCHIVE_NAME), REPLACE_EXISTING);
    Files.copy(policy, userDir.resolve(POLICY_FILE), REPLACE_EXISTING);
    Files.copy(testClass, userDir.resolve(TEST_NAME + ".class"),
               REPLACE_EXISTING);
    Files.createDirectories(userDir.resolve("tmp"));
}
 
Example 12
Project: elasticsearch_my   File: SecurityTests.java   View Source Code Vote up 5 votes
public void testEnsureRegularFile() throws IOException {
    Path p = createTempDir();

    // regular file
    Path regularFile = p.resolve("regular");
    Files.createFile(regularFile);
    try {
        Security.ensureDirectoryExists(regularFile);
        fail("didn't get expected exception");
    } catch (IOException expected) {}
}
 
Example 13
Project: openjdk-jdk10   File: AnnotationProcessing.java   View Source Code Vote up 5 votes
@Test
public void testAPMultiModule(Path base) throws Exception {
    Path moduleSrc = base.resolve("module-src");
    Path m1 = moduleSrc.resolve("m1x");
    Path m2 = moduleSrc.resolve("m2x");

    Path classes = base.resolve("classes");

    Files.createDirectories(classes);

    tb.writeJavaFiles(m1,
                      "module m1x { }",
                      "package impl1; public class Impl1 { }");

    tb.writeJavaFiles(m2,
                      "module m2x { }",
                      "package impl2; public class Impl2 { }");

    String log = new JavacTask(tb)
            .options("--module-source-path", moduleSrc.toString(),
                     "-processor", AP.class.getName(),
                     "-AexpectedEnclosedElements=m1x=>impl1,m2x=>impl2")
            .outdir(classes)
            .files(findJavaFiles(moduleSrc))
            .run()
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.isEmpty())
        throw new AssertionError("Unexpected output: " + log);
}
 
Example 14
Project: openjdk-jdk10   File: ModuleInfoTest.java   View Source Code Vote up 5 votes
/**
 * Verify that a simple loop is detected.
 */
@Test
public void testRequiresSelf(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "module M { requires M; }");
    String log = new JavacTask(tb)
            .options("-XDrawDiagnostics")
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.contains("module-info.java:1:21: compiler.err.cyclic.requires: M"))
        throw new Exception("expected output not found");
}
 
Example 15
Project: openjdk-jdk10   File: AddReadsTest.java   View Source Code Vote up 5 votes
private Path prepareTestJar(Path base) throws Exception {
    Path legacySrc = base.resolve("legacy-src");
    tb.writeJavaFiles(legacySrc,
                      "package api; public abstract class Api {}");
    Path legacyClasses = base.resolve("legacy-classes");
    Files.createDirectories(legacyClasses);

    String log = new JavacTask(tb)
            .options()
            .outdir(legacyClasses)
            .files(findJavaFiles(legacySrc))
            .run()
            .writeAll()
            .getOutput(Task.OutputKind.DIRECT);

    if (!log.isEmpty()) {
        throw new Exception("unexpected output: " + log);
    }

    Path lib = base.resolve("lib");

    Files.createDirectories(lib);

    Path jar = lib.resolve("test-api-1.0.jar");

    new JarTask(tb, jar)
      .baseDir(legacyClasses)
      .files("api/Api.class")
      .run();

    return jar;
}
 
Example 16
Project: openjdk-jdk10   File: ContainsTest.java   View Source Code Vote up 5 votes
@Test
public void testJarPath(Path base) throws IOException {
    // Test that we can look up in jar files on a search path.
    // In this case, the path we look up must come from open file system
    // as used by the file manager.
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "package p; class C { }");
    Path classes = Files.createDirectories(base.resolve("classes"));
    new JavacTask(tb)
        .options("-sourcepath", src.toString())
        .outdir(classes)
        .files(findJavaFiles(src))
        .run()
        .writeAll();

    Path jar = base.resolve("classes.jar");
    new JarTask(tb).run("cf", jar.toString(), "-C", classes.toString(), "p");

    Path c = src.resolve("p/C.java");
    Path x = base.resolve("src2/p/C.java");

    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.CLASS_PATH, List.of(src, jar));

        checkContains(fm, StandardLocation.CLASS_PATH, c, true);
        checkContains(fm, StandardLocation.CLASS_PATH, x, false);

        JavaFileObject fo = fm.list(StandardLocation.CLASS_PATH, "p",
                EnumSet.of(JavaFileObject.Kind.CLASS), false).iterator().next();

        checkContains(fm, StandardLocation.CLASS_PATH, fo, true);
    }
}
 
Example 17
Project: elasticsearch_my   File: ScriptServiceTests.java   View Source Code Vote up 5 votes
@Before
public void setup() throws IOException {
    Path genericConfigFolder = createTempDir();
    baseSettings = Settings.builder()
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(Environment.PATH_CONF_SETTING.getKey(), genericConfigFolder)
            .put(ScriptService.SCRIPT_MAX_COMPILATIONS_PER_MINUTE.getKey(), 10000)
            .build();
    resourceWatcherService = new ResourceWatcherService(baseSettings, null);
    scriptEngineService = new TestEngineService();
    dangerousScriptEngineService = new TestDangerousEngineService();
    TestEngineService defaultScriptServiceEngine = new TestEngineService(Script.DEFAULT_SCRIPT_LANG) {};
    scriptEnginesByLangMap = ScriptModesTests.buildScriptEnginesByLangMap(
            new HashSet<>(Arrays.asList(scriptEngineService, defaultScriptServiceEngine)));
    //randomly register custom script contexts
    int randomInt = randomIntBetween(0, 3);
    //prevent duplicates using map
    Map<String, ScriptContext.Plugin> contexts = new HashMap<>();
    for (int i = 0; i < randomInt; i++) {
        String plugin;
        do {
            plugin = randomAsciiOfLength(randomIntBetween(1, 10));
        } while (ScriptContextRegistry.RESERVED_SCRIPT_CONTEXTS.contains(plugin));
        String operation;
        do {
            operation = randomAsciiOfLength(randomIntBetween(1, 30));
        } while (ScriptContextRegistry.RESERVED_SCRIPT_CONTEXTS.contains(operation));
        String context = plugin + "_" + operation;
        contexts.put(context, new ScriptContext.Plugin(plugin, operation));
    }
    scriptEngineRegistry = new ScriptEngineRegistry(Arrays.asList(scriptEngineService, dangerousScriptEngineService,
            defaultScriptServiceEngine));
    scriptContextRegistry = new ScriptContextRegistry(contexts.values());
    scriptSettings = new ScriptSettings(scriptEngineRegistry, scriptContextRegistry);
    scriptContexts = scriptContextRegistry.scriptContexts().toArray(new ScriptContext[scriptContextRegistry.scriptContexts().size()]);
    logger.info("--> setup script service");
    scriptsFilePath = genericConfigFolder.resolve("scripts");
    Files.createDirectories(scriptsFilePath);
}
 
Example 18
Project: chipKIT-importer   File: LinuxArduinoConfig.java   View Source Code Vote up 4 votes
@Override
public Path getSketchPath() {
    Path userHomePath = Paths.get( System.getProperty("user.home") );
    return userHomePath.resolve("Arduino");
}
 
Example 19
Project: googles-monorepo-demo   File: MoreFilesTest.java   View Source Code Vote up 4 votes
public void testCreateParentDirectories_symlinkParentExists() throws IOException {
  Path symlink = tempDir.resolve("linkToDir");
  Files.createSymbolicLink(symlink, root());
  Path file = symlink.resolve("foo");
  MoreFiles.createParentDirectories(file);
}
 
Example 20
Project: openjdk-jdk10   File: ExportsUnexported.java   View Source Code Vote up 4 votes
@Test
public void testSuppressResetProperly(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_api = src.resolve("api");
    tb.writeJavaFiles(src_api,
                      "module api {\n" +
                      "    exports api;\n" +
                      "}\n",
                      "package api;\n" +
                      "public class Api {\n" +
                      "    @SuppressWarnings(\"exports\")\n" +
                      "    public PackagePrivateClass f1;\n" +
                      "    public PackagePrivateClass f2;\n" +
                      "    @SuppressWarnings(\"exports\")\n" +
                      "    public void t() {}\n" +
                      "    public PackagePrivateClass f3;\n" +
                      "    @SuppressWarnings(\"exports\")\n" +
                      "    public static class C {\n" +
                      "        public PackagePrivateClass f4;\n" +
                      "    }\n" +
                      "    public PackagePrivateClass f5;\n" +
                      "}\n" +
                      "class PackagePrivateClass<T> {}\n");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);

    List<String> log = new JavacTask(tb)
            .options("-XDrawDiagnostics",
                     "-Werror",
                     "--module-source-path", src.toString(),
                     "-Xlint:exports")
            .outdir(classes)
            .files(findJavaFiles(src))
            .run(Task.Expect.FAIL)
            .writeAll()
            .getOutputLines(Task.OutputKind.DIRECT);

    List<String> expected = Arrays.asList(
        "Api.java:5:12: compiler.warn.leaks.not.accessible: kindname.class, api.PackagePrivateClass, api",
        "Api.java:8:12: compiler.warn.leaks.not.accessible: kindname.class, api.PackagePrivateClass, api",
        "Api.java:13:12: compiler.warn.leaks.not.accessible: kindname.class, api.PackagePrivateClass, api",
        "- compiler.err.warnings.and.werror",
        "1 error",
        "3 warnings"
    );

    if (!log.equals(expected))
        throw new Exception("expected output not found");
}