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:org.cryptomator.ui.MainApplication.java

void handleCommandLineArg(final MainController ctrl, String arg) {
    Path file = FileSystems.getDefault().getPath(arg);
    if (!Files.exists(file)) {
        try {//from www.  j  ava2  s.  co  m
            if (!Files.isDirectory(Files.createDirectories(file))) {
                return;
            }
        } catch (IOException e) {
            return;
        }
        // directory created.
    } else if (Files.isRegularFile(file)) {
        if (StringUtils.endsWithIgnoreCase(file.getFileName().toString(), Aes256Cryptor.MASTERKEY_FILE_EXT)) {
            file = file.getParent();
        } else {
            // is a file, but not a masterkey file
            return;
        }
    }
    Path f = file;
    Platform.runLater(() -> {
        ctrl.addDirectory(f);
        ctrl.toFront();
    });
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

/**
 * {@inheritDoc}//from  w  ww .  j ava 2 s.co m
 */
@Override
public void putContentToFile(RepositoryFileReference ref, String content, MediaType mediaType)
        throws IOException {
    if (mediaType == null) {
        // quick hack for storing mime type called this method
        assert (ref.getFileName().endsWith(Constants.SUFFIX_MIMETYPE));
        // we do not need to store the mime type of the file containing the mime type
        // information
    } else {
        this.setMimeType(ref, mediaType);
    }
    Path path = this.ref2AbsolutePath(ref);
    FileUtils.createDirectory(path.getParent());
    Files.write(path, content.getBytes());
}

From source file:com.yqboots.initializer.web.controller.ProjectInitializerController.java

@RequestMapping(value = "/", method = RequestMethod.POST)
public Object startup(@ModelAttribute(WebKeys.MODEL) @Valid final ProjectInitializerForm form,
        final BindingResult bindingResult, final ModelMap model) throws IOException {
    if (bindingResult.hasErrors()) {
        return FORM_URL;
    }//ww  w .  ja  va2 s . co m

    Path path;

    final MultipartFile file = form.getFile();
    if (StringUtils.isNotBlank(file.getName())) {
        try (InputStream inputStream = file.getInputStream()) {
            path = initializer.startup(form.getMetadata(), form.getTheme(), inputStream);
        }
    } else {
        path = initializer.startup(form.getMetadata(), form.getTheme());
    }

    final HttpEntity<byte[]> result = FileWebUtils.downloadFile(path,
            new MediaType("application", "zip", StandardCharsets.UTF_8));

    // clear temporary folder
    final Path parent = path.getParent();
    FileUtils.deleteDirectory(parent.toFile());

    // clear model
    model.clear();

    return result;
}

From source file:br.com.thiaguten.archive.AbstractArchive.java

/**
 * Generic decompress implemetation/*from  w  w  w.  j  a  v  a 2  s  .com*/
 */
@Override
public Path decompress(Path path) throws IOException {
    Path decompressDir = removeExtension(path);

    logger.debug("reading archive file " + path);

    try (ArchiveInputStream archiveInputStream = createArchiveInputStream(
            new BufferedInputStream(newInputStream(path)))) {

        // creates a new decompress folder to not override if already exists
        // if you do not want this behavior, just comment this line
        decompressDir = createFile(ArchiveAction.DECOMPRESS, decompressDir.getParent(), decompressDir);

        createDirectories(decompressDir);

        logger.debug("creating the decompress destination directory " + decompressDir);

        ArchiveEntry entry;
        while ((entry = archiveInputStream.getNextEntry()) != null) {
            if (archiveInputStream.canReadEntryData(entry)) {

                final String entryName = entry.getName();
                final Path target = Paths.get(decompressDir.toString(), entryName);
                final Path parent = target.getParent();

                if (parent != null && !exists(parent)) {
                    createDirectories(parent);
                }

                logger.debug("reading compressed path " + entryName);

                if (!entry.isDirectory()) {
                    try (OutputStream outputStream = new BufferedOutputStream(newOutputStream(target))) {

                        logger.debug("writting compressed " + entryName + " file in the decompress directory");

                        //                            byte[] content = new byte[(int) entry.getSize()];
                        //                            outputStream.write(content);
                        IOUtils.copy(archiveInputStream, outputStream);
                    }
                }
            }
        }

        logger.debug("finishing the decompress in the directory: " + decompressDir);

    }

    return decompressDir;
}

From source file:org.niord.core.repo.ThumbnailService.java

/**
 * Returns or creates the a thumbnail for the given file if it is an image.
 * Otherwise, null is returned//from w  w  w  .  j av  a2  s .co  m
 *
 * @param file the file to create a thumbnail for
 * @param type the type of image
 * @param size the size of the thumbnail
 * @return the thumbnail file or null if none was found or created
 */
public Path createThumbnail(Path file, String type, IconSize size) {

    try {
        // Construct the thumbnail name by appending "_thumb_size" to the file name
        String thumbName = String.format("%s_thumb_%d.%s",
                FilenameUtils.removeExtension(file.getFileName().toString()), size.getSize(),
                FilenameUtils.getExtension(file.getFileName().toString()));

        // Check if the thumbnail already exists
        Path thumbFile = file.getParent().resolve(thumbName);
        if (Files.isRegularFile(thumbFile) && Files.getLastModifiedTime(thumbFile).toMillis() >= Files
                .getLastModifiedTime(file).toMillis()) {
            return thumbFile;
        }

        // Check whether to use VIPS or java
        if (StringUtils.isNotBlank(vipsCmd) && vipsFileTypes.contains(type.toLowerCase())) {
            // Use VIPS
            createThumbnailUsingVips(file, thumbFile, size);

        } else {
            // Use java APIs
            createThumbnailUsingJava(file, thumbFile, size);
        }

        return thumbFile;

    } catch (IOException e) {
        // Alas, no thumbnail
        return null;
    }
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for creating new file")
public void testCreateDirWithParentDir() throws IOException {
    Path filepath = tempDirPath.resolve("temp-dir").resolve("nested-dir");
    FileUtils.deleteDirectory(filepath.toFile());
    try {//from www . j  ava  2 s . c om
        BValue[] args = { new BString(filepath.toString()), new BBoolean(true) };
        BRunUtil.invoke(compileResult, "testCreateDir", args);
        assertTrue(Files.exists(filepath));
    } finally {
        FileUtils.deleteDirectory(filepath.getParent().toFile());
    }
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Returns or creates the a thumbnail for the given file if it is an image.
 * Otherwise, null is returned/* www .java2s.  co  m*/
 *
 * @param file the file to create a thumbnail for
 * @param type the type of image
 * @param size the size of the thumbnail
 * @return the thumbnail file or null if none was found or created
 */
public Path createThumbnail(Path file, String type, IconSize size) {

    try {
        // Construct the thumbnail name by appending "_thumb_size" to the file name
        String thumbName = String.format("%s_thumb_%d.%s",
                FilenameUtils.removeExtension(file.getFileName().toString()), size.getSize(),
                FilenameUtils.getExtension(file.getFileName().toString()));

        // Check if the thumbnail already exists
        Path thumbFile = file.getParent().resolve(thumbName);
        if (Files.isRegularFile(thumbFile) && Files.getLastModifiedTime(thumbFile).toMillis() >= Files
                .getLastModifiedTime(file).toMillis()) {
            return thumbFile;
        }

        // Check whether to use VIPS or java
        if (StringUtils.isNotBlank(vipsCmd) && vipsFileTypes.contains(type.toLowerCase())) {
            // Use VIPS
            createThumbnailUsingVips(file, thumbFile, size);

        } else {
            // Use java APIs
            createThumbnailUsingJava(file, thumbFile, size);
        }

        return thumbFile;

    } catch (Throwable e) {
        // Alas, no thumbnail
        return null;
    }
}

From source file:org.opennms.features.newts.converter.NewtsConverter.java

private void processStoreByMetricResource(final Path metaPath) {
    // Use the containing directory as resource path
    final Path path = metaPath.getParent();

    // Extract the metric name from the file name
    final String metric = FilenameUtils.removeExtension(metaPath.getFileName().toString());

    // Load the '.meta' file to get the group name
    final Properties meta = new Properties();
    try (final BufferedReader r = Files.newBufferedReader(metaPath)) {
        meta.load(r);// w  ww  .ja va  2s  .  c  om

    } catch (final IOException e) {
        LOG.error("Failed to read .meta file: {}", metaPath, e);
        return;
    }

    final String group = meta.getProperty("GROUP");
    if (group == null) {
        LOG.warn("No group information found - please verify storageStrategy settings");
        return;
    }

    // Process the resource
    this.executor.execute(() -> this.processResource(path, metric, group));
}

From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java

public Path copyBundle(final Path extractedGitBundle, final Map<String, String> metadata) throws IOException {

    final Path bundleDestination = buildBundleDestination(metadata);

    LOGGER.debug("Copying received bundle from temporary location " + extractedGitBundle + " to "
            + bundleDestination);/*w  ww . j a va 2  s .c  o m*/
    if (Files.exists(bundleDestination)) {
        Files.copy(extractedGitBundle, bundleDestination, StandardCopyOption.REPLACE_EXISTING);
    } else {
        Files.createDirectories(bundleDestination.getParent());
        Files.copy(extractedGitBundle, bundleDestination);
    }

    registerCreatedFile(extractedGitBundle.toFile());
    registerCreatedFile(bundleDestination.toFile());

    return bundleDestination;
}

From source file:org.discosync.ApplySyncPack.java

/**
 * Apply a syncpack to a target directory.
 *//*from ww w. j a  va2s . c om*/
protected void applySyncPack(String syncPackDir, String targetDir) throws SQLException, IOException {

    // read file operations from database
    File fileOpDbFile = new File(syncPackDir, "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();

    Iterator<FileListEntry> it = db.getFileListOperationIterator();

    Path syncFileBaseDir = Paths.get(syncPackDir, "files");
    String syncFileBaseDirStr = syncFileBaseDir.toAbsolutePath().toString();

    int filesCopied = 0;
    int filesReplaced = 0;
    int filesDeleted = 0;
    long copySize = 0L;
    long deleteSize = 0L;

    // Collect directories during processing.
    List<FileListEntry> directoryOperations = new ArrayList<>();

    // First process all files, then the directories
    while (it.hasNext()) {

        FileListEntry e = it.next();

        // Remember directories
        if (e.isDirectory()) {
            directoryOperations.add(e);
            continue;
        }

        String path = e.getPath();
        Path sourcePath = Paths.get(syncFileBaseDirStr, path); // may not exist
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // copy new file, target files should not exist
            if (Files.exists(targetPath)) {
                System.out
                        .println("Error: the file should not exist: " + targetPath.toAbsolutePath().toString());
            } else {
                if (!Files.exists(targetPath.getParent())) {
                    Files.createDirectories(targetPath.getParent());
                }

                Files.copy(sourcePath, targetPath);
                filesCopied++;
                copySize += e.getSize();
            }

        } else if (e.getOperation() == FileOperations.REPLACE) {
            // replace existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            filesReplaced++;
            copySize += e.getSize();

        } else if (e.getOperation() == FileOperations.DELETE) {
            // delete existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            } else {
                long fileSize = Files.size(targetPath);
                if (fileSize != e.getSize()) {
                    // show info, delete anyway
                    System.out.println(
                            "Info: the file size is different: " + targetPath.toAbsolutePath().toString());
                }
                deleteSize += fileSize;
                Files.delete(targetPath);
                filesDeleted++;
            }
        }
    }

    db.close();

    // Sort directory list to ensure directories are deleted bottom-up (first /dir1/dir2, then /dir1)
    Collections.sort(directoryOperations, new Comparator<FileListEntry>() {
        @Override
        public int compare(FileListEntry e1, FileListEntry e2) {
            return e2.getPath().compareTo(e1.getPath().toString());
        }
    });

    // Now process directories - create and delete empty directories
    for (FileListEntry e : directoryOperations) {

        String path = e.getPath();
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // create directory if needed
            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }
        } else if (e.getOperation() == FileOperations.DELETE) {

            if (!Files.exists(targetPath)) {
                System.out.println(
                        "Info: Directory to DELETE does not exist: " + targetPath.toAbsolutePath().toString());

            } else if (!Files.isDirectory(targetPath, LinkOption.NOFOLLOW_LINKS)) {
                System.out.println("Info: Directory to DELETE is not a directory, but a file: "
                        + targetPath.toAbsolutePath().toString());

            } else if (!Utils.isDirectoryEmpty(targetPath)) {
                System.out.println("Info: Directory to DELETE is not empty, but should be empty: "
                        + targetPath.toAbsolutePath().toString());

            } else {
                // delete directory
                Files.delete(targetPath);
            }
        }
    }

    System.out.println("Apply of syncpack '" + syncPackDir + "' to directory '" + targetDir + "' finished.");
    System.out.println("Files copied  : " + String.format("%,d", filesCopied));
    System.out.println("Files replaced: " + String.format("%,d", filesReplaced));
    System.out.println("Files deleted : " + String.format("%,d", filesDeleted));
    System.out.println("Bytes copied  : " + String.format("%,d", copySize));
    System.out.println("Bytes deleted : " + String.format("%,d", deleteSize));
}