Example usage for java.nio.file Path getFileName

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

Introduction

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

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

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   ww w  .  ja va 2  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:com.cloudbees.clickstack.util.Files2.java

/**
 * Find a file matching {@code $artifactId*$type} in the given {@code srcDir}.
 *
 * @param srcDir/* www  .  j a v  a 2 s .c  o m*/
 * @param artifactId
 * @param type
 * @return
 * @throws IllegalStateException More or less than 1 matching artifact found
 * @throws RuntimeIOException
 */
@Nonnull
public static Path findArtifact(@Nonnull Path srcDir, @Nonnull final String artifactId,
        @Nonnull final String type) throws RuntimeIOException, IllegalStateException {
    Preconditions.checkArgument(Files.isDirectory(srcDir), "Source %s is not a directory",
            srcDir.toAbsolutePath());
    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path entry) throws IOException {
            String fileName = entry.getFileName().toString();
            if (fileName.startsWith(artifactId) && fileName.endsWith("." + type)) {
                return true;
            } else {
                return false;
            }
        }
    };
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(srcDir, filter)) {
        try {
            return Iterables.getOnlyElement(paths);
        } catch (NoSuchElementException e) {
            throw new IllegalStateException("Artifact '" + artifactId + ":" + type + "' not found in path: "
                    + srcDir + ", absolutePath: " + srcDir.toAbsolutePath());
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "More than 1 version of artifact '" + artifactId + ":" + type + "' found in path: " + srcDir
                            + ", absolutePath: " + srcDir.toAbsolutePath() + " -> " + paths);
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception finding artifact " + artifactId + "@" + type + " in " + srcDir);
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * @param srcDir//from   ww w  . j a  v  a  2s.  com
 * @param pattern
 * @return
 * @throws RuntimeIOException
 * @throws IllegalStateException More or less than 1 child dir found
 */
@Nonnull
public static Path findUniqueDirectoryBeginningWith(@Nonnull Path srcDir, @Nonnull final String pattern)
        throws RuntimeIOException, IllegalStateException {
    Preconditions.checkArgument(Files.isDirectory(srcDir), "Source %s is not a directory",
            srcDir.toAbsolutePath());

    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path entry) throws IOException {
            String fileName = entry.getFileName().toString();
            if (pattern == null) {
                return true;
            } else if (fileName.startsWith(pattern)) {
                return true;
            } else {
                return false;
            }
        }
    };

    try (DirectoryStream<Path> paths = Files.newDirectoryStream(srcDir, filter)) {
        try {
            return Iterables.getOnlyElement(paths);
        } catch (NoSuchElementException e) {
            throw new IllegalStateException("Directory beginning with '" + pattern + "' not found in path: "
                    + srcDir + ", absolutePath: " + srcDir.toAbsolutePath());
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "More than 1 directory beginning with '" + pattern + "' found in path: " + srcDir
                            + ", absolutePath: " + srcDir.toAbsolutePath() + " -> " + paths);
        }
    } catch (IOException e) {
        throw new RuntimeIOException(
                "Exception finding unique child directory beginning with " + filter + "in " + srcDir);
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

@Nonnull
public static Path copyArtifactToDirectory(@Nonnull Path sourceDir, @Nonnull String artifactId,
        @Nonnull Path dest) throws RuntimeIOException {
    Path source = findArtifact(sourceDir, artifactId);
    try {//from   w w  w.j  av a2s. c o  m
        return Files.copy(source, dest.resolve(source.getFileName()));
    } catch (IOException e) {
        throw new RuntimeIOException("Exception copying " + source.getFileName() + " to " + sourceDir, e);
    }
}

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

private static void uploadFiles(OperationResult operationResult, Map<Path, File> localPathDriveFileMapping,
        Drive client, Path srcDir, boolean overwrite, final StopRequester stopRequester,
        final HasStatusReporter statusReporter) throws IOException {

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

    int count = 0;
    for (Path path : filesQueue) {
        try {//from  w ww.  j a  va  2s. c o m
            if (statusReporter != null) {
                BasicFileAttributes attr = io.uploader.drive.util.FileUtils.getFileAttr(path);
                StringBuilder sb = new StringBuilder();
                sb.append("Transfering files (");
                sb.append(path.getFileName().toString());
                if (attr != null) {
                    sb.append(" - size: ");
                    sb.append(io.uploader.drive.util.FileUtils.humanReadableByteCount(attr.size(), true));
                }
                sb.append(")");
                statusReporter.setStatus(sb.toString());
            }

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

            final 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() + ")...");
            }

            InputStreamProgressFilter.StreamProgressCallback progressCallback = null;
            if (statusReporter != null) {
                progressCallback = new InputStreamProgressFilter.StreamProgressCallback() {

                    @Override
                    public void onStreamProgress(double progress) {
                        if (statusReporter != null) {
                            statusReporter.setCurrentProgress(progress);
                        }
                    }
                };
            }
            uploadFile(operationResult, client, driveParent, path, overwrite, progressCallback);

            ++count;
            if (statusReporter != null) {
                double p = ((double) count) / filesQueue.size();
                statusReporter.setTotalProgress(p);
                statusReporter.setStatus("Transfering files...");
            }
        } catch (Throwable e) {
            logger.error("Error occurred while transfering the file " + path.toString(), e);
            operationResult.setStatus(OperationCompletionStatus.ERROR);
            operationResult.addError(path, e);
        }
    }
}

From source file:com.liferay.sync.engine.service.SyncAccountService.java

public static SyncAccount addSyncAccount(String filePathName, String lanCertificate, boolean lanEnabled,
        String lanKey, String lanServerUuid, String login, int maxConnections, String oAuthConsumerKey,
        String oAuthConsumerSecret, boolean oAuthEnabled, String oAuthToken, String oAuthTokenSecret,
        String password, String pluginVersion, int pollInterval, Map<SyncSite, List<SyncFile>> ignoredSyncFiles,
        SyncUser syncUser, boolean trustSelfSigned, String url) throws Exception {

    // Sync account

    SyncAccount syncAccount = new SyncAccount();

    syncAccount.setFilePathName(filePathName);
    syncAccount.setLanCertificate(lanCertificate);
    syncAccount.setLanEnabled(lanEnabled);
    syncAccount.setLanKey(lanKey);//from  ww w.j a va 2  s.c o  m
    syncAccount.setLanServerUuid(lanServerUuid);
    syncAccount.setLogin(login);
    syncAccount.setMaxConnections(maxConnections);
    syncAccount.setPluginVersion(pluginVersion);
    syncAccount.setOAuthConsumerKey(oAuthConsumerKey);
    syncAccount.setOAuthConsumerSecret(oAuthConsumerSecret);
    syncAccount.setOAuthEnabled(oAuthEnabled);
    syncAccount.setOAuthToken(oAuthToken);
    syncAccount.setOAuthTokenSecret(SyncEncryptor.encrypt(oAuthTokenSecret));
    syncAccount.setPassword(SyncEncryptor.encrypt(password));
    syncAccount.setPollInterval(pollInterval);
    syncAccount.setTrustSelfSigned(trustSelfSigned);
    syncAccount.setUrl(url);

    _syncAccountPersistence.create(syncAccount);

    // Sync file

    Path filePath = Paths.get(filePathName);

    Path dataFilePath = Files.createDirectories(filePath.resolve(".data"));

    if (OSDetector.isWindows()) {
        Files.setAttribute(dataFilePath, "dos:hidden", true);
    }

    SyncFileService.addSyncFile(null, null, false, null, filePathName, null,
            String.valueOf(filePath.getFileName()), 0, 0, 0, SyncFile.STATE_SYNCED,
            syncAccount.getSyncAccountId(), SyncFile.TYPE_SYSTEM);

    // Sync sites

    for (Map.Entry<SyncSite, List<SyncFile>> entry : ignoredSyncFiles.entrySet()) {

        // Sync site

        SyncSite syncSite = entry.getKey();

        String siteFilePathName = FileUtil.getFilePathName(syncAccount.getFilePathName(),
                syncSite.getSanitizedName());

        while (true) {
            SyncSite existingSyncSite = SyncSiteService.fetchSyncSite(siteFilePathName,
                    syncAccount.getSyncAccountId());

            if (existingSyncSite == null) {
                break;
            }

            siteFilePathName = FileUtil.getNextFilePathName(siteFilePathName);
        }

        syncSite.setFilePathName(siteFilePathName);

        syncSite.setRemoteSyncTime(-1);
        syncSite.setSyncAccountId(syncAccount.getSyncAccountId());

        SyncSiteService.update(syncSite);

        // Sync file

        SyncFileService.addSyncFile(null, null, false, null, syncSite.getFilePathName(), null,
                syncSite.getName(), 0, syncSite.getGroupId(), 0, SyncFile.STATE_SYNCED,
                syncSite.getSyncAccountId(), SyncFile.TYPE_SYSTEM);

        if (syncSite.isActive() && !FileUtil.exists(Paths.get(syncSite.getFilePathName()))) {

            Files.createDirectories(Paths.get(syncSite.getFilePathName()));
        }

        // Sync files

        for (SyncFile childSyncFile : entry.getValue()) {
            childSyncFile.setModifiedTime(0);
            childSyncFile.setState(SyncFile.STATE_UNSYNCED);
            childSyncFile.setSyncAccountId(syncSite.getSyncAccountId());

            SyncFileService.update(childSyncFile);
        }
    }

    // Sync user

    if (syncUser != null) {
        syncUser.setSyncAccountId(syncAccount.getSyncAccountId());

        SyncUserService.update(syncUser);
    }

    return syncAccount;
}

From source file:com.cloudbees.clickstack.util.Files2.java

private static void dump(@Nonnull Path path, int depth) throws RuntimeIOException {
    try {/*  ww  w  .j  a v  a  2s.c  o m*/
        depth++;
        String icon = Files.isDirectory(path) ? " + " : " |- ";
        System.out.println(Strings.repeat(" ", depth) + icon + path.getFileName() + "\t"
                + PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));

        if (Files.isDirectory(path)) {
            DirectoryStream<Path> children = Files.newDirectoryStream(path);
            for (Path child : children) {
                dump(child, depth);
            }
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception dumping " + path, e);
    }
}

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

public static File uploadFile(OperationResult operationResult, Drive client, final File driveParent, Path path,
        boolean overwrite, InputStreamProgressFilter.StreamProgressCallback progressCallback) throws Throwable {

    File ret = null;//ww w  .ja v a 2 s.  co  m
    AtomicInteger tryCounter = new AtomicInteger();
    while (true) {
        try {
            // check if file already exists, if yes, check the etag
            String mineType = findMineType(path);
            String title = path.getFileName().toString();

            //FileList fileList = DriveUtils.findFilesWithTitleAndMineType(client, title, 
            //      DriveUtils.newId(driveParent), DriveUtils.newMineType(mineType), null);
            FileList fileList = DriveUtils.findFilesWithTitleAndMineType(client, title,
                    DriveUtils.newId(driveParent), null, null);

            if (fileList.getItems() == null || fileList.getItems().isEmpty()) {
                // there exists no file with the name title, we create it
                ret = insertFile(client, path.getFileName().toString(), null, DriveUtils.newId(driveParent),
                        DriveUtils.newMineType(mineType), path.toString(), progressCallback);
            } else if (!overwrite) {
                // there already exists at least one file with the name title, we do nothing
                logger.info("File with the name '" + title + "' and type '" + mineType
                        + "' already exists in directory "
                        + ((driveParent == null) ? ("root") : (driveParent.getTitle())) + " (there are "
                        + fileList.getItems().size() + " copies), it will be ignored");
                ret = fileList.getItems().get(0);
            } else {
                // there exists at least one file with the name title
                if (fileList.getItems().size() > 1) {
                    // here there are more than one file with the name title.
                    // this is an unexpected situation! A warning message will be displayed
                    StringBuilder sb = new StringBuilder();
                    sb.append("The folder '");
                    sb.append(driveParent.getTitle());
                    sb.append("' contains ");
                    sb.append(fileList.getItems().size());
                    sb.append(" files with the same name '");
                    sb.append(path.getFileName().toString());
                    sb.append("'.");

                    // all the files with the name title are identical, we delete the unnecessary copies
                    String refMd5 = fileList.getItems().get(0).getMd5Checksum();
                    boolean allIdentical = true;
                    for (File file : fileList.getItems()) {
                        if (!refMd5.equals(file.getMd5Checksum())) {
                            allIdentical = false;
                            break;
                        }
                    }
                    if (allIdentical) {
                        // remove unnecessary copies
                        boolean toBeTrashed = false;
                        for (File file : fileList.getItems()) {
                            if (toBeTrashed) {
                                logger.info("Trashed duplicated file " + file.getTitle());
                                DriveUtils.trashFile(client, DriveUtils.newId(file.getId()));
                            }
                            toBeTrashed = true;
                        }
                        sb.append(
                                " The duplicated copies have been trashed and the remaining copy has been updated'");
                        operationResult.addWarning(path, OperationResult.newWarning(sb.toString()));

                        //  we update the now unique remaining file if required
                        String localEtag = io.uploader.drive.util.FileUtils.getMD5(path.toFile());
                        ret = updateFile(localEtag, client, fileList.getItems().get(0), null, null,
                                DriveUtils.newMineType(mineType), path.toString(), progressCallback);
                    } else {
                        // there are discrepancies between the files with the name title
                        // we add the new file without modifying the existing ones
                        sb.append(" The file '");
                        sb.append(path.toString());
                        sb.append("' was uploaded as a new file");
                        operationResult.addWarning(path, OperationResult.newWarning(sb.toString()));

                        ret = insertFile(client, path.getFileName().toString(), null,
                                DriveUtils.newId(driveParent), DriveUtils.newMineType(mineType),
                                path.toString(), progressCallback);
                    }
                } else {
                    // there already exists only one file with the name title, we update the file if required
                    String localEtag = io.uploader.drive.util.FileUtils.getMD5(path.toFile());
                    ret = updateFile(localEtag, client, fileList.getItems().get(0), null, null,
                            DriveUtils.newMineType(mineType), path.toString(), progressCallback);
                }
            }
            break;
        } catch (Throwable e) {
            dealWithException(e, tryCounter);
            logger.info("Is about to retry...");
        }
    }
    return ret;
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy the given {@code zipSubFilePath} of the given {@code zipFile} into the {@code destDir} if this sub file exists.
 *
 * @param zipFile        the source zip file (e.g. {@code path/to/app.war}
 * @param zipSubFilePath sub file path in the zip file (e.g. {@code /WEB-INF/web.xml}
 * @param destDir/* www .  j a v a  2s. c  o  m*/
 * @param trimSourcePath indicates if the source path should be trimmed creating the dest file (e.g. should {@code WEB-INF/web.xml} be copied as
 *                       {@code dest-dir/WEB-INF/web.xml} or as {@code dest-dir/web.xml})
 * @throws RuntimeIOException
 */
@Nullable
public static Path unzipSubFileIfExists(@Nonnull Path zipFile, @Nonnull String zipSubFilePath,
        @Nonnull final Path destDir, boolean trimSourcePath) throws RuntimeIOException {
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath("/");

            Path subFile = root.resolve(zipSubFilePath);
            if (Files.exists(subFile)) {
                // make file path relative
                Path destFile;
                if (trimSourcePath) {
                    destFile = destDir.resolve(subFile.getFileName().toString());
                } else {
                    if (Strings2.beginWith(zipSubFilePath, "/")) {
                        destFile = destDir.resolve("." + zipSubFilePath);
                    } else {
                        destFile = destDir.resolve(zipSubFilePath);
                    }
                }
                // create parent dirs if needed
                Files.createDirectories(destFile.getParent());
                // copy
                return Files.copy(subFile, destFile, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.COPY_ATTRIBUTES);
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubFilePath + " to " + destDir,
                e);
    }
}

From source file:Search.java

void search(Path file) throws IOException {
    Path name = file.getFileName();
    if (name != null && name.equals(searchedFile)) {
        System.out.println("Searched file was found: " + searchedFile + " in " + file.toRealPath().toString());
        found = true;//ww w. ja  v a 2s  .  c o  m
    }
}