Example usage for java.nio.file Path getRoot

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

Introduction

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

Prototype

Path getRoot();

Source Link

Document

Returns the root component of this path as a Path object, or null if this path does not have a root component.

Usage

From source file:org.commonwl.view.researchobject.ROBundleService.java

/**
 * Add files to this bundle from a list of repository contents
 * @param gitDetails The Git information for the repository
 * @param bundle The RO bundle to add files/directories to
 * @param bundlePath The current path within the RO bundle
 * @param gitRepo The Git repository//from w  w  w  . j a v  a  2 s  .  c  om
 * @param repoPath The current path within the Git repository
 * @param authors The combined set of authors for al the files
 */
private void addFilesToBundle(GitDetails gitDetails, Bundle bundle, Path bundlePath, Git gitRepo, Path repoPath,
        Set<HashableAgent> authors, Workflow workflow) throws IOException {
    File[] files = repoPath.toFile().listFiles();
    for (File file : files) {
        if (!file.getName().equals(".git")) {
            if (file.isDirectory()) {

                // Create a new folder in the RO for this directory
                Path newBundlePath = bundlePath.resolve(file.getName());
                Files.createDirectory(newBundlePath);

                // Create git details object for subfolder
                GitDetails subfolderGitDetails = new GitDetails(gitDetails.getRepoUrl(), gitDetails.getBranch(),
                        Paths.get(gitDetails.getPath()).resolve(file.getName()).toString());

                // Add all files in the subdirectory to this new folder
                addFilesToBundle(subfolderGitDetails, bundle, newBundlePath, gitRepo,
                        repoPath.resolve(file.getName()), authors, workflow);

            } else {
                try {
                    // Where to store the new file
                    Path bundleFilePath = bundlePath.resolve(file.getName());
                    Path gitFolder = Paths.get(gitDetails.getPath());
                    String relativePath = gitFolder.resolve(file.getName()).toString();
                    Path gitPath = bundlePath.getRoot().resolve(relativePath); // would start with /

                    // Get direct URL permalink
                    URI rawURI = new URI("https://w3id.org/cwl/view/git/" + workflow.getLastCommit() + gitPath
                            + "?format=raw");

                    // Variable to store file contents and aggregation
                    String fileContent = null;
                    PathMetadata aggregation;

                    // Download or externally link if oversized
                    if (file.length() <= singleFileSizeLimit) {
                        // Save file to research object bundle
                        fileContent = readFileToString(file);
                        Bundles.setStringValue(bundleFilePath, fileContent);

                        // Set retrieved information for this file in the manifest
                        aggregation = bundle.getManifest().getAggregation(bundleFilePath);
                        aggregation.setRetrievedFrom(rawURI);
                        aggregation.setRetrievedBy(appAgent);
                        aggregation.setRetrievedOn(aggregation.getCreatedOn());
                    } else {
                        logger.info("File " + file.getName() + " is too large to download - "
                                + FileUtils.byteCountToDisplaySize(file.length()) + "/"
                                + FileUtils.byteCountToDisplaySize(singleFileSizeLimit)
                                + ", linking externally to RO bundle");

                        // Set information for this file in the manifest
                        aggregation = bundle.getManifest().getAggregation(rawURI);
                        Proxy bundledAs = new Proxy();
                        bundledAs.setURI();
                        bundledAs.setFolder(repoPath);
                        aggregation.setBundledAs(bundledAs);
                    }

                    // Special handling for cwl files
                    boolean cwl = FilenameUtils.getExtension(file.getName()).equals("cwl");
                    if (cwl) {
                        // Correct mime type (no official standard for yaml)
                        aggregation.setMediatype("text/x-yaml");

                        // Add conformsTo for version extracted from regex
                        if (fileContent != null) {
                            Matcher m = cwlVersionPattern.matcher(fileContent);
                            if (m.find()) {
                                aggregation.setConformsTo(new URI("https://w3id.org/cwl/" + m.group(1)));
                            }
                        }
                    }

                    try {
                        // Add authors from git commits to the file
                        Set<HashableAgent> fileAuthors = gitService.getAuthors(gitRepo, gitPath.toString());

                        if (cwl) {
                            // Attempt to get authors from cwl description - takes priority
                            ResultSet descAuthors = rdfService.getAuthors(
                                    bundlePath.resolve(file.getName()).toString().substring(10),
                                    workflow.getIdentifier());
                            if (descAuthors.hasNext()) {
                                QuerySolution authorSoln = descAuthors.nextSolution();
                                HashableAgent newAuthor = new HashableAgent();
                                if (authorSoln.contains("name")) {
                                    newAuthor.setName(authorSoln.get("name").toString());
                                }
                                if (authorSoln.contains("email")) {
                                    newAuthor.setUri(new URI(authorSoln.get("email").toString()));
                                }
                                if (authorSoln.contains("orcid")) {
                                    newAuthor.setOrcid(new URI(authorSoln.get("orcid").toString()));
                                }
                                fileAuthors.remove(newAuthor);
                                fileAuthors.add(newAuthor);
                            }
                        }

                        authors.addAll(fileAuthors);
                        aggregation.setAuthoredBy(new ArrayList<>(fileAuthors));
                    } catch (GitAPIException ex) {
                        logger.error("Could not get commits for file " + repoPath, ex);
                    }

                    // Set retrieved information for this file in the manifest
                    aggregation.setRetrievedFrom(rawURI);
                    aggregation.setRetrievedBy(appAgent);
                    aggregation.setRetrievedOn(aggregation.getCreatedOn());

                } catch (URISyntaxException ex) {
                    logger.error("Error creating URI for RO Bundle", ex);
                }
            }
        }
    }
}

From source file:org.easyrec.utils.io.TreeCopy.java

/**
* Resolve a path against another path with a potentially different
* {@link FileSystem} or {@link FileSystemProvider}
*
* <p>{@link Path#resolve(Path)} will refuse to operate if its argument is
* issued from a different provider (with a {@link
* ProviderMismatchException}); moreover, if the argument is issued from the
* same provider but is on a different filesystem, the result of the
* resolution may be on the argument's filesystem, not the caller's.</p>
*
* <p>This method will attempt to resolve the second path against the first
* so that the result is <em>always</em> associated to the filesystem (and
* therefore provider) of the first argument. For the resolution to operate,
* the following conditions must be met for {@code path2}:</p>
*
* <ul>// www .j a va 2  s.com
*     <li>if it is not absolute, it must not have a root;</li>
*     <li>if it is absolute, it must have a root, and the string
*     representation of this root must match a string representation of one
*     possible root of the first path's filesystem.</li>
* </ul>
*
* <p>If the conditions above are not satisfied, this method throws an
* {@link UnresolvablePathException} (unchecked).</p>
*
* <p>If both paths are issued from the same filesystem, this method will
* delegate to {@code path1}'s {@code .resolve()}; if they are from
* different filesystems but share the same provider, this method returns:
* </p>
*
* <pre>
*     path1.resolve(path1.getFileSystem().getPath(path2.toString()))
* </pre>
*
* <p>This means that for instance it is possible to resolve a Unix path
* against a Windows path, or the reverse, as long as the second path is
* not absolute (the root paths of both filesystems are incompatible):</p>
*
* <ul>
*     <li>resolving {@code foo/bar/baz} against {@code c:} will return
*     {@code c:\foo\bar\baz};</li>
*     <li>resolving {@code baz\quux} against {@code /foo/bar} will return
*     {@code /foo/bar/baz/quux}.</li>
* </ul>
*
* @param path1 the first path
* @param path2 the second path
* @return the resolved path
* @throws UnresolvablePathException see description
* @throws InvalidPathException {@code path2} is from a different provider,
* and one of its name elements is invalid according to {@code path1}'s
* filesystem
*
* @see FileSystem#getPath(String, String...)
* @see FileSystem#getRootDirectories()
*/
@SuppressWarnings("ObjectEquality")
private Path resolve(final Path path1, final Path path2) throws IOException {

    final FileSystem fs1 = Objects.requireNonNull(path1).getFileSystem();
    final FileSystem fs2 = Objects.requireNonNull(path2).getFileSystem();

    if (fs1 == fs2)
        return path1.resolve(path2);

    if (fs1.provider() == fs2.provider())
        return path1.resolve(fs1.getPath(path2.toString()));

    final boolean isAbsolute = path2.isAbsolute();
    final Path root2 = path2.getRoot();

    final String errmsg = isAbsolute ? "path to resolve is absolute but has no root"
            : "path to resolve is not absolute but has a root";

    // Always tricky to read an xor...
    if (isAbsolute ^ root2 != null)
        throw new IOException(errmsg);

    Path ret;

    if (isAbsolute) {
        /*
         * Check if the root of path2 is compatible with path1
         */
        final String path2Root = root2.toString();

        boolean foundRoot = false;

        for (final Path root1 : fs1.getRootDirectories())
            if (root1.toString().equals(path2Root))
                foundRoot = true;

        if (!foundRoot)
            throw new IOException("root of path to resolve " + "is incompatible with source path");

        ret = fs1.getPath(path2Root);
    } else {
        /*
         * Since the empty path is defined as having one empty name
         * component, which is rather awkward, we don't want to take the
         * risk of triggering bugs in FileSystem#getPath(); instead, check
         * that the string representation of path2 is empty, and if it is,
         * just return path1.
         */
        if (path2.toString().isEmpty())
            return path1;

        ret = path1;
    }

    for (final Path element : path2)
        ret = ret.resolve(element.toString());

    return ret;
}

From source file:org.moe.gradle.remote.Server.java

public String getSDKRemotePath(@NotNull File file) throws IOException {
    Require.nonNull(file);//from  w  w w.jav a2 s.  co m

    final Path filePath = file.toPath().toAbsolutePath();
    final Path sdk = plugin.getSDK().getRoot().toPath().toAbsolutePath();

    if (!filePath.getRoot().equals(sdk.getRoot())) {
        throw new IOException("non-sdk file");
    }

    final Path relative = sdk.relativize(filePath);
    return getRemotePath(getSdkDir(), relative);
}

From source file:ropes.MainWindow.java

private void jButton_changePathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_changePathActionPerformed
    final JFileChooser fc = new JFileChooser(getSelectedPathFromCMB());
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnVal = fc.showOpenDialog(MainWindow.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        Path p = Paths.get(file.toString());
        //if root is changed via the change path botton, then also change to the right media in the combobox
        if (!p.getRoot().toString().equals(getSelectedPathFromCMB())) {
            for (int i = 0; i < jComboBox_media.getItemCount(); i++) {
                if (jComboBox_media.getItemAt(i).toString().contains(p.getRoot().toString())) {
                    jComboBox_media.setSelectedIndex(i);
                    break;
                }//  ww w  .  j  a v a2s  . c o m
            }
        }

        jLabel_path.setText(file.toString());
    }

}