Example usage for java.nio.file Path getParent

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

Introduction

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

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:us.colloquy.index.IndexHandler.java

public void getURIForAllLetters(Set<DocumentPointer> uriList, String letterDirectory, boolean useOnlyNumber) {
    ///Documents/Tolstoy/diaries

    Path pathToLetters = FileSystems.getDefault().getPath(letterDirectory);

    List<Path> results = new ArrayList<>();

    int maxDepth = 6;

    try (Stream<Path> stream = Files.find(pathToLetters, maxDepth, (path, attr) -> {
        return String.valueOf(path).endsWith(".ncx");
    })) {/*from  w  ww  .java 2s .com*/

        stream.forEach(results::add);

        //            String joined = stream
        //                    .sorted()
        //                    .map(String::valueOf)
        //                    .collect(Collectors.joining("; "));
        //
        //            System.out.println("\nFound: " + joined);

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("files: " + results.size());

    try {

        for (Path res : results) {
            Path parent = res.getParent();

            //                System.out.println("---------------------------------------------");
            //                System.out.println(parent.toString());
            //use jsoup to list all files that contain something useful
            Document doc = Jsoup.parse(res.toFile(), "UTF-8");

            String title = "";

            for (Element element : doc.getElementsByTag("docTitle")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {
                    title = child.text();
                    // System.out.println("Title: " + title);
                }
            }

            for (Element element : doc.getElementsByTag("navPoint")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {
                    String label = child.text();

                    if (StringUtils.isNotEmpty(label)) {
                        if (label.matches("?")) {
                            System.out.println("------------------");
                        }

                        String url = child.getElementsByTag("content").attr("src");

                        if (label.matches(".*\\d{1,3}.*[?--?]+.*") && StringUtils.isNotEmpty(url)) {
                            DocumentPointer documentPointer = new DocumentPointer(
                                    parent.toString() + File.separator + url.replaceAll("#.*", ""), title);

                            uriList.add(documentPointer);
                            //                                System.out.println("nav point: " + label + " src " + parent.toString()
                            //                                        + System.lineSeparator() + url.replaceAll("#.*",""));

                        } else if (label.matches(".*\\d{1,3}.*") && StringUtils.isNotEmpty(url)
                                && useOnlyNumber) {
                            DocumentPointer documentPointer = new DocumentPointer(
                                    parent.toString() + File.separator + url.replaceAll("#.*", ""), title);

                            uriList.add(documentPointer);
                            //                                System.out.println("nav point: " + label + " src " + parent.toString()
                            //                                        + System.lineSeparator() + url.replaceAll("#.*",""));

                        } else {
                            // System.out.println("nav point: " + label + " src " + child.getElementsByTag("content").attr("src"));
                        }

                    }
                }
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    //        System.out.println("Size: " + uriList.size());

    //        for (DocumentPointer pointer : uriList)
    //        {
    //            //parse and
    //            System.out.println(pointer.getSourse() + "\t" + pointer.getUri());
    //        }
}

From source file:us.colloquy.index.IndexHandler.java

public void getURIForAllDiaries(List<DocumentPointer> documentPointers, Path pathToLetters) {
    List<Path> results = new ArrayList<>();

    int maxDepth = 6;

    try (Stream<Path> stream = Files.find(pathToLetters, maxDepth, (path, attr) -> {
        return String.valueOf(path).endsWith(".ncx");
    })) {//from   w  ww. j a v  a  2 s .com

        stream.forEach(results::add);

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("files: " + results.size());

    try {

        for (Path res : results) {
            Path parent = res.getParent();

            //                System.out.println("---------------------------------------------");
            //                System.out.println(parent.toString());
            //use jsoup to list all files that contain something useful
            Document doc = Jsoup.parse(res.toFile(), "UTF-8");

            String title = "";

            for (Element element : doc.getElementsByTag("docTitle")) {
                //Letter letter = new Letter();

                // StringBuilder content = new StringBuilder();

                for (Element child : element.children()) {
                    title = child.text();
                    // System.out.println("Title: " + title);
                }
            }

            //  System.out.println("==========================   " + res.toString() + " ==========================");

            boolean startPrinting = false;

            boolean newFile = true;

            for (Element element : doc.getElementsByTag("navPoint")) {

                //get nav label and content

                Element navLabelElement = element.select("navLabel").first();
                Element srsElement = element.select("content").first();

                String navLabel = "";
                String srs = "";

                if (navLabelElement != null) {
                    navLabel = navLabelElement.text().replaceAll("\\*", "").trim();
                }

                if (srsElement != null) {
                    srs = srsElement.attr("src");
                }

                if ("??".matches(navLabel))

                {
                    startPrinting = false;

                    // System.out.println("----------------- end of file pointer ---------------");
                }

                if (StringUtils.isNotEmpty(navLabel)
                        && navLabel.matches("??.*|?? ?.*") && newFile) {
                    newFile = false;
                    startPrinting = true;
                }

                if (startPrinting && !navLabel
                        .matches("(|??? ??)")) {
                    // System.out.println("----------------- file pointer ---------------");
                    //   System.out.println(navLabel + "\t" + srs);

                    DocumentPointer documentPointer = new DocumentPointer(
                            parent.toString() + File.separator + srs.replaceAll("#.*", ""), title);

                    documentPointers.add(documentPointer);
                }

            }

            //   System.out.println("==========================   END OF FILE ==========================");

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Size: " + documentPointers.size());

    //  for (DocumentPointer pointer : documentPointers)
    // {
    //parse and
    //     System.out.println(pointer.getSourse() + "\t" + pointer.getUri());
}

From source file:fr.ortolang.diffusion.client.cmd.CopyCommand.java

private void copy(Path localPath, String workspace, String remotePath) {
    try {/*  w  w  w .j a v a  2s  . c o m*/
        Files.walkFileTree(localPath, new FileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteDir = remotePath + localPath.getParent().relativize(dir).toString();
                    System.out.println("Copying dir " + dir + " to " + workspace + ":" + remoteDir);
                    try {
                        client.writeCollection(workspace, remoteDir, "");
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy dir ").append(dir).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                switch (mode) {
                case "objects":
                    String remoteFile = remotePath + localPath.getParent().relativize(file).toString();
                    System.out.println("Copying file " + file + " to " + workspace + ":" + remoteFile);
                    try {
                        client.writeDataObject(workspace, remoteFile, "", file.toFile(), null);
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteFile)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                case "metadata":
                    String remoteDir = remotePath
                            + localPath.getParent().relativize(file).getParent().toString();
                    System.out.println("Creating metadata file " + file + " to " + workspace + ":" + remoteDir);
                    String name = file.getFileName().toString();
                    try {
                        client.writeMetaData(workspace, remoteDir, name, null, file.toFile());
                    } catch (OrtolangClientException | OrtolangClientAccountException e) {
                        e.printStackTrace();
                        errors.append("-> Unable to copy file ").append(file).append(" to ").append(remoteDir)
                                .append("\r\n");
                        return FileVisitResult.TERMINATE;
                    }
                    break;
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        System.out.println("Unable to walk file tree: " + e.getMessage());
    }
}

From source file:org.apache.uima.ruta.descriptor.RutaDescriptorBuilder.java

private String getRelativeLocation(URI target, String base) {
    if (base == null) {
        return null;
    }/*w ww  .j  a  v a 2  s . com*/
    Path basePath = Paths.get(base);
    if (!basePath.toFile().isDirectory()) {
        basePath = basePath.getParent();
    }
    Path targetPath = null;
    try {
        targetPath = Paths.get(target);
    } catch (Exception e) {
        return null;
    }
    Path relativePath = null;
    try {
        relativePath = basePath.relativize(targetPath);
    } catch (Exception e) {
        return null;
    }
    // HOTFIX: avoid windows paths. No generic solution to access a portable string found yet for
    // Path
    String result = relativePath.toString().replaceAll("\\\\", "/");
    return result;
}

From source file:org.fao.geonet.api.cssstyle.CssStyleSettingsService.java

/**
 * Initialize less file in data folder.//from  ww  w . ja  va2 s.c  o  m
 *
 * @param path the path
 * @return the path
 * @throws IOException Signals that an I/O exception has occurred.
 */

private Path initializeLessFileInDataFolder(String path) throws IOException {
    final Path lessPath = Paths.get(path + "/gn_dynamic_style.json");
    try {
        Files.createFile(lessPath);
    } catch (final FileAlreadyExistsException e1) {
        Files.delete(lessPath);
        Files.createFile(lessPath);
    } catch (final NoSuchFileException e2) {
        final Path tmp = lessPath.getParent();
        Files.createDirectories(tmp);
        Files.createFile(lessPath);
    }
    return lessPath;
}

From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java

private JsonObject getJsonObjForFile(Path root, List<String> extensions) {
    JsonObject rootObj = new JsonObject();
    Path fileName = root.getFileName();
    if (fileName != null) {
        rootObj.addProperty(NODE_LABEL, fileName.toString());
    } else {/*w  ww . j a va 2  s.c o m*/
        rootObj.addProperty(NODE_LABEL, root.toString());
    }
    rootObj.addProperty(NODE_ID, root.toAbsolutePath().toString());
    Path parent = root.getParent();
    if (parent != null) {
        rootObj.addProperty(PARENT, parent.toAbsolutePath().toString());
    }
    if (Files.isDirectory(root)) {
        rootObj.addProperty(NODE_TYPE, FOLDER_TYPE);
        try {
            File rootFile = root.toFile();
            boolean hasChildren = Boolean.FALSE;
            if (rootFile != null) {
                // check if this folder contains sub-directories
                File[] subDirs = rootFile.listFiles(File::isDirectory);
                if (subDirs != null && subDirs.length > 0) {
                    hasChildren = Boolean.TRUE;
                } else {
                    // if there are no sub-directories, check whether this folder
                    // contains files with given extension list
                    String[] list = extensions != null && !extensions.isEmpty()
                            ? rootFile.list(new SuffixFileFilter(extensions, INSENSITIVE))
                            : rootFile.list();
                    if (list != null && list.length > 0) {
                        hasChildren = true;
                    }
                }
            }
            rootObj.addProperty(NODE_CHILDREN, hasChildren);
        } catch (Exception e) {
            logger.debug("Error while fetching children of " + root.toString(), e);
            rootObj.addProperty(NODE_ERROR, e.toString());
        }
    } else if (Files.isRegularFile(root)) {
        rootObj.addProperty(NODE_TYPE, FILE_TYPE);
        rootObj.addProperty(NODE_CHILDREN, Boolean.FALSE);
    }
    return rootObj;
}

From source file:org.codice.ddf.configuration.migration.ExportMigrationReportImplTest.java

@Test
public void testRecordExternalSoftlink() throws Exception {
    final Path absoluteFilePath = ddfHome.resolve(createFile(createDirectory(DIRS), FILENAME)).toAbsolutePath();
    final String filename2 = "file2.ext";
    final Path absoluteFilePath2 = createSoftLink(absoluteFilePath.getParent(), filename2, absoluteFilePath);

    initContext();// w w  w .j a  v a2  s  .c  o m
    final ExportMigrationEntryImpl entry = new ExportMigrationEntryImpl(context, absoluteFilePath2);

    Assert.assertThat(xreport.recordExternal(entry, true), Matchers.sameInstance(xreport));

    final Map<String, Object> metadata = xreport.getMetadata();

    Assert.assertThat(metadata, Matchers.hasEntry(Matchers.equalTo(MigrationContextImpl.METADATA_EXTERNALS),
            Matchers.instanceOf(List.class)));
    final List<Object> xmetadata = (List<Object>) metadata.get(MigrationContextImpl.METADATA_EXTERNALS);

    Assert.assertThat(xmetadata,
            Matchers.allOf(Matchers.iterableWithSize(1), Matchers.contains(Matchers.instanceOf(Map.class))));
    final Map<String, Object> emetadata = (Map<String, Object>) xmetadata.get(0);

    Assert.assertThat(emetadata,
            Matchers.allOf(Matchers.aMapWithSize(4),
                    Matchers.hasEntry(MigrationEntryImpl.METADATA_NAME, entry.getName()),
                    Matchers.hasEntry(MigrationEntryImpl.METADATA_FOLDER, (Object) false),
                    Matchers.hasKey(MigrationEntryImpl.METADATA_CHECKSUM),
                    Matchers.hasEntry(MigrationEntryImpl.METADATA_SOFTLINK, (Object) true)));
}

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

private void extractFile(ImmutableSet.Builder<Path> filesWritten, ZipFile zip, DirectoryCreator creator,
        Path target, ZipArchiveEntry entry) throws IOException {
    ProjectFilesystem filesystem = creator.getFilesystem();
    if (filesystem.isFile(target, LinkOption.NOFOLLOW_LINKS)) { // NOPMD for clarity
        // pass//from www  .j  a  v  a 2 s. c o  m
    } else if (filesystem.exists(target, LinkOption.NOFOLLOW_LINKS)) {
        filesystem.deleteRecursivelyIfExists(target);
    } else if (target.getParent() != null) {
        creator.forcefullyCreateDirs(target.getParent());
    }
    filesWritten.add(target);
    writeZipContents(zip, entry, filesystem, target);
}

From source file:org.apache.marmotta.platform.core.services.importer.ImportWatchServiceImpl.java

/**
 * Get the target context. /*from w ww .ja  v a  2s  .  c o  m*/
 * The algorithm is as follows:
 * <ol>
 * <li>check for a file "conf" (configurable, see {@link #CONFIG_KEY_CONF_FILE}) which specifies 
 * the target content using {@link Properties} syntax (key {@code context}), then use is; or
 * <li>check if the sub-directory is a url-encoded URI, then use it; or
 * <li>construct the context by using {@link ConfigurationService#getBaseContext()} and the relative sub-dirs and use it; or
 * <li>use the default context as a general fallback.
 * </ol>
 * 
 * @param file the file
 * @return the context URI
 * @throws URISyntaxException 
 */
private URI getTargetContext(Path file) throws URISyntaxException {
    // Check for a configFile
    final Path config = file.getParent()
            .resolve(configurationService.getStringConfiguration(CONFIG_KEY_CONF_FILE, "config"));
    if (Files.isReadable(config)) {
        Properties prop = loadConfigFile(file);
        final String _c = prop.getProperty("context");
        if (_c != null) {
            try {
                URI context = contextService.createContext(_c);
                log.debug("using context {} from config file {}", context, config);
                return context;
            } catch (URISyntaxException e) {
                log.warn("invalid context {} in config file {}, ignoring", _c, config);
            }
        } else {
            log.trace("no context defined in config file {}", config);
        }
    }

    // Check for url-encoded directory
    Path subDir = getImportRoot().relativize(file.getParent());
    if (StringUtils.isBlank(subDir.toString())) {
        log.trace("using default context for file {}", file);
        return contextService.getDefaultContext();
    } else if (StringUtils.startsWith(subDir.toString(), "http%3A%2F%2F")) {
        log.debug("using url-encoded context {} for import of {}", subDir, file);
        try {
            return contextService.createContext(URLDecoder.decode(subDir.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("Error url-decoding context name '{}', so using the default one: {}", subDir,
                    e.getMessage());
            return contextService.getDefaultContext();
        }
    } else {
        final String _c = String.format("%s/%s", configurationService.getBaseContext().replaceFirst("/$", ""),
                subDir);
        final URI context = contextService.createContext(_c);
        log.debug("using context {} based on relative subdir {} for file {}", context, subDir, file);
        return context;
    }
}

From source file:joachimeichborn.geotag.ui.parts.PicturesView.java

@Inject
public void setSelection(
        @Named(IServiceConstants.ACTIVE_SELECTION) @Optional final PictureSelection aPictureSelection) {
    final MPart activePart = partService.getActivePart();
    if (activePart != null && activePart.getElementId().equals(PICTURES_PART_ID)) {
        if (nameLabel != null && aPictureSelection != null) {
            final List<Picture> pictures = aPictureSelection.getSelection();
            selectedPicturesLabel.setText(String.format(SELECTED_PICTURES, pictures.size()));
            if (pictures.size() == 1) {
                final Picture picture = pictures.get(0);
                final Path file = picture.getFile();
                lastKey = new PreviewKey(file.toString(), 160, 120);
                preview.setImage(previewRepo.getPreview(lastKey, true, this));
                previewContainer.setVisible(true);
                previewLabel.repaint();/*  www  .j ava  2s.com*/
                nameLabel.setText(file.getFileName().toString());
                pathLabel.setText(file.getParent().toString());
                fillGeocodingDetails(picture.getGeocoding());
            } else {
                nameLabel.setText("");
                pathLabel.setText("");
                previewContainer.setVisible(false);
                fillGeocodingDetails(null);
            }
        }
    }
}