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

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

Introduction

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

Prototype

public static void cleanDirectory(File directory) throws IOException 

Source Link

Document

Cleans a directory without deleting it.

Usage

From source file:org.opendaylight.controller.config.yang.logback.config.LogbackModuleWithInitialConfigurationTest.java

public ObjectName createBeans()
        throws JoranException, InstanceAlreadyExistsException, IOException, MalformedObjectNameException,
        InstanceNotFoundException, ValidationException, ConflictingVersionException {

    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(lc);/*from   w w w  .  j  a  v a 2 s  .c  o m*/
    configurator.doConfigure("src/test/resources/simple_config_logback.xml");
    File f = new File("target/it");
    if (f.exists())
        FileUtils.cleanDirectory(f);
    ch.qos.logback.classic.Logger logger = lc.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    ch.qos.logback.core.rolling.RollingFileAppender<ILoggingEvent> fileAppender = (ch.qos.logback.core.rolling.RollingFileAppender<ILoggingEvent>) logger
            .getAppender("VARLOGFILE");
    fileAppender.start();

    ch.qos.logback.core.ConsoleAppender<ILoggingEvent> consoleAppender = (ch.qos.logback.core.ConsoleAppender<ILoggingEvent>) logger
            .getAppender("STDOUT");
    consoleAppender.start();
    List<RollingFileAppenderTO> rollingAppenders = new ArrayList<>();
    RollingFileAppenderTO rollingApp = new RollingFileAppenderTO();
    rollingApp.setAppend(fileAppender.isAppend());
    PatternLayoutEncoder enc = (PatternLayoutEncoder) fileAppender.getEncoder();
    rollingApp.setEncoderPattern(enc.getPattern());
    rollingApp.setFileName(fileAppender.getFile());
    FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) fileAppender.getRollingPolicy();
    rollingApp.setRollingPolicyType("FixedWindowRollingPolicy");
    rollingApp.setMaxIndex(rollingPolicy.getMaxIndex());
    rollingApp.setMinIndex(rollingPolicy.getMinIndex());
    SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = (SizeBasedTriggeringPolicy<ILoggingEvent>) fileAppender
            .getTriggeringPolicy();
    rollingApp.setMaxFileSize(triggeringPolicy.getMaxFileSize());
    rollingApp.setName(fileAppender.getName());
    rollingApp.setFileNamePattern(rollingPolicy.getFileNamePattern());
    rollingAppenders.add(rollingApp);

    assertEquals(rollingApp.getFileName(), "target/osgi.log");
    assertEquals(rollingApp.getMaxFileSize(), "50MB");
    assertEquals(rollingApp.getName(), "VARLOGFILE");

    List<ConsoleAppenderTO> consoleAppenders = new ArrayList<>();
    ConsoleAppenderTO consoleApp = new ConsoleAppenderTO();
    enc = (PatternLayoutEncoder) consoleAppender.getEncoder();
    consoleApp.setEncoderPattern(enc.getPattern());
    consoleApp.setName(consoleAppender.getName());
    consoleApp.setThresholdFilter("ALL");
    consoleAppenders.add(consoleApp);

    List<FileAppenderTO> fileAppenders = new ArrayList<>();

    List<LoggerTO> loggersDTOs = new ArrayList<>();
    LoggerTO log = new LoggerTO();
    log.setAppenders(Arrays.asList(fileAppender.getName(), consoleApp.getName()));

    log.setLevel(logger.getLevel().toString());
    log.setLoggerName(logger.getName());
    loggersDTOs.add(log);

    ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
    ObjectName nameRetrieved = transaction.lookupConfigBean(factory.getImplementationName(),
            LogbackModuleFactory.INSTANCE_NAME);
    LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameRetrieved, LogbackModuleMXBean.class);

    bean.setLoggerTO(loggersDTOs);
    bean.setRollingFileAppenderTO(rollingAppenders);
    bean.setConsoleAppenderTO(consoleAppenders);
    bean.setFileAppenderTO(fileAppenders);

    transaction.commit();

    return nameRetrieved;
}

From source file:org.opendaylight.controller.config.yang.logback.config.LogbackWithXmlConfigModuleTest.java

@Before
public void setUp() throws JoranException, IOException {

    factory = new LogbackModuleFactory();
    super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));

    lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    lc.reset();//from w  w w  .  java  2  s.  c o m
    configurator.setContext(lc);
    configurator.doConfigure("src/test/resources/simple_config_logback.xml");
    File f = new File("target/it");
    if (f.exists())
        FileUtils.cleanDirectory(f);
}

From source file:org.openehealth.ipf.commons.lbs.store.DiskStore.java

private void deleteDirWithRetry(File dir) {
    for (int attempt = 1; attempt <= 5; ++attempt) {
        try {/*from w  ww .  j  a  v a2 s.co  m*/
            FileUtils.cleanDirectory(dir);
            return;
        } catch (IOException e) {
            if (attempt < 5) {
                log.debug("Attempt to delete directory '" + dir + "' failed. Retrying deletion.");
                sleep();
            } else {
                log.warn("Deletion of directory '" + dir.getAbsolutePath() + "' failed due to: "
                        + e.getMessage());
                throw new ResourceIOException("Could not delete: " + dir, e);
            }
        }
    }
}

From source file:org.openhab.persistence.db4o.internal.Db4oPersistenceServiceTest.java

@Test
public void testRemoveObsoleteBackupFiles() throws IOException {
    String testDbDirName = "./target/etc/db4o/";

    File db4oDir = new File(testDbDirName);
    db4oDir.mkdirs();//from   w  w w.  j  a  v  a  2s .  c o  m
    FileUtils.cleanDirectory(db4oDir);

    for (int index = 0; index < backupFileNames.length; index++) {
        new File(testDbDirName + backupFileNames[index] + "_store.db4o.bak").createNewFile();
    }
    Assert.assertEquals(backupFileNames.length, db4oDir.listFiles().length);

    // Method under Test
    backupJob.removeObsoleteBackupFiles(testDbDirName);

    // Expected results ...
    File[] result = db4oDir.listFiles();
    Arrays.sort(result);

    Assert.assertEquals(Db4oConfiguration.maxBackups, result.length);
    for (int index = 0; index < result.length; index++) {
        Assert.assertEquals(backupFileNames[expectedResultIndexes[index]] + "_store.db4o.bak",
                result[index].getName());
    }
}

From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java

/**
 * @see org.openmrs.module.conceptmanagementapps.api.ConceptManagementAppsService#startManageSnomedCTProcess(java.lang.String,
 *      java.lang.String, org.openmrs.ConceptSource)
 *///from w w  w  .ja v a  2 s  .  c  o  m
@Transactional
public void startManageSnomedCTProcess(String process, String snomedFileDirectory, ConceptSource snomedSource)
        throws APIException, FileNotFoundException {

    try {

        snomedIndexFileDirectoryLocation = OpenmrsUtil.getApplicationDataDirectory() + "/tempLucene";

        currentSnomedCTProcess = new ManageSnomedCTProcess(process);
        currentSnomedCTProcess.setCurrentManageSnomedCTProcessDirectoryLocation(snomedFileDirectory);

        ConceptManagementAppsProperties cmap = new ConceptManagementAppsProperties();
        String snomedSourceUuid;
        if (snomedSource != null) {
            snomedSourceUuid = snomedSource.getUuid();
        } else {
            snomedSourceUuid = cmap.getSnomedCTConceptSourceUuidGlobalProperty(
                    ConceptManagementAppsConstants.SNOMED_CT_CONCEPT_SOURCE_UUID_GP);
        }

        indexSnomedFiles(snomedFileDirectory);

        if (process.contains("addSnomedCTNames")) {

            addNamesToSnomedCTTerms(snomedFileDirectory, snomedSourceUuid);
        }
        if (process.contains("addSnomedCTAncestors")) {

            addAncestorsToSnomedCTTerms(snomedFileDirectory, snomedSourceUuid);
        }
        if (process.contains("addSnomedCTRelationships")) {

            addRelationshipsToSnomedCTTerms(snomedFileDirectory, snomedSourceUuid);
        }
    } finally {
        try {
            FileUtils.cleanDirectory(new File(snomedIndexFileDirectoryLocation));

        } catch (IOException e) {
            log.error("Error cleaning Lucene Index Directory ", e);
        }
    }

}

From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java

/**
 * Adds the ancestors to the SNOMED CT terms. Uses the International Release RF2 version from
 * Unified Medical Language System (UMLS) to find the children contained in the
 * /SnomedCT_Release_INT_20130131/RF2Release/Full/Terminology/ Relationship file
 * /*  w  ww.  j av a  2s.c  o m*/
 * @param snomedFileDirectory
 * @param snomedSourceUuid
 * @throws APIException
 */
private void addAncestorsToSnomedCTTerms(String snomedFileDirectory, String snomedSourceUuid)
        throws APIException {

    ConceptService cs = Context.getConceptService();

    ConceptSource snomedSource = cs.getConceptSourceByUuid(snomedSourceUuid);

    List<ConceptReferenceTerm> sourceRefTerms = getConceptReferenceTermsWithSpecifiedSourceIfIncluded(
            snomedSource, 0, -1, "code", 1);
    List<ConceptReferenceTerm> listOfTermsToSave = new ArrayList<ConceptReferenceTerm>();

    Set<Long> listOfNewTermIds = new HashSet<Long>();
    Set<Integer> listOfDocIds = new HashSet<Integer>();
    Set<Integer> listOfExistingIds = new HashSet<Integer>();
    Set<ConceptReferenceTerm> listOfNewTerms = new HashSet<ConceptReferenceTerm>();

    IndexReader reader = null;

    try {
        reader = DirectoryReader.open(FSDirectory.open(new File(snomedIndexFileDirectoryLocation)));
        IndexSearcher searcher = new IndexSearcher(reader);

        for (ConceptReferenceTerm term : sourceRefTerms) {
            if (!getManageSnomedCTProcessCancelled()) {
                Set<Integer> tmpListOfDocIds = new HashSet<Integer>();

                tmpListOfDocIds = searchIndexesGetAncestorTermIds(term.getCode(), listOfNewTermIds,
                        listOfDocIds, snomedSource, searcher);

                listOfExistingIds.add(term.getCode().hashCode());

                listOfDocIds.addAll(tmpListOfDocIds);
            } else {
                return;
            }

        }

        listOfNewTerms = createNewTerms(listOfDocIds, searcher, snomedSource, listOfExistingIds);
        listOfTermsToSave.addAll(listOfNewTerms);

        if (listOfTermsToSave != null) {
            saveNewOrUpdatedRefTerms(listOfTermsToSave, cs);
        }

    } catch (IOException e) {
        log.error("Error Adding Ancestors ", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            FileUtils.cleanDirectory(new File(snomedIndexFileDirectoryLocation));

        } catch (IOException e) {
            log.error("Error Adding Ancestors ", e);
        }
    }

}

From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java

/**
 * Adds the relationships to the SNOMED CT terms. Uses the International Release RF2 version
 * from Unified Medical Language System (UMLS) to find the children contained in the
 * /SnomedCT_Release_INT_20130131/RF2Release/Full/Terminology/ Relationship file
 * /*from  w  w  w. ja  va  2s.  c  o m*/
 * @param snomedFileDirectory
 * @param snomedSourceUuid
 * @throws APIException
 */
private void addRelationshipsToSnomedCTTerms(String snomedFileDirectory, String snomedSourceUuid)
        throws APIException {

    ConceptService cs = Context.getConceptService();

    ConceptSource snomedSource = cs.getConceptSourceByUuid(snomedSourceUuid);
    ConceptMapType snomedMapType = cs
            .getConceptMapTypeByUuid(ConceptManagementAppsConstants.SAME_AS_CONCEPT_MAP_TYPE_UUID);

    List<ConceptReferenceTerm> listOfMappedTerms = new ArrayList<ConceptReferenceTerm>();

    IndexReader reader = null;

    try {
        reader = DirectoryReader.open(FSDirectory.open(new File(snomedIndexFileDirectoryLocation)));
        IndexSearcher searcher = new IndexSearcher(reader);

        List<ConceptReferenceTerm> sourceRefTermsNew = getConceptReferenceTermsWithSpecifiedSourceIfIncluded(
                snomedSource, 0, -1, "code", 1);
        listOfMappedTerms = createNewMappings(sourceRefTermsNew, searcher, snomedMapType);
        if (listOfMappedTerms != null) {
            saveNewOrUpdatedRefTerms(listOfMappedTerms, cs);
        }

    } catch (IOException e) {

    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            FileUtils.cleanDirectory(new File(snomedIndexFileDirectoryLocation));

        } catch (IOException e) {
            log.error("Error Adding Parents ", e);
        }
    }

}

From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java

/**
 * Adds the names to the SNOMED CT terms. Uses the International Release RF2 version from
 * Unified Medical Language System (UMLS) to find the names contained in the
 * /SnomedCT_Release_INT_20130131/RF2Release/Full/Terminology/ Description file
 * /*from  w  w w  . j  a  va2  s.c  om*/
 * @param snomedFileDirectory
 * @param snomedSourceUuid
 * @throws APIException
 */
private void addNamesToSnomedCTTerms(String snomedFileDirectory, String snomedSourceUuid) throws APIException {

    ConceptService cs = Context.getConceptService();

    ConceptSource snomedSource = cs.getConceptSourceByUuid(snomedSourceUuid);

    List<ConceptReferenceTerm> sourceRefTerms = getConceptReferenceTermsWithSpecifiedSourceIfIncluded(
            snomedSource, 0, -1, "code", 1);
    List<ConceptReferenceTerm> listOfUpdatedTerms = new ArrayList<ConceptReferenceTerm>();

    IndexReader reader = null;

    try {

        reader = DirectoryReader.open(FSDirectory.open(new File(snomedIndexFileDirectoryLocation)));
        IndexSearcher searcher = new IndexSearcher(reader);

        listOfUpdatedTerms = addNamesToAllReferenceTerms(sourceRefTerms, searcher);
        if (listOfUpdatedTerms != null) {
            saveNewOrUpdatedRefTerms(listOfUpdatedTerms, cs);
        }

    } catch (IOException e) {

        log.error("Error Adding Names ", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            FileUtils.cleanDirectory(new File(snomedIndexFileDirectoryLocation));

        } catch (IOException e) {
            log.error("Error Adding Names ", e);
        }
    }

}

From source file:org.openmrs.web.filter.initialization.TestInstallUtil.java

/**
 * Extracts .omod files from the specified {@link InputStream} and copies them to the module
 * repository of the test application data directory, the method always closes the InputStream
 * before returning//from   w w  w. jav a2  s.  c  o  m
 *
 * @param in the {@link InputStream} for the zip file
 */
@SuppressWarnings("rawtypes")
protected static boolean addZippedTestModules(InputStream in) {
    ZipFile zipFile = null;
    FileOutputStream out = null;
    File tempFile = null;
    boolean successfullyAdded = true;

    try {
        tempFile = File.createTempFile("modules", null);
        out = new FileOutputStream(tempFile);
        IOUtils.copy(in, out);
        zipFile = new ZipFile(tempFile);
        Enumeration entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping directory: " + entry.getName());
                }
                continue;
            }

            String fileName = entry.getName();
            if (fileName.endsWith(".omod")) {
                //Convert the names of .omod files located in nested directories so that they get
                //created under the module repo directory when being copied
                if (fileName.contains(System.getProperty("file.separator"))) {
                    fileName = new File(entry.getName()).getName();
                }

                if (log.isDebugEnabled()) {
                    log.debug("Extracting module file: " + fileName);
                }

                //use the module repository folder GP value if specified
                String moduleRepositoryFolder = FilterUtil
                        .getGlobalPropertyValue(ModuleConstants.REPOSITORY_FOLDER_PROPERTY);
                if (StringUtils.isBlank(moduleRepositoryFolder)) {
                    moduleRepositoryFolder = ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT;
                }

                //At this point 'OpenmrsConstants.APPLICATION_DATA_DIRECTORY' is still null so we need check
                //for the app data directory defined in the runtime props file if any otherwise the logic in
                //the OpenmrsUtil.getDirectoryInApplicationDataDirectory(String) will default to the other
                String appDataDirectory = Context.getRuntimeProperties()
                        .getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY);
                if (StringUtils.isNotBlank(appDataDirectory)) {
                    OpenmrsUtil.setApplicationDataDirectory(appDataDirectory);
                }

                File moduleRepository = OpenmrsUtil
                        .getDirectoryInApplicationDataDirectory(moduleRepositoryFolder);

                //delete all previously added modules in case of prior test installations
                FileUtils.cleanDirectory(moduleRepository);

                OpenmrsUtil.copyFile(zipFile.getInputStream(entry),
                        new BufferedOutputStream(new FileOutputStream(new File(moduleRepository, fileName))));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring file that is not a .omod '" + fileName);
                }
            }
        }
    } catch (IOException e) {
        log.error("An error occured while copying modules to the test system:", e);
        successfullyAdded = false;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                log.error("Failed to close zip file: ", e);
            }
        }
        if (tempFile != null) {
            tempFile.delete();
        }
    }

    return successfullyAdded;
}

From source file:org.openpnp.machine.reference.camera.TableScannerCamera.java

public synchronized void clearCache() throws IOException {
    FileUtils.cleanDirectory(cacheDirectory);
    pcs.firePropertyChange("cacheSizeDescription", null, getCacheSizeDescription());
}