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.nokia.helium.jpa.ORMEntityManager.java

/**  
 * Constructor./*from  w  w w .j a v  a2 s .c o m*/
 * @param urlPath path for which entity manager to be
 * created.
 */
@SuppressWarnings("unchecked")
public ORMEntityManager(String urlPath) throws Exception {
    String name = "metadata";
    Hashtable persistProperties = new Hashtable();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + urlPath);
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    File dbFile = new File(urlPath);
    commitCountObject = new ORMCommitCount();
    if (dbFile.exists()) {
        try {
            log.debug("checking db integrity for :" + urlPath);
            if (!checkDatabaseIntegrity(urlPath)) {
                log.debug("db integrity failed cleaning up old db");
                try {
                    log.debug("deleting the url path" + urlPath);
                    FileUtils.forceDelete(dbFile);
                    log.debug("successfully removed the urlpath" + urlPath);
                } catch (java.io.IOException iex) {
                    log.debug("deleting the db directory failed", iex);
                    throw new BuildException("failed deleting corrupted db", iex);
                }
            } else {
                log.debug("db exists and trying to create entity manager");
                EntityManagerFactory factory = Persistence.createEntityManagerFactory(name, persistProperties);
                entityManager = factory.createEntityManager();
                entityManager.getTransaction().begin();
                return;
            }
        } catch (Exception ex) {
            log.debug("Failed to open the database, might be corrupted, creating new db", ex);
            try {
                FileUtils.deleteDirectory(dbFile);
            } catch (java.io.IOException iex) {
                log.debug("deleting the db directory failed");
                throw iex;
            }
        }
    }
    log.debug("url path not exists" + urlPath + "creating it");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + urlPath + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    EntityManagerFactory factory = Persistence.createEntityManagerFactory(name, persistProperties);
    entityManager = factory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(new Version());
    entityManager.getTransaction().commit();
    entityManager.clear();
    entityManager.getTransaction().begin();
}

From source file:edu.lternet.pasta.auditmanager.AuditCleaner.java

/**
 * Removes any audit records XML file that is older than the specified 
 * time-to-live (ttl)./*from  w  ww  .  j  a  v a  2 s . c om*/
 * 
 * @param ttl
 *            The time-to-live value in milliseconds.
 */
public void doClean(Long ttl) {
    File tmpDir = new File(this.tmpDir);
    String[] ext = { "xml" };
    Long time = new Date().getTime();
    Long lastModified = null;

    Collection<File> files = FileUtils.listFiles(tmpDir, ext, false);

    for (File file : files) {
        if (file != null && file.exists()) {
            lastModified = file.lastModified();
            // Remove file if older than the ttl
            if (lastModified + ttl <= time) {
                try {
                    FileUtils.forceDelete(file);
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.linkedin.pinot.core.startree.TestStarTreeSegmentCreator.java

@AfterClass
public void afterClass() throws Exception {
    if (System.getProperty("startree.test.keep.dir") == null) {
        FileUtils.forceDelete(indexDir);
    }/*from   w  w  w . j av  a2 s.  c  o m*/
}

From source file:com.nokia.helium.metadata.tests.TestORMFMPPLoader.java

/**
 * Delete the database after test completion.
 * @throws IOException//from   ww  w  .j  a  va 2 s  . c  o  m
 */
@After
public void cleanupDatabase() throws IOException {
    FileUtils.forceDelete(database);
}

From source file:com.mindquarry.desktop.workspace.conflict.ObstructedConflict.java

@Override
public void beforeRemoteStatus() throws ClientException, IOException {
    File file = new File(status.getPath());
    switch (action) {
    case UNKNOWN:
        // client did not set a conflict resolution
        log.error("ObstructedConflict with no action set: " + status.getPath());
        //throw new CancelException("ObstructedConflict with no action set: " + status.getPath());
        break;//from   w  ww. j  av a2s  .c  o  m

    case RENAME:
        log.info("renaming " + file.getAbsolutePath() + " to " + newName);

        File destination = new File(file.getParentFile(), newName);
        FileHelper.renameTo(file, destination);

        client.add(destination.getPath(), true, true);

        // restore file or folder (updating to working copy base revision)
        client.update(status.getPath(), Revision.BASE, true);

        break;

    case REVERT:
        log.info("reverting obstructed file/folder: " + status.getPath());

        FileUtils.forceDelete(file);

        // restore file or folder (updating to working copy base revision)
        client.update(status.getPath(), Revision.BASE, true);

        break;
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPrivateKeyEncryption01() throws Throwable {
    File file = new File("testPrivateKeyEncryption01.key");

    if (file.exists())
        FileUtils.forceDelete(file);

    PrivateKey privateKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPrivate();/*from  ww  w  .j  a v a  2s.  co  m*/

    KeyFileUtilities.writeEncryptedPrivateKey(privateKey, file, "myTestPassword01".toCharArray());

    PrivateKey privateKey2 = KeyFileUtilities.readEncryptedPrivateKey(file, "myTestPassword01".toCharArray());

    assertNotNull("The key should not be null.", privateKey2);
    assertFalse("The objects should not be the same.", privateKey == privateKey2);
    assertEquals("The keys should be the same.", privateKey, privateKey2);

    FileUtils.forceDelete(file);
}

From source file:edu.kit.trufflehog.model.configdata.FilterDataModelTest.java

/**
 * <p>//from   w w w. jav a  2  s.  co m
 *     Ends everything after the test
 * </p>
 *
 * @throws Exception Passes any errors that occurred during the test on
 */
@After
public void tearDown() throws Exception {
    filterDataModel.close();
    if (databaseFile.exists()) {
        FileUtils.forceDelete(databaseFile);
    }
}

From source file:com.baasbox.configuration.IosCertificateHandler.java

@Override
public void change(Object iCurrentValue, Object iNewValue) {

    if (iNewValue == null) {
        return;/*  ww w  .java 2 s  .c  o  m*/
    }
    String folder = BBConfiguration.getPushCertificateFolder();
    File f = new File(folder);
    if (!f.exists()) {
        f.mkdirs();
    }
    ConfigurationFileContainer newValue = null;
    ConfigurationFileContainer currentValue = null;
    if (iNewValue != null && iNewValue instanceof ConfigurationFileContainer) {

        newValue = (ConfigurationFileContainer) iNewValue;
    }
    if (iCurrentValue != null) {
        if (iCurrentValue instanceof String) {
            try {
                currentValue = new ObjectMapper().readValue(iCurrentValue.toString(),
                        ConfigurationFileContainer.class);
            } catch (Exception e) {
                if (BaasBoxLogger.isDebugEnabled())
                    BaasBoxLogger.debug("unable to convert value to ConfigurationFileContainer");
            }
        } else if (iCurrentValue instanceof ConfigurationFileContainer) {
            currentValue = (ConfigurationFileContainer) iCurrentValue;
        }
    }
    if (currentValue != null) {
        File oldFile = new File(folder + sep + currentValue.getName());
        if (oldFile.exists()) {
            try {
                FileUtils.forceDelete(oldFile);
            } catch (Exception e) {
                BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            }
        }
    }
    if (newValue != null) {
        File newFile = new File(folder + sep + newValue.getName());
        try {
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
        } catch (IOException ioe) {
            throw new RuntimeException("unable to create file:" + ExceptionUtils.getMessage(ioe));
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(newValue.getContent());
        try {
            FileUtils.copyInputStreamToFile(bais, newFile);
            bais.close();
        } catch (IOException ioe) {
            //TODO:more specific exception
            throw new RuntimeException(ExceptionUtils.getMessage(ioe));
        }

    } else {
        BaasBoxLogger.warn("Ios Certificate Handler invoked with wrong parameters");
        //TODO:throw an exception?
    }

}

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

public synchronized EntityManagerFactory create(File database) throws MetadataException {
    EntityManagerFactory factory;//from w w w.ja va  2s .c  o m
    String name = "metadata";
    Hashtable<String, String> persistProperties = new Hashtable<String, String>();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    // This swallow all the output log from derby.
    System.setProperty("derby.stream.error.field",
            "com.nokia.helium.metadata.DerbyFactoryManagerCreator.DEV_NULL");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database.getAbsolutePath());
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    if (database.exists()) {
        if (!checkDatabaseIntegrity(database)) {
            try {
                FileUtils.forceDelete(database);
            } catch (java.io.IOException iex) {
                throw new MetadataException("Failed deleting corrupted db: " + iex, iex);
            }
        } else {
            return Persistence.createEntityManagerFactory(name, persistProperties);
        }
    }
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    factory = Persistence.createEntityManagerFactory(name, persistProperties);
    EntityManager entityManager = factory.createEntityManager();
    // Pushing default data into the current schema
    try {
        entityManager.getTransaction().begin();
        // Version of the schema is pushed.
        entityManager.persist(new Version());
        // Default set of severity is pushed.
        for (SeverityEnum.Severity severity : SeverityEnum.Severity.values()) {
            Severity pData = new Severity();
            pData.setSeverity(severity.toString());
            entityManager.persist(pData);
        }
        entityManager.getTransaction().commit();
    } finally {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
            entityManager.clear();
        }
        entityManager.close();
    }
    return factory;
}

From source file:edu.ur.hibernate.file.db.HbFileServerDAOTest.java

/**
 * Setup for testing//from  w  w w  . j ava2 s  . c o  m
 * 
 * this deletes exiting test directories if they exist
 */
@BeforeMethod
public void cleanDirectory() {
    try {
        File f = new File(properties.getProperty("HbFileServerDAOTest.test_path"));
        if (f.exists()) {
            FileUtils.forceDelete(f);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}