Example usage for java.nio.file Path resolve

List of usage examples for java.nio.file Path resolve

Introduction

In this page you can find the example usage for java.nio.file Path resolve.

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testStripsPrefixAndIgnoresSiblings() throws IOException {
    byte[] bazDotSh = "echo \"baz.sh\"\n".getBytes(Charsets.UTF_8);
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        zip.putArchiveEntry(new ZipArchiveEntry("foo"));
        zip.closeArchiveEntry();/*ww  w.j  a v a2 s  .  c  om*/
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz.txt"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();

        ZipArchiveEntry exeEntry = new ZipArchiveEntry("foo/bar/baz.sh");
        exeEntry.setUnixMode(
                (int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        exeEntry.setMethod(ZipEntry.STORED);
        exeEntry.setSize(bazDotSh.length);
        zip.putArchiveEntry(exeEntry);
        zip.write(bazDotSh);

        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("sibling"));
        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("sibling/some/dir/and/file.txt"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();
    }

    Path extractFolder = Paths.get("output_dir", "nested");

    ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmpFolder.getRoot());

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(zipFile, filesystem, extractFolder,
            Optional.of(Paths.get("foo")), ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);

    assertFalse(filesystem.isDirectory(extractFolder.resolve("sibling")));
    assertFalse(filesystem.isDirectory(extractFolder.resolve("foo")));
    assertFalse(filesystem.isDirectory(extractFolder.resolve("some")));

    Path bazDotTxtPath = extractFolder.resolve("bar").resolve("baz.txt");
    Path bazDotShPath = extractFolder.resolve("bar").resolve("baz.sh");

    assertTrue(filesystem.isDirectory(extractFolder.resolve("bar")));
    assertTrue(filesystem.isFile(bazDotTxtPath));
    assertTrue(filesystem.isFile(bazDotShPath));
    assertTrue(filesystem.isExecutable(bazDotShPath));
    assertEquals(new String(bazDotSh), filesystem.readFileIfItExists(bazDotShPath).get());
    assertEquals(new String(DUMMY_FILE_CONTENTS), filesystem.readFileIfItExists(bazDotTxtPath).get());
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);//from   ww w  .java 2 s  .c  om
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output,
            ImmutableSortedSet.of(Paths.get("input.jar")), /* main class */ null, tmp.resolve("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context).getExitCode());

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

/**
 * From the constructor of {@link JarInputStream}:
 * <p>//from  w w w .j a v  a  2  s .co m
 * This implementation assumes the META-INF/MANIFEST.MF entry
 * should be either the first or the second entry (when preceded
 * by the dir META-INF/). It skips the META-INF/ and then
 * "consumes" the MANIFEST.MF to initialize the Manifest object.
 * <p>
 * A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be
 * included, adding them to the output jar, while merging manifest files, writing the merged
 * manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't
 * be able to find the manifest for.
 */
@Test
public void manifestShouldBeSecondEntryInJar() throws IOException {
    Path manifestPath = Paths.get(JarFile.MANIFEST_NAME);

    // Create a directory with a manifest in it and more than two files.
    Path dir = folder.newFolder();
    Manifest dirManifest = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("From-Dir", "cheese");
    dirManifest.getEntries().put("Section", attrs);

    Files.createDirectories(dir.resolve(manifestPath).getParent());
    try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) {
        dirManifest.write(out);
    }
    Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8));

    // Create a jar with a manifest and more than two other files.
    Path inputJar = folder.newFile("example.jar");
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) {
        byte[] data = "hello world".getBytes(UTF_8);
        ZipEntry entry = new ZipEntry("C.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("cc.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("META-INF/");
        zos.putNextEntry(entry);
        zos.closeEntry();

        // Note: at end of the stream. Technically invalid.
        entry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(entry);
        Manifest zipManifest = new Manifest();
        attrs = new Attributes();
        attrs.putValue("From-Zip", "peas");
        zipManifest.getEntries().put("Section", attrs);
        zipManifest.write(zos);
        zos.closeEntry();
    }

    // Merge and check that the manifest includes everything
    Path output = folder.newFile("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new FakeProjectFilesystem(folder.getRoot()), output,
            ImmutableSortedSet.of(dir, inputJar), null, null);
    int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode();

    assertEquals(0, exitCode);

    Manifest manifest;
    try (InputStream is = Files.newInputStream(output); JarInputStream jis = new JarInputStream(is)) {
        manifest = jis.getManifest();
    }

    assertNotNull(manifest);
    Attributes readAttributes = manifest.getAttributes("Section");
    assertEquals(2, readAttributes.size());
    assertEquals("cheese", readAttributes.getValue("From-Dir"));
    assertEquals("peas", readAttributes.getValue("From-Zip"));
}

From source file:eu.eubrazilcc.lvl.service.io.ImportSequencesTask.java

private Callable<Integer> importGenBankSubTask(final List<String> ids, final EntrezHelper entrez,
        final File tmpDir, final Format format, final String extension) {
    return new Callable<Integer>() {
        private int efetchCount = 0;

        @Override//from w w  w .ja  v  a2  s  .com
        public Integer call() throws Exception {
            setStatus("Finding missing sequences between GenBank and the local collection");
            // filter out the sequence that are already stored in the database, creating a new set
            // with the identifiers that are missing from the database. Using a set ensures that 
            // duplicate identifiers are also removed from the original list
            final List<String> ids2 = from(ids).transform(new Function<String, String>() {
                @Override
                public String apply(final String id) {
                    String result = id;
                    for (int i = 0; i < filters.size() && result != null; i++) {
                        final RecordFilter filter = filters.get(i);
                        if (filter.canBeApplied(GENBANK)) {
                            result = filters.get(i).filterById(id);
                        }
                    }
                    return result;
                }
            }).filter(notNull()).toSet().asList();
            if (ids2.size() > 0) {
                setStatus("Fetching sequences from GenBank");
                // update progress
                int pendingCount = pending.addAndGet(ids2.size());
                setProgress(100.0d * fetched.get() / pendingCount);
                // fetch sequence files
                final Path tmpDir2 = createTempDirectory(tmpDir.toPath(), "fetch_seq_task_");
                entrez.efetch(ids2, 0, MAX_RECORDS_FETCHED, tmpDir2.toFile(), format);
                // import sequence files to the database
                for (final String id : ids2) {
                    setStatus("Importing GenBank sequences into local collection");
                    final Path source = tmpDir2.resolve(id + "." + extension);
                    try {
                        // insert sequence in the database
                        final GBSeq gbSeq = GBSEQ_XMLB.typeFromFile(source.toFile());
                        final T sequence = parseSequence(gbSeq, builder);
                        dao.insert(sequence);
                        efetchCount++;
                        LOGGER.info("New GBSeqXML file stored: " + source.toString());
                        // update progress
                        int fetchedCount = fetched.incrementAndGet();
                        setProgress(100.0d * fetchedCount / pending.get());
                        // extract references from the sequence
                        pmids.addAll(getPubMedIds(gbSeq));
                    } catch (Exception e) {
                        LOGGER.warn("Failed to import sequence from file: " + source.getFileName(), e);
                    }
                }
            }
            checkState(ids2.size() == efetchCount, "No all sequences were imported");
            return efetchCount;
        }
    };
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testSymlinkForceCanDeleteDirectory() throws IOException {
    Path realFileDir = Files.createDirectory(tmp.getRoot().resolve("realfile"));
    Files.createFile(realFileDir.resolve("file"));
    Files.createFile(realFileDir.resolve("file2"));
    Path symlinkDir = Files.createDirectory(tmp.getRoot().resolve("symlink"));
    Files.createFile(symlinkDir.resolve("junk"));

    filesystem.createSymLink(symlinkDir, realFileDir, true);

    try (Stream<Path> paths = Files.list(symlinkDir)) {
        List<Path> filesFound = paths.collect(Collectors.toList());
        assertThat(filesFound, containsInAnyOrder(symlinkDir.resolve("file"), symlinkDir.resolve("file2")));
    }// www. j  a  v  a  2  s  .c  om
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testInstallPluginWithBadChecksum() throws IOException {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir.resolve("_site"));
    Files.createFile(pluginDir.resolve("_site").resolve("somefile"));
    String pluginUrl = createPluginWithBadChecksum(pluginDir, "description", "fake desc", "version", "1.0",
            "site", "true");
    assertStatus(String.format(Locale.ROOT, "install %s --verbose", pluginUrl), ExitStatus.IO_ERROR);
    assertThatPluginIsNotListed(pluginName);
    assertFileNotExists(environment.pluginsFile().resolve(pluginName).resolve("_site"));
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testInstallSitePlugin() throws IOException {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir.resolve("_site"));
    Files.createFile(pluginDir.resolve("_site").resolve("somefile"));
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "site", "true");
    ExitStatus status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    assertThat("Terminal output was: " + terminal.getTerminalOutput(), status, is(ExitStatus.OK));
    assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("Name: fake-plugin"))));
    assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("Description:"))));
    assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("Site:"))));
    assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("Version:"))));
    assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("JVM:"))));
    assertThatPluginIsListed(pluginName);
    // We want to check that Plugin Manager moves content to _site
    assertFileExists(environment.pluginsFile().resolve(pluginName).resolve("_site"));
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testInstallSitePluginVerbose() throws IOException {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir.resolve("_site"));
    Files.createFile(pluginDir.resolve("_site").resolve("somefile"));
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "site", "true");
    ExitStatus status = new PluginManagerCliParser(terminal)
            .execute(args("install " + pluginUrl + " --verbose"));
    assertThat("Terminal output was: " + terminal.getTerminalOutput(), status, is(ExitStatus.OK));
    assertThat(terminal.getTerminalOutput(), hasItem(containsString("Name: fake-plugin")));
    assertThat(terminal.getTerminalOutput(), hasItem(containsString("Description: fake desc")));
    assertThat(terminal.getTerminalOutput(), hasItem(containsString("Site: true")));
    assertThat(terminal.getTerminalOutput(), hasItem(containsString("Version: 1.0")));
    assertThat(terminal.getTerminalOutput(), hasItem(containsString("JVM: false")));
    assertThatPluginIsListed(pluginName);
    // We want to check that Plugin Manager moves content to _site
    assertFileExists(environment.pluginsFile().resolve(pluginName).resolve("_site"));
}

From source file:me.ryanhamshire.griefprevention.FlatFileDataStore.java

@Override
public void loadWorldData(World world) {
    WorldProperties worldProperties = world.getProperties();
    DimensionType dimType = worldProperties.getDimensionType();
    Path dimPath = rootConfigPath.resolve(((IMixinDimensionType) dimType).getModId())
            .resolve(((IMixinDimensionType) dimType).getEnumName());
    if (!Files.exists(dimPath.resolve(worldProperties.getWorldName()))) {
        try {//w  ww . ja v a2s . c  o m
            Files.createDirectories(dimPath.resolve(worldProperties.getWorldName()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // create/load configs
    // create dimension config
    DataStore.dimensionConfigMap.put(worldProperties.getUniqueId(),
            new GriefPreventionConfig<DimensionConfig>(Type.DIMENSION, dimPath.resolve("dimension.conf")));
    // create world config
    DataStore.worldConfigMap.put(worldProperties.getUniqueId(), new GriefPreventionConfig<>(Type.WORLD,
            dimPath.resolve(worldProperties.getWorldName()).resolve("world.conf")));

    GPClaimManager claimWorldManager = new GPClaimManager(worldProperties);
    this.claimWorldManagers.put(worldProperties.getUniqueId(), claimWorldManager);

    // check if world has existing data
    Path oldWorldDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(claimDataPath);
    Path oldPlayerDataPath = rootWorldSavePath.resolve(worldProperties.getWorldName()).resolve(playerDataPath);
    if (worldProperties.getUniqueId() == Sponge.getGame().getServer().getDefaultWorld().get().getUniqueId()) {
        oldWorldDataPath = rootWorldSavePath.resolve(claimDataPath);
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
        // use global player data
        oldPlayerDataPath = rootWorldSavePath.resolve(playerDataPath);
    }

    Path newWorldDataPath = dimPath.resolve(worldProperties.getWorldName());

    try {
        // Check for old data location
        if (Files.exists(oldWorldDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP claim data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP claim data from "
                    + oldWorldDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldWorldDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }
        if (Files.exists(oldPlayerDataPath)) {
            GriefPreventionPlugin.instance.getLogger().info("Detected GP player data in old location.");
            GriefPreventionPlugin.instance.getLogger().info("Migrating GP player data from "
                    + oldPlayerDataPath.toAbsolutePath() + " to " + newWorldDataPath.toAbsolutePath() + "...");
            FileUtils.moveDirectoryToDirectory(oldPlayerDataPath.toFile(), newWorldDataPath.toFile(), true);
            GriefPreventionPlugin.instance.getLogger().info("Done.");
        }

        // Create data folders if they do not exist
        if (!Files.exists(newWorldDataPath.resolve("ClaimData"))) {
            Files.createDirectories(newWorldDataPath.resolve("ClaimData"));
        }
        if (DataStore.USE_GLOBAL_PLAYER_STORAGE) {
            if (!globalPlayerDataPath.toFile().exists()) {
                Files.createDirectories(globalPlayerDataPath);
            }
        } else if (!Files.exists(newWorldDataPath.resolve("PlayerData"))) {
            Files.createDirectories(newWorldDataPath.resolve("PlayerData"));
        }

        // Migrate RedProtectData if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) {
            Path redProtectFilePath = redProtectDataPath
                    .resolve("data_" + worldProperties.getWorldName() + ".conf");
            Path gpMigratedPath = redProtectDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(redProtectFilePath) && !Files.exists(gpMigratedPath)) {
                RedProtectMigrator.migrate(world, redProtectFilePath, newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
        // Migrate Polis data if enabled
        if (GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.polisMigrator) {
            Path claimsFilePath = polisDataPath.resolve("claims.conf");
            Path teamsFilePath = polisDataPath.resolve("teams.conf");
            Path gpMigratedPath = polisDataPath.resolve("gp_migrated_" + worldProperties.getWorldName());
            if (Files.exists(claimsFilePath) && Files.exists(teamsFilePath) && !Files.exists(gpMigratedPath)) {
                PolisMigrator.migrate(world, claimsFilePath, teamsFilePath,
                        newWorldDataPath.resolve("ClaimData"));
                Files.createFile(gpMigratedPath);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Load Claim Data
    try {
        File[] files = newWorldDataPath.resolve("ClaimData").toFile().listFiles();
        if (files != null && files.length > 0) {
            this.loadClaimData(files, worldProperties);
            GriefPreventionPlugin.instance.getLogger()
                    .info("[" + worldProperties.getWorldName() + "] " + files.length + " total claims loaded.");
        }

        if (GriefPreventionPlugin.getGlobalConfig().getConfig().playerdata.useGlobalPlayerDataStorage) {
            files = globalPlayerDataPath.toFile().listFiles();
        } else {
            files = newWorldDataPath.resolve("PlayerData").toFile().listFiles();
        }
        if (files != null && files.length > 0) {
            this.loadPlayerData(worldProperties, files);
        }

        // If a wilderness claim was not loaded, create a new one
        if (claimWorldManager.getWildernessClaim() == null) {
            claimWorldManager.createWildernessClaim(worldProperties);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // handle default flag permissions
    this.setupDefaultPermissions(world);
}

From source file:edu.usc.goffish.gofs.util.partitioning.metis.MetisPartitioner.java

private Path partition(Path workingDir, Path metisInputPath, int numPartitions) throws IOException {

    // prepare metis command
    ProcessHelper.CommandBuilder command = new ProcessHelper.CommandBuilder(_metisBinaryPath.toString());
    if (_extraMetisOptions != null) {
        command.append(_extraMetisOptions);
    }/*from   ww  w. j a  v a 2 s.  c  o m*/
    command.append(metisInputPath).append(Integer.toString(numPartitions));

    // run metis
    try {
        System.out.println("executing: \"" + command + "\"");
        ProcessHelper.runProcess(workingDir.toFile(), true, command.toArray());
    } catch (InterruptedException e) {
        throw new IOException(e);
    }

    return workingDir.resolve(metisInputPath.getFileName() + ".part." + numPartitions);
}