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:com.legstar.protobuf.cobol.ProtoCobol.java

/**
 * Starting from a proto file, two steps are needed to produce the file
 * descriptor:/*from  w w  w  . ja  v a  2  s . co m*/
 * <ul>
 * <li>Invoke the protoc compiler to produce a java class source code</li>
 * <li>Invoke the java compiler to turn the source to binary</li>
 * </ul>
 * 
 * @param protoFile
 * @param protoPath
 * @param timeout
 * @return
 * @throws ProtoCobolException
 */
public FileDescriptor toFileDescriptor(File protoFile, File protoPath, int timeout) throws ProtoCobolException {
    try {
        File javaOut = new File(FileUtils.getTempDirectory(), "ProtoCobol" + System.currentTimeMillis());
        javaOut.mkdirs();
        File javaSourceFile = runProtoJava(protoFile,
                (protoPath == null) ? protoFile.getParentFile() : protoPath, javaOut, timeout);
        Class<?> clazz = runJavaCompiler(javaOut, javaSourceFile);
        FileDescriptor fileDescriptor = toFileDescriptor(clazz);
        FileUtils.forceDelete(javaOut);
        return fileDescriptor;
    } catch (IOException e) {
        throw new ProtoCobolException(e);
    }
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void renameObject(String[] backup, String bucket, String oldName, String newName) throws IOException {
    if (backup == null || bucket == null || oldName == null || newName == null)
        return;/*from  w  w  w .j a v a 2  s . c o m*/

    File oldObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + oldName);
    File newObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + newName);

    if (oldObjectFile.exists()) {
        if (newObjectFile.exists()) {
            backup[0] = new String(
                    rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + newName + ".backup");
            File backupFile = new File(backup[0]);
            if (backupFile.exists()) {
                FileUtils.forceDelete(backupFile);
            }
            FileUtils.moveFile(newObjectFile, backupFile);
        }
        FileUtils.moveFile(oldObjectFile, newObjectFile);
    }
}

From source file:com.wavemaker.commons.util.IOUtils.java

/**
 * Delete a directory or file; if a directory, delete its children recursively.
 *
 * @param dir/* w ww  .  j  av a  2s  .  co m*/
 * @throws IOException
 */
public static void deleteRecursive(File dir) throws IOException {
    FileUtils.forceDelete(dir);
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * //w ww.  jav  a2 s.  c o  m
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:com.freedomotic.environment.impl.EnvironmentRepositoryImpl.java

private boolean removeEnvironmentFile(File environmentFile) {
    if (environmentFile == null) {
        LOG.warn("No file defined in this environment, so no deletion occurs.");
        return false;
    }/* w w  w.  ja v  a2  s  . c  o  m*/

    if (environmentFile.exists()) {
        try {
            FileUtils.forceDelete(environmentFile);
            return true;
        } catch (IOException e) {
            LOG.warn("Error while removing file \"{}\", please try manually.",
                    environmentFile.getAbsolutePath(), Freedomotic.getStackTraceInfo(e));
            return false;
        }
    } else {
        LOG.warn("File \"{}\" does not exist", environmentFile.getAbsolutePath());
        return false;
    }
}

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

/**
 * Delete a directory or file; if a directory, delete its children recursively.
 * //from w ww.  j  a v  a 2  s .  c  o m
 * @param dir
 * @throws IOException
 */
public static void deleteRecursive(File dir) throws IOException {

    FileUtils.forceDelete(dir);
}

From source file:com.taobao.android.builder.tools.cache.FileCacheCenter.java

/**
 * Query the file, if the local file does not exist, try to read the cache from the cloud
 *
 * @param type//from   w ww  .j a  v a 2s. c  o m
 * @param key
 * @param folder
 * @return
 * @throws FileCacheException
 */
public static File queryFile(String type, String key, boolean folder, boolean remote)
        throws FileCacheException {

    if (!BUILD_CACHE_ENABLED) {
        return null;
    }

    File localCacheFile = localCache.getLocalCacheFile(type, key);
    if (localCacheFile.exists()) {

        if (folder != localCacheFile.isDirectory()) {
            try {
                FileUtils.forceDelete(localCacheFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            throw new FileCacheException("local dir is folder " + folder);
        }

        logger.log(type + "." + key + " query local cache  " + localCacheFile.getAbsolutePath() + " success");
        return localCacheFile;
    } else {
        logger.log(type + "." + key + " miss local cache  " + localCacheFile.getAbsolutePath());
    }

    if (null == networkCache || !remote) {
        return localCacheFile;
    }

    try {

        boolean success = networkCache.fetchFile(type, key, localCacheFile, folder);

        logger.log(type + "." + key + " fetch remote cache  " + localCacheFile.getAbsolutePath() + success);

        if (success) {
            return localCacheFile;
        }

    } catch (Throwable e) {

        logger.log(
                type + "." + key + " fetch remote cache  " + localCacheFile.getAbsolutePath() + " exception");
        e.printStackTrace();
    }

    logger.log(type + "." + key + " get cache file failed  " + localCacheFile.getAbsolutePath());
    try {
        FileUtils.forceDelete(localCacheFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return localCacheFile;

}

From source file:hoot.services.controllers.ingest.BasemapResource.java

protected void _deleteBaseMap(String bmName) throws Exception {
    //List<String> delList = new ArrayList<String>();
    String controlFolder = _ingestStagingPath + "/BASEMAP/";
    String tileDirectoryPath = _tileServerPath + "/BASEMAP/" + bmName;

    File tileDir = new File(tileDirectoryPath);
    if (tileDir.exists()) {
        FileUtils.forceDelete(tileDir);
    }//from  w w w .ja  va2  s  .  c  o m

    File dir = new File(controlFolder);
    FileFilter fileFilter = new WildcardFileFilter(bmName + ".*");
    File[] files = dir.listFiles(fileFilter);
    for (int i = 0; i < files.length; i++) {
        File curFile = files[i];
        FileUtils.forceDelete(curFile);
        //delList.add(curFile.getPath());
    }

}

From source file:architecture.ee.web.attachment.DefaultImageManager.java

private void deleteImageFileCache(Image image) {
    Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
            FileFilterUtils.prefixFileFilter(String.valueOf(image.getImageId())),
            FileFilterUtils.suffixFileFilter(".bin"));
    for (File file : files) {
        log.debug(file.getPath() + ":" + file.isFile());
        try {/*from  w ww  . j  a va  2s.com*/
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            log.error(e);
        }
    }

}

From source file:com.cws.esolutions.security.processors.impl.CertificateRequestProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.ICertificateRequestProcessor#generateCertificateRequest(com.cws.esolutions.security.processors.dto.CertificateRequest)
 *//*  w ww  . j a  v  a2 s  . com*/
public CertificateResponse generateCertificateRequest(final CertificateRequest request)
        throws CertificateRequestException {
    final String methodName = ICertificateRequestProcessor.CNAME
            + "#generateCertificateRequest(final CertificateRequest request) throws CertificateRequestException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("CertificateRequest: {}", request);
    }

    CertificateResponse response = new CertificateResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount authUser = request.getUserAccount();
    final List<String> subjectData = new ArrayList<String>(Arrays.asList(request.getCommonName(),
            request.getOrganizationalUnit(), request.getOrganizationName(), request.getLocalityName(),
            request.getStateName(), request.getCountryName(), request.getContactEmail()));
    final File rootDirectory = FileUtils.getFile(certConfig.getRootDirectory());
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + request.getCommonName());
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + request.getCommonName());
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + request.getCommonName());
    final File storeDirectory = FileUtils
            .getFile(certConfig.getStoreDirectory() + "/" + request.getCommonName());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("authUser: {}", authUser);
        DEBUGGER.debug("subjectData: {}", subjectData);
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
    }

    try {
        if (!(rootDirectory.canWrite())) {
            if (!(rootDirectory.mkdirs())) {
                throw new IOException(
                        "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new FileNotFoundException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new FileNotFoundException("Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(privateKeyDirectory.canWrite())) {
            if (!(privateKeyDirectory.mkdirs())) {
                throw new IOException(
                        "Private directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(publicKeyDirectory.canWrite())) {
            if (!(publicKeyDirectory.mkdirs())) {
                throw new IOException(
                        "Private directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(csrDirectory.canWrite())) {
            if (!(csrDirectory.mkdirs())) {
                throw new IOException(
                        "CSR directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        if (!(storeDirectory.canWrite())) {
            if (!(storeDirectory.mkdirs())) {
                throw new IOException(
                        "Keystore directory either does not exist or cannot be written to. Cannot continue.");
            }
        }

        // check if an there's an existing entry, if so just return it
        if (FileUtils
                .getFile(csrDirectory + "/" + request.getCommonName() + SecurityServiceConstants.CSR_FILE_EXT)
                .exists()) {
            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setCsrFile(FileUtils.getFile(
                    csrDirectory + "/" + request.getCommonName() + SecurityServiceConstants.CSR_FILE_EXT));

            return response;
        }

        File csrFile = processor.createCertificateRequest(subjectData, request.getStorePassword(),
                request.getValidityPeriod(), request.getKeySize());

        if (DEBUG) {
            DEBUGGER.debug("File: {}", csrFile);
        }

        if (csrFile != null) {
            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setCsrFile(csrFile);
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new CertificateRequestException(iox.getMessage(), iox);
    } catch (CertificateManagementException cmx) {
        // clean up
        try {
            FileUtils.forceDelete(privateKeyDirectory);
            FileUtils.forceDelete(publicKeyDirectory);
            FileUtils.forceDelete(csrDirectory);
            FileUtils.forceDelete(storeDirectory);
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }

        ERROR_RECORDER.error(cmx.getMessage(), cmx);

        throw new CertificateRequestException(cmx.getMessage(), cmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.GENERATECERT);
            auditEntry.setUserAccount(authUser);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}