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

The following examples show how to use java.nio.file.Path#resolve() . 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: DockerTestUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: ServerSideTlsCaClientAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: ModuleBuilder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: ModulePluginSmokeTest.java    From gradle-modules-plugin with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: MultiModuleModeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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");
}
 
Example 6
Source File: AndroidManifestParserTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 7
Source File: ModuleInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example 8
Source File: SystemTest.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
@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)));
}
 
Example 9
Source File: AbstractCliCompileTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
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();
}
 
Example 10
Source File: TestFiles.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 11
Source File: DeploymentScannerUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example 12
Source File: WatchedFileHashCacheTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@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")));
}
 
Example 13
Source File: Factory.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: Copy.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: ModuleFinder.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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() );
}
 
Example 16
Source File: AppleTestIntegrationTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@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")));
}
 
Example 17
Source File: AbstractMavenProjectBuilder.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 18
Source File: EclipsePluginClassloader.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public EclipsePluginClassloader(ClassLoader parentClassloader, Path projectFolder) {
	super(parentClassloader);
	this.projectFolder = projectFolder;
	this.classFolder = projectFolder.resolve("target/classes");
}
 
Example 19
Source File: SettingsGradleProjectContributorTests.java    From initializr with Apache License 2.0 4 votes vote down vote up
private TextAssert assertSettings(SettingsGradleProjectContributor contributor) throws IOException {
	Path projectDir = Files.createTempDirectory(this.directory, "project-");
	contributor.contribute(projectDir);
	return new TextAssert(projectDir.resolve("test.gradle"));
}
 
Example 20
Source File: GitRepository.java    From copybara with Apache License 2.0 4 votes vote down vote up
/** 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);
}