java.nio.file.Path#resolve ( )源码实例Demo

下面列出了java.nio.file.Path#resolve ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private Signer createEthSigner(final TlsCertificateDefinition certInCa, final Path testDir)
    throws Exception {

  final Path passwordPath = testDir.resolve("keystore.passwd");
  writeString(passwordPath, serverCert.getPassword());

  final TlsOptions serverOptions =
      new BasicTlsOptions(
          serverCert.getPkcs12File(),
          passwordPath.toFile(),
          Optional.of(BasicClientAuthConstraints.caOnly()));

  final SignerConfigurationBuilder configBuilder = new SignerConfigurationBuilder();
  configBuilder.withServerTlsOptions(serverOptions);
  configBuilder.withOverriddenCA(certInCa);

  final ClientTlsConfig clientTlsConfig = new ClientTlsConfig(serverCert, clientCert);

  return new Signer(
      configBuilder.build(),
      new NodeConfigurationBuilder().build(),
      new NodePorts(1, 2),
      clientTlsConfig);
}
 
private static void assertExpectedClassFileFormats(
        String subprojectName, int mainJavaRelease, int moduleInfoJavaRelease) {
    Path basePath = Path.of("test-project-mixed").resolve(subprojectName).resolve("build/classes");
    Path classesDir = basePath.resolve("java/main");
    Path moduleInfoClassesDir = basePath.resolve("module-info");

    List<Path> moduleInfoPaths = Stream.of(classesDir, moduleInfoClassesDir)
            .map(dir -> dir.resolve("module-info.class"))
            .filter(path -> path.toFile().isFile())
            .collect(Collectors.toList());
    assertEquals(1, moduleInfoPaths.size(), "module-info.class found in multiple locations: " + moduleInfoPaths);
    Path moduleInfoClassPath = moduleInfoPaths.get(0);
    try {
        SmokeTestHelper.assertClassFileJavaVersion(moduleInfoJavaRelease, moduleInfoClassPath);

        Path nonModuleInfoClassPath = SmokeTestHelper.anyNonModuleInfoClassFilePath(classesDir);
        SmokeTestHelper.assertClassFileJavaVersion(mainJavaRelease, nonModuleInfoClassPath);
    } catch (IOException e) {
        fail(e);
    }
}
 
源代码3 项目: openjdk-jdk9   文件: MultiModuleModeTest.java
@Test
public void testCantFindModule(Path base) throws Exception {
    Path src = base.resolve("src");
    Path src_m1 = src.resolve("m1x");
    tb.writeJavaFiles(src_m1, "module m1x { }");
    Path misc = base.resolve("misc");
    tb.writeJavaFiles(misc, "package p; class C { }");
    Path classes = base.resolve("classes");
    tb.createDirectories(classes);

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

    if (!log.contains("C.java:1:1: compiler.err.not.in.module.on.module.source.path"))
        throw new Exception("expected output not found");
}
 
源代码4 项目: openjdk-jdk9   文件: ModuleBuilder.java
/**
 * Writes the module declaration and associated additional compilation
 * units to a module directory within a given directory.
 * @param srcDir the directory in which a directory will be created
 *  to contain the source files for the module
 * @return the directory containing the source files for the module
 */
public Path write(Path srcDir) throws IOException {
    Files.createDirectories(srcDir);
    List<String> sources = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    if (!comment.isEmpty()) {
        sb.append("/**\n * ")
                .append(comment.replace("\n", "\n * "))
                .append("\n */\n");
    }
    sb.append("module ").append(name).append(" {\n");
    requires.forEach(r -> sb.append("    " + r + "\n"));
    exports.forEach(e -> sb.append("    " + e + "\n"));
    opens.forEach(o -> sb.append("    " + o + "\n"));
    uses.forEach(u -> sb.append("    " + u + "\n"));
    provides.forEach(p -> sb.append("    " + p + "\n"));
    sb.append("}");
    sources.add(sb.toString());
    sources.addAll(content);
    Path moduleSrc = srcDir.resolve(name);
    tb.writeJavaFiles(moduleSrc, sources.toArray(new String[]{}));
    return moduleSrc;
}
 
源代码5 项目: openjdk-jdk8u   文件: DockerTestUtils.java
/**
 * Build a docker image that contains JDK under test.
 * The jdk will be placed under the "/jdk/" folder inside the docker file system.
 *
 * @param imageName     name of the image to be created, including version tag
 * @param dockerfile    name of the dockerfile residing in the test source;
 *                      we check for a platform specific dockerfile as well
 *                      and use this one in case it exists
 * @param buildDirName  name of the docker build/staging directory, which will
 *                      be created in the jtreg's scratch folder
 * @throws Exception
 */
public static void
    buildJdkDockerImage(String imageName, String dockerfile, String buildDirName)
        throws Exception {
    Path buildDir = Paths.get(".", buildDirName);
    if (Files.exists(buildDir)) {
        throw new RuntimeException("The docker build directory already exists: " + buildDir);
    }
    // check for the existance of a platform specific docker file as well
    String platformSpecificDockerfile = dockerfile + "-" + Platform.getOsArch();
    if (Files.exists(Paths.get(Utils.TEST_SRC, platformSpecificDockerfile))) {
      dockerfile = platformSpecificDockerfile;
    }

    Path jdkSrcDir = Paths.get(Utils.TEST_JDK);
    Path jdkDstDir = buildDir.resolve("jdk");

    Files.createDirectories(jdkDstDir);

    // Copy JDK-under-test tree to the docker build directory.
    // This step is required for building a docker image.
    Files.walkFileTree(jdkSrcDir, new CopyFileVisitor(jdkSrcDir, jdkDstDir));
    buildDockerImage(imageName, Paths.get(Utils.TEST_SRC, dockerfile), buildDir);
}
 
源代码6 项目: jsr203-hadoop   文件: TestFiles.java
@Test
public void createFile() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  Path path = rootPath.resolve("test");

  Set<PosixFilePermission> perms = EnumSet.of(
      PosixFilePermission.OWNER_READ,
      PosixFilePermission.OWNER_WRITE, 
      PosixFilePermission.OWNER_EXECUTE,
      PosixFilePermission.GROUP_READ);
  Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));
}
 
源代码7 项目: marathonv5   文件: Copy.java
public static Path copy(Path source, Path target, Operation operation) throws IOException {
    if (source.equals(target)) {
        return null;
    }
    Path dest = target.resolve(source.getFileName());
    if (operation == Operation.CUT && dest.equals(source)) {
        return null;
    }
    dest = getUnique(dest);
    // follow links when copying files
    EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    TreeCopier tc = new TreeCopier(source, dest, operation);
    Files.walkFileTree(source, opts, Integer.MAX_VALUE, tc);
    return dest;
}
 
源代码8 项目: org.openntf.domino   文件: Factory.java
private static Path getConfigFileFallback() {
	Path progpath = Paths.get(System.getProperty("notes.binary")); //$NON-NLS-1$
	Path iniFile = progpath.resolve("notes.ini"); //$NON-NLS-1$
	if (!Files.exists(iniFile)) {
		progpath = Paths.get(System.getProperty("user.dir")); //$NON-NLS-1$
		iniFile = progpath.resolve("notes.ini"); //$NON-NLS-1$
	}
	if (!Files.exists(iniFile)) {
		progpath = Paths.get(System.getProperty("java.home")); //$NON-NLS-1$
		if (progpath.endsWith("jvm")) { //$NON-NLS-1$
			iniFile = progpath.getParent().resolve("notes.ini"); //$NON-NLS-1$
		} else {
			iniFile = progpath.resolve("notes.ini"); //$NON-NLS-1$
		}
	}
	if (!Files.exists(iniFile)) {
		progpath = Paths.get(System.getProperty("java.library.path")); // Otherwise the tests will not work //$NON-NLS-1$
		iniFile = progpath.resolve("notes.ini"); //$NON-NLS-1$
	}
	if (!Files.exists(iniFile)) {
		if (progpath.toString().contains("framework")) { //$NON-NLS-1$
			String pp2 = progpath.toString().replace("framework", ""); //$NON-NLS-1$ //$NON-NLS-2$
			iniFile = Paths.get(pp2).resolve("notes.ini"); //$NON-NLS-1$
			if (!Files.exists(iniFile)) {
				Factory.println("WARNING: Unable to read environment for log setup. Please look at the following properties...");
				for (Object rawName : System.getProperties().keySet()) {
					if (rawName instanceof String) {
						Factory.println((String) rawName + " = " + System.getProperty((String) rawName));
					}
				}
			}
		}
	}
	return iniFile;
}
 
源代码9 项目: buck   文件: WatchedFileHashCacheTest.java
@Test
public void thatWillGetIsCorrect() throws IOException {
  ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
  Path buckOut = filesystem.getBuckPaths().getBuckOut();
  filesystem.mkdirs(buckOut);
  Path buckOutFile = buckOut.resolve("file.txt");
  Path otherFile = Paths.get("file.txt");
  filesystem.writeContentsToPath("data", buckOutFile);
  filesystem.writeContentsToPath("other data", otherFile);
  WatchedFileHashCache cache = new WatchedFileHashCache(filesystem, fileHashCacheMode);
  assertFalse(cache.willGet(filesystem.getPath("buck-out/file.txt")));
  assertTrue(cache.willGet(filesystem.getPath("file.txt")));
}
 
源代码10 项目: buck   文件: AndroidManifestParserTest.java
@Test
public void testEmptyMinSdkVersionWhenAttributeMissing() {
  Path directory = TestDataHelper.getTestDataDirectory(this);
  Path androidManifestPath =
      directory.resolve("manifests/missing_min_sdk_attribute/AndroidManifest.xml");
  Optional<String> minSdkVersion = androidManifestParser.parseMinSdkVersion(androidManifestPath);

  Assert.assertFalse(minSdkVersion.isPresent());
}
 
/**
 * https://issues.jboss.org/browse/WFCORE-1890
 *
 * When FS deployment is erplaced with a managed deployment with same name it is not marked as undeployed and reboot will fail.
 */
@Test
public void testReplaceDeploymentWithPersistentDeployment() throws Exception {
    container.start();
    try {
        try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient())  {
            final PathAddress persistentDeploymentAddress = PathAddress.pathAddress(DEPLOYMENT, JAR_ONE);
            addDeploymentScanner(client, 0, true, true);
            try {
                Path deployDir = getDeployDirPath();
                // deploy an file-system deployment
                container.stop();
                createDeployment(deployDir.resolve(JAR_ONE), "org.jboss.modules");
                container.start();
                Path deployedMarker = deployDir.resolve(JAR_ONE + ".deployed");
                waitFor(String.format("Missing .deployed marker for %s", JAR_ONE),
                        () -> Files.exists(deployedMarker));
                Assert.assertTrue(String.format("%s should be deployed", JAR_ONE), exists(client, persistentDeploymentAddress));
                //Replace deployment
                Archive<?> validDeployment = createDeploymentArchive("org.jboss.modules");
                replaceWithPersistent(client, JAR_ONE, validDeployment);
                Assert.assertTrue(String.format("%s should be deployed", JAR_ONE), exists(client, persistentDeploymentAddress));
                waitFor(String.format("Missing .undeployed marker for %s", JAR_ONE),
                        () -> Files.exists(deployDir.resolve(JAR_ONE + ".undeployed")));
            } finally {
                removeDeploymentScanner(client);
                client.execute(Util.createRemoveOperation(persistentDeploymentAddress));
            }
        }
    } finally {
        container.stop();
    }
}
 
源代码12 项目: n4js   文件: AbstractCliCompileTest.java
private static File setupWorkspace(String testDataRoot, String testDataSet,
		Predicate<N4JSProjectName> n4jsLibrariesPredicate, boolean createYarnWorkspace) throws IOException {
	Path fixture = new File(testDataRoot, testDataSet).toPath();
	Path root = FileUtils.createTempDirectory(testDataRoot + "_" + testDataSet + "_");
	root = root.toFile().getCanonicalFile().toPath();
	Path wsp = root.resolve(WSP);
	N4CliHelper.setupWorkspace(fixture, wsp, n4jsLibrariesPredicate, createYarnWorkspace);
	return wsp.toFile();
}
 
源代码13 项目: openjdk-jdk9   文件: ModuleInfoTest.java
@Test
public void testTooOpenModule(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src, "open open module M { }",
            "package p1; public class A { }");
    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:6: compiler.err.expected.module"))
        throw new Exception("expected output not found");
}
 
源代码14 项目: yajsync   文件: SystemTest.java
@Test
public void testClientCopyPreserveGid() throws IOException
{
    if (!User.JVM_USER.equals(User.ROOT)) {
        return;
    }

    Path src = _tempDir.newFolder().toPath();
    Path dst = Paths.get(src.toString() + ".dst");

    Path srcDir = src.resolve("dir");
    Path srcFile = srcDir.resolve("file");
    Files.createDirectory(srcDir);
    FileUtil.writeToFiles(1, srcFile);
    FileUtil._fileManager.setGroupId(srcFile, User.NOBODY.id());

    Files.createDirectory(dst);
    Path copyOfSrc = dst.resolve(src.getFileName());
    Files.createDirectory(copyOfSrc);
    Path dstDir = copyOfSrc.resolve("dir");
    Path dstFile = dstDir.resolve("file");
    Files.createDirectory(dstDir);
    FileUtil.writeToFiles(1, dstFile);

    ReturnStatus status = fileCopy(src, dst, "--recursive", "--group",
                                   "--numeric-ids");

    assertTrue(status.rc == 0);
    assertTrue(FileUtil.isDirectory(dst));
    assertTrue(FileUtil.isDirectoriesIdentical(src, copyOfSrc));
    assertTrue(FileUtil.isFileSameGroup(FileUtil._fileManager.stat(srcFile),
                                        FileUtil._fileManager.stat(dstFile)));
}
 
源代码15 项目: jolie   文件: ModuleFinder.java
/**
 * Perform a lookup to a ol filename from basePath
 * 
 * @param basePath base path for lookup
 * @param filename a filename
 * @return a new path of ol file, null if file is not found
 */
static Path olLookup( Path basePath, String filename ) throws FileNotFoundException {
	Path olPath = basePath.resolve( filename + ".ol" );
	if( Files.exists( olPath ) ) {
		return olPath;
	}
	throw new FileNotFoundException( olPath.toString() );
}
 
源代码16 项目: copybara   文件: GitRepository.java
/** Creates a new repository in the given directory. The new repo is not bare. */
public static GitRepository newRepo(boolean verbose, Path path, GitEnvironment gitEnv,
    Duration fetchTimeout, boolean noVerify) {
  return new GitRepository(path.resolve(".git"), path, verbose, gitEnv, fetchTimeout, noVerify);
}
 
private TextAssert assertSettings(SettingsGradleProjectContributor contributor) throws IOException {
	Path projectDir = Files.createTempDirectory(this.directory, "project-");
	contributor.contribute(projectDir);
	return new TextAssert(projectDir.resolve("test.gradle"));
}
 
源代码18 项目: buck   文件: AppleTestIntegrationTest.java
@Test
public void testWithDepsCompileDeps() throws Exception {
  assumeTrue(
      AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.IPHONESIMULATOR));
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "apple_test_with_lib_deps", tmp);
  workspace.setUp();

  BuildTarget buildTarget = workspace.newBuildTarget("//:foo#compile-deps");
  workspace
      .runBuckCommand(
          "build",
          "--config",
          "cxx.default_platform=iphonesimulator-x86_64",
          buildTarget.getFullyQualifiedName())
      .assertSuccess();

  Path projectRoot = Paths.get(tmp.getRoot().toFile().getCanonicalPath());
  Path outputPath =
      projectRoot.resolve(
          BuildTargetPaths.getGenPath(filesystem, buildTarget.withAppendedFlavors(), "%s")
              .resolve(AppleTestDescription.COMPILE_DEPS.toString()));
  Path archivePath = outputPath.resolve("code").resolve("TEST_DEPS.a");

  ProcessExecutor.Result binaryFileTypeResult =
      workspace.runCommand("file", "-b", archivePath.toString());
  assertEquals(0, binaryFileTypeResult.getExitCode());
  assertThat(
      binaryFileTypeResult.getStdout().orElse(""),
      containsString("current ar archive random library"));

  ProcessExecutor.Result otoolResult =
      workspace.runCommand("otool", "-L", archivePath.toString());
  assertEquals(0, otoolResult.getExitCode());
  String otoolStdout = otoolResult.getStdout().orElse("");
  assertThat(otoolStdout, containsString("Bar.m.o"));
  assertThat(otoolStdout, containsString("Baz.m.o"));
  assertThat(otoolStdout, not(containsString("Foo.m.o")));

  ProcessExecutor.Result nmResult = workspace.runCommand("nm", "-p", archivePath.toString());
  assertEquals(0, nmResult.getExitCode());
  String nmStdout = nmResult.getStdout().orElse("");
  assertThat(nmStdout, containsString("t +[Bar bar]"));
  assertThat(nmStdout, containsString("t +[Baz baz]"));
  assertThat(nmStdout, not(containsString("_OBJC_CLASS_$_Foo")));
}
 
源代码19 项目: BIMserver   文件: EclipsePluginClassloader.java
public EclipsePluginClassloader(ClassLoader parentClassloader, Path projectFolder) {
	super(parentClassloader);
	this.projectFolder = projectFolder;
	this.classFolder = projectFolder.resolve("target/classes");
}
 
源代码20 项目: syndesis   文件: AbstractMavenProjectBuilder.java
@Override
public Project build(IntegrationSource source) {
    try {
        Path projectDir = Files.createTempDirectory(outputDir, name);

        LOG.info(String.format("Building integration project in directory: '%s'", projectDir.toAbsolutePath()));

        ProjectGenerator projectGenerator = new ProjectGenerator(projectGeneratorConfiguration,
                new StaticIntegrationResourceManager(source),
                mavenProperties);
        try (TarArchiveInputStream in = new TarArchiveInputStream(projectGenerator.generate(source.get(), System.out::println))) {
            ArchiveEntry archiveEntry = in.getNextEntry();
            while (archiveEntry != null) {
                Path fileOrDirectory = projectDir.resolve(archiveEntry.getName());
                if (archiveEntry.isDirectory()) {
                    if (!Files.exists(fileOrDirectory)) {
                        Files.createDirectories(fileOrDirectory);
                    }
                } else {
                    Path parent = fileOrDirectory.getParent();
                    if (parent != null) {
                        Files.createDirectories(parent);
                    }
                    Files.copy(in, fileOrDirectory);
                }

                archiveEntry = in.getNextEntry();
            }
        }

        customizePomFile(source, projectDir.resolve("pom.xml"));
        customizeIntegrationFile(source, projectDir.resolve("src").resolve("main").resolve("resources").resolve("syndesis").resolve("integration").resolve("integration.json"));

        // auto add secrets and other integration test settings to application properties
        Files.write(projectDir.resolve("src").resolve("main").resolve("resources").resolve("application.properties"),
                getApplicationProperties(source).getBytes(Charset.forName("utf-8")), StandardOpenOption.APPEND);
        return new Project.Builder().projectPath(projectDir).build();
    } catch (IOException e) {
        throw new IllegalStateException("Failed to create integration project", e);
    }
}