Example usage for org.apache.commons.io FileUtils forceDeleteOnExit

List of usage examples for org.apache.commons.io FileUtils forceDeleteOnExit

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils forceDeleteOnExit.

Prototype

public static void forceDeleteOnExit(File file) throws IOException 

Source Link

Document

Schedules a file to be deleted when JVM exits.

Usage

From source file:edu.kit.dama.transfer.client.impl.AbstractTransferClient.java

/**
 * Perform cleanup operations in case of a successful transfer. During cleanup
 * the temporary transfer directory will be removed. If the removal fails, the
 * deletion will be sheduled to be performed during exit.
 *//*from   www  .  ja va 2s.co m*/
private void cleanup() {
    setStatus(TRANSFER_STATUS.CLEANUP);
    String tempDir = null;
    LOGGER.info(" * Performing cleanup");
    CleanupManager.getSingleton().performCleanup(transferContainer.getUniqueTransferIdentifier());
    //wait a while as sometimes FileUtils.deleteDirectory() finds files which were deleted by the CleanupManager
    try {
        Thread.sleep(500);
    } catch (InterruptedException ex) {
    }
    //try to remove the tmp directory
    try {
        tempDir = StagingUtils.getTempDir(transferContainer);
        LOGGER.debug("Try to remove temporary transfer directory '{}'", tempDir);
        FileUtils.deleteDirectory(new File(tempDir));
    } catch (IOException ioe) {
        if (tempDir == null) {
            LOGGER.warn("Cleanup failed. Could not obtain temporary transfer directory", ioe);
        } else {
            LOGGER.warn("Cleanup failed. Trying to schedule DeleteOnExit", ioe);
            try {
                FileUtils.forceDeleteOnExit(new File(tempDir));
            } catch (IOException ioe2) {
                LOGGER.warn("Failed to shedule DeleteOnExit. Please remove the temporary directory manually.",
                        ioe2);
            }
        }
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicUpdater.java

static void deleteFile(File granule) throws IOException {
    if (!FileUtils.deleteQuietly(granule)) {
        try {/*from   w w w.jav a2  s  .  c om*/
            FileUtils.forceDelete(granule);
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(e.getLocalizedMessage(), e);
            }

            // delete on exit
            FileUtils.forceDeleteOnExit(granule);
        }
    }
}

From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStreamTest.java

private EncryptedFile encryptedFile(SecretKey key, SupportedCipherDetails cipherDetails, long plaintextSize)
        throws IOException {
    File temp = File.createTempFile("encrypted", ".data");
    FileUtils.forceDeleteOnExit(temp);

    try (InputStream in = testURL.openStream()) {
        return encryptedFile(key, cipherDetails, plaintextSize, in);
    }//from w ww  . j a  va  2s  . c om
}

From source file:com.joyent.manta.client.crypto.MantaEncryptedObjectInputStreamTest.java

private EncryptedFile encryptedFile(SecretKey key, SupportedCipherDetails cipherDetails, long plaintextSize,
        InputStream in) throws IOException {
    File temp = File.createTempFile("encrypted", ".data");
    FileUtils.forceDeleteOnExit(temp);

    try (FileOutputStream out = new FileOutputStream(temp)) {
        MantaInputStreamEntity entity = new MantaInputStreamEntity(in, plaintextSize);
        EncryptingEntity encryptingEntity = new EncryptingEntity(key, cipherDetails, entity);
        encryptingEntity.writeTo(out);/*w  w  w. j  av a2  s . co m*/

        Assert.assertEquals(temp.length(), encryptingEntity.getContentLength(),
                "Ciphertext doesn't equal calculated size");

        return new EncryptedFile(encryptingEntity.getCipher(), temp);
    }
}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

@Override
public <T> void saveUserSettings(String aUsername, Project aProject, Mode aSubject, T aConfigurationObject)
        throws IOException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
    Properties property = new Properties();
    for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
        if (wrapper.getPropertyValue(value.getName()) == null) {
            continue;
        }//from  w  w  w .ja v  a2  s  .c o  m
        property.setProperty(aSubject + "." + value.getName(),
                wrapper.getPropertyValue(value.getName()).toString());
    }
    String propertiesPath = dir.getAbsolutePath() + PROJECT + aProject.getId() + SETTINGS + aUsername;
    // append existing preferences for the other mode
    if (new File(propertiesPath, annotationPreferencePropertiesFileName).exists()) {
        // aSubject = aSubject.equals(Mode.ANNOTATION) ? Mode.CURATION :
        // Mode.ANNOTATION;
        for (Entry<Object, Object> entry : loadUserSettings(aUsername, aProject).entrySet()) {
            String key = entry.getKey().toString();
            // Maintain other Modes of annotations confs than this one
            if (!key.substring(0, key.indexOf(".")).equals(aSubject.toString())) {
                property.put(entry.getKey(), entry.getValue());
            }
        }
    }
    FileUtils.forceDeleteOnExit(new File(propertiesPath, annotationPreferencePropertiesFileName));
    FileUtils.forceMkdir(new File(propertiesPath));
    property.store(new FileOutputStream(new File(propertiesPath, annotationPreferencePropertiesFileName)),
            null);

    createLog(aProject).info(" Saved preferences file [" + annotationPreferencePropertiesFileName
            + "] for project [" + aProject.getName() + "] with ID [" + aProject.getId() + "] to location: ["
            + propertiesPath + "]");
    createLog(aProject).removeAllAppenders();

}

From source file:de.tudarmstadt.ukp.clarin.webanno.api.dao.RepositoryServiceDbData.java

@Override
public <T> void saveHelpContents(T aConfigurationObject) throws IOException {
    BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(aConfigurationObject);
    Properties property = new Properties();
    for (PropertyDescriptor value : wrapper.getPropertyDescriptors()) {
        if (wrapper.getPropertyValue(value.getName()) == null) {
            continue;
        }/*from w w w  . j  a  v  a  2s.  c o  m*/
        property.setProperty(value.getName(), wrapper.getPropertyValue(value.getName()).toString());
    }
    File helpFile = new File(dir.getAbsolutePath() + HELP_FILE);
    if (helpFile.exists()) {
        FileUtils.forceDeleteOnExit(helpFile);
    } else {
        helpFile.createNewFile();
    }
    property.store(new FileOutputStream(helpFile), null);

}

From source file:com.siblinks.ws.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}/*from w  w w.j  a  va2 s.  co  m*/
 */
@Override
@RequestMapping(value = "/uploadAvatar", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Response> uploadAvatar(@RequestParam("uploadfile") final MultipartFile uploadfile,
        @RequestParam(value = "userid") final String userid,
        @RequestParam("imageUrl") final String oldNameImgAvatar) throws IOException {

    String filename = "";
    String name = "";
    String filepath = "";
    BufferedOutputStream stream = null;
    SimpleResponse response = null;
    try {
        String directory = environment.getProperty("directoryAvatar");
        String service = environment.getProperty("directoryGetAvatar");
        String strExtenstionFile = environment.getProperty("file.upload.image.type");
        name = uploadfile.getOriginalFilename();
        String nameExt = FilenameUtils.getExtension(name);
        boolean status = strExtenstionFile.contains(nameExt.toLowerCase());
        if (directory != null && status) {
            RandomString randomName = new RandomString();
            filename = randomName.random() + "." + "png";
            filepath = "" + Paths.get(directory, filename);
            // Save the file locally
            File file = new File(filepath);
            File parentDir = file.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            stream = new BufferedOutputStream(new FileOutputStream(file));
            stream.write(uploadfile.getBytes());

            Object[] queryParams = { service + filename, userid };
            dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_AVARTAR_USER, queryParams);
            boolean insertUpdateObject = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_AVARTAR_USER,
                    queryParams);

            // Remove image avatar old
            if (insertUpdateObject && oldNameImgAvatar != null && !"".equals(oldNameImgAvatar)) {
                String fileName = oldNameImgAvatar.substring(oldNameImgAvatar.lastIndexOf("/"),
                        oldNameImgAvatar.length());
                File fileOld = new File(directory + fileName);
                if (fileOld.exists()) {
                    FileUtils.forceDeleteOnExit(fileOld);
                }
                activityLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_PROFILE, "U",
                        "You updated your avatar", userid, null));
            }
            // Successful return path image avatar
            response = new SimpleResponse(SibConstants.SUCCESS, service + filename);
        } else {
            response = new SimpleResponse(SibConstants.FAILURE, "Not found path or file is not exist");
        }
    } catch (Exception e) {
        response = new SimpleResponse(SibConstants.FAILURE, "Upload avatar error");
        logger.debug("Upload avartar error " + e.getMessage());
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException io) {
            // Do Nothing
        }
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:nl.knaw.huygens.alexandria.dropwizard.cli.CommandIntegrationTest.java

private void tearDownWorkDir() throws IOException {
    File directory = new File(workDirectory.toAbsolutePath().toString());
    FileUtils.forceDeleteOnExit(directory);
}

From source file:npanday.plugin.partcover.PartCoverCompilerMojo.java

public void execute() throws MojoExecutionException {
    try {//w w w .  j a v  a2  s . c o  m
        if (!outputDirectory.exists()) {
            outputDirectory.mkdirs();
        }

        StringBuilder line = new StringBuilder();
        line.append(" \"").append(partCover).append("\" --target \"").append(nUnit).append("\" --target-args ")
                .append(assemblyName);

        if (include != null && include.length() > 0) {
            line.append(" --include ").append(include);
        }
        if (exclude != null && exclude.length() > 0) {
            line.append(" --exclude ").append(exclude);
        }

        line.append(" --output ").append(outputDirectory).append("/coverage.xml");

        int exitValue = executeCommandLine(line.toString());

        // clean up 
        FileUtils.forceDeleteOnExit(new File(project.getBasedir(), "partcover.driver.log"));
        FileUtils.forceDeleteOnExit(new File(project.getBasedir(), "TestResult.xml"));
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing coverage", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing coverage", e);
    }
}

From source file:org.apache.beam.sdk.io.hcatalog.EmbeddedMetastoreService.java

EmbeddedMetastoreService(String baseDirPath) throws IOException {
    FileUtils.forceDeleteOnExit(new File(baseDirPath));

    String hiveDirPath = makePathASafeFileName(baseDirPath + "/hive");
    String testDataDirPath = makePathASafeFileName(hiveDirPath + "/data/"
            + EmbeddedMetastoreService.class.getCanonicalName() + System.currentTimeMillis());
    String testWarehouseDirPath = makePathASafeFileName(testDataDirPath + "/warehouse");

    hiveConf = new HiveConf(getClass());
    hiveConf.setVar(HiveConf.ConfVars.PREEXECHOOKS, "");
    hiveConf.setVar(HiveConf.ConfVars.POSTEXECHOOKS, "");
    hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
    hiveConf.setVar(HiveConf.ConfVars.METASTOREWAREHOUSE, testWarehouseDirPath);
    hiveConf.setBoolVar(HiveConf.ConfVars.HIVEOPTIMIZEMETADATAQUERIES, true);
    hiveConf.setVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_MANAGER,
            "org.apache.hadoop.hive.ql.security.authorization.plugin.sqlstd." + "SQLStdHiveAuthorizerFactory");
    hiveConf.set("test.tmp.dir", hiveDirPath);

    System.setProperty("derby.stream.error.file", "/dev/null");
    driver = new Driver(hiveConf);
    sessionState = SessionState.start(new CliSessionState(hiveConf));
}