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:org.apache.taverna.databundle.DataBundles.java

public static Path newListItem(Path list) throws IOException {
    createList(list);//from  ww  w  . j ava 2 s .c o m
    return list.resolve(Long.toString(getListSize(list)));
}

From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java

private static void writeLimits(Network network, EurostagDictionary dictionary, Domain domain, OutputStream os)
        throws IOException {
    GenericArchive archive = domain.getArchiveFactory().create(GenericArchive.class);
    try (FileSystem fileSystem = ShrinkWrapFileSystems.newFileSystem(archive)) {
        Path rootDir = fileSystem.getPath("/");
        // dump first current limits for each of the branches
        try (BufferedWriter writer = Files.newBufferedWriter(rootDir.resolve(CURRENT_LIMITS_CSV),
                StandardCharsets.UTF_8)) {
            for (Line l : network.getLines()) {
                dumpLimits(dictionary, writer, l);
            }/*  w  w w  .  java2 s.  c o m*/
            for (TwoWindingsTransformer twt : network.getTwoWindingsTransformers()) {
                dumpLimits(dictionary, writer, twt);
            }
            for (DanglingLine dl : network.getDanglingLines()) {
                dumpLimits(dictionary, writer, dl.getId(), dl.getCurrentLimits(), null,
                        dl.getTerminal().getVoltageLevel().getNominalV(),
                        dl.getTerminal().getVoltageLevel().getNominalV());
            }
        }
        try (BufferedWriter writer = Files.newBufferedWriter(rootDir.resolve(VOLTAGE_LIMITS_CSV),
                StandardCharsets.UTF_8)) {
            for (Bus b : network.getBusBreakerView().getBuses()) {
                VoltageLevel vl = b.getVoltageLevel();
                if (!Float.isNaN(vl.getLowVoltageLimit()) && !Float.isNaN(vl.getHighVoltageLimit())) {
                    writer.write(dictionary.getEsgId(b.getId()));
                    writer.write(";");
                    writer.write(Float.toString(vl.getLowVoltageLimit()));
                    writer.write(";");
                    writer.write(Float.toString(vl.getHighVoltageLimit()));
                    writer.write(";");
                    writer.write(Float.toString(vl.getNominalV()));
                    writer.newLine();
                }
            }
        }

        //dump lines dictionary, for WP43 integration
        dumpLinesDictionary(network, dictionary, rootDir);
        //dump buses dictionary, for WP43 integration
        dumpBusesDictionary(network, dictionary, rootDir);
    }

    archive.as(ZipExporter.class).exportTo(os);
}

From source file:org.apache.taverna.databundle.DataBundles.java

private static Path anyExtension(Path directory, String fileName) throws IOException {
    Path path = directory.resolve(fileName);

    // Prefer the fileName as it is
    if (Files.exists(path))
        return path;
    // Strip any existing extension
    String fileNameNoExt = filenameWithoutExtension(path);
    Path withoutExt = path.resolveSibling(fileNameNoExt);
    if (Files.exists(withoutExt))
        return withoutExt;

    // Check directory for path.*
    for (Path p : newDirectoryStream(directory, fileNameNoExt + ".*"))
        /*/*ww w. j  a va  2s.  c  o m*/
         * We'll just return the first one
         * 
         * TODO: Should we fail if there's more than one?
         */
        return p;

    /*
     * Nothing? Then let's give the existing one; perhaps it is to be
     * created.
     */
    return path;
}

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

/**
 * Get a listing of all files in a zip file that start with a prefix, ignore others
 *
 * @param zip The zip file to scan/*from   w  w w  .j  a v a2  s .co m*/
 * @param relativePath The relative path where the extraction will be rooted
 * @param prefix The prefix that will be stripped off.
 * @return The list of paths in {@code zip} sorted by path so dirs come before contents. Prefixes
 *     are stripped from paths in the zip file, such that foo/bar/baz.txt with a prefix of foo/
 *     will be in the map at {@code relativePath}/bar/baz.txt
 */
private static SortedMap<Path, ZipArchiveEntry> getZipFilePathsStrippingPrefix(ZipFile zip, Path relativePath,
        Path prefix, PatternsMatcher entriesToExclude) {
    SortedMap<Path, ZipArchiveEntry> pathMap = new TreeMap<>();
    for (ZipArchiveEntry entry : Collections.list(zip.getEntries())) {
        String entryName = entry.getName();
        if (entriesToExclude.matchesAny(entryName)) {
            continue;
        }
        Path entryPath = Paths.get(entryName);
        if (entryPath.startsWith(prefix)) {
            Path target = relativePath.resolve(prefix.relativize(entryPath)).normalize();
            pathMap.put(target, entry);
        }
    }
    return pathMap;
}

From source file:io.hightide.TemplateFetcher.java

public static Path extractTemplate(Path tempFile, Path targetDir) throws IOException {
    try (FileInputStream fin = new FileInputStream(tempFile.toFile());
            BufferedInputStream in = new BufferedInputStream(fin);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn)) {
        TarArchiveEntry entry;//from  ww  w . j  a  v  a 2 s  . c  o  m
        Path rootDir = null;
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry.getName());
            if (entry.isDirectory()) {
                if (isNull(rootDir)) {
                    rootDir = targetDir.resolve(entry.getName());
                }
                Files.createDirectory(targetDir.resolve(entry.getName()));
            } else {
                int count;
                byte data[] = new byte[BUFFER];

                FileOutputStream fos = new FileOutputStream(targetDir.resolve(entry.getName()).toFile());
                BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.close();
            }
        }

        return rootDir;
    }
}

From source file:org.apache.taverna.databundle.DataBundles.java

public static Path getIntermediate(Bundle dataBundle, UUID uuid) throws IOException {
    String fileName = uuid.toString();
    Path intermediates = getIntermediates(dataBundle);
    // Folder is named after first 2 characters of UUID
    Path folder = intermediates.resolve(fileName.substring(0, 2));
    createDirectories(folder);/*from  w  ww . ja  v a2  s.c o m*/
    return anyExtension(folder, fileName);
}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void addFileToZip(@Nonnull Path sourceStream, @Nonnull Path destZipFile, @Nonnull String destFile,
        CopyOption... copyOptions) {
    try (FileSystem zipFileSystem = createZipFileSystem(destZipFile, false)) {
        final Path root = zipFileSystem.getPath("/");
        Path destFilePath = root.resolve(destFile);
        Files.createDirectories(destFilePath.getParent());
        logger.debug("Copy {} to {}, destFile: {}", sourceStream, destFile, destFilePath);

        Files.copy(sourceStream, destFilePath, copyOptions);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception adding file " + sourceStream + " to " + destZipFile, e);
    }/*from ww w .  j  a va2  s. c  om*/
}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void addFileToZip(@Nonnull InputStream sourceFile, @Nonnull Path destZipFile,
        @Nonnull String destFile, CopyOption... copyOptions) {
    try (FileSystem zipFileSystem = createZipFileSystem(destZipFile, false)) {
        final Path root = zipFileSystem.getPath("/");
        Path destFilePath = root.resolve(destFile);
        Files.createDirectories(destFilePath.getParent());
        logger.debug("Copy {} to {}, destFile: {}", sourceFile, destFile, destFilePath);

        Files.copy(sourceFile, destFilePath, copyOptions);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception adding file " + sourceFile + " to " + destZipFile, e);
    }/*from   ww w.ja v  a  2s . c o m*/
}

From source file:com.facebook.buck.zip.Unzip.java

/**
 * Unzips a file to a destination and returns the paths of the written files.
 *//*w  w  w . j ava2 s  .  co m*/
public static ImmutableList<Path> extractZipFile(Path zipFile, ProjectFilesystem filesystem, Path relativePath,
        ExistingFileMode existingFileMode) throws IOException {
    // if requested, clean before extracting
    if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) {
        try (ZipFile zip = new ZipFile(zipFile.toFile())) {
            Enumeration<ZipArchiveEntry> entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();
                filesystem.deleteRecursivelyIfExists(relativePath.resolve(entry.getName()));
            }
        }
    }
    ImmutableList.Builder<Path> filesWritten = ImmutableList.builder();
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = entry.getName();
            Path target = relativePath.resolve(fileName);

            // TODO(bolinfest): Keep track of which directories have already been written to avoid
            // making unnecessary Files.createDirectories() calls. In practice, a single zip file will
            // have many entries in the same directory.

            if (entry.isDirectory()) {
                // Create the directory and all its parent directories
                filesystem.mkdirs(target);
            } else {
                // Create parent folder
                filesystem.createParentDirs(target);

                filesWritten.add(target);
                // Write file
                try (InputStream is = zip.getInputStream(entry)) {
                    if (entry.isUnixSymlink()) {
                        filesystem.createSymLink(target,
                                filesystem.getPath(new String(ByteStreams.toByteArray(is), Charsets.UTF_8)),
                                /* force */ true);
                    } else {
                        try (OutputStream out = filesystem.newFileOutputStream(target)) {
                            ByteStreams.copy(is, out);
                        }
                    }
                }

                // restore mtime for the file
                filesystem.resolve(target).toFile().setLastModified(entry.getTime());

                // TODO(shs96c): Implement what the comment below says we should do.
                //
                // Sets the file permissions of the output file given the information in {@code entry}'s
                // extra data field. According to the docs at
                // http://www.opensource.apple.com/source/zip/zip-6/unzip/unzip/proginfo/extra.fld there
                // are two extensions that might support file permissions: Acorn and ASi UNIX. We shall
                // assume that inputs are not from an Acorn SparkFS. The relevant section from the docs:
                //
                // <pre>
                //    The following is the layout of the ASi extra block for Unix.  The
                //    local-header and central-header versions are identical.
                //    (Last Revision 19960916)
                //
                //    Value         Size        Description
                //    -----         ----        -----------
                //   (Unix3) 0x756e        Short       tag for this extra block type ("nu")
                //   TSize         Short       total data size for this block
                //   CRC           Long        CRC-32 of the remaining data
                //   Mode          Short       file permissions
                //   SizDev        Long        symlink'd size OR major/minor dev num
                //   UID           Short       user ID
                //   GID           Short       group ID
                //   (var.)        variable    symbolic link filename
                //
                //   Mode is the standard Unix st_mode field from struct stat, containing
                //   user/group/other permissions, setuid/setgid and symlink info, etc.
                // </pre>
                //
                // From the stat man page, we see that the following mask values are defined for the file
                // permissions component of the st_mode field:
                //
                // <pre>
                //   S_ISUID   0004000   set-user-ID bit
                //   S_ISGID   0002000   set-group-ID bit (see below)
                //   S_ISVTX   0001000   sticky bit (see below)
                //
                //   S_IRWXU     00700   mask for file owner permissions
                //
                //   S_IRUSR     00400   owner has read permission
                //   S_IWUSR     00200   owner has write permission
                //   S_IXUSR     00100   owner has execute permission
                //
                //   S_IRWXG     00070   mask for group permissions
                //   S_IRGRP     00040   group has read permission
                //   S_IWGRP     00020   group has write permission
                //   S_IXGRP     00010   group has execute permission
                //
                //   S_IRWXO     00007   mask for permissions for others
                //   (not in group)
                //   S_IROTH     00004   others have read permission
                //   S_IWOTH     00002   others have write permission
                //   S_IXOTH     00001   others have execute permission
                // </pre>
                //
                // For the sake of our own sanity, we're going to assume that no-one is using symlinks,
                // but we'll check and throw if they are.
                //
                // Before we do anything, we should check the header ID. Pfft!
                //
                // Having jumped through all these hoops, it turns out that InfoZIP's "unzip" store the
                // values in the external file attributes of a zip entry (found in the zip's central
                // directory) assuming that the OS creating the zip was one of an enormous list that
                // includes UNIX but not Windows, it first searches for the extra fields, and if not found
                // falls through to a code path that supports MS-DOS and which stores the UNIX file
                // attributes in the upper 16 bits of the external attributes field.
                //
                // We'll support neither approach fully, but we encode whether this file was executable
                // via storing 0100 in the fields that are typically used by zip implementations to store
                // POSIX permissions. If we find it was executable, use the platform independent java
                // interface to make this unpacked file executable.

                Set<PosixFilePermission> permissions = MorePosixFilePermissions
                        .fromMode(entry.getExternalAttributes() >> 16);
                if (permissions.contains(PosixFilePermission.OWNER_EXECUTE)) {
                    MoreFiles.makeExecutable(filesystem.resolve(target));
                }
            }
        }
    }
    return filesWritten.build();
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy the given {@code zipSubFilePath} of the given {@code zipFile} into the {@code destDir} if this sub file exists.
 *
 * @param zipFile        the source zip file (e.g. {@code path/to/app.war}
 * @param zipSubFilePath sub file path in the zip file (e.g. {@code /WEB-INF/web.xml}
 * @param destDir/*  w w  w  . j a  v a 2  s  . c om*/
 * @param trimSourcePath indicates if the source path should be trimmed creating the dest file (e.g. should {@code WEB-INF/web.xml} be copied as
 *                       {@code dest-dir/WEB-INF/web.xml} or as {@code dest-dir/web.xml})
 * @throws RuntimeIOException
 */
@Nullable
public static Path unzipSubFileIfExists(@Nonnull Path zipFile, @Nonnull String zipSubFilePath,
        @Nonnull final Path destDir, boolean trimSourcePath) throws RuntimeIOException {
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath("/");

            Path subFile = root.resolve(zipSubFilePath);
            if (Files.exists(subFile)) {
                // make file path relative
                Path destFile;
                if (trimSourcePath) {
                    destFile = destDir.resolve(subFile.getFileName().toString());
                } else {
                    if (Strings2.beginWith(zipSubFilePath, "/")) {
                        destFile = destDir.resolve("." + zipSubFilePath);
                    } else {
                        destFile = destDir.resolve(zipSubFilePath);
                    }
                }
                // create parent dirs if needed
                Files.createDirectories(destFile.getParent());
                // copy
                return Files.copy(subFile, destFile, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.COPY_ATTRIBUTES);
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubFilePath + " to " + destDir,
                e);
    }
}