Example usage for java.nio.file Path startsWith

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

Introduction

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

Prototype

default boolean startsWith(String other) 

Source Link

Document

Tests if this path starts with a Path , constructed by converting the given path string, in exactly the manner specified by the #startsWith(Path) startsWith(Path) method.

Usage

From source file:org.apache.taverna.robundle.manifest.Manifest.java

public void populateFromBundle() throws IOException {
    final Set<Path> potentiallyEmptyFolders = new LinkedHashSet<>();

    final Set<URI> existingAggregationsToPrune = new HashSet<>(aggregates.keySet());

    walkFileTree(bundle.getRoot(), new SimpleFileVisitor<Path>() {
        @SuppressWarnings("deprecation")
        @Override//from www. java2 s . c  o  m
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            super.postVisitDirectory(dir, exc);
            if (potentiallyEmptyFolders.remove(dir)) {
                URI uri = relativeToBundleRoot(dir.toUri());
                existingAggregationsToPrune.remove(uri);
                PathMetadata metadata = aggregates.get(uri);
                if (metadata == null) {
                    metadata = new PathMetadata();
                    aggregates.put(uri, metadata);
                }
                metadata.setFile(withSlash(dir));
                metadata.setFolder(withSlash(dir.getParent()));
                metadata.setProxy();
                metadata.setCreatedOn(getLastModifiedTime(dir));
                potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
                return CONTINUE;
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (dir.startsWith(RO) || dir.startsWith(META_INF))
                return SKIP_SUBTREE;
            potentiallyEmptyFolders.add(withSlash(dir));
            potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
            return CONTINUE;
        }

        @SuppressWarnings("deprecation")
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            potentiallyEmptyFolders.remove(withSlash(file.getParent()));
            if (file.startsWith(MIMETYPE))
                return CONTINUE;
            if (manifest.contains(file))
                // Don't aggregate the manifests
                return CONTINUE;

            // super.visitFile(file, attrs);
            URI uri = relativeToBundleRoot(file.toUri());
            existingAggregationsToPrune.remove(uri);
            PathMetadata metadata = aggregates.get(uri);
            if (metadata == null) {
                metadata = new PathMetadata();
                aggregates.put(uri, metadata);
            }
            metadata.setFile(file);
            if (metadata.getMediatype() == null)
                // Don't override if already set
                metadata.setMediatype(guessMediaType(file));
            metadata.setFolder(withSlash(file.getParent()));
            metadata.setProxy();
            metadata.setCreatedOn(getLastModifiedTime(file));
            potentiallyEmptyFolders.remove(file.getParent());
            return CONTINUE;
        }
    });
    for (URI preExisting : existingAggregationsToPrune) {
        PathMetadata meta = aggregates.get(preExisting);
        if (meta.getFile() != null)
            /*
             * Don't remove 'virtual' resources, only aggregations that went
             * to files
             */
            aggregates.remove(preExisting);
    }
}

From source file:com.github.podd.example.ExamplePoddClient.java

public Map<Path, String> uploadToStorage(final List<Path> bagsToUpload, final String sshServerFingerprint,
        final String sshHost, final int portNo, final String username, final Path pathToPublicKey,
        final Path localRootPath, final Path remoteRootPath, final PasswordFinder keyExtractor)
        throws PoddClientException, NoSuchAlgorithmException, IOException {
    final Map<Path, String> results = new ConcurrentHashMap<>();

    final ConcurrentMap<Path, ConcurrentMap<PoddDigestUtils.Algorithm, String>> digests = PoddDigestUtils
            .getDigests(bagsToUpload);/*  www  .  j a  v  a 2 s.  com*/

    try (SSHClient sshClient = new SSHClient(ExamplePoddClient.DEFAULT_CONFIG);) {
        sshClient.useCompression();
        sshClient.addHostKeyVerifier(sshServerFingerprint);
        sshClient.connect(sshHost, portNo);
        if (!Files.exists(pathToPublicKey)) {
            throw new PoddClientException("Could not find public key: " + pathToPublicKey);
        }
        if (!SecurityUtils.isBouncyCastleRegistered()) {
            throw new PoddClientException("Bouncy castle needed");
        }
        final FileKeyProvider rsa = new PKCS8KeyFile();
        rsa.init(pathToPublicKey.toFile(), keyExtractor);
        sshClient.authPublickey(username, rsa);
        // Session session = sshClient.startSession();
        try (SFTPClient sftp = sshClient.newSFTPClient();) {
            for (final Path nextBag : bagsToUpload) {
                // Check to make sure that the bag was under the local root path
                final Path localPath = nextBag.toAbsolutePath();
                if (!localPath.startsWith(localRootPath)) {
                    this.log.error(
                            "Local bag path was not a direct descendant of the local root path: {} {} {}",
                            localRootPath, nextBag, localPath);
                    throw new PoddClientException(
                            "Local bag path was not a direct descendant of the local root path: " + localPath
                                    + " " + localRootPath);
                }

                // Take the local root path out to get the subpath to use on the remote
                final Path remoteSubPath = localPath.subpath(localRootPath.getNameCount(),
                        nextBag.getNameCount() - 1);

                this.log.info("Remote sub path: {}", remoteSubPath);

                final Path remoteDirPath = remoteRootPath.resolve(remoteSubPath);
                this.log.info("Remote dir path: {}", remoteDirPath);

                final Path remoteBagPath = remoteDirPath.resolve(nextBag.getFileName());

                this.log.info("Remote bag path: {}", remoteBagPath);

                boolean fileFound = false;
                boolean sizeCorrect = false;
                try {
                    // check details of a remote bag
                    final FileAttributes attribs = sftp.lstat(remoteBagPath.toAbsolutePath().toString());
                    final long localSize = Files.size(nextBag);
                    final long remoteSize = attribs.getSize();

                    if (localSize <= 0) {
                        this.log.error("Local bag was empty: {}", nextBag);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (remoteSize <= 0) {
                        this.log.warn("Remote bag was empty: {} {}", nextBag, attribs);
                        sizeCorrect = false;
                        fileFound = false;
                    } else if (localSize == remoteSize) {
                        this.log.info("Found file on remote already with same size as local: {} {}", nextBag,
                                remoteBagPath);
                        sizeCorrect = true;
                        fileFound = true;
                    } else {
                        sizeCorrect = false;
                        fileFound = true;
                        // We always assume that a non-zero local file is correct
                        // The bags contain time-stamps that will be modified when they are
                        // regenerated, likely changing the file-size, and hopefully changing
                        // the digest checksums
                        // throw new PoddClientException(
                        // "Could not automatically compare file sizes (need manual intervention to delete one) : "
                        // + nextBag + " " + remoteBagPath + " localSize=" + localSize
                        // + " remoteSize=" + remoteSize);
                    }
                } catch (final IOException e) {
                    // lstat() throws an IOException if the file does not exist
                    // Ignore
                    sizeCorrect = false;
                    fileFound = false;
                }

                final ConcurrentMap<Algorithm, String> bagDigests = digests.get(nextBag);
                if (bagDigests.isEmpty()) {
                    this.log.error("No bag digests were generated for bag: {}", nextBag);
                }
                for (final Entry<Algorithm, String> entry : bagDigests.entrySet()) {
                    final Path localDigestPath = localPath
                            .resolveSibling(localPath.getFileName() + entry.getKey().getExtension());
                    // Create the local digest file
                    Files.copy(
                            new ReaderInputStream(new StringReader(entry.getValue()), StandardCharsets.UTF_8),
                            localDigestPath);
                    final Path remoteDigestPath = remoteBagPath
                            .resolveSibling(remoteBagPath.getFileName() + entry.getKey().getExtension());
                    boolean nextDigestFileFound = false;
                    boolean nextDigestCorrect = false;
                    try {
                        final Path tempFile = Files.createTempFile("podd-digest-",
                                entry.getKey().getExtension());
                        final SFTPFileTransfer sftpFileTransfer = new SFTPFileTransfer(sftp.getSFTPEngine());
                        sftpFileTransfer.download(remoteBagPath.toAbsolutePath().toString(),
                                tempFile.toAbsolutePath().toString());
                        nextDigestFileFound = true;

                        final List<String> allLines = Files.readAllLines(tempFile, StandardCharsets.UTF_8);
                        if (allLines.isEmpty()) {
                            nextDigestCorrect = false;
                        } else if (allLines.size() > 1) {
                            nextDigestCorrect = false;
                        }
                        // Check if the digests match exactly
                        else if (allLines.get(0).equals(entry.getValue())) {
                            nextDigestCorrect = true;
                        } else {
                            nextDigestCorrect = false;
                        }
                    } catch (final IOException e) {
                        nextDigestFileFound = false;
                        nextDigestCorrect = false;
                    }
                    if (nextDigestFileFound && nextDigestCorrect) {
                        this.log.info(
                                "Not copying digest to remote as it exists and contains the same content as the local digest");
                    } else if (nextDigestFileFound && !nextDigestCorrect) {
                        this.log.error("Found remote digest but content was not correct: {} {}",
                                localDigestPath, remoteDigestPath);
                        sftp.rm(remoteDigestPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    } else if (!nextDigestFileFound) {
                        this.log.info("About to make directories on remote: {}", remoteDirPath);
                        sftp.mkdirs(remoteDirPath.toString());
                        this.log.info("Copying digest to remote: {}", remoteDigestPath);
                        sftp.put(new FileSystemFile(localDigestPath.toString()), remoteDigestPath.toString());
                    }
                }

                if (fileFound && sizeCorrect) {
                    this.log.info("Not copying bag to remote as it exists and is the same size as local bag");
                } else if (fileFound && !sizeCorrect) {
                    this.log.error("Found remote bag but size was not correct: {} {}", nextBag, remoteBagPath);
                    sftp.rm(remoteBagPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                } else if (!fileFound) {
                    this.log.info("About to make directories on remote: {}", remoteDirPath);
                    sftp.mkdirs(remoteDirPath.toString());
                    this.log.info("Copying bag to remote: {}", remoteBagPath);
                    sftp.put(new FileSystemFile(localPath.toString()), remoteBagPath.toString());
                }

            }
        }
    } catch (final IOException e) {
        throw new PoddClientException("Could not copy a bag to the remote location", e);
    }

    return results;
}

From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java

/**
 * Resolve file path avoiding Potential Path Traversals
 *
 * @param baseDirPath base directory file path
 * @param fileName    filename/*from w  w  w. j a v  a  2s  . c o  m*/
 * @return
 */
public static String resolvePath(String baseDirPath, String fileName) {
    final Path basePath = Paths.get(baseDirPath);
    final Path filePath = Paths.get(fileName);
    if (!basePath.isAbsolute()) {
        throw new IllegalArgumentException("Base directory path '" + baseDirPath + "' must be absolute");
    }
    if (filePath.isAbsolute()) {
        throw new IllegalArgumentException(
                "Invalid file name '" + fileName + "' with an absolute file path is provided");
    }
    // Join the two paths together, then normalize so that any ".." elements
    final Path resolvedPath = basePath.resolve(filePath).normalize();

    // Make sure the resulting path is still within the required directory.
    if (!resolvedPath.startsWith(basePath.normalize())) {
        throw new IllegalArgumentException("File '" + fileName + "' is not within the required directory.");
    }

    return String.valueOf(resolvedPath);
}