Example usage for org.apache.commons.io FileDeleteStrategy FORCE

List of usage examples for org.apache.commons.io FileDeleteStrategy FORCE

Introduction

In this page you can find the example usage for org.apache.commons.io FileDeleteStrategy FORCE.

Prototype

FileDeleteStrategy FORCE

To view the source code for org.apache.commons.io FileDeleteStrategy FORCE.

Click Source Link

Document

The singleton instance for forced file deletion, which always deletes, even if the file represents a non-empty directory.

Usage

From source file:actions.RepDownload.java

/**
 * Downloads a repository from the Internet, adds it up to the big archive
 * and then moves forward to the next one
 * @param repositoryDetails A repository line from our text file
 *///from ww  w .  j a  va2s  .  c o m
private void getRepository(final String repositoryDetails, final int slotId, final String specificFolder) {
    // there always needs to be a space, otherwise exit the processing
    int i1 = repositoryDetails.indexOf(" ");
    if (i1 == -1) {
        System.out.println("DR195 - Error, unable to process: " + repositoryDetails);
        System.exit(-1);
    }
    // now get the repository name
    final String repository = repositoryDetails.substring(0, i1);

    System.out.println(slotId + "-> Downloading: " + repository);

    // Create the path where the files will be downloaded onto
    File localPath = new File(folderDownload + "/" + slotId + "/" + specificFolder, repository);
    utils_deprecated.files.mkdirs(localPath);

    // do the download of files
    boolean success = download(slotId, localPath, repository);
    //svnExport(repository, localPath);

    // did we had success in downloading the files?
    if (success == false) {
        // move to the next one on the list
        return;
    }

    // delete the files that are not needed
    files.deleteHiddenFilesAndFolders(localPath, 25);
    deleteUnwantedFiles(localPath, 25);

    // now archive these files
    writeBigFiles(localPath, slotId);

    // now delete these files
    File localDelete;
    try {
        localDelete = new File(folderDownload.getCanonicalPath(), slotId + "");
        files.deleteHiddenFilesAndFolders(localDelete, 25);
        FileDeleteStrategy.FORCE.deleteQuietly(localDelete);
    } catch (IOException ex) {
        Logger.getLogger(RepDownload.class.getName()).log(Level.SEVERE, null, ex);

    }

    // all done with success, write this name on our log of actions
    utils_deprecated.files.addTextToFile(fileLog, "\n" + repository);

    // all done
    repCounter++;
    System.out.println(slotId + "--> #" + repCounter + ": " + repository);

    // clean up the slot
    slots[slotId] = false;
}

From source file:actions.DownloadSPDX.java

/**
 * Downloads a repository from the Internet, adds it up to the big archive
 * and then moves forward to the next one
 * @param repositoryDetails A repository line from our text file
 *///  w  ww .j  a  v  a  2s .com
private void getRepository(final String repositoryDetails, final int slotId, final String specificFolder) {
    // there always needs to be a space, otherwise exit the processing
    int i1 = repositoryDetails.indexOf(" ");
    if (i1 == -1) {
        System.out.println("DS364 - Error, unable to process: " + repositoryDetails);
        System.exit(-1);
    }
    // now get the repository name
    final String repository = repositoryDetails.substring(0, i1);

    System.out.println(slotId + "-> Downloading: " + repository);

    // Create the path where the files will be downloaded onto
    final File localPath = new File(folderDownload + "/" + slotId + "/" + specificFolder, repository);
    utils.files.mkdirs(localPath);

    final String packageName = repository.replace("/", "-");

    // create the file where the SPDX document will be placed
    final File localSPDX = new File(folderDownload + "/" + slotId + "/", packageName + ".spdx");

    // delete the older file if existing already
    localSPDX.delete();

    // do the download of files
    boolean success = download(slotId, localPath, repository);
    //svnExport(repository, localPath);

    // did we had success in downloading the files?
    if (success == false) {
        // move to the next one on the list
        return;
    }

    // delete the files that are not needed
    files.deleteHiddenFilesAndFolders(localPath, 25);
    // do we want to only index a specific type of files?
    //        deleteUnwantedFiles(localPath, 25);

    // create an SPDX document
    main.cmdLine.createCmdLineSPDX(localSPDX, localPath, packageName, "https://github.com/" + repository,
            "Nuno Brito");

    // now archive these files
    writeBigFile(localSPDX, slotId);

    //        System.out.println("Testing!!!!  ");
    //        System.exit(2);

    // now delete these files
    File localDelete;
    try {
        localDelete = new File(folderDownload.getCanonicalPath(), slotId + "");
        files.deleteHiddenFilesAndFolders(localDelete, 25);
        FileDeleteStrategy.FORCE.deleteQuietly(localDelete);
        // delete the SPDX document
        localSPDX.delete();
    } catch (IOException ex) {
        Logger.getLogger(DownloadSPDX.class.getName()).log(Level.SEVERE, null, ex);

    }

    // all done with success, write this name on our log of actions
    utils.files.addTextToFile(fileLog, "\n" + repository);

    // all done
    repCounter++;
    System.out.println(slotId + "--> #" + repCounter + ": " + repository);

    // clean up the slot
    slots[slotId] = false;
}

From source file:com.adaptris.core.runtime.StandardMessageErrorDigestTest.java

public void testMBean_RemoveDigestEntry_ByEntry_WithDelete() throws Exception {
    String adapterName = this.getClass().getSimpleName() + "." + getName();
    Adapter adapter = createAdapter(adapterName);
    StandardMessageErrorDigester digester = createDigester();
    digester.setUniqueId(getName());/*from  w  w w  . jav a2  s.  c o  m*/
    adapter.setMessageErrorDigester(digester);
    List<BaseComponentMBean> mBeans = createJmxManagers(adapter);
    File tempDir = Files.createTempDirectory(this.getClass().getSimpleName()).toFile();
    tempDir.deleteOnExit();
    cleaner.track(tempDir, digester, FileDeleteStrategy.FORCE);
    try {
        start(adapter);
        register(mBeans);
        ObjectName adapterObj = createAdapterObjectName(adapterName);
        ObjectName digesterObj = createMessageErrorDigestObjectName(adapterName, getName());

        StandardMessageErrorDigesterJmxMBean errDigester = JMX.newMBeanProxy(mBeanServer, digesterObj,
                StandardMessageErrorDigesterJmxMBean.class);
        // The files don't actually exist; so they won't be deleted;
        List<AdaptrisMessage> msgs = createAndDigest(digester, "testDigest", tempDir.getCanonicalPath());

        assertNotNull(errDigester.getDigest());
        assertEquals(5, errDigester.getDigest().size());
        assertEquals(5, errDigester.getTotalErrorCount());
        errDigester.remove(new MessageDigestErrorEntry(msgs.get(0).getUniqueId(), null), true);
        assertEquals(4, errDigester.getDigest().size());
        assertEquals(5, errDigester.getTotalErrorCount());
    } finally {
        stop(adapter);
    }
}

From source file:actions.RepDownload.java

/**
 * Delete a file if it recognised as non-desired
 * @param file     The file to analyse//from  w w w .j av a 2s  .c o  m
 */
private void deleteUnwantedFile(final File file) {
    // get the file name
    final String fileName = file.getName();
    // do our tests
    // at the moment we only want java files
    if (fileName.endsWith(wantedFileType) == false) {
        FileDeleteStrategy.FORCE.deleteQuietly(file);
    }
}

From source file:com.adaptris.core.runtime.StandardMessageErrorDigestTest.java

public void testMBean_RemoveDigestEntry_ByMessageId_WithDelete() throws Exception {
    String adapterName = this.getClass().getSimpleName() + "." + getName();
    Adapter adapter = createAdapter(adapterName);
    StandardMessageErrorDigester digester = createDigester();
    digester.setUniqueId(getName());/* w  w w  .ja  v  a 2s  .c  o  m*/
    adapter.setMessageErrorDigester(digester);
    List<BaseComponentMBean> mBeans = createJmxManagers(adapter);
    File tempDir = Files.createTempDirectory(this.getClass().getSimpleName()).toFile();
    tempDir.deleteOnExit();
    cleaner.track(tempDir, digester, FileDeleteStrategy.FORCE);
    try {
        start(adapter);
        register(mBeans);
        ObjectName adapterObj = createAdapterObjectName(adapterName);
        ObjectName digesterObj = createMessageErrorDigestObjectName(adapterName, getName());

        StandardMessageErrorDigesterJmxMBean errDigester = JMX.newMBeanProxy(mBeanServer, digesterObj,
                StandardMessageErrorDigesterJmxMBean.class);
        // The files don't actually exist; so they won't be deleted;
        List<AdaptrisMessage> msgs = createAndDigest(digester, "testDigest", tempDir.getCanonicalPath());

        assertNotNull(errDigester.getDigest());
        assertEquals(5, errDigester.getDigest().size());
        assertEquals(5, errDigester.getTotalErrorCount());
        errDigester.remove(msgs.get(0).getUniqueId(), true);
        assertEquals(4, errDigester.getDigest().size());
        assertEquals(5, errDigester.getTotalErrorCount());
    } finally {
        stop(adapter);
    }
}

From source file:nl.uva.sne.disambiguation.Main.java

public static void main(String args[]) throws IOException, Exception {
    String filterredDictionary = null, outDir = null;
    if (args != null) {

        filterredDictionary = args[0];/*from w  ww . j  a v a 2 s.  com*/
        outDir = args[1];

        props = args[args.length - 1];
        if (props.endsWith(".properties")) {
            propertiesPath = props;
        }
    }
    List<Term> terms = null;
    Properties properties = FileUtils.getProperties(propertiesPath);
    try {
        //          $HOME/textdocs/dictionaryAll.csv $HOME/textdocs/term_dictionaryPOS_expert_validation.csv $HOME/Downloads/jsonTerms

        //            String className = "nl.uva.sne.disambiguators.BabelNet";
        //            String className = "nl.uva.sne.disambiguators.Wikipedia";
        //            String className = "nl.uva.sne.disambiguators.Wikidata";
        //            String className = "nl.uva.sne.disambiguators.WordNet";
        String className = "nl.uva.sne.disambiguators.MetaDisambiguator";

        Class c = Class.forName(className);
        Object obj = c.newInstance();
        DisambiguatorImpl disambiguator = (DisambiguatorImpl) obj;
        disambiguator.configure(properties);
        terms = disambiguator.disambiguateTerms(filterredDictionary);

    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException
            | ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (terms != null) {
            try {
                writeTerms2Json(terms, outDir);
                terms = buildGraph(terms, null);
                export2SKOS(terms, outDir + File.separator + "taxonomy.rdf", String.valueOf(1));
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        String cachePath = properties.getProperty("cache.path");
        File cacheFolder = new File(cachePath).getParentFile();
        if (cacheFolder.exists()) {
            for (File file : cacheFolder.listFiles()) {
                if (file.getAbsolutePath().endsWith(".lock")) {
                    FileDeleteStrategy.FORCE.delete(file);
                }
            }
        }
    }

    Logger.getLogger(Main.class.getName()).log(Level.INFO, "-----Done-----");
}

From source file:org.asqatasun.sebuilder.tools.ProfileFactory.java

/**
 * /*from w w w. j  av  a 2  s . c o  m*/
 * @param firefoxProfile 
 */
public void shutdownFirefoxProfile(FirefoxProfile firefoxProfile) {
    try {
        if (deleteProfileData) {
            FileDeleteStrategy.FORCE.delete(new File(netExportPathMap.get(firefoxProfile)));
        }
    } catch (IOException ex) {
        Logger.getLogger(this.getClass()).error(ex);
    }
    netExportPathMap.remove(firefoxProfile);
}

From source file:org.deteter.test.deleterTest.java

@Test
public void delete() {
    lista = new ArrayList<>();
    //File dir = new File("C:\\Users\\JORGE_000\\Desktop\\nexus-oss");
    File dir = new File(
            "c:\\abcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxyabcdefghijklmnopqrssttuvwxy");
    //FileUtils.deleteDirectory(dir);
    //FileUtils.deleteDirectory(dir);
    //FileDeleteStrategy.FORCE.delete(dir);
    agregar(dir);// w  w  w.ja v a2  s .c  o m
    System.out.println(dir.isDirectory());
    /*for (File f : lista) {
    try {
        System.out.println(f.getCanonicalPath());
    } catch (Exception ex) {
        System.out.println(ex);
    }
    }*/
    ListIterator<File> i = lista.listIterator(lista.size());
    try {
        while (i.hasPrevious()) {
            File f = i.previous();
            //f.delete();
            FileDeleteStrategy.FORCE.delete(f);
            //System.out.println(f.getCanonicalPath());
        }
        FileDeleteStrategy.FORCE.delete(dir);
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:org.dspace.app.itemimport.ItemImportServiceImpl.java

/**
 * //from w w  w .j av  a2s.  co  m
 * Given a local file or public URL to a zip file that has the Simple Archive Format, this method imports the contents to DSpace
 * @param filepath The filepath to local file or the public URL of the zip file
 * @param owningCollection The owning collection the items will belong to
 * @param otherCollections The collections the created items will be inserted to, apart from the owning one
 * @param resumeDir In case of a resume request, the directory that containsthe old mapfile and data 
 * @param inputType The input type of the data (bibtex, csv, etc.), in case of local file
 * @param context The context
 * @param template whether to use template item
 * @throws Exception if error
 */
@Override
public void processUIImport(String filepath, Collection owningCollection, String[] otherCollections,
        String resumeDir, String inputType, Context context, final boolean template) throws Exception {
    final EPerson oldEPerson = context.getCurrentUser();
    final String[] theOtherCollections = otherCollections;
    final Collection theOwningCollection = owningCollection;
    final String theFilePath = filepath;
    final String theInputType = inputType;
    final String theResumeDir = resumeDir;
    final boolean useTemplateItem = template;

    Thread go = new Thread() {
        @Override
        public void run() {
            Context context = null;

            String importDir = null;
            EPerson eperson = null;

            try {

                // create a new dspace context
                context = new Context();
                eperson = ePersonService.find(context, oldEPerson.getID());
                context.setCurrentUser(eperson);
                context.turnOffAuthorisationSystem();

                boolean isResume = theResumeDir != null;

                List<Collection> collectionList = new ArrayList<>();
                if (theOtherCollections != null) {
                    for (String colID : theOtherCollections) {
                        UUID colId = UUID.fromString(colID);
                        if (!theOwningCollection.getID().equals(colId)) {
                            Collection col = collectionService.find(context, colId);
                            if (col != null) {
                                collectionList.add(col);
                            }
                        }
                    }
                }

                importDir = ConfigurationManager.getProperty("org.dspace.app.batchitemimport.work.dir")
                        + File.separator + "batchuploads" + File.separator + context.getCurrentUser().getID()
                        + File.separator
                        + (isResume ? theResumeDir : (new GregorianCalendar()).getTimeInMillis());
                File importDirFile = new File(importDir);
                if (!importDirFile.exists()) {
                    boolean success = importDirFile.mkdirs();
                    if (!success) {
                        log.info("Cannot create batch import directory!");
                        throw new Exception("Cannot create batch import directory!");
                    }
                }

                String dataPath = null;
                String dataDir = null;

                if (theInputType.equals("saf")) { //In case of Simple Archive Format import (from remote url)
                    dataPath = importDirFile + File.separator + "data.zip";
                    dataDir = importDirFile + File.separator + "data_unzipped2" + File.separator;
                } else if (theInputType.equals("safupload")) { //In case of Simple Archive Format import (from upload file)
                    FileUtils.copyFileToDirectory(new File(theFilePath), importDirFile);
                    dataPath = importDirFile + File.separator + (new File(theFilePath)).getName();
                    dataDir = importDirFile + File.separator + "data_unzipped2" + File.separator;
                } else { // For all other imports
                    dataPath = importDirFile + File.separator + (new File(theFilePath)).getName();
                    dataDir = importDirFile + File.separator + "data" + File.separator;
                }

                //Clear these files, if a resume
                if (isResume) {
                    if (!theInputType.equals("safupload")) {
                        (new File(dataPath)).delete();
                    }
                    (new File(importDirFile + File.separator + "error.txt")).delete();
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    FileDeleteStrategy.FORCE.delete(
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                }

                //In case of Simple Archive Format import we need an extra effort to download the zip file and unzip it
                String sourcePath = null;
                if (theInputType.equals("saf")) {
                    OutputStream os = new FileOutputStream(dataPath);

                    byte[] b = new byte[2048];
                    int length;

                    InputStream is = new URL(theFilePath).openStream();
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }

                    is.close();
                    os.close();

                    sourcePath = unzip(new File(dataPath), dataDir);

                    //Move files to the required folder
                    FileUtils.moveDirectory(new File(sourcePath),
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    dataDir = importDirFile + File.separator + "data_unzipped" + File.separator;
                } else if (theInputType.equals("safupload")) {
                    sourcePath = unzip(new File(dataPath), dataDir);
                    //Move files to the required folder
                    FileUtils.moveDirectory(new File(sourcePath),
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    dataDir = importDirFile + File.separator + "data_unzipped" + File.separator;
                }

                //Create mapfile path
                String mapFilePath = importDirFile + File.separator + "mapfile";

                List<Collection> finalCollections = null;
                if (theOwningCollection != null) {
                    finalCollections = new ArrayList<>();
                    finalCollections.add(theOwningCollection);
                    finalCollections.addAll(collectionList);
                }

                setResume(isResume);

                if (theInputType.equals("saf") || theInputType.equals("safupload")) { //In case of Simple Archive Format import
                    addItems(context, finalCollections, dataDir, mapFilePath, template);
                } else { // For all other imports (via BTE)
                    addBTEItems(context, finalCollections, theFilePath, mapFilePath, useTemplateItem,
                            theInputType, dataDir);
                }

                // email message letting user know the file is ready for
                // download
                emailSuccessMessage(context, eperson, mapFilePath);

                context.complete();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                String exceptionString = ExceptionUtils.getStackTrace(e);

                try {
                    File importDirFile = new File(importDir + File.separator + "error.txt");
                    PrintWriter errorWriter = new PrintWriter(importDirFile);
                    errorWriter.print(exceptionString);
                    errorWriter.close();

                    emailErrorMessage(eperson, exceptionString);
                    throw new Exception(e.getMessage());
                } catch (Exception e2) {
                    // wont throw here
                }
            }

            finally {
                // Make sure the database connection gets closed in all conditions.
                try {
                    context.complete();
                } catch (SQLException sqle) {
                    context.abort();
                }
            }
        }

    };

    go.isDaemon();
    go.start();

}

From source file:org.dspace.app.itemimport.ItemImportServiceImpl.java

@Override
public void deleteBatchUpload(Context c, String uploadId) throws Exception {
    String uploadDir = null;//from   w  w  w  .  j  a va  2  s .com
    String mapFilePath = null;

    uploadDir = getImportUploadableDirectory(c.getCurrentUser()) + File.separator + uploadId;
    mapFilePath = uploadDir + File.separator + "mapfile";

    this.deleteItems(c, mapFilePath);
    FileDeleteStrategy.FORCE.delete(new File(uploadDir));
}