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

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

Introduction

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

Prototype

public static void forceDelete(File file) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

public void importSampleContents() throws IOException, GitAPIException {
    // TODO: synchronization is not quite correct here, but should be okay in this edge case
    if (listBranches().isEmpty()) {
        ILock lock = lockManager.lockAll();
        List<String> branches;
        try {//from   ww  w.j  av  a 2s. co m
            File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
            FileUtils.forceDelete(gitDir);

            Git.cloneRepository().setURI(DocumentrConstants.SAMPLE_REPO_URL).setDirectory(gitDir).setBare(true)
                    .call();

            Repository centralRepo = null;
            File centralRepoGitDir;
            try {
                centralRepo = getCentralRepositoryInternal(true);
                centralRepoGitDir = centralRepo.getDirectory();
                StoredConfig config = centralRepo.getConfig();
                config.unsetSection("remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$
                config.unsetSection("branch", "master"); //$NON-NLS-1$ //$NON-NLS-2$
                config.save();
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            branches = listBranches();
            for (String branchName : branches) {
                File repoDir = new File(reposDir, branchName);
                Repository repo = null;
                try {
                    repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString())
                            .setDirectory(repoDir).call().getRepository();

                    Git git = Git.wrap(repo);
                    RefSpec refSpec = new RefSpec(
                            "refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
                    git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
                    git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
                    git.checkout().setName(branchName).call();
                } finally {
                    RepositoryUtil.closeQuietly(repo);
                }
            }
        } finally {
            lockManager.unlock(lock);
        }

        for (String branch : branches) {
            eventBus.post(new BranchCreatedEvent(projectName, branch));
        }
    }
}

From source file:massbank.BatchSearchWorker.java

public void run() {
    File attacheDir = null;/*from www.j  ava  2 s. co m*/
    try {
        // wWu?"Rinning"
        JobManager jobMgr = new JobManager();
        jobMgr.setRunning(this.jobId);

        GetConfig conf = new GetConfig(MassBankEnv.get(MassBankEnv.KEY_BASE_URL));
        this.serverUrl = conf.getServerUrl();

        String tempDir = MassBankEnv.get(MassBankEnv.KEY_TOMCAT_TEMP_PATH);
        File temp = File.createTempFile("batchRes", ".txt");
        String queryFilePath = (!this.fileName.equals("")) ? tempDir + this.fileName : "";
        String resultFilePath = (!temp.getName().equals("")) ? tempDir + temp.getName() : "";

        // ** open temporary file
        File f1 = new File(queryFilePath);
        File f2 = new File(resultFilePath);
        BufferedReader in = new BufferedReader(new FileReader(f1));
        this.writer = new PrintWriter(new BufferedWriter(new FileWriter(f2)));
        String line = "";
        String name = "";
        String peak = "";
        int peakLineCnt = 0;
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<String> peaks = new ArrayList<String>();
        while ((line = in.readLine()) != null) {
            line = line.trim();

            // R?g?sXLbv
            if (line.startsWith("//")) {
                continue;
            }
            // NAME^O
            else if (line.matches("^Name:.*")) {
                name = line.replaceFirst("^Name: *", "").trim();
            } else if (line.matches(".*:.*")) {
            } else if (line.equals("")) {
                if (peakLineCnt > 0) {
                    names.add(name);
                    peaks.add(peak);
                    name = "";
                    peak = "";
                    peakLineCnt = 0;
                }
            } else {
                peak += line;
                if (!line.substring(line.length() - 1).equals(";")) {
                    peak += ";";
                }
                peakLineCnt++;
            }
        }
        in.close();
        if (peakLineCnt > 0) {
            names.add(name);
            peaks.add(peak);
        }

        // ???
        for (int i = 0; i < names.size(); i++) {
            boolean ret = doSearch(names.get(i), peaks.get(i), i);
            // Xbh?I
            if (isTerminated) {
                break;
            }
        }
        writer.flush();
        writer.close();

        if (isTerminated) {
            f2.delete();
            return;
        }

        if (!this.mailAddress.equals("")) {
            // ??[?M???
            SendMailInfo info = new SendMailInfo(MassBankEnv.get(MassBankEnv.KEY_BATCH_SMTP),
                    MassBankEnv.get(MassBankEnv.KEY_BATCH_FROM), this.mailAddress);
            info.setFromName(MassBankEnv.get(MassBankEnv.KEY_BATCH_NAME));
            info.setSubject("MassBank Batch Service Results");
            info.setContents("Dear Users,\n\nThank you for using MassBank Batch Service.\n" + "\n"
                    + "The results for your request dated '" + this.time + "' are attached to this e-mail.\n"
                    + "\n" + "----------------------------------------------\n"
                    + "MassBank - High Quality Mass Spectral Database\n" + "  URL: " + serverUrl + "\n"
                    + "  E-mail: " + MassBankEnv.get(MassBankEnv.KEY_BATCH_FROM));

            // Ytt@C??fBNg
            attacheDir = new File(tempDir + "batch_" + RandomStringUtils.randomAlphanumeric(9));
            while (attacheDir.exists()) {
                attacheDir = new File(tempDir + "batch_" + RandomStringUtils.randomAlphanumeric(9));
            }
            attacheDir.mkdir();

            // Ytt@C???ieLXg`?j
            String dirPath = attacheDir.getPath();
            String textFilePath = dirPath + "/results.txt";
            String textZipPath = dirPath + "/results.zip";
            File textFile = new File(textFilePath);
            textFile.createNewFile();
            createTextFile(f2, textFile);
            FileUtil.makeZip(textZipPath, textFilePath);

            // T}??
            String summaryFilePath = dirPath + "/summary.html";
            String summaryZipPath = dirPath + "/summary.zip";
            File summaryFile = new File(summaryFilePath);
            summaryFile.createNewFile();
            createSummary(f2, summaryFile);
            FileUtil.makeZip(summaryZipPath, summaryFilePath);
            info.setFiles(new File[] { new File(summaryZipPath), new File(textZipPath) });

            // ??[?M
            SendMail.send(info);
        }

        // ?Zbg
        jobMgr.setResult(this.jobId, resultFilePath);

        // wWu?"Completed"
        jobMgr.setCompleted(this.jobId);

        // NGt@C?t@C??
        f1.delete();
        f2.delete();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (attacheDir != null && attacheDir.isDirectory()) {
            try {
                FileUtils.forceDelete(attacheDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.websqrd.catbot.setting.CatbotSettings.java

public static boolean deleteRepo(String id) {
    String repoFilename = "repository_" + id + ".xml";
    String repoConfigFileDir = getKey(repoFilename);
    File frepo = new File(repoConfigFileDir);
    if (frepo.exists()) {
        try {/*from   ww w  .j  a  v  a  2  s .  c o  m*/
            FileUtils.forceDelete(frepo);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return true;
    } else {
        return false;
    }
}

From source file:com.wavemaker.common.util.IOUtilsTest.java

public void testDeleteOnExitDNE() throws Exception {

    File tempDir = IOUtils.createTempDirectory("testDeleteOnExit", "tmp");
    assertTrue(tempDir.exists());//from  www .j  a  v a  2s . com
    FileUtils.forceDelete(tempDir);
    IOUtils.deleteFileOnShutdown(tempDir);

    // and now, hopefully, we won't see that file ever
}

From source file:com.agiletec.plugins.jpavatar.aps.system.services.avatar.AvatarManager.java

@Override
@AfterReturning(pointcut = "execution(* com.agiletec.aps.system.services.user.IUserManager.removeUser(..)) && args(key)")
public void removeAvatar(Object key) throws ApsSystemException {
    String username = null;//w  w  w.  j  av a  2 s.c o  m
    try {
        if (key instanceof String) {
            username = key.toString();
        } else if (key instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) key;
            username = userDetails.getUsername();
        }
        username = username.toLowerCase();
        File fileToDelete = this.getAvatarResource(username);
        if (null != fileToDelete) {
            FileUtils.forceDelete(fileToDelete);
        }
    } catch (Throwable t) {
        _logger.error("Error deleting avatar for user {}", username, t);
        throw new ApsSystemException("Error deleting avatar for user " + username, t);
    }
}

From source file:hu.bme.mit.sette.common.tasks.RunnerProjectGenerator.java

/**
 * Writes the runner project out.//  www  . j  a  v a  2s  .  co m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ParseException
 *             If the source code has parser errors.
 * @throws ParserConfigurationException
 *             If a DocumentBuilder cannot be created which satisfies the
 *             configuration requested or when it is not possible to create
 *             a Transformer instance.
 * @throws TransformerException
 *             If an unrecoverable error occurs during the course of the
 *             transformation.
 */
private void writeRunnerProject()
        throws IOException, ParseException, ParserConfigurationException, TransformerException {
    // TODO revise whole method
    // TODO now using JAPA, which does not support Java 7 -> maybe ANTLR
    // supports
    // better

    // create INFO file
    // TODO later maybe use an XML file!!!

    File infoFile = new File(getRunnerProjectSettings().getBaseDirectory(), "SETTE-INFO");

    StringBuilder infoFileData = new StringBuilder();
    infoFileData.append("Tool name: " + getTool().getName()).append('\n');
    infoFileData.append("Tool version: " + getTool().getVersion()).append('\n');
    infoFileData.append("Tool supported Java version: " + getTool().getSupportedJavaVersion()).append('\n');

    // TODO externalise somewhere the date format string
    String generatedAt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    infoFileData.append("Generated at: ").append(generatedAt).append('\n');

    String id = generatedAt + ' ' + getTool().getName() + " (" + getTool().getVersion() + ')';
    infoFileData.append("ID: ").append(id).append('\n');

    FileUtils.write(infoFile, infoFileData);

    // copy snippets
    FileUtils.copyDirectory(getSnippetProjectSettings().getSnippetSourceDirectory(),
            getRunnerProjectSettings().getSnippetSourceDirectory(), false);

    // remove SETTE annotations and imports from file
    Collection<File> filesWritten = FileUtils.listFiles(getRunnerProjectSettings().getSnippetSourceDirectory(),
            null, true);

    mainLoop: for (File file : filesWritten) {
        CompilationUnit compilationUnit = JavaParser.parse(file);

        // remove SETTE annotations
        if (compilationUnit.getTypes() != null) {
            for (TypeDeclaration type : compilationUnit.getTypes()) {
                if (type.getAnnotations() != null) {
                    for (Iterator<AnnotationExpr> iterator = type.getAnnotations().iterator(); iterator
                            .hasNext();) {
                        AnnotationExpr annot = iterator.next();

                        String annotStr = annot.toString().trim();

                        // TODO enhance
                        // if container and has req version and it is java 7
                        // and tool does not support -> remove
                        if (annotStr.startsWith("@SetteSnippetContainer")
                                && annotStr.contains("requiredJavaVersion")
                                && annotStr.contains("JavaVersion.JAVA_7")
                                && !getTool().supportsJavaVersion(JavaVersion.JAVA_7)) {
                            // TODO error handling
                            // remove file
                            System.err.println("Skipping file: " + file + " (required Java version: "
                                    + JavaVersion.JAVA_7 + ")");
                            FileUtils.forceDelete(file);
                            continue mainLoop;

                        }

                        // TODO enhance
                        if (annot.getName().toString().startsWith("Sette")) {
                            iterator.remove();
                        }
                    }
                }

                if (type.getMembers() != null) {
                    for (BodyDeclaration member : type.getMembers()) {
                        if (member.getAnnotations() != null) {
                            for (Iterator<AnnotationExpr> iterator = member.getAnnotations()
                                    .iterator(); iterator.hasNext();) {
                                AnnotationExpr annotation = iterator.next();

                                // TODO enhance
                                if (annotation.getName().toString().startsWith("Sette")) {
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }
            }
        }

        // remove SETTE imports
        if (compilationUnit.getImports() != null) {
            for (Iterator<ImportDeclaration> iterator = compilationUnit.getImports().iterator(); iterator
                    .hasNext();) {
                ImportDeclaration importDeclaration = iterator.next();

                // TODO enhance
                String p1 = "hu.bme.mit.sette.annotations";
                String p2 = "hu.bme.mit.sette.snippets.inputs";
                // TODO enhance
                String p3 = "catg.CATG";
                String p4 = "hu.bme.mit.sette.common.snippets.JavaVersion";

                if (importDeclaration.getName().toString().equals(p3)) {
                    // keep CATG
                } else if (importDeclaration.getName().toString().equals(p4)) {
                    iterator.remove();
                } else if (importDeclaration.getName().toString().startsWith(p1)) {
                    iterator.remove();
                } else if (importDeclaration.getName().toString().startsWith(p2)) {
                    iterator.remove();
                }
            }
        }

        // save edited source code
        FileUtils.write(file, compilationUnit.toString());
    }

    // copy libraries
    if (getSnippetProjectSettings().getLibraryDirectory().exists()) {
        FileUtils.copyDirectory(getSnippetProjectSettings().getLibraryDirectory(),
                getRunnerProjectSettings().getSnippetLibraryDirectory(), false);
    }

    // create project
    this.eclipseProject.save(getRunnerProjectSettings().getBaseDirectory());
}

From source file:net.nicholaswilliams.java.licensing.TestFileLicenseProvider.java

@Test
public void testGetLicenseData05() throws IOException {
    File temp = new File("testGetLicenseData05.lic");
    FileUtils.writeByteArrayToFile(temp, Base64.encodeBase64("another get 05".getBytes()));

    this.provider = EasyMock.createMockBuilder(FileLicenseProvider.class).addMockedMethod("getLicenseFile")
            .createStrictMock();/*w w  w.  j a  v a 2 s.  co m*/

    EasyMock.expect(this.provider.getLicenseFile("test05")).andReturn(new File("testGetLicenseData05.lic"));
    EasyMock.replay(this.provider);

    this.provider.setBase64Encoded(true);
    byte[] data = this.provider.getLicenseData("test05");

    assertNotNull("The data should not be null.", data);
    assertEquals("The data is not correct.", "another get 05", new String(data));

    FileUtils.forceDelete(temp);
}

From source file:models.utils.FileIoUtils.java

/**
 * This will delete all files and folder under the path. Very careful
 * 20130918//from  ww  w  . ja v  a2 s . com
 * 
 * SAFE GUARD: only with adhoc logs
 * 
 * @param folderName
 * @return
 */
public static boolean deleteAllFileAndDirInFolder(String folderName) {

    boolean success = true;

    // safeguard:
    if (!(folderName.contains("adhoc") || folderName.contains("logs"))) {
        models.utils.LogUtils.printLogError(
                "Looks like this folder is not logs folder in deleteAllFileAndDirInFolder(). Safeguard activated. "
                        + "NO OPS on this case. Return. ForderName:" + folderName);
        return success;
    }

    try {

        VirtualFile virtualDir = VirtualFile.fromRelativePath(folderName);
        List<VirtualFile> virtualFileList = virtualDir.list();

        if (virtualFileList == null) {
            models.utils.LogUtils.printLogError(
                    "virtualFileList is NULL! in getFileNamesInFolder()" + DateUtils.getNowDateTimeStrSdsm());
        }

        models.utils.LogUtils.printLogNormal(
                "Delete: Under folder: " + folderName + ",  File/dir count is " + virtualFileList.size());

        for (int i = 0; i < virtualFileList.size(); i++) {

            if (virtualFileList.get(i).getRealFile().isFile()) {
                String fileName = virtualFileList.get(i).getName();

                if ((!fileName.equalsIgnoreCase(VarUtils.FILE_NAME_APP_LOG_EMPTY))) {

                    if (VarUtils.IN_DETAIL_DEBUG) {
                        models.utils.LogUtils.printLogNormal("File " + fileName);
                    }

                    FileUtils.forceDelete(virtualFileList.get(i).getRealFile());
                }
            } else if (virtualFileList.get(i).getRealFile().isDirectory()) {
                models.utils.LogUtils.printLogNormal("Directory " + virtualFileList.get(i).getName());

                FileUtils.deleteDirectory(virtualFileList.get(i).getRealFile());
            }
        } // end for

    } catch (Throwable t) {
        t.printStackTrace();
        success = false;
    }

    return success;
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpDir = new File("tmpDir");
    tmpDir.mkdir();/*from  w w  w.j av a 2 s  . co  m*/
    try {
        String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "extract", "-a",
                "RandomLSB", "-sf", "" + carrier.toPath(), "-xd", "" + tmpDir.toPath() };
        Process process = Runtime.getRuntime().exec(args);
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        byte b[] = new byte[inputStream.available()];
        inputStream.read(b, 0, b.length);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String originalCarrierPath = "";
    if (tmpDir.listFiles().length == 1) {
        File tmpMessage = tmpDir.listFiles()[0];
        byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpMessage);
        PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
        RestoredFile message = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
        message.originalFilePath = payloadSegment.getPayloadPath();
        originalCarrierPath = payloadSegment.getCarrierPath();
        FileUtils.writeByteArrayToFile(message, payloadSegment.getPayloadBytes());
        message.validateChecksum(payloadSegment.getPayloadChecksum());
        message.restorationNote = "Payload can be restored correctly.";
        message.wasPayload = true;
        restoredFiles.add(message);
    }
    FileUtils.forceDelete(tmpDir);
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    FileUtils.copyFile(carrier, copiedCarrier);
    copiedCarrier.wasCarrier = true;
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    copiedCarrier.originalFilePath = originalCarrierPath;
    restoredFiles.add(copiedCarrier); // The carrier can not be restored;
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectExportPanel.java

/**
 * Copy, if exists, curation documents to a folder that will be exported as Zip file
 *
 * @param aProject//from w w w  .j a  v  a2 s. co  m
 *            The {@link Project}
 * @param aCurationDocumentExist
 *            Check if Curation document exists
 * @param aCopyDir
 *            The folder where curated documents are copied to be exported as Zip File
 */
private void exportCuratedDocuments(ProjectExportModel aModel, File aCopyDir)
        throws FileNotFoundException, UIMAException, IOException, ClassNotFoundException {
    // Get all the source documents from the project
    List<de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument> documents = repository
            .listSourceDocuments(aModel.project);

    // Determine which format to use for export.
    Class<?> writer;
    if (FORMAT_AUTO.equals(aModel.format)) {
        writer = WebannoCustomTsvWriter.class;
    } else {
        writer = repository.getWritableFormats().get(repository.getWritableFormatId(aModel.format));
        if (writer == null) {
            writer = WebannoCustomTsvWriter.class;
        }
    }

    int initProgress = progress - 1;
    int i = 1;
    for (de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument sourceDocument : documents) {
        File curationCasDir = new File(aCopyDir + CURATION_AS_SERIALISED_CAS + sourceDocument.getName());
        FileUtils.forceMkdir(curationCasDir);

        File curationDir = new File(aCopyDir + CURATION_FOLDER + sourceDocument.getName());
        FileUtils.forceMkdir(curationDir);

        // If the curation document is exist (either finished or in progress
        if (sourceDocument.getState().equals(SourceDocumentState.CURATION_FINISHED)
                || sourceDocument.getState().equals(SourceDocumentState.CURATION_IN_PROGRESS)) {
            File curationCasFile = repository.getCasFile(sourceDocument, CURATION_USER);
            if (curationCasFile.exists()) {
                // Copy CAS - this is used when importing the project again
                FileUtils.copyFileToDirectory(curationCasFile, curationCasDir);

                // Copy secondary export format for convenience - not used during import
                File curationFile = repository.exportAnnotationDocument(sourceDocument, CURATION_USER, writer,
                        CURATION_USER, Mode.CURATION);
                FileUtils.copyFileToDirectory(curationFile, curationDir);
                FileUtils.forceDelete(curationFile);
            }
        }

        progress = initProgress + (int) Math.ceil(((double) i) / documents.size() * 10.0);
        i++;
    }
}