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.roda.core.storage.fs.FSUtils.java

/**
 * Method that safely updates a file, given an inputstream, by copying the
 * content of the stream to a temporary file which then gets moved into the
 * final location (doing an atomic move). </br>
 * </br>/*from   w  ww. ja v  a 2 s.  com*/
 * In theory (as it depends on the file system implementation), this method is
 * useful for ensuring thread safety. </br>
 * </br>
 * NOTE: the stream is closed in the end.
 * 
 * @param stream
 *          stream with the content to be updated
 * @param toPath
 *          location of the file being updated
 * 
 * @throws IOException
 *           if an error occurs while copying/moving
 * 
 */
public static void safeUpdate(InputStream stream, Path toPath) throws IOException {
    try {
        Path tempToPath = toPath.getParent()
                .resolve(toPath.getFileName().toString() + ".temp" + System.nanoTime());
        Files.copy(stream, tempToPath);
        Files.move(tempToPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:it.baeyens.arduino.managers.Manager.java

/**
 * Given a platform description in a json file download and install all
 * needed stuff. All stuff is including all tools and core files and
 * hardware specific libraries. That is (on windows) inclusive the make.exe
 * /*  www .  j a va  2s .co m*/
 * @param platform
 * @param monitor
 * @param object
 * @return
 */
static public IStatus downloadAndInstall(ArduinoPlatform platform, boolean forceDownload,
        IProgressMonitor monitor) {

    IStatus status = downloadAndInstall(platform.getUrl(), platform.getArchiveFileName(),
            platform.getInstallPath(), forceDownload, monitor);
    if (!status.isOK()) {
        return status;
    }
    MultiStatus mstatus = new MultiStatus(status.getPlugin(), status.getCode(), status.getMessage(),
            status.getException());

    for (ToolDependency tool : platform.getToolsDependencies()) {
        monitor.setTaskName(InstallProgress.getRandomMessage());
        mstatus.add(tool.install(monitor));
    }
    // On Windows install make from equations.org
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        try {
            Path makePath = Paths
                    .get(ConfigurationPreferences.getPathExtensionPath().append("make.exe").toString()); //$NON-NLS-1$
            if (!makePath.toFile().exists()) {
                Files.createDirectories(makePath.getParent());
                URL makeUrl = new URL("ftp://ftp.equation.com/make/32/make.exe"); //$NON-NLS-1$
                Files.copy(makeUrl.openStream(), makePath);
                makePath.toFile().setExecutable(true, false);
            }

        } catch (IOException e) {
            mstatus.add(new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Downloading_make_exe, e));
        }
    }

    return mstatus.getChildren().length == 0 ? Status.OK_STATUS : mstatus;

}

From source file:it.baeyens.arduino.managers.Manager.java

private static void loadLibraryIndex(boolean download) {
    try {/*from  ww  w.ja  v a2 s. c om*/
        URL librariesUrl = new URL(Defaults.LIBRARIES_URL);
        String localFileName = Paths.get(librariesUrl.getPath()).getFileName().toString();
        Path librariesPath = Paths
                .get(ConfigurationPreferences.getInstallationPath().append(localFileName).toString());
        File librariesFile = librariesPath.toFile();
        if (!librariesFile.exists() || download) {
            librariesPath.getParent().toFile().mkdirs();
            Files.copy(librariesUrl.openStream(), librariesPath, StandardCopyOption.REPLACE_EXISTING);
        }
        if (librariesFile.exists()) {
            try (InputStreamReader reader = new InputStreamReader(new FileInputStream(librariesFile),
                    Charset.forName("UTF8"))) { //$NON-NLS-1$
                libraryIndex = new Gson().fromJson(reader, LibraryIndex.class);
                libraryIndex.resolve();
            }
        }
    } catch (IOException e) {
        Common.log(new Status(IStatus.WARNING, Activator.getId(), "Failed to load library index", e)); //$NON-NLS-1$
    }

}

From source file:org.apache.taverna.robundle.Bundles.java

protected static void safeMoveOrCopy(Path source, Path destination, boolean move) throws IOException {
    // First just try to do an atomic move with overwrite
    try {//from  w ww.  j a  v a2  s  . c o m
        if (move && source.getFileSystem().provider().equals(destination.getFileSystem().provider())) {
            move(source, destination, ATOMIC_MOVE, REPLACE_EXISTING);
            return;
        }
    } catch (AtomicMoveNotSupportedException ex) {
        // Do the fallback by temporary files below
    }

    destination = destination.toAbsolutePath();

    String tmpName = destination.getFileName().toString();
    Path tmpDestination = createTempFile(destination.getParent(), tmpName, ".tmp");
    Path backup = null;
    try {
        if (move) {
            /*
             * This might do a copy if filestores differ .. hence to avoid
             * an incomplete (and partially overwritten) destination, we do
             * it first to a temporary file
             */
            move(source, tmpDestination, REPLACE_EXISTING);
        } else {
            copy(source, tmpDestination, REPLACE_EXISTING);
        }

        if (exists(destination)) {
            if (isDirectory(destination))
                // ensure it is empty
                try (DirectoryStream<Path> ds = newDirectoryStream(destination)) {
                    if (ds.iterator().hasNext())
                        throw new DirectoryNotEmptyException(destination.toString());
                }
            // Keep the files for roll-back in case it goes bad
            backup = createTempFile(destination.getParent(), tmpName, ".orig");
            move(destination, backup, REPLACE_EXISTING);
        }
        // OK ; let's swap over
        try {
            // prefer ATOMIC_MOVE
            move(tmpDestination, destination, REPLACE_EXISTING, ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException ex) {
            /*
             * possibly a network file system as src/dest should be in same
             * folder
             */
            move(tmpDestination, destination, REPLACE_EXISTING);
        } finally {
            if (!exists(destination) && backup != null)
                // Restore the backup
                move(backup, destination);
        }
        // It went well, tidy up
        if (backup != null)
            deleteIfExists(backup);
    } finally {
        deleteIfExists(tmpDestination);
    }
}

From source file:misc.FileHandler.java

/**
 * Creates any non-existing parent directories for the given file name path.
 * /* ww w  .j a  v a2s.  c  o  m*/
 * @param fileName
 *            path to a file name. May include arbitrary many parent
 *            directories. May not be <code>null</code>.
 * @return <code>true</code>, if all parent directories were created
 *         successfully or if there were not any parent directories to
 *         create. Otherwise, <code>false</code> is returned.
 */
public static boolean makeParentDirs(Path fileName) {
    if (fileName == null) {
        throw new NullPointerException("fileName may not be null!");
    }

    boolean result = true;
    Path normalizedPath = fileName.normalize();
    Path parent = normalizedPath.getParent();

    if (parent != null) {
        result = parent.toFile().mkdirs();
    }

    return result;
}

From source file:org.roda.core.storage.fs.FSUtils.java

public static void deleteEmptyAncestorsQuietly(Path binVersionPath, Path upToParent) {
    if (binVersionPath == null) {
        return;/*from w w w . j  av  a 2 s  . co  m*/
    }

    Path parent = binVersionPath.getParent();
    while (parent != null && !parent.equals(upToParent)) {
        try {
            Files.deleteIfExists(parent);
            parent = parent.getParent();
        } catch (DirectoryNotEmptyException e) {
            // cancel clean-up
            parent = null;
        } catch (IOException e) {
            LOGGER.warn("Could not cleanup binary version directories", e);
        }
    }
}

From source file:org.roda.core.storage.fs.FSUtils.java

public static CloseableIterable<BinaryVersion> listBinaryVersions(final Path historyDataPath,
        final Path historyMetadataPath, final StoragePath storagePath)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException {
    Path fauxPath = getEntityPath(historyDataPath, storagePath);
    final Path parent = fauxPath.getParent();
    final String baseName = fauxPath.getFileName().toString();

    CloseableIterable<BinaryVersion> iterable;

    try {//from   w w  w .j a  va2  s . com
        final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(parent,
                new DirectoryStream.Filter<Path>() {

                    @Override
                    public boolean accept(Path entry) throws IOException {
                        String fileName = entry.getFileName().toString();
                        int lastIndexOfDot = fileName.lastIndexOf(VERSION_SEP);

                        return lastIndexOfDot > 0 ? fileName.substring(0, lastIndexOfDot).equals(baseName)
                                : false;
                    }
                });

        final Iterator<Path> pathIterator = directoryStream.iterator();
        iterable = new CloseableIterable<BinaryVersion>() {

            @Override
            public Iterator<BinaryVersion> iterator() {
                return new Iterator<BinaryVersion>() {

                    @Override
                    public boolean hasNext() {
                        return pathIterator.hasNext();
                    }

                    @Override
                    public BinaryVersion next() {
                        Path next = pathIterator.next();
                        BinaryVersion ret;
                        try {
                            ret = convertPathToBinaryVersion(historyDataPath, historyMetadataPath, next);
                        } catch (GenericException | NotFoundException | RequestNotValidException e) {
                            LOGGER.error("Error while list path " + parent + " while parsing resource " + next,
                                    e);
                            ret = null;
                        }

                        return ret;
                    }

                };
            }

            @Override
            public void close() throws IOException {
                directoryStream.close();
            }
        };

    } catch (NoSuchFileException e) {
        throw new NotFoundException("Could not find versions of " + storagePath, e);
    } catch (IOException e) {
        throw new GenericException("Error finding version of " + storagePath, e);
    }

    return iterable;
}

From source file:org.roda.core.storage.fs.FSUtils.java

public static Path getBinaryHistoryMetadataPath(Path historyDataPath, Path historyMetadataPath, Path path) {
    Path relativePath = historyDataPath.relativize(path);
    String fileName = relativePath.getFileName().toString();
    return historyMetadataPath.resolve(relativePath.getParent().resolve(fileName + METADATA_SUFFIX));
}

From source file:io.uploader.drive.drive.DriveOperations.java

private static Map<Path, File> createDirectoriesStructure(OperationResult operationResult, Drive client,
        File driveDestDirectory, Path srcDir, final StopRequester stopRequester,
        final HasStatusReporter statusReporter) throws IOException {

    Queue<Path> directoriesQueue = io.uploader.drive.util.FileUtils.getAllFilesPath(srcDir,
            FileFinderOption.DIRECTORY_ONLY);

    if (statusReporter != null) {
        statusReporter.setCurrentProgress(0.0);
        statusReporter.setTotalProgress(0.0);
        statusReporter.setStatus("Checking/creating directories structure...");
    }//from   www. jav a2  s.c o m

    long count = 0;
    Path topParent = srcDir.getParent();
    Map<Path, File> localPathDriveFileMapping = new HashMap<Path, File>();
    localPathDriveFileMapping.put(topParent, driveDestDirectory);
    for (Path path : directoriesQueue) {
        try {
            if (statusReporter != null) {
                statusReporter.setCurrentProgress(0.0);
                statusReporter.setStatus(
                        "Checking/creating directories structure... (" + path.getFileName().toString() + ")");
            }

            if (hasStopBeenRequested(stopRequester)) {
                if (statusReporter != null) {
                    statusReporter.setStatus("Stopped!");
                }
                operationResult.setStatus(OperationCompletionStatus.STOPPED);
                return localPathDriveFileMapping;
            }

            File driveParent = localPathDriveFileMapping.get(path.getParent());
            if (driveParent == null) {
                throw new IllegalStateException(
                        "The path " + path.toString() + " does not have any parent in the drive (parent path "
                                + path.getParent().toString() + ")...");
            }
            // check whether driveParent already exists, otherwise create it
            File driveDirectory = createDirectoryIfNotExist(client, driveParent, path.getFileName().toString());
            localPathDriveFileMapping.put(path, driveDirectory);

            ++count;
            if (statusReporter != null) {
                double p = ((double) count) / directoriesQueue.size();
                statusReporter.setTotalProgress(p);
                statusReporter.setCurrentProgress(1.0);
            }
        } catch (Throwable e) {
            logger.error("Error occurred while creating the directory " + path.toString(), e);
            operationResult.setStatus(OperationCompletionStatus.ERROR);
            operationResult.addError(path, e);
        }
    }
    return localPathDriveFileMapping;
}

From source file:org.eclipse.vorto.codegen.api.CopyResourceTask.java

private String getOutputPath(Path file) {
    String parentPath = file.getParent().toString().replace("\\", "/");
    String outputPath = parentPath
            .substring(parentPath.lastIndexOf(this.basePath.getPath()) + this.basePath.getPath().length());
    if (outputPath.startsWith("/")) {
        outputPath = outputPath.substring(1);
    }/*from w w w.j  a  va2 s  . co m*/
    return outputPath.isEmpty() ? this.targetPath : this.targetPath + "/" + outputPath;
}