Example usage for java.nio.file Files deleteIfExists

List of usage examples for java.nio.file Files deleteIfExists

Introduction

In this page you can find the example usage for java.nio.file Files deleteIfExists.

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:org.fao.geonet.api.site.SiteApi.java

@ApiOperation(value = "Set catalog logo", notes = "Logos are stored in the data directory "
        + "resources/images/harvesting as PNG or GIF images. "
        + "When a logo is assigned to the catalog, a new "
        + "image is created in images/logos/<catalogUuid>.png.", nickname = "setLogo")
@RequestMapping(path = "/logo", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.PUT)
@PreAuthorize("hasRole('UserAdmin')")
@ResponseStatus(HttpStatus.NO_CONTENT)//from w ww. j  ava2 s.co m
@ApiResponses(value = { @ApiResponse(code = 204, message = "Logo set."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_USER_ADMIN) })
public void setLogo(@ApiParam(value = "Logo to use for the catalog") @RequestParam("file") String file,
        @ApiParam(value = "Create favicon too", required = false) @RequestParam(defaultValue = "false", required = false) boolean asFavicon

) throws Exception {
    ApplicationContext appContext = ApplicationContextHolder.get();
    Path logoDirectory = Resources.locateHarvesterLogosDirSMVC(appContext);

    checkFileName(file);
    FilePathChecker.verify(file);

    SettingManager settingMan = appContext.getBean(SettingManager.class);
    GeonetworkDataDirectory dataDirectory = appContext.getBean(GeonetworkDataDirectory.class);
    String nodeUuid = settingMan.getSiteId();

    try {
        Path logoFilePath = logoDirectory.resolve(file);
        Path nodeLogoDirectory = dataDirectory.getResourcesDir().resolve("images");
        if (!Files.exists(logoFilePath)) {
            logoFilePath = nodeLogoDirectory.resolve("harvesting").resolve(file);
        }
        try (InputStream inputStream = Files.newInputStream(logoFilePath)) {
            BufferedImage source = ImageIO.read(inputStream);

            if (asFavicon) {
                ApiUtils.createFavicon(source, dataDirectory.getResourcesDir().resolve("images")
                        .resolve("logos").resolve("favicon.png"));
            } else {
                Path logo = nodeLogoDirectory.resolve("logos").resolve(nodeUuid + ".png");
                Path defaultLogo = nodeLogoDirectory.resolve("images").resolve("logo.png");

                if (!file.endsWith(".png")) {
                    try (OutputStream logoOut = Files.newOutputStream(logo);
                            OutputStream defLogoOut = Files.newOutputStream(defaultLogo);) {
                        ImageIO.write(source, "png", logoOut);
                        ImageIO.write(source, "png", defLogoOut);
                    }
                } else {
                    Files.deleteIfExists(logo);
                    IO.copyDirectoryOrFile(logoFilePath, logo, false);
                    Files.deleteIfExists(defaultLogo);
                    IO.copyDirectoryOrFile(logoFilePath, defaultLogo, false);
                }
            }
        }
    } catch (Exception e) {
        throw new Exception(
                "Unable to move uploaded thumbnail to destination directory. Error: " + e.getMessage());
    }
}

From source file:org.apache.storm.utils.ServerUtils.java

private static boolean downloadResourcesAsSupervisorAttempt(ClientBlobStore cb, String key, String localFile) {
    boolean isSuccess = false;
    try (FileOutputStream out = new FileOutputStream(localFile); InputStreamWithMeta in = cb.getBlob(key);) {
        long fileSize = in.getFileLength();

        byte[] buffer = new byte[1024];
        int len;//from www.ja va 2s  .  co m
        int downloadFileSize = 0;
        while ((len = in.read(buffer)) >= 0) {
            out.write(buffer, 0, len);
            downloadFileSize += len;
        }

        isSuccess = (fileSize == downloadFileSize);
    } catch (TException | IOException e) {
        LOG.error("An exception happened while downloading {} from blob store.", localFile, e);
    }
    if (!isSuccess) {
        try {
            Files.deleteIfExists(Paths.get(localFile));
        } catch (IOException ex) {
            LOG.error("Failed trying to delete the partially downloaded {}", localFile, ex);
        }
    }
    return isSuccess;
}

From source file:net.mozq.picto.core.ProcessCore.java

private static ProcessDataStatus process(ProcessCondition processCondition, ProcessData processData,
        Function<ProcessData, ProcessDataStatus> overwriteConfirm) throws IOException {

    ProcessDataStatus status;/* www.j a va  2 s.c  o m*/

    Path destParentPath = processData.getDestPath().getParent();
    if (destParentPath != null) {
        Files.createDirectories(destParentPath);
    }

    if (processCondition.isCheckDigest()
            || (processCondition.isChangeExifDate() && processData.getBaseDate() != null)
            || processCondition.isRemveExifTagsGps() || processCondition.isRemveExifTagsAll()) {
        Path destTempPath = null;
        try {
            destTempPath = Files.createTempFile(processData.getDestPath().getParent(),
                    processData.getDestPath().getFileName().toString(), null);

            if (processCondition.isCheckDigest()) {
                String algorithm = FILE_DIGEST_ALGORITHM;

                MessageDigest srcMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(processData.getSrcPath())), srcMD)) {
                    Files.copy(is, destTempPath, OPTIONS_COPY_REPLACE);
                }
                byte[] srcDigest = srcMD.digest();

                MessageDigest destMD = newMessageDigest(algorithm);
                try (InputStream is = new DigestInputStream(
                        new BufferedInputStream(Files.newInputStream(destTempPath)), destMD)) {
                    byte[] b = new byte[1024];
                    while (is.read(b) != -1) {
                    }
                }
                byte[] destDigest = destMD.digest();

                if (!isSame(srcDigest, destDigest)) {
                    throw new PictoFileDigestMismatchException(
                            Messages.getString("message.error.digest.mismatch"));
                }
            } else if (processCondition.isRemveExifTagsAll()) {
                ExifRewriter exifRewriter = new ExifRewriter();
                try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                    exifRewriter.removeExifMetadata(processData.getSrcPath().toFile(), os);
                } catch (ImageReadException | ImageWriteException e) {
                    throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                }
            } else if (processCondition.isChangeExifDate() || processCondition.isRemveExifTagsGps()) {
                ImageMetadata imageMetadata = getImageMetadata(processData.getSrcPath());
                TiffOutputSet outputSet = getOutputSet(imageMetadata);
                if (outputSet == null) {
                    Files.copy(processData.getSrcPath(), destTempPath, OPTIONS_COPY_REPLACE);
                } else {
                    if (processCondition.isChangeExifDate()) {
                        SimpleDateFormat exifDateFormat = new SimpleDateFormat(EXIF_DATE_PATTERN);
                        exifDateFormat.setTimeZone(processCondition.getTimeZone());
                        String exifBaseDate = exifDateFormat.format(processData.getBaseDate());

                        DecimalFormat exifSubsecFormat = new DecimalFormat(EXIF_SUBSEC_PATTERN);
                        String exifBaseSubsec = exifSubsecFormat
                                .format((int) (processData.getBaseDate().getTime() / 10) % 100);

                        try {
                            TiffOutputDirectory rootDirectory = outputSet.getRootDirectory();
                            TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                            if (rootDirectory != null) {
                                rootDirectory.removeField(TiffTagConstants.TIFF_TAG_DATE_TIME);
                                rootDirectory.add(TiffTagConstants.TIFF_TAG_DATE_TIME, exifBaseDate);
                            }
                            if (exifDirectory != null) {
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME, exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_ORIGINAL,
                                        exifBaseSubsec);

                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, exifBaseDate);
                                exifDirectory.removeField(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED);
                                exifDirectory.add(ExifTagConstants.EXIF_TAG_SUB_SEC_TIME_DIGITIZED,
                                        exifBaseSubsec);
                            }
                        } catch (ImageWriteException e) {
                            throw new PictoFileChangeException(Messages.getString("message.error.edit.file"),
                                    e);
                        }
                    }

                    if (processCondition.isRemveExifTagsGps()) {
                        outputSet.removeField(ExifTagConstants.EXIF_TAG_GPSINFO);
                    }

                    ExifRewriter exifRewriter = new ExifRewriter();
                    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(destTempPath))) {
                        exifRewriter.updateExifMetadataLossless(processData.getSrcPath().toFile(), os,
                                outputSet);
                    } catch (ImageReadException | ImageWriteException e) {
                        throw new PictoFileChangeException(Messages.getString("message.error.edit.file"), e);
                    }
                }
            }

            Path destPath;
            if (processCondition.getOperationType() == OperationType.Overwrite) {
                destPath = processData.getSrcPath();
            } else {
                destPath = processData.getDestPath();
            }
            try {
                Files.move(destTempPath, destPath, OPTIONS_MOVE);
                if (processCondition.getOperationType() == OperationType.Move) {
                    Files.deleteIfExists(processData.getSrcPath());
                }
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    // Overwrite
                    Files.move(destTempPath, destPath, OPTIONS_MOVE_REPLACE);
                    if (processCondition.getOperationType() == OperationType.Move) {
                        Files.deleteIfExists(processData.getSrcPath());
                    }
                    status = ProcessDataStatus.Success;
                }
            }
        } finally {
            if (destTempPath != null) {
                Files.deleteIfExists(destTempPath);
            }
        }
    } else {
        switch (processCondition.getOperationType()) {
        case Copy:
            try {
                Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.copy(processData.getSrcPath(), processData.getDestPath(), OPTIONS_COPY_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Move:
            try {
                Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE);
                status = ProcessDataStatus.Success;
            } catch (FileAlreadyExistsException e) {
                status = confirmOverwrite(processCondition, processData, overwriteConfirm);
                if (status == ProcessDataStatus.Processing) {
                    Files.move(processData.getSrcPath(), processData.getDestPath(), OPTIONS_MOVE_REPLACE);
                    status = ProcessDataStatus.Success;
                }
            }
            break;
        case Overwrite:
            // NOP
            status = ProcessDataStatus.Success;
            break;
        default:
            throw new IllegalStateException(processCondition.getOperationType().toString());
        }
    }

    if (status == ProcessDataStatus.Success) {
        FileTime creationFileTime = processData.getSrcFileAttributes().creationTime();
        FileTime modifiedFileTime = processData.getSrcFileAttributes().lastModifiedTime();
        FileTime accessFileTime = processData.getSrcFileAttributes().lastAccessTime();
        if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate()
                || processCondition.isChangeFileAccessDate()) {
            if (processData.getBaseDate() != null) {
                FileTime baseFileTime = FileTime.fromMillis(processData.getBaseDate().getTime());
                if (processCondition.isChangeFileCreationDate()) {
                    creationFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileModifiedDate()) {
                    modifiedFileTime = baseFileTime;
                }
                if (processCondition.isChangeFileAccessDate()) {
                    accessFileTime = baseFileTime;
                }
            }
        }
        BasicFileAttributeView attributeView = Files.getFileAttributeView(processData.getDestPath(),
                BasicFileAttributeView.class);
        attributeView.setTimes(modifiedFileTime, accessFileTime, creationFileTime);
    }

    return status;
}

From source file:org.corehunter.services.simple.FileBasedDatasetServices.java

private void removeDataInternal(String datasetId) throws DatasetException {

    dataCache.remove(datasetId);//from   w ww  .  j  a  va  2s  .c om

    try {
        Files.deleteIfExists(getDataPath(datasetId, CoreHunterDataType.GENOTYPIC));

        Files.deleteIfExists(getDataPath(datasetId, CoreHunterDataType.PHENOTYPIC));

        Files.deleteIfExists(getDataPath(datasetId, CoreHunterDataType.DISTANCES));
    } catch (IOException e) {
        throw new DatasetException(e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

private boolean createSiteRepository(String site) {
    boolean success = true;
    Path siteRepoPath = Paths.get(rootPath, "sites", site);
    try {/*www . j  ava2s .c  om*/
        Files.deleteIfExists(siteRepoPath);
        siteRepoPath = Paths.get(siteRepoPath.toAbsolutePath().toString(), ".git");
        Repository repository = FileRepositoryBuilder.create(siteRepoPath.toFile());
        repository.create();
    } catch (IOException e) {
        logger.error("Error while creating repository for site " + site, e);
        success = false;
    }
    return success;
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;//from  w  w  w  .ja  va  2 s .  c om
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected void updateFile(SyncFile sourceSyncFile, SyncFile targetSyncFile, String filePathName)
        throws Exception {

    if (checkUnsynced(sourceSyncFile, targetSyncFile, filePathName)) {
        return;//from  w ww . j  a v a  2s . c  o  m
    }

    if (sourceSyncFile.getTypePK() != targetSyncFile.getTypePK()) {
        _logger.error("Source type pk {} does not match target {} for {}", sourceSyncFile.getTypePK(),
                targetSyncFile.getTypePK(), sourceSyncFile.getFilePathName());
    }

    String previousChecksum = sourceSyncFile.getChecksum();
    String previousFilePathName = sourceSyncFile.getFilePathName();
    long previousParentFolderId = sourceSyncFile.getParentFolderId();
    String previousType = sourceSyncFile.getType();
    String previousVersion = sourceSyncFile.getVersion();
    long previousVersionId = sourceSyncFile.getVersionId();

    boolean filePathChanged = processFilePathChange(sourceSyncFile, targetSyncFile);

    sourceSyncFile.setChangeLog(targetSyncFile.getChangeLog());
    sourceSyncFile.setChecksum(targetSyncFile.getChecksum());
    sourceSyncFile.setDescription(targetSyncFile.getDescription());
    sourceSyncFile.setExtension(targetSyncFile.getExtension());
    sourceSyncFile.setExtraSettings(targetSyncFile.getExtraSettings());
    sourceSyncFile.setLanTokenKey(targetSyncFile.getLanTokenKey());
    sourceSyncFile.setLockExpirationDate(targetSyncFile.getLockExpirationDate());
    sourceSyncFile.setLockUserId(targetSyncFile.getLockUserId());
    sourceSyncFile.setLockUserName(targetSyncFile.getLockUserName());
    sourceSyncFile.setModifiedTime(targetSyncFile.getModifiedTime());
    sourceSyncFile.setSize(targetSyncFile.getSize());
    sourceSyncFile.setType(targetSyncFile.getType());
    sourceSyncFile.setTypePK(targetSyncFile.getTypePK());
    sourceSyncFile.setUserId(targetSyncFile.getUserId());
    sourceSyncFile.setUserName(targetSyncFile.getUserName());
    sourceSyncFile.setVersion(targetSyncFile.getVersion());
    sourceSyncFile.setVersionId(targetSyncFile.getVersionId());

    SyncFileService.update(sourceSyncFile);

    if (filePathChanged && !Validator.isBlank(previousChecksum)
            && previousChecksum.equals(targetSyncFile.getChecksum())) {

        sourceSyncFile.setState(SyncFile.STATE_SYNCED);

        if (previousParentFolderId == sourceSyncFile.getParentFolderId()) {
            sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_RENAMED_REMOTE);
        } else {
            sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_MOVED_REMOTE);
        }

        SyncFileService.update(sourceSyncFile);

        return;
    }

    Path filePath = Paths.get(targetSyncFile.getFilePathName());

    if (!previousType.equals(sourceSyncFile.getType())) {
        if (previousType.equals(SyncFile.TYPE_FOLDER)) {
            FileUtils.deleteDirectory(filePath.toFile());
        } else {
            Files.deleteIfExists(filePath);
        }
    }

    if (!FileUtil.exists(filePath)) {
        if (targetSyncFile.isFolder()) {
            Path targetFilePath = Paths.get(filePathName);

            Files.createDirectories(targetFilePath);

            sourceSyncFile.setState(SyncFile.STATE_SYNCED);
            sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_UPDATED_REMOTE);

            SyncFileService.update(sourceSyncFile);

            FileKeyUtil.writeFileKey(targetFilePath, String.valueOf(sourceSyncFile.getSyncFileId()), false);
        } else {
            downloadFile(sourceSyncFile, null, 0, false);
        }
    } else if (targetSyncFile.isFile() && FileUtil.isModified(targetSyncFile, filePath)) {

        downloadFile(sourceSyncFile, previousVersion, previousVersionId,
                !IODeltaUtil.isIgnoredFilePatchingExtension(targetSyncFile));
    } else {
        sourceSyncFile.setState(SyncFile.STATE_SYNCED);

        if (previousFilePathName.equals(sourceSyncFile.getFilePathName())) {
            sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_NONE);
        } else {
            sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_RENAMED_REMOTE);
        }

        SyncFileService.update(sourceSyncFile);
    }
}

From source file:org.jboss.as.logging.HandlerOperationsTestCase.java

private void testCommonFileOperations(final KernelServices kernelServices, final ModelNode address)
        throws Exception {
    // Create a directory a new directory
    final LoggingTestEnvironment env = LoggingTestEnvironment.get();
    final Path dir = Paths.get(env.getLogDir().getAbsolutePath(), "file-dir");
    Files.createDirectories(dir);
    // Attempt to add a file-handler with the dir for the path
    ModelNode op = OperationBuilder.createAddOperation(address)
            .addAttribute(CommonAttributes.FILE, createFileValue(null, dir.toString())).build();
    executeOperationForFailure(kernelServices, op);

    // Clean-up//from ww w.j  a v a2 s  .c  o  m
    Files.deleteIfExists(dir);
}

From source file:org.fao.geonet.kernel.harvest.harvester.geonet.Aligner.java

/**
 *  Updates the record on the database. The force parameter allows you to force an update even
 * if the date is not more updated, to make sure transformation and attributes assigned by the
 * harvester are applied. Also, it changes the ownership of the record so it is assigned to the
 * new harvester that last updated it.//  w ww .j a va 2  s  . c  om
* @param ri
* @param id
* @param localRating
* @param useChangeDate
* @param localChangeDate
* @param force
* @throws Exception
 */
private void updateMetadata(final RecordInfo ri, final String id, final boolean localRating,
        final boolean useChangeDate, String localChangeDate, Boolean force) throws Exception {
    final Element md[] = { null };
    final Element publicFiles[] = { null };
    final Element privateFiles[] = { null };

    if (localUuids.getID(ri.uuid) == null && !force) {
        if (log.isDebugEnabled())
            log.debug("  - Skipped metadata managed by another harvesting node. uuid:" + ri.uuid + ", name:"
                    + params.getName());
    } else {
        if (force || !useChangeDate || ri.isMoreRecentThan(localChangeDate)) {
            Path mefFile = retrieveMEF(ri.uuid);

            try {
                String fileType = "mef";
                MEFLib.Version version = MEFLib.getMEFVersion(mefFile);
                if (version != null && version.equals(MEFLib.Version.V2)) {
                    fileType = "mef2";
                }

                IVisitor visitor = fileType.equals("mef2") ? new MEF2Visitor() : new MEFVisitor();

                MEFLib.visit(mefFile, visitor, new IMEFVisitor() {
                    public void handleMetadata(Element mdata, int index) throws Exception {
                        md[index] = mdata;
                    }

                    //-----------------------------------------------------------------

                    public void handleMetadataFiles(DirectoryStream<Path> files, Element info, int index)
                            throws Exception {
                        // Import valid metadata
                        Element metadataValidForImport = extractValidMetadataForImport(files, info);

                        if (metadataValidForImport != null) {
                            handleMetadata(metadataValidForImport, index);
                        }
                    }

                    public void handleInfo(Element info, int index) throws Exception {
                        updateMetadata(ri, id, md[index], info, localRating, force);
                        publicFiles[index] = info.getChild("public");
                        privateFiles[index] = info.getChild("private");
                    }

                    //-----------------------------------------------------------------

                    public void handlePublicFile(String file, String changeDate, InputStream is, int index)
                            throws IOException {
                        handleFile(id, file, "public", changeDate, is, publicFiles[index]);
                    }

                    public void handleFeatureCat(Element md, int index) throws Exception {
                        // Feature Catalog not managed for harvesting
                    }

                    public void handlePrivateFile(String file, String changeDate, InputStream is, int index)
                            throws IOException {
                        handleFile(id, file, "private", changeDate, is, privateFiles[index]);
                    }

                });
            } catch (Exception e) {
                //--- we ignore the exception here. Maybe the metadata has been removed just now
                result.unretrievable++;
            } finally {
                try {
                    Files.deleteIfExists(mefFile);
                } catch (IOException e) {
                    log.warning("Unable to delete mefFile: " + mefFile);
                }

            }
        } else {
            result.unchangedMetadata++;
        }
    }
}

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

public static void deleteEmptyAncestorsQuietly(Path binVersionPath, Path upToParent) {
    if (binVersionPath == null) {
        return;/*  w  w  w.  j  av a  2s  .  c o 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);
        }
    }
}