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:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void deleteObjectRollback(String[] backup, String bucket, String object) throws IOException {
    if (backup == null || backup[0] == null || bucket == null || object == null)
        return;/*from  w w  w.  ja va2 s . co  m*/
    File oldObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + object);
    File backupFile = new File(backup[0]);

    if (backupFile.exists()) {
        if (oldObjectFile.exists()) {
            FileUtils.forceDelete(oldObjectFile);
        }
        FileUtils.moveFile(backupFile, oldObjectFile);
    }
}

From source file:mx.itesm.imb.ImbOperationsImpl.java

/**
 * @see mx.itesm.imb.ImbCommands#generateEntitiesSchemas()
 *///from w  w  w .j  a va  2  s .  co  m
@SuppressWarnings("unchecked")
public void generateEntitiesSchemas() {
    String tns;
    int tnsIndex;
    File srcFile;
    String antPath;
    int processCode;
    Process process;
    File schemaFile;
    File schemasDir;
    String entityName;
    String packageName;
    File schemagenFile;
    int rootElementIndex;
    String rootElementName;
    List<String> enumNames;
    String schemagenContents;
    String schemaFileContents;
    List<String> outputContents;
    SortedSet<FileDetails> entries;
    List<String> typesSchemaContents;
    List<String> detailsSchemaContents;

    try {
        // Identify the classes that should generate schemas
        antPath = pathResolver.getRoot(Path.SRC_MAIN_JAVA) + File.separatorChar + "**" + File.separatorChar
                + "*_Roo_JavaBean.aj";
        entries = fileManager.findMatchingAntPath(antPath);

        // Clean directory where the schemas will be generated
        schemasDir = new File(pathResolver.getRoot(Path.SRC_MAIN_JAVA) + "/schema_temp");

        // Generate Java Beans for the identified schemas
        for (FileDetails file : entries) {
            srcFile = file.getFile();
            entityName = srcFile.getName().replace("_Roo_JavaBean.aj", "");
            outputContents = new ArrayList<String>();

            // Format file
            packageName = "";
            for (String line : (List<String>) FileUtils.readLines(srcFile)) {
                // Remove annotations
                if (!line.contains("@")) {
                    // Change form aspect to class declaration
                    if (line.startsWith("privileged")) {
                        outputContents.add("@javax.xml.bind.annotation.XmlRootElement(namespace =\"http://"
                                + packageName + "\")\n");
                        outputContents.add(line.replace("privileged", "public").replace("aspect", "class")
                                .replace("_Roo_JavaBean", ""));
                    } else {
                        // Remove aspect details
                        outputContents.add(line.replace(entityName + ".", ""));
                    }
                }

                if (line.startsWith("package")) {
                    packageName = line.replace("package", "").replace(";", "").trim() + ".imb";
                }
            }

            // Write file
            FileUtils.writeLines(new File(schemasDir, entityName + ".java"), outputContents);
            logger.log(Level.INFO, "Generating XML schema for " + srcFile);
        }

        // Copy enum types to avoid compilation errors
        antPath = pathResolver.getRoot(Path.SRC_MAIN_JAVA) + File.separatorChar + "**" + File.separatorChar
                + "*.java";
        entries = fileManager.findMatchingAntPath(antPath);
        enumNames = new ArrayList<String>();
        for (FileDetails file : entries) {
            if (FileUtils.readFileToString(file.getFile()).contains("enum")) {
                enumNames.add(file.getFile().getName().replace(".java", "").toLowerCase());
                FileUtils.copyFile(file.getFile(), new File(schemasDir, file.getFile().getName()));
            }
        }

        // Execute schemagen
        schemagenFile = new File(schemasDir, "build.xml");
        schemagenContents = FileUtils.readFileToString(ImbOperationsImpl.schemagenBuildFile);
        schemagenContents = schemagenContents.replace("${output.dir}", schemasDir.getAbsolutePath());
        schemagenContents = schemagenContents.replace("${src.dir}", schemasDir.getAbsolutePath());
        FileUtils.writeStringToFile(schemagenFile, schemagenContents);
        process = Runtime.getRuntime().exec("ant -buildfile " + schemagenFile.getAbsolutePath());
        processCode = process.waitFor();

        // Error while executing schemagen
        if (processCode != 0) {
            throw new RuntimeException();
        }

        // Merge schemas and clean up
        typesSchemaContents = FileUtils.readLines(new File(schemasDir, "schema1.xsd"));
        detailsSchemaContents = FileUtils.readLines(new File(schemasDir, "schema2.xsd"));
        outputContents = new ArrayList<String>(typesSchemaContents.size() + detailsSchemaContents.size());

        // Elements
        for (String line : typesSchemaContents) {
            if (!line.contains("<xs:import") && !line.contains("</xs:schema")) {
                if (line.contains("<xs:schema")) {
                    tnsIndex = line.indexOf("targetNamespace=") + "targetNamespace=".length() + 1;
                    tns = line.substring(tnsIndex, line.indexOf("\"", tnsIndex));
                    logger.log(Level.INFO, "index: " + tnsIndex + ", tns: " + tns);
                    outputContents.add(line.substring(0, line.length() - 1) + " xmlns:tns=\"" + tns + "\">");
                } else {
                    outputContents.add(line.replace("type=\"", "type=\"tns:"));
                }
            }
        }

        // Details
        for (String line : detailsSchemaContents) {
            if (!line.contains("<xs:import") && !line.contains("<?xml") && !line.contains("<xs:schema")) {
                if (line.contains("type=")) {
                    // References to other types in the same schema
                    if (!line.contains("type=\"xs:")) {
                        outputContents.add(line.replace("type=\"", "type=\"tns:"));
                    } else {
                        outputContents.add(line);
                    }
                } else {
                    outputContents.add(line);
                    // IMB Id
                    if (line.contains("<xs:sequence")) {
                        outputContents.add("<xs:element name=\"imbId\" type=\"xs:long\" minOccurs=\"0\"/>");
                    }
                }
            }
        }

        // Schema file
        schemaFile = new File(pathResolver.getRoot(Path.SRC_MAIN_RESOURCES), "/schema.xsd");
        FileUtils.writeLines(schemaFile, outputContents);

        // Root element
        schemaFileContents = FileUtils.readFileToString(schemaFile);
        rootElementIndex = schemaFileContents.indexOf("xs:element name=\"");
        rootElementName = schemaFileContents.substring(rootElementIndex + "xs:element name=\"".length(),
                schemaFileContents.indexOf("\"", rootElementIndex + "xs:element name=\"".length() + 1));
        schemaFileContents = schemaFileContents.replace("type=\"tns:" + rootElementName + "\"/>", ">");
        schemaFileContents = schemaFileContents.replace("<xs:complexType name=\"" + rootElementName + "\">",
                "<xs:complexType>");
        schemaFileContents = schemaFileContents.replace("</xs:complexType>", "</xs:complexType></xs:element>");
        FileUtils.writeStringToFile(schemaFile, schemaFileContents);

        FileUtils.forceDelete(schemasDir);
        logger.log(Level.INFO, "XML schemas correctly generated");
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while generating entities schemas: " + e.getMessage(), e);
    }
}

From source file:com.datasalt.pangool.solr.SolrRecordWriter.java

@Override
public void close(TaskAttemptContext context) throws IOException, InterruptedException {
    if (context != null) {
        heartBeater.setProgress(context);
    }//from   w  w  w . j  ava  2s.  c o m
    try {
        if (batch.size() > 0) {
            batchWriter.queueBatch(batch);
            batch.clear();
        }
        heartBeater.needHeartBeat();
        batchWriter.close(context, core);
        if (outputZipFile) {
            context.setStatus("Writing Zip");
            packZipFile(); // Written to the perm location
        } else {
            context.setStatus("Copying Index");
            fs.completeLocalOutput(perm, local); // copy to dfs
        }
    } catch (Exception e) {
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new IOException(e);
    } finally {
        heartBeater.cancelHeartBeat();
        File tempFile = new File(local.toString());
        if (tempFile.exists()) {
            FileUtils.forceDelete(new File(local.toString()));
        }
    }

    context.setStatus("Done");
}

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

public void confirm(String[] backup) throws IOException {
    if (backup == null || backup[0] == null)
        return;//from  w w  w .  j a v  a  2  s. co  m

    File backupFile = new File(backup[0]);
    if (backupFile.exists()) {
        FileUtils.forceDelete(backupFile);
    }
}

From source file:com.alibaba.otter.shared.common.utils.NioUtils.java

/**
 * ??jvm//from w w  w. j  a  v a 2 s.  c om
 * 
 * @param dest
 * @param retryTimes
 */
public static boolean delete(File dest, final int retryTimes) {
    if (dest == null) {
        return false;
    }

    if (false == dest.exists()) {
        return true;
    }

    int totalRetry = retryTimes;
    if (retryTimes < 1) {
        totalRetry = 1;
    }

    int retry = 0;
    while (retry++ < totalRetry) {
        try {
            FileUtils.forceDelete(dest);
            return true;
        } catch (FileNotFoundException ex) {
            return true;
        } catch (Exception ex) {
            // 
            int wait = (int) Math.pow(retry, retry) * timeWait;
            wait = (wait < timeWait) ? timeWait : wait;
            if (retry == totalRetry) {
                try {
                    FileUtils.forceDeleteOnExit(dest);
                    return false;
                } catch (Exception e) {
                    // ignore
                }
            } else {
                // 
                logger.warn(String.format("[%s] delete() - retry %s failed : wait [%s] ms , caused by %s",
                        dest.getAbsolutePath(), retry, wait, ex.getMessage()));
                try {
                    Thread.sleep(wait);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }
    }

    return false;
}

From source file:com.silverpeas.util.FileUtil.java

/**
 * Moves the specified source file to the specified destination. If the destination exists, it is
 * then replaced by the source; if the destination is a directory, then it is deleted with all of
 * its contain.//from   ww w  .  java  2s  .  c  o m
 *
 * @param source the file to move.
 * @param destination the destination file of the move.
 * @throws IOException if the source or the destination is invalid or if an error occurs while
 * moving the file.
 */
public static void moveFile(File source, File destination) throws IOException {
    if (destination.exists()) {
        FileUtils.forceDelete(destination);
    }
    FileUtils.moveFile(source, destination);
}

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

@Test
@Category(UnitTest.class)
public void TestCreateNativeRequestOsmZipAndOsm() throws Exception {
    String input = "osm.zip";
    String jobId = "test-id-123";
    String wkdirpath = homeFolder + "/upload/" + jobId;
    File workingDir = new File(wkdirpath);
    FileUtils.forceMkdir(workingDir);/*w w  w  . java  2 s .  c  om*/
    org.junit.Assert.assertTrue(workingDir.exists());

    File srcFile = new File(homeFolder + "/test-files/service/FileUploadResourceTest/" + input);
    File destFile = new File(wkdirpath + "/" + input);
    FileUtils.copyFile(srcFile, destFile);
    org.junit.Assert.assertTrue(destFile.exists());

    FileUploadResource res = new FileUploadResource();

    // Let's test zip
    JSONArray results = new JSONArray();
    JSONObject zipStat = new JSONObject();
    List<String> inputsList = new ArrayList<String>();
    inputsList.add(input);

    res._buildNativeRequest(jobId, "osm", "zip", input, results, zipStat);

    int shpCnt = 0;
    int osmCnt = 0;
    int fgdbCnt = 0;

    int zipCnt = 0;
    int shpZipCnt = 0;
    int osmZipCnt = 0;
    int fgdbZipCnt = 0;
    List<String> zipList = new ArrayList<String>();

    shpZipCnt += (Integer) zipStat.get("shpzipcnt");
    fgdbZipCnt += (Integer) zipStat.get("fgdbzipcnt");
    osmZipCnt += (Integer) zipStat.get("osmzipcnt");

    zipList.add("osm");
    zipCnt++;

    // osm
    input = "osm1.osm";
    srcFile = new File(homeFolder + "/test-files/service/FileUploadResourceTest/" + input);
    destFile = new File(wkdirpath + "/" + input);
    FileUtils.copyFile(srcFile, destFile);
    org.junit.Assert.assertTrue(destFile.exists());

    inputsList.add(input);

    res._buildNativeRequest(jobId, "osm1", "osm", input, results, zipStat);

    shpCnt += (Integer) zipStat.get("shpcnt");
    fgdbCnt += (Integer) zipStat.get("fgdbcnt");
    osmCnt += (Integer) zipStat.get("osmcnt");

    // Test zip containing fgdb + shp
    JSONArray resA = res._createNativeRequest(results, zipCnt, shpZipCnt, fgdbZipCnt, osmZipCnt, shpCnt,
            fgdbCnt, osmCnt, zipList, "TDSv61.js", jobId, "osm", inputsList);

    JSONObject req = (JSONObject) resA.get(0);
    JSONArray params = (JSONArray) req.get("params");

    int nP = 0;

    for (Object o : params) {
        JSONObject oJ = (JSONObject) o;

        if (oJ.get("INPUT") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT").toString()
                    .equals("\"osm/DcGisRoads.osm\" \"osm/DcTigerRoads.osm\" \"osm1.osm\" "));
            nP++;
        }

        if (oJ.get("INPUT_PATH") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_PATH").toString().equals("upload/test-id-123"));
            nP++;
        }

        if (oJ.get("INPUT_TYPE") != null) {
            org.junit.Assert.assertTrue(oJ.get("INPUT_TYPE").toString().equals("OSM"));
            nP++;
        }

        if (oJ.get("UNZIP_LIST") != null) {
            org.junit.Assert.assertTrue(oJ.get("UNZIP_LIST").toString().equals("osm"));
            nP++;
        }
    }
    org.junit.Assert.assertTrue(nP == 4);
    FileUtils.forceDelete(workingDir);
}

From source file:com.ibm.soatf.component.soap.SOAPComponent.java

private void generateEnvelope() throws SoapComponentException {
    try {//  w  w w . j  av a 2s  .  c  o  m
        final String filename = new StringBuilder(serviceName).append(NAME_DELIMITER).append(operationName)
                .append(NAME_DELIMITER).append(REQUEST_FILE_SUFFIX).toString();
        final File file = new File(workingDir, filename);

        String delimiter = "";
        if (!serviceURI.startsWith("/")) {
            delimiter = "/";
        }
        final ManagedServer managedServer = osbCluster.getManagedServer().get(0);
        final URL url = new URL(DEFAULT_PROTO, managedServer.getHostName(), managedServer.getPort(),
                delimiter + serviceURI + WSDL_SUFFIX);
        ProgressMonitor.init(6, "Reading WSDL from the server..."); //there are 2 ProgressMonitor events inside SoapLegacyFacade
        final SoapLegacyFacade facade = new SoapLegacyFacade(url);
        final Binding binding = findBindingForOperationName(facade, operationName);
        final BindingOperation operation = binding.getBindingOperation(operationName, null, null);
        ProgressMonitor.increment("Building envelope...");
        String envelope = facade.buildSoapMessageFromInput(binding, operation, SoapContext.DEFAULT);
        ProgressMonitor.increment("Setting custom values...");
        for (Entry<String, SOAPConfig.EnvelopeConfig.Element> xpath : customValues.entrySet()) {
            //Element e = XmlUtils.getElementForXPath(envelope, xpath.getKey());
            envelope = XmlUtils.setTextToElement(envelope, transformXPath(xpath.getKey()),
                    xpath.getValue().getElementValue());
            List<SOAPConfig.EnvelopeConfig.Element.Attribute> attrs = xpath.getValue().getAttribute();
            if (attrs != null) {
                for (SOAPConfig.EnvelopeConfig.Element.Attribute attr : attrs) {
                    envelope = XmlUtils.setTextToElementAttribute(envelope, transformXPath(xpath.getKey()),
                            attr.getAttrName(), attr.getAttrValue());
                }
            }
        }

        String msg = "Successfuly generated request envelope for operation: " + operationName;
        cor.addMsg(msg);
        ProgressMonitor.increment("Writing file...");
        if (file.exists()) {
            FileUtils.forceDelete(file);
        }

        FileUtils.writeStringToFile(file, envelope);
        msg = "Request envelope for operation: " + operationName + " was stored in [FILE: %s]";
        logger.debug(String.format(msg, file.getAbsolutePath()));
        cor.addMsg(msg, "<a href='file://" + file.getAbsolutePath() + "'>" + file.getAbsolutePath() + "</a>",
                FileSystem.getRelativePath(file));
        cor.markSuccessful();
    } catch (IOException | WSDLException ex) {
        throw new SoapComponentException(ex);
    }
}

From source file:eu.asterics.ape.packaging.Packager.java

/**
 * Does all steps of a build/make process. Fetching target dir properties, creating project/build directories, copying all URIs.
 * @throws IOException/* w  w w  .ja  va 2 s  .com*/
 * @throws URISyntaxException
 * @throws ParseException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 * @throws BundleManagementException
 * @throws APEConfigurationException 
 */
public void makeAll() throws IOException, URISyntaxException, ParseException, ParserConfigurationException,
        SAXException, TransformerException, BundleManagementException, APEConfigurationException {
    try {
        Notifier.debug("Deleting APE.buildDir before copying: " + buildDir, null);
        FileUtils.forceDelete(buildDir);
    } catch (IOException e) {
        Notifier.warning("Could not delete APE.buildDir: " + buildDir, e);
    }

    copyFiles();
    Notifier.info("FINISHED copying ARE: Go to the following folder and try it out: " + buildMergedDir);
}

From source file:com.spectralogic.ds3cli.certification.Certification_Test.java

private static boolean testBulkPutAndBulkGetPerformance(final String testDescription, final Integer numFiles,
        final Long fileSize) throws Exception {
    final String bucketName = "test_bulk_performance_" + testDescription;

    boolean success = false;
    try {/*from   w w  w  .j a  va  2 s .  co m*/
        // Start BULK_PUT
        OUT.insertLog("Create bucket.");
        final String createBucketCmd = "--http -c put_bucket -b " + bucketName;
        final CommandResponse createBucketResponse = Util.command(client, createBucketCmd);
        OUT.insertCommand(createBucketCmd, createBucketResponse.getMessage());
        assertThat(createBucketResponse.getReturnCode(), is(0));

        OUT.insertLog("List bucket.");
        final String listBucketCmd = "--http -c get_bucket -b " + bucketName;
        final CommandResponse getBucketResponse = Util.command(client, listBucketCmd);
        OUT.insertCommand(listBucketCmd, getBucketResponse.getMessage());
        assertThat(getBucketResponse.getReturnCode(), is(0));

        // Create temp files for BULK_PUT
        OUT.insertLog("Creating ");
        final Path bulkPutLocalTempDir = CertificationUtil.createTempFiles(bucketName, numFiles, fileSize);

        OUT.insertLog("Bulk PUT from bucket " + bucketName);
        final long startPutTime = getCurrentTime();
        final String putBulkCmd = "--http -c put_bulk -b " + bucketName + " -d "
                + bulkPutLocalTempDir.toString();
        final CommandResponse putBulkResponse = Util.command(client, putBulkCmd);
        OUT.insertCommand(putBulkCmd, putBulkResponse.getMessage());
        final long endPutTime = getCurrentTime();
        assertThat(putBulkResponse.getReturnCode(), is(0));
        OUT.insertPerformanceMetrics(startPutTime, endPutTime, numFiles * fileSize, true);

        final CommandResponse getBucketResponseAfterBulkPut = Util.command(client, listBucketCmd);
        OUT.insertCommand(listBucketCmd, getBucketResponseAfterBulkPut.getMessage());
        assertThat(getBucketResponseAfterBulkPut.getReturnCode(), is(0));

        // Free up disk space
        FileUtils.forceDelete(bulkPutLocalTempDir.toFile());

        // Start BULK_GET from the same bucket that we just did the BULK_PUT to, with a new local directory
        final Path bulkGetLocalTempDir = Files.createTempDirectory(bucketName);

        final long startGetTime = getCurrentTime();
        OUT.insertLog("Bulk GET from bucket " + bucketName);
        final String getBulkCmd = "--http -c get_bulk -b " + bucketName + " -d "
                + bulkGetLocalTempDir.toString() + " -nt 3";
        final CommandResponse getBulkResponse = Util.command(client, getBulkCmd);
        OUT.insertCommand(getBulkCmd, getBucketResponse.getMessage());
        final long endGetTime = getCurrentTime();
        OUT.insertPerformanceMetrics(startGetTime, endGetTime, numFiles * fileSize, true);
        assertThat(getBulkResponse.getReturnCode(), is(0));
        success = true;

        // Free up disk space
        FileUtils.forceDelete(bulkGetLocalTempDir.toFile());
    } finally {
        Util.deleteBucket(client, bucketName);
    }
    return success;
}