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

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

Introduction

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

Prototype

public static void cleanDirectory(File directory) throws IOException 

Source Link

Document

Cleans a directory without deleting it.

Usage

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @throws WebStoreAttachmentException /*from  ww w  .j a  v  a 2 s .  com*/
 * 
 */
public WebStoreAttachmentMgr(final String urlStr, final String keyStr) throws WebStoreAttachmentException {
    attachment_key = keyStr == null ? "" : keyStr;
    server_url = urlStr;

    downloadCacheDir = new File(UIRegistry.getAppDataDir() + File.separator + "download_cache");
    if (!downloadCacheDir.exists()) {
        if (!downloadCacheDir.mkdir()) {
            downloadCacheDir = null;
            throw new WebStoreAttachmentException("Failed to create download cache dir.");
        }

    } else {
        try {
            FileUtils.cleanDirectory(downloadCacheDir);
        } catch (IOException e) {
        }
    }

    getURLSetupXML(urlStr);
    testKey();
}

From source file:eu.esdihumboldt.hale.server.templates.war.components.TemplateUploadForm.java

/**
 * Constructor//  ww w  .j  a v a  2  s . c  om
 * 
 * @param id the component ID
 * @param templateId the identifier of the template to update, or
 *            <code>null</code> to create a new template
 */
public TemplateUploadForm(String id, String templateId) {
    super(id);
    this.templateId = templateId;

    Form<Void> form = new Form<Void>("upload") {

        private static final long serialVersionUID = 716487990605324922L;

        @Override
        protected void onSubmit() {
            List<FileUpload> uploads = file.getFileUploads();
            if (uploads != null && !uploads.isEmpty()) {
                final boolean newTemplate = TemplateUploadForm.this.templateId == null;
                final String templateId;
                final File dir;
                File oldContent = null;
                if (newTemplate) {
                    // attempt to reserve template ID
                    Pair<String, File> template;
                    try {
                        template = templates.reserveResource(determinePreferredId(uploads));
                    } catch (ScavengerException e) {
                        error(e.getMessage());
                        return;
                    }
                    templateId = template.getFirst();
                    dir = template.getSecond();
                } else {
                    templateId = TemplateUploadForm.this.templateId;
                    dir = new File(templates.getHuntingGrounds(), templateId);

                    // archive old content
                    try {
                        Path tmpFile = Files.createTempFile("hale-template", ".zip");
                        try (OutputStream out = Files.newOutputStream(tmpFile);
                                ZipOutputStream zos = new ZipOutputStream(out)) {
                            IOUtils.zipDirectory(dir, zos);
                        }
                        oldContent = tmpFile.toFile();
                    } catch (IOException e) {
                        log.error("Error saving old template content to archive", e);
                    }

                    // delete old content
                    try {
                        FileUtils.cleanDirectory(dir);
                    } catch (IOException e) {
                        log.error("Error deleting old template content", e);
                    }
                }

                try {
                    for (FileUpload upload : uploads) {
                        if (isZipFile(upload)) {
                            // extract uploaded file
                            IOUtils.extract(dir, new BufferedInputStream(upload.getInputStream()));
                        } else {
                            // copy uploaded file
                            File target = new File(dir, upload.getClientFileName());
                            ByteStreams.copy(upload.getInputStream(), new FileOutputStream(target));
                        }
                    }

                    // trigger scan after upload
                    if (newTemplate) {
                        templates.triggerScan();
                    } else {
                        templates.forceUpdate(templateId);
                    }

                    TemplateProject ref = templates.getReference(templateId);
                    if (ref != null && ref.isValid()) {
                        info("Successfully uploaded project");
                        boolean infoUpdate = (updateInfo != null) ? (updateInfo.getModelObject()) : (false);
                        onUploadSuccess(this, templateId, ref.getProjectInfo(), infoUpdate);
                    } else {
                        if (newTemplate) {
                            templates.releaseResourceId(templateId);
                        } else {
                            restoreContent(dir, oldContent);
                        }
                        error((ref != null) ? (ref.getNotValidMessage())
                                : ("Uploaded files could not be loaded as HALE project"));
                    }

                } catch (Exception e) {
                    if (newTemplate) {
                        templates.releaseResourceId(templateId);
                    } else {
                        restoreContent(dir, oldContent);
                    }
                    log.error("Error while uploading file", e);
                    error("Error saving the file");
                }
            } else {
                warn("Please provide a file for upload");
            }
        }

        @Override
        protected void onFileUploadException(FileUploadException e, Map<String, Object> model) {
            if (e instanceof SizeLimitExceededException) {
                final String msg = "Only files up to  " + bytesToString(getMaxSize(), Locale.US)
                        + " can be uploaded.";
                error(msg);
            } else {
                final String msg = "Error uploading the file: " + e.getLocalizedMessage();
                error(msg);

                log.warn(msg, e);
            }
        }

    };
    add(form);

    // multipart always needed for uploads
    form.setMultiPart(true);

    // max size for upload
    if (UserUtil.isAdmin()) {
        // admin max upload size
        form.setMaxSize(Bytes.megabytes(100));
    } else {
        // normal user max upload size
        // TODO differentiate between logged in and anonymous user?
        form.setMaxSize(Bytes.megabytes(15));
    }

    // Add file input field for multiple files
    form.add(file = new FileUploadField("file"));
    file.add(new IValidator<List<FileUpload>>() {

        private static final long serialVersionUID = -5668788086384105101L;

        @Override
        public void validate(IValidatable<List<FileUpload>> validatable) {
            if (validatable.getValue().isEmpty()) {
                validatable.error(new ValidationError("No source files specified."));
            }
        }

    });

    // add anonym/recaptcha panel
    boolean loggedIn = UserUtil.getLogin() != null;
    WebMarkupContainer anonym = new WebMarkupContainer("anonym");

    if (loggedIn) {
        anonym.add(new WebMarkupContainer("recaptcha"));
    } else {
        anonym.add(new RecaptchaPanel("recaptcha"));
    }

    anonym.add(
            new BookmarkablePageLink<>("login", ((BaseWebApplication) getApplication()).getLoginPageClass()));

    anonym.setVisible(!loggedIn);
    form.add(anonym);

    // update panel
    WebMarkupContainer update = new WebMarkupContainer("update");
    update.setVisible(templateId != null);

    updateInfo = new CheckBox("updateInfo", Model.of(true));
    update.add(updateInfo);

    form.add(update);

    // feedback panel
    form.add(new BootstrapFeedbackPanel("feedback"));
}

From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java

/**
 * Setup reference data and temporary directory for the output builder.
 * @throws Exception if temporary directory could not be created
 *//* w  w w  . ja  v a 2 s. c o  m*/
private void setup() throws Exception {
    String tempDir = conf.getTemporaryDirectoryPath();
    String hashAlgURI = conf.getHashAlgorithmURI();

    hashCalculator = new HashCalculator(hashAlgURI);
    timestamp = Long.toString(new Date().getTime());
    tempConfPath = Paths.get(tempDir, String.format("%s-v%d", SIGNED_DIRECTORY_NAME, version));
    tempDirPath = Paths.get(tempDir, timestamp);

    log.debug("Creating directories {}", tempDirPath);

    Files.createDirectories(tempDirPath);

    log.debug("Clean directory {}", tempDirPath);

    FileUtils.cleanDirectory(tempDirPath.toFile());

    dataBoundary = randomBoundary();
    envelopeBoundary = randomBoundary();
    envelopeHeader = HEADER_CONTENT_TYPE + ": "
            + mpRelatedContentType(envelopeBoundary, MultiPartWriter.MULTIPART_MIXED) + "\n\n";
}

From source file:es.uvigo.ei.sing.adops.datatypes.ProjectExperiment.java

@Override
public void deleteResult() {
    if (this.hasResult())
        this.getResult().delete(); // Will be deleted on the update method.

    try {/*  w  w w.  j  a v a2 s .  c  om*/
        if (this.filesFolder.isDirectory())
            FileUtils.cleanDirectory(this.filesFolder);
    } catch (IOException e) {
    }

    this.result = null;

    this.setChanged();
    this.notifyObservers();
}

From source file:net.jawr.web.resource.bundle.global.preprocessor.css.smartsprites.CssSmartSpritesGlobalPreprocessor.java

/**
 * Generates the image sprites from the smartsprites annotation in the CSS,
 * rewrite the CSS files to references the generated sprites.
 * //  w ww. ja v a 2 s  .c  o m
 * @param cssRsHandler
 *            the css resourceHandler
 * @param imgRsHandler
 *            the image resourceHandler
 * @param resourcePaths
 *            the set of CSS resource paths to handle
 * @param jawrConfig
 *            the Jawr config
 * @param charset
 *            the charset
 */
private void generateSprites(ResourceReaderHandler cssRsHandler, ImageResourcesHandler imgRsHandler,
        Set<String> resourcePaths, JawrConfig jawrConfig, Charset charset) {

    MessageLevel msgLevel = MessageLevel.valueOf(ERROR_LEVEL);
    String sinkLevel = WARN_LEVEL;
    if (LOGGER.isTraceEnabled() || LOGGER.isDebugEnabled() || LOGGER.isInfoEnabled()) { // logLevel.isGreaterOrEqual(Level.DEBUG)
        msgLevel = MessageLevel.valueOf(INFO_LEVEL);
        sinkLevel = INFO_LEVEL;
    } else if (LOGGER.isWarnEnabled() || LOGGER.isErrorEnabled()) { // logLevel.isGreaterOrEqual(Level.WARN)
        msgLevel = MessageLevel.valueOf(WARN_LEVEL);
        sinkLevel = WARN_LEVEL;
    }

    MessageLog messageLog = new MessageLog(new MessageSink[] { new LogMessageSink(sinkLevel) });

    SmartSpritesResourceHandler smartSpriteRsHandler = new SmartSpritesResourceHandler(cssRsHandler,
            imgRsHandler.getRsReaderHandler(), jawrConfig.getGeneratorRegistry(),
            imgRsHandler.getConfig().getGeneratorRegistry(), charset.toString(), messageLog);

    smartSpriteRsHandler
            .setContextPath(jawrConfig.getProperty(JawrConstant.JAWR_CSS_URL_REWRITER_CONTEXT_PATH));

    String outDir = cssRsHandler.getWorkingDirectory() + JawrConstant.CSS_SMARTSPRITES_TMP_DIR;

    // Create temp directories
    File tmpDir = new File(outDir);

    if (!tmpDir.exists()) {
        if (!tmpDir.mkdirs()) {
            throw new BundlingProcessException("Impossible to create temporary directory : " + outDir);
        }
    } else {
        // Clean temp directories
        try {
            FileUtils.cleanDirectory(tmpDir);
        } catch (IOException e) {
            throw new BundlingProcessException("Impossible to clean temporary directory : " + outDir, e);
        }
    }

    SmartSpritesParameters params = new SmartSpritesParameters("/", null, outDir, null, msgLevel, "",
            PngDepth.valueOf("AUTO"), false, charset.toString());
    // TODO : use below parameters when Smartsprites will handle
    // keepingSpriteTrack parameter
    // SmartSpritesParameters params = new SmartSpritesParameters("/", null,
    // outDir, null, msgLevel, "", PngDepth.valueOf("AUTO"), false,
    // charset.toString(), true);

    SpriteBuilder spriteBuilder = new SpriteBuilder(params, messageLog, smartSpriteRsHandler);
    try {
        spriteBuilder.buildSprites(resourcePaths);
    } catch (IOException e) {
        throw new BundlingProcessException("Unable to build sprites", e);
    }
}

From source file:com.talis.entity.db.babudb.bulk.BabuDbEntityDatabaseBuilder.java

private void initWorkingDirs(File rootDir) throws IOException {
    LOG.info("Initialising Database root directory: {}", rootDir.getAbsolutePath());
    if (!rootDir.isDirectory() && rootDir.exists()) {
        String msg = String.format("Invalid Database root: {}", rootDir.getAbsolutePath());
        LOG.error(msg);/* www .  j a  v a2  s  .c  om*/
        throw new RuntimeException(msg);
    }
    FileUtils.forceMkdir(rootDir);
    FileUtils.cleanDirectory(rootDir);
}

From source file:com.taobao.android.apatch.MergePatch.java

public static void main(String[] args) throws IOException, PatchException {

    File tablauncher = new File("/Users/seker/log/temp/tablauncher.apatch");
    File commonbiz = new File("/Users/seker/log/temp/commonbiz.apatch");

    File[] files = new File[] { tablauncher, commonbiz };

    File out = new File("/Users/seker/log/temp/apatch/");
    FileUtils.cleanDirectory(out);

    String keystore = "/Users/seker/programs/debugsign/seker.keystore";
    String password = "12345678";
    String alias = "seker.keystore";
    String entry = "12345678";
    String name = "main";

    MergePatch mergePatch = new MergePatch(files, name, out);
    mergePatch.doMerge();//from  w  w  w. j  ava2  s  . c om
}

From source file:fr.inria.oak.paxquery.xparser.client.XClient.java

private void deleteOldGraphFiles(String graphsPath) {
    try {//from w w  w.  j  a  va2 s .co  m
        FileUtils.cleanDirectory(new File(graphsPath));
        // java.nio.file.Path pathDOT = FileSystems.getDefault().getPath(graphsPath, "*.dot");
        // java.nio.file.Path pathPNG = FileSystems.getDefault().getPath(graphsPath, "*.png");
        // boolean successDOT = Files.deleteIfExists(pathDOT);
        // boolean successPNG = Files.deleteIfExists(pathPNG);
    } catch (IOException ioe) {
        System.out.println("Exception deleting old graph files: " + ioe.getMessage());
    }
}

From source file:edu.uci.ics.pregelix.core.join.JoinTest.java

@Test
public void customerOrderCIDJoinMulti() throws Exception {
    ClusterConfig.setStorePath(PATH_TO_CLUSTER_STORE);
    ClusterConfig.setClusterPropertiesPath(PATH_TO_CLUSTER_PROPERTIES);
    cleanupStores();/*from  w  w w.j  a v  a2s .com*/
    PregelixHyracksIntegrationUtil.init();

    FileUtils.forceMkdir(new File(EXPECT_RESULT_DIR));
    FileUtils.forceMkdir(new File(ACTUAL_RESULT_DIR));
    FileUtils.cleanDirectory(new File(EXPECT_RESULT_DIR));
    FileUtils.cleanDirectory(new File(ACTUAL_RESULT_DIR));
    runCreate();
    runBulkLoad();
    runHashJoin();
    runIndexJoin();
    TestUtils.compareWithResult(new File(EXPECTED_RESULT_FILE), new File(ACTUAL_RESULT_FILE));

    FileUtils.cleanDirectory(new File(EXPECT_RESULT_DIR));
    FileUtils.cleanDirectory(new File(ACTUAL_RESULT_DIR));
    runLeftOuterHashJoin();
    runIndexRightOuterJoin();
    TestUtils.compareWithResult(new File(EXPECTED_RESULT_FILE), new File(ACTUAL_RESULT_FILE));

    PregelixHyracksIntegrationUtil.deinit();
}

From source file:eu.europa.esig.dss.tsl.service.TSLRepository.java

public void clearRepository() {
    try {/*  w  ww  . j a  v  a 2  s. c  o  m*/
        FileUtils.cleanDirectory(new File(cacheDirectoryPath));
        tsls.clear();
    } catch (IOException e) {
        logger.error("Unable to clean cache directory : " + e.getMessage(), e);
    }
}