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.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * {@inheritDoc}//from w w  w. j a  v  a2s.co  m
 */
@Override
public void run() {

    final Path tempArchiveFile = arguments.tempArchiveFile;
    final Path finalArchiveFile = arguments.finalArchiveFile;

    try (final ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(
            Files.newOutputStream(tempArchiveFile))) {

        zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
        zipOutputStream.setLevel(Deflater.BEST_COMPRESSION);

        final RepositoryElement repository = buildOrgUnitRepository(arguments.backup, arguments.userId);
        repository.setName("");

        zipRepository(repository, zipOutputStream, "");

        // TODO Delete existing previous organization file(s).

        // Renames temporary '.tmp' file to complete '.zip' file.
        Files.move(tempArchiveFile, finalArchiveFile, StandardCopyOption.REPLACE_EXISTING);

    } catch (final Throwable t) {

        if (LOG.isErrorEnabled()) {
            LOG.error("An error occurred during backup archive generation process.", t);
        }

        try {

            Files.deleteIfExists(tempArchiveFile);
            Files.deleteIfExists(finalArchiveFile);

        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("An error occurred while deleting archive error file.", e);
            }
        }
    }
}

From source file:org.codice.ddf.catalog.plugin.metacard.backup.storage.filestorage.MetacardBackupFileStorage.java

private void deleteBackupIfPresent(String filename) throws MetacardBackupException {
    Path metacardPath = getMetacardDirectory(filename);
    if (metacardPath == null) {
        LOGGER.debug("Unable to delete backup for: {}", filename);
        throw new MetacardBackupException("Unable to delete backup");
    }/*w  w  w  . j a  v a2s .c  o  m*/

    try {
        Files.deleteIfExists(metacardPath);
        while (metacardPath.getParent() != null
                && !metacardPath.getParent().toString().equals(outputDirectory)) {
            metacardPath = metacardPath.getParent();
            if (isDirectoryEmpty(metacardPath)) {
                FileUtils.deleteDirectory(metacardPath.toFile());
            }
        }
    } catch (IOException e) {
        LOGGER.debug("Unable to delete backup file {}", metacardPath, e);
        throw new MetacardBackupException("Unable to delete backup file", e);
    }
}

From source file:org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManager.java

private void deleteFile(FileUploadInfo fileInfo) {
    getLogger().debug("deleteFile({})", fileInfo);
    try {//w  w w  .  j a v a  2 s . c o  m
        Files.deleteIfExists(uploadPathHandler.getLocalFilePath(fileInfo));
        fileUploadInfoRepository.remove(fileInfo);
    } catch (IOException ex) {
        throw new IllegalStateException(ex.getMessage(), ex);
    }
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreService.java

@Override
public FileStoreMapper store(File file, String fileName, String mimeType, String moduleName,
        boolean deleteFile) {
    try {//from  www .j a v  a2  s . co m
        FileStoreMapper fileMapper = new FileStoreMapper(randomUUID().toString(),
                defaultString(fileName, file.getName()));
        Path newFilePath = this.createNewFilePath(fileMapper, moduleName);
        Files.copy(file.toPath(), newFilePath);
        fileMapper.setContentType(mimeType);
        if (deleteFile && Files.deleteIfExists(file.toPath()))
            LOG.info("File store source file deleted");
        return fileMapper;
    } catch (IOException e) {
        throw new ApplicationRuntimeException(
                String.format(FILE_STORE_ERROR, this.fileStoreBaseDir, getCityCode(), moduleName), e);
    }
}

From source file:com.eucalyptus.blockstorage.SnapshotUploadCheckerTask.java

private void cleanupAbortedUploads() {
    try (TransactionResource snapTran = Entities.transactionFor(SnapshotUploadInfo.class)) {
        List<SnapshotUploadInfo> snapUploadInfoList = Entities
                .query(new SnapshotUploadInfo().withState(SnapshotUploadState.aborted));
        for (SnapshotUploadInfo snapUploadInfo : snapUploadInfoList) {
            LOG.debug("Cleaning aborted entity " + snapUploadInfo);
            try (TransactionResource partTran = Entities.transactionFor(SnapshotPart.class)) {
                List<SnapshotPart> parts = Entities
                        .query(new SnapshotPart(snapUploadInfo.getSnapshotId(), snapUploadInfo.getBucketName(),
                                snapUploadInfo.getKeyName(), snapUploadInfo.getUploadId()));
                for (SnapshotPart part : parts) {
                    if (StringUtils.isNotBlank(part.getFileName())) {
                        LOG.debug("Deleting snapshot part from disk: " + part.getFileName());
                        if (!Files.deleteIfExists(Paths.get(part.getFileName()))) {
                            LOG.warn("Could not delete snapshot part from disk: " + part.getFileName());
                        }//from w  w  w  . j a  v  a2 s . c om
                    }
                    part.setState(SnapshotPartState.cleaned);
                }
                partTran.commit();
            }
            snapUploadInfo.setPurgeTime(System.currentTimeMillis() + SnapshotUploadInfo.PURGE_INTERVAL);
            snapUploadInfo.setState(SnapshotUploadState.cleaned);
        }
        snapTran.commit();
    } catch (Exception e) {
        LOG.debug("Error updating snapshot upload state during clean up" + e);
    }
}

From source file:org.wso2.carbon.launcher.test.OSGiLibBundleDeployerTest.java

@Test(description = "Attempts to load OSGi bundle information from a source directory with an existing "
        + "bundle removed", priority = 4)
public void testRemovingExistingBundle() throws IOException {
    String equinoxLauncherVersion = System.getProperty("equinox.launcher.version");
    BundleInfo bundleInfoRemoved = BundleInfo.getInstance(
            "org.eclipse.equinox.launcher," + equinoxLauncherVersion + ",../../" + Constants.OSGI_LIB
                    + "/org.eclipse.equinox.launcher_" + equinoxLauncherVersion + ".jar,4,true");

    Path lib = Paths.get(carbonHome, Constants.OSGI_LIB);
    Files.deleteIfExists(
            Paths.get(lib.toString(), "org.eclipse.equinox.launcher_" + equinoxLauncherVersion + ".jar"));

    List<BundleInfo> expected = getExpectedBundleInfo();
    expected.remove(bundleInfoRemoved);//from w  w w .  jav a2s .c o  m

    OSGiLibBundleDeployer deployer = new OSGiLibBundleDeployer();
    deployer.notify(new CarbonServerEvent(CarbonServerEvent.STARTING, null));

    Path bundlesInfo = Paths.get(carbonHome, Constants.PROFILE_REPOSITORY, Constants.DEFAULT_PROFILE,
            "configuration", "org.eclipse.equinox.simpleconfigurator", bundlesInfoFile);
    List<BundleInfo> actual = getActualBundleInfo(bundlesInfo);
    Assert.assertTrue(compareBundleInfo(expected, actual));
}

From source file:com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest.java

@Test(expected = IllegalStateException.class)
public void testWriteAfterClose() throws IOException {
    final Path path = Paths.get("target/tmp/test/testConsumerMultiClose.json");
    path.toFile().deleteOnExit();//from   w  w  w  .j  av a 2  s  . com
    Files.deleteIfExists(path);
    final JsonBenchmarkConsumer consumer = new JsonBenchmarkConsumer(path);

    final Result result = DataCreator.createResult();
    consumer.accept(result);
    consumer.close();
    // Should throw
    consumer.accept(result);
}

From source file:com.liferay.sync.engine.documentlibrary.handler.BaseJSONHandler.java

protected boolean handlePortalException(String exception) throws Exception {
    if (exception.equals("")) {
        return false;
    }/*from   w  w w  . j a v  a2  s.co  m*/

    if (_logger.isDebugEnabled()) {
        _logger.debug("Handling exception {}", exception);
    }

    if (exception.equals("com.liferay.portal.DuplicateLockException")) {
        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_DUPLICATE_LOCK);

        SyncFileService.update(syncFile);
    } else if (exception.equals("com.liferay.portal.kernel.upload.UploadException")
            || exception.contains("SizeLimitExceededException")) {

        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_EXCEEDED_SIZE_LIMIT);

        SyncFileService.update(syncFile);
    } else if (exception.equals("com.liferay.portal.security.auth.PrincipalException")) {

        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_INVALID_PERMISSIONS);

        SyncFileService.update(syncFile);
    } else if (exception.equals("com.liferay.portlet.documentlibrary.FileNameException")) {

        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_INVALID_FILE_NAME);

        SyncFileService.update(syncFile);
    } else if (exception.equals("com.liferay.portlet.documentlibrary." + "NoSuchFileEntryException")) {

        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

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

        Files.deleteIfExists(filePath);

        SyncFileService.deleteSyncFile(syncFile);
    } else if (exception.equals("com.liferay.sync.SyncServicesUnavailableException")) {

        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId());

        syncAccount.setState(SyncAccount.STATE_DISCONNECTED);
        syncAccount.setUiEvent(SyncAccount.UI_EVENT_SYNC_SERVICES_NOT_ACTIVE);

        SyncAccountService.update(syncAccount);

        retryServerConnection();
    } else if (exception.equals("com.liferay.portal.kernel.jsonwebservice." + "NoSuchJSONWebServiceException")
            || exception.equals("java.lang.RuntimeException")) {

        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId());

        syncAccount.setState(SyncAccount.STATE_DISCONNECTED);
        syncAccount.setUiEvent(SyncAccount.UI_EVENT_SYNC_WEB_MISSING);

        SyncAccountService.update(syncAccount);

        retryServerConnection();
    } else if (exception.equals("java.lang.SecurityException")) {
        throw new HttpResponseException(HttpStatus.SC_UNAUTHORIZED, "Authenticated access required");
    }

    return true;
}

From source file:wherehows.common.utils.JobsUtilTest.java

@Test
public void testMultipleLinesSameProperties() throws IOException, ConfigurationException {
    String dir = "/tmp/";
    String propertyStr = "var1=com.mysql.jdbc.driver\n" + "var1=username\n" + "var1=password\n" + "var2=3301\n"
            + "var2=1000\n" + "var3=http://wherehows.com\n" + "var1=mysql\n" + "var4=wherehows\n"
            + "var5=1000,10,3\n" + "var5=true\n";
    ;/*w w w  . j  a  v  a  2 s .co  m*/
    Properties props = new Properties();
    Path path = createPropertiesFile(propertyStr);

    props = getJobConfigProperties(path.toFile());

    Assert.assertNotEquals(props, null);
    Assert.assertEquals(props.getProperty("var1", ""), "com.mysql.jdbc.driver,username,password,mysql");
    Assert.assertEquals(props.getProperty("var2"), "3301,1000");
    Assert.assertEquals(props.getProperty("var3"), "http://wherehows.com");
    Assert.assertEquals(props.getProperty("var4"), "wherehows");
    Assert.assertEquals(props.getProperty("var5"), "1000,10,3,true");

    Files.deleteIfExists(path);
}

From source file:com.eucalyptus.blockstorage.async.SnapshotTransferCleaner.java

private void cleanupAbortedUploads() {
    try (TransactionResource snapTran = Entities.transactionFor(SnapshotUploadInfo.class)) {
        List<SnapshotUploadInfo> snapUploadInfoList = Entities
                .query(new SnapshotUploadInfo().withState(SnapshotUploadState.aborted));
        for (SnapshotUploadInfo snapUploadInfo : snapUploadInfoList) {
            LOG.debug("Cleaning aborted entity " + snapUploadInfo);
            try (TransactionResource partTran = Entities.transactionFor(SnapshotPart.class)) {
                List<SnapshotPart> parts = Entities
                        .query(new SnapshotPart(snapUploadInfo.getSnapshotId(), snapUploadInfo.getBucketName(),
                                snapUploadInfo.getKeyName(), snapUploadInfo.getUploadId()));
                for (SnapshotPart part : parts) {
                    if (StringUtils.isNotBlank(part.getFileName())) {
                        LOG.debug("Deleting snapshot part from disk: " + part.getFileName());
                        if (!Files.deleteIfExists(Paths.get(part.getFileName()))) {
                            LOG.debug(part.getFileName() + " not found, skipping delete");
                        }//  ww  w  . j  av  a2  s. c o  m
                    }
                    part.setState(SnapshotPartState.cleaned);
                }
                partTran.commit();
            }
            snapUploadInfo.setPurgeTime(System.currentTimeMillis() + SnapshotUploadInfo.PURGE_INTERVAL);
            snapUploadInfo.setState(SnapshotUploadState.cleaned);
        }
        snapTran.commit();
    } catch (Exception e) {
        LOG.debug("Error updating snapshot upload state during clean up" + e);
    }
}