Example usage for java.io FileFilter FileFilter

List of usage examples for java.io FileFilter FileFilter

Introduction

In this page you can find the example usage for java.io FileFilter FileFilter.

Prototype

FileFilter

Source Link

Usage

From source file:iTests.framework.utils.WebuiTestUtils.java

private static String findJarFilenameByRegexPattern(final String folderPath, final Pattern pattern)
        throws FileNotFoundException {

    final File folder = new File(folderPath);
    if (!folder.isDirectory()) {
        throw new FileNotFoundException(folder + " is not a directory.");
    }/* www  .  ja va 2  s .c  om*/

    final File[] files = folder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return pattern.matcher(file.getName()).matches();
        }
    });

    if (files.length != 1) {
        throw new FileNotFoundException("Folder " + folderPath
                + " should contain exactly one jar that satisfies the pattern " + pattern.toString());
    }

    return files[0].getName();
}

From source file:de.huxhorn.lilith.swing.MainFrame.java

/**
 * To be called after setVisible(true)...
 *///from w w w.  ja  v a 2 s .com
public void startUp() {
    //Thread referenceCollection=new Thread(new ColorsCollectionRunnable(), "ColorCacheCleanupThread");
    //referenceCollection.setDaemon(true);
    //referenceCollection.start();

    setSplashStatusText("Executing autostart items.");
    // Autostart
    {
        File autostartDir = new File(startupApplicationPath, "autostart");
        if (autostartDir.mkdirs()) {
            if (logger.isDebugEnabled())
                logger.debug("Created '{}'.", autostartDir.getAbsolutePath());
        }
        File[] autoFiles = autostartDir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        });

        if (autoFiles != null && autoFiles.length > 0) {
            Arrays.sort(autoFiles, new Comparator<File>() {
                public int compare(File o1, File o2) {
                    return o1.getAbsolutePath().compareTo(o2.getAbsolutePath());
                }
            });
            for (File current : autoFiles) {
                AutostartRunnable r = new AutostartRunnable(current);
                autostartProcesses.add(r);
                Thread t = new Thread(r, current.getAbsolutePath());
                t.setDaemon(true);
                t.start();
            }
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("No autostart files defined in '{}'.", autostartDir.getAbsolutePath());
            }
        }
    }

    // go to source
    {
        gotoSource = new SerializingGoToSource();
        //gotoSource.start() started when needed...
    }

    setSplashStatusText("Creating global views.");
    SourceIdentifier globalSourceIdentifier = new SourceIdentifier("global", null);

    loggingFileDump = new FileDumpEventHandler<LoggingEvent>(globalSourceIdentifier, loggingFileBufferFactory);
    accessFileDump = new FileDumpEventHandler<AccessEvent>(globalSourceIdentifier, accessFileBufferFactory);
    setGlobalLoggingEnabled(applicationPreferences.isGlobalLoggingEnabled());

    BlockingCircularBuffer<EventWrapper<LoggingEvent>> loggingEventQueue = new LilithBuffer<LoggingEvent>(
            applicationPreferences, 1000);
    BlockingCircularBuffer<EventWrapper<AccessEvent>> accessEventQueue = new LilithBuffer<AccessEvent>(
            applicationPreferences, 1000);

    SourceManagerImpl<LoggingEvent> lsm = new SourceManagerImpl<LoggingEvent>(loggingEventQueue);
    // add global view
    EventSource<LoggingEvent> globalLoggingEventSource = new EventSourceImpl<LoggingEvent>(
            globalSourceIdentifier, loggingFileDump.getBuffer(), true);
    lsm.addSource(globalLoggingEventSource);

    setSplashStatusText("Creating internal view.");
    // add internal lilith logging
    EventSource<LoggingEvent> lilithLoggingEventSource = new EventSourceImpl<LoggingEvent>(
            InternalLilithAppender.getSourceIdentifier(), InternalLilithAppender.getBuffer(), false);
    lsm.addSource(lilithLoggingEventSource);

    setLoggingEventSourceManager(lsm);

    SourceManagerImpl<AccessEvent> asm = new SourceManagerImpl<AccessEvent>(accessEventQueue);
    // add global view
    EventSource<AccessEvent> globalAccessEventSource = new EventSourceImpl<AccessEvent>(globalSourceIdentifier,
            accessFileDump.getBuffer(), true);
    asm.addSource(globalAccessEventSource);
    setAccessEventSourceManager(asm);

    ConverterRegistry<LoggingEvent> loggingConverterRegistry = new ConverterRegistry<LoggingEvent>();
    loggingConverterRegistry.addConverter(new LogbackLoggingConverter());
    loggingConverterRegistry.addConverter(new Log4jLoggingConverter());
    loggingConverterRegistry.addConverter(new Log4j2LoggingConverter());

    ConverterRegistry<AccessEvent> accessConverterRegistry = new ConverterRegistry<AccessEvent>();
    accessConverterRegistry.addConverter(new LogbackAccessConverter());

    setSplashStatusText("Starting event receivers.");

    try {
        ConvertingServerSocketEventSourceProducer<LoggingEvent> producer = new ConvertingServerSocketEventSourceProducer<LoggingEvent>(
                4560, loggingConverterRegistry, new LoggingEventSourceIdentifierUpdater());
        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        ConvertingServerSocketEventSourceProducer<LoggingEvent> producer = new ConvertingServerSocketEventSourceProducer<LoggingEvent>(
                4445, loggingConverterRegistry, new LoggingEventSourceIdentifierUpdater());
        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LoggingEventProtobufServerSocketEventSourceProducer producer = new LoggingEventProtobufServerSocketEventSourceProducer(
                ClassicMultiplexSocketAppender.COMPRESSED_DEFAULT_PORT, true);

        loggingEventSourceManager.addEventSourceProducer(producer);
        // TODO: senderService.addLoggingProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LoggingEventProtobufServerSocketEventSourceProducer producer = new LoggingEventProtobufServerSocketEventSourceProducer(
                ClassicMultiplexSocketAppender.UNCOMPRESSED_DEFAULT_PORT, false);

        loggingEventSourceManager.addEventSourceProducer(producer);
        // TODO: senderService.addLoggingProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithXmlMessageLoggingServerSocketEventSourceProducer producer = new LilithXmlMessageLoggingServerSocketEventSourceProducer(
                ClassicXmlMultiplexSocketAppender.UNCOMPRESSED_DEFAULT_PORT, false);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithXmlMessageLoggingServerSocketEventSourceProducer producer = new LilithXmlMessageLoggingServerSocketEventSourceProducer(
                ClassicXmlMultiplexSocketAppender.COMPRESSED_DEFAULT_PORT, true);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithJsonMessageLoggingServerSocketEventSourceProducer producer = new LilithJsonMessageLoggingServerSocketEventSourceProducer(
                ClassicJsonMultiplexSocketAppender.UNCOMPRESSED_DEFAULT_PORT, false);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithJsonMessageLoggingServerSocketEventSourceProducer producer = new LilithJsonMessageLoggingServerSocketEventSourceProducer(
                ClassicJsonMultiplexSocketAppender.COMPRESSED_DEFAULT_PORT, true);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithXmlStreamLoggingServerSocketEventSourceProducer producer = new LilithXmlStreamLoggingServerSocketEventSourceProducer(
                ZeroDelimitedClassicXmlMultiplexSocketAppender.DEFAULT_PORT);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        LilithJsonStreamLoggingServerSocketEventSourceProducer producer = new LilithJsonStreamLoggingServerSocketEventSourceProducer(
                ZeroDelimitedClassicJsonMultiplexSocketAppender.DEFAULT_PORT);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        JulXmlStreamLoggingServerSocketEventSourceProducer producer = new JulXmlStreamLoggingServerSocketEventSourceProducer(
                11020);

        loggingEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        ConvertingServerSocketEventSourceProducer<AccessEvent> producer = new ConvertingServerSocketEventSourceProducer<AccessEvent>(
                4570, accessConverterRegistry, null);
        accessEventSourceManager.addEventSourceProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }
    try {
        AccessEventProtobufServerSocketEventSourceProducer producer = new AccessEventProtobufServerSocketEventSourceProducer(
                AccessMultiplexSocketAppender.COMPRESSED_DEFAULT_PORT, true);

        accessEventSourceManager.addEventSourceProducer(producer);
        // TODO: senderService.addAccessProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    try {
        AccessEventProtobufServerSocketEventSourceProducer producer = new AccessEventProtobufServerSocketEventSourceProducer(
                AccessMultiplexSocketAppender.UNCOMPRESSED_DEFAULT_PORT, false);

        accessEventSourceManager.addEventSourceProducer(producer);
        // TODO: senderService.addAccessProducer(producer);
    } catch (IOException ex) {
        if (logger.isWarnEnabled())
            logger.warn("Exception while creating event producer!", ex);
    }

    setSplashStatusText("Setting up event handlers.");

    rrdLoggingEventHandler = new RrdLoggingEventHandler();
    rrdLoggingEventHandler.setBasePath(new File(startupApplicationPath, "statistics"));
    setStatisticsEnabled(applicationPreferences.isLoggingStatisticEnabled());
    AlarmSoundLoggingEventHandler loggingEventAlarmSound = new AlarmSoundLoggingEventHandler();
    loggingEventAlarmSound.setSounds(sounds);

    FileSplitterEventHandler<LoggingEvent> fileSplitterLoggingEventHandler = new FileSplitterEventHandler<LoggingEvent>(
            loggingFileBufferFactory, loggingEventSourceManager);

    List<EventHandler<LoggingEvent>> loggingHandlers = new ArrayList<EventHandler<LoggingEvent>>();

    loggingHandlers.add(rrdLoggingEventHandler);
    loggingHandlers.add(loggingEventAlarmSound);
    loggingHandlers.add(fileSplitterLoggingEventHandler);
    loggingHandlers.add(loggingFileDump);

    // crashes the app using j2se 6
    //if(application.isMac())
    //{
    //   UserNotificationLoggingEventHandler notification = new UserNotificationLoggingEventHandler(application);
    //   loggingHandlers.add(notification);
    //}
    loggingEventSourceManager.setEventHandlers(loggingHandlers);
    loggingEventSourceManager.start();

    List<EventHandler<AccessEvent>> accessHandlers = new ArrayList<EventHandler<AccessEvent>>();

    FileSplitterEventHandler<AccessEvent> fileSplitterAccessEventHandler = new FileSplitterEventHandler<AccessEvent>(
            accessFileBufferFactory, accessEventSourceManager);
    AlarmSoundAccessEventHandler accessEventAlarmSound = new AlarmSoundAccessEventHandler();
    accessEventAlarmSound.setSounds(sounds);
    accessHandlers.add(accessEventAlarmSound);
    accessHandlers.add(fileSplitterAccessEventHandler);
    accessHandlers.add(accessFileDump);

    // crashes the app using j2se 6
    //if(application.isMac())
    //{
    //   UserNotificationAccessEventHandler notification = new UserNotificationAccessEventHandler(application);
    //   accessHandlers.add(notification);
    //}

    accessEventSourceManager.setEventHandlers(accessHandlers);
    accessEventSourceManager.start();

    viewActions.updateWindowMenu();
    application.setEnabledAboutMenu(true);
    application.setEnabledPreferencesMenu(true);
    application.addApplicationListener(new MyApplicationListener());

    if (enableBonjour) {
        senderService.start();
    }
    if (applicationPreferences.isCheckingForUpdate()) {
        checkForUpdate(false);
    }
    updateConditions(); // to initialize active conditions.

    if (applicationPreferences.isShowingTipOfTheDay()) {
        showTipOfTheDayDialog();
    }

    cleanObsoleteFiles();

    traySupport = TraySupport.getInstance();
    if (traySupport != null) {
        traySupport.setMainFrame(this);
    }
    setSplashStatusText("Finished.");
    //      viewActions.requestMenuBarFocus();
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

/**
 * This method extracts language properties from the corresponding node in the config file.
 *//*  w w  w  . j  a va  2  s.co  m*/
private void extractLangProps() {
    boolean update = false;

    String def = props.getString("lang.default");
    File langDir = new File(ApplicationPath.LANGUAGE_DIR);
    logger.info("Loading language pack files info");
    logger.info("Default language pack is " + def);
    FileFilter filter = new FileFilter() { // accept .xml files
        public boolean accept(File pathname) {
            if (pathname.getName().toLowerCase().endsWith(".xml")) {
                return true;
            }
            return false;
        }
    };
    File[] langs = langDir.listFiles(filter);
    LanguagePack lp;

    logger.info("Found these language packs: " + Arrays.asList(langs));

    for (int i = 0; i < langs.length; i++) {
        XmlReader reader = null;
        try {
            reader = new XmlReader(langs[i]);
        } catch (Exception e) {
            if (langs[i].getName().endsWith("english.xml")) {
                logger.doFatal(e);
            } else {
                logger.warn("Cannot open language pack " + def + " due to the following error:");
                logger.log(e);
                update = true;
                props.setProperty("lang.default", "en_US");
                def = "en_US";
                logger.warn("Default language pack set to: " + def);
            }
        }
        lp = new LanguagePack();
        lp.file = langs[i].getName();
        Element locale = reader.getElement("locale");
        lp.localizedName = locale.getAttribute("localizedName");
        lp.name = locale.getAttribute("name");
        lp.id = locale.getAttribute("id");
        lp.direction = locale.getAttribute("direction");
        lp.author = reader.getDocumentElement().getAttribute("creator");
        if (lp.localizedName == null) {
            lp.localizedName = lp.name;
        }
        language.add(lp);
        if (lp.id.equals(def)) {
            language.setActiveLanguagePack(def);
        }
    }

    if (update) {
        updateFile();
    }
}

From source file:io.fabric8.maven.plugin.mojo.build.ResourceMojo.java

private void addProfiledResourcesFromSubirectories(KubernetesListBuilder builder, File resourceDir,
        EnricherManager enricherManager) throws IOException, MojoExecutionException {
    File[] profileDirs = resourceDir.listFiles(new FileFilter() {
        @Override/*from  ww w.  ja v a  2 s  . c  o  m*/
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    if (profileDirs != null) {
        for (File profileDir : profileDirs) {
            Profile profile = ProfileUtil.findProfile(profileDir.getName(), resourceDir);
            if (profile == null) {
                throw new MojoExecutionException(String.format(
                        "Invalid profile '%s' given as directory in %s. "
                                + "Please either define a profile of this name or move this directory away",
                        profileDir.getName(), resourceDir));
            }

            ProcessorConfig enricherConfig = profile.getEnricherConfig();
            File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(profileDir);
            if (resourceFiles.length > 0) {
                KubernetesListBuilder profileBuilder = readResourceFragments(resourceFiles);
                enricherManager.createDefaultResources(enricherConfig, profileBuilder);
                enricherManager.enrich(enricherConfig, profileBuilder);
                KubernetesList profileItems = profileBuilder.build();
                for (HasMetadata item : profileItems.getItems()) {
                    builder.addToItems(item);
                }
            }
        }
    }
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Import lock box files./*from ww  w. jav a 2s.  com*/
 *
 * @param now The current date.
 * @param isNowHoliday Indicate whether current is holiday
 * @return true if execution is successful; false to retry.
 * @throws BatchProcessingException If major error occurred.
 */
private boolean importFiles(Date now, boolean isNowHoliday) throws BatchProcessingException {
    StringBuilder procMessage = new StringBuilder();
    procMessage.append("Service Credit Batch started at ");
    procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now));
    procMessage.append(" on ");
    procMessage.append(DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now));
    procMessage.append(". Batch done at @#$%EndingTime%$#@.");
    procMessage.append(CRLF).append(CRLF);

    File inputDirectory = new File(inputDirectoryPath);
    if (!inputDirectory.exists() || !inputDirectory.isDirectory() || !inputDirectory.canRead()) {
        logger.error("Can not read folder: " + inputDirectory);

        procMessage.append("THE NETWORK IS DOWN! ");
        procMessage.append(CRLF);
        procMessage.append("Network Services not Available for Service Credit. Cannot access the ");
        procMessage.append(inputDirectoryPath);
        procMessage.append(" network folder. Please ask the Help Desk to investigate. ");
        procMessage.append("SERVICE CREDIT IS SHUT DOWN UNTIL THIS ERROR IS FIXED! ");
        notifyByEmail(procMessage.toString(), "SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", "Testing Network");
        auditError("SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", procMessage.toString());
        return false;
    }

    // Filter the input lockbox files
    final String regex = wildCardInput.replace("?", ".?").replace("*", ".*?");
    File[] inputFiles = inputDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File inputFile) {
            if (inputFile.getName().matches(regex)) {
                if (inputFile.isFile() && inputFile.canRead() && inputFile.canWrite()) {
                    return true;
                }
                logger.warn("Does not have read/write permission to file: " + inputFile);
            }
            return false;
        }
    });

    if (inputFiles.length == 0) {
        if (!isNowHoliday && Boolean.TRUE != todayAuditBatch.getFileReceived()) {
            logger.error("No files arrived today in: " + inputDirectory);

            procMessage.append("Today's Lockbox Bank File has not arrived. Please notify Production Control"
                    + " and BSG that the data file is not in the ");
            procMessage.append(inputDirectoryPath);
            procMessage.append(" network share. The nightly batch process is scheduled to run at ");
            procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now));
            procMessage.append(" and today's import should run before that time. ");
            notifyByEmail(procMessage.toString(), "SERVICE CREDIT LOCKBOX FILE IS LATE!", "ERROR");
            auditError("SERVICE CREDIT LOCKBOX FILE IS LATE!", procMessage.toString());
            return false;
        }
        return true;
    }

    // Mark file arrived
    if (Boolean.TRUE != todayAuditBatch.getFileReceived()) {
        todayAuditBatch.setFileReceived(true);
        try {
            todayAuditBatch = mergeEntity(todayAuditBatch);
        } catch (PersistenceException pe) {
            throw new BatchProcessingException(
                    "Database error while updating audit batch log when importing files", pe);
        }
    }

    // Import files
    logger.info("Start importing files in: " + inputDirectory);
    for (File inputFile : inputFiles) {
        if (!inputFile.exists() || !inputFile.isFile() || !inputFile.canRead()) {
            // Just make sure
            logger.warn("Lockbox file is not a readable file: " + inputFile);
            continue;
        }

        importFile(procMessage, inputFile);
    }
    logger.info("End importing files in: " + inputDirectory);

    return true;
}

From source file:com.aliyun.odps.mapred.LocalJobRunner.java

private void moveOutputs() throws IOException {
    TableInfo[] output = OutputUtils.getTables(conf);
    if (output == null) {
        return;/*w ww. j a va  2 s .  c om*/
    }
    for (TableInfo table : output) {
        String label = table.getLabel();

        String projName = table.getProjectName();
        if (projName == null) {
            projName = wareHouse.getOdps().getDefaultProject();
        }
        String tblName = table.getTableName();
        Map<String, String> partSpec = table.getPartSpec();

        File tempTblDir = jobDirecotry.getOutputDir(table.getLabel());
        File whOutputDir = wareHouse.createPartitionDir(projName, tblName, PartitionUtils.convert(partSpec));
        if (wareHouse.existsTable(projName, tblName)) {
            LOG.info("Reload warehouse table:" + tblName);
            LocalRunUtils.removeDataFiles(whOutputDir);
            wareHouse.copyDataFiles(tempTblDir, null, whOutputDir, wareHouse.getInputColumnSeperator());
        } else {
            LOG.info("Copy output to warehouse: label=" + label + " -> " + whOutputDir.getAbsolutePath());
            File whOutputTableDir = wareHouse.getTableDir(projName, tblName);
            // copy schema file
            FileUtils.copyDirectory(tempTblDir, whOutputTableDir, new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String filename = pathname.getName();
                    if (filename.equals("__schema__")) {
                        return true;
                    }
                    return false;
                }
            });
            // copy data files
            FileUtils.copyDirectory(tempTblDir, whOutputDir, new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    String filename = pathname.getName();
                    if (filename.equals("__schema__")) {
                        return false;
                    }
                    return true;
                }
            });
        }
    }
}

From source file:io.fabric8.git.internal.GitDataStore.java

@Override
public void exportProfiles(final String version, final String outputFileName, String wildcard) {
    final File outputFile = new File(outputFileName);
    outputFile.getParentFile().mkdirs();
    final FileFilter filter;
    if (Strings.isNotBlank(wildcard)) {
        final WildcardFileFilter matcher = new WildcardFileFilter(wildcard);
        filter = new FileFilter() {
            @Override/*w  w w . j  av  a 2 s . com*/
            public boolean accept(File file) {
                // match either the file or parent folder
                boolean answer = matcher.accept(file);
                if (!answer) {
                    File parentFile = file.getParentFile();
                    if (parentFile != null) {
                        answer = accept(parentFile);
                    }
                }
                return answer;
            }
        };
    } else {
        filter = null;
    }
    assertValid();
    gitOperation(new GitOperation<String>() {
        public String call(Git git, GitContext context) throws Exception {
            checkoutVersion(git, version);
            return doExportProfiles(git, context, outputFile, filter);
        }
    });
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Deletes a database including its journal file and other auxiliary files
 * that may have been created by the database engine.
 *
 * @param file The database file path.//  w ww .  jav a2 s.co  m
 * @return True if the database was successfully deleted.
 */
public static boolean deleteDatabase(File file) {
    if (file == null) {
        throw new IllegalArgumentException("file must not be null");
    }

    boolean deleted;
    deleted = file.delete();
    deleted |= new File(file.getPath() + "-journal").delete();
    deleted |= new File(file.getPath() + "-shm").delete();
    deleted |= new File(file.getPath() + "-wal").delete();

    File dir = file.getParentFile();
    if (dir != null) {
        final String prefix = file.getName() + "-mj";
        final FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File candidate) {
                return candidate.getName().startsWith(prefix);
            }
        };
        for (File masterJournal : dir.listFiles(filter)) {
            deleted |= masterJournal.delete();
        }
    }
    return deleted;
}

From source file:org.opendatakit.aggregate.odktables.api.perf.AggregateSynchronizer.java

/**
 * Get all the files under the given folder, excluding those directories that
 * are the concatenation of folder and a member of excluding. If the member of
 * excluding is a directory, none of its children will be synched either.
 * <p>//from   w w  w . ja v  a  2  s . c  om
 * If the folder doesn't exist it returns an empty list.
 * <p>
 * If the file exists but is not a directory, logs an error and returns an
 * empty list.
 * 
 * @param folder
 * @param excluding
 *          can be null--nothing will be excluded. Should be relative to the
 *          given folder.
 * @param relativeTo
 *          the path to which the returned paths will be relative. A null
 *          value makes them relative to the folder parameter. If it is non
 *          null, folder must start with relativeTo, or else the files in
 *          folder could not possibly be relative to relativeTo. In this case
 *          will throw an IllegalArgumentException.
 * @return the relative paths of the files under the folder--i.e. the paths
 *         after the folder parameter, not including the first separator
 * @throws IllegalArgumentException
 *           if relativeTo is not a substring of folder.
 */
private List<String> getAllFilesUnderFolder(File baseFolder, final Set<String> excludingNamedItemsUnderFolder) {
    String appName = ODKFileUtils.extractAppNameFromPath(baseFolder);

    // Return an empty list of the folder doesn't exist or is not a directory
    if (!baseFolder.exists()) {
        return new ArrayList<String>();
    } else if (!baseFolder.isDirectory()) {
        logger.error("[getAllFilesUnderFolder] folder is not a directory: " + baseFolder.getAbsolutePath());
        return new ArrayList<String>();
    }

    // construct the set of starting directories and files to process
    File[] partials = baseFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            if (excludingNamedItemsUnderFolder == null) {
                return true;
            } else {
                return !excludingNamedItemsUnderFolder.contains(pathname.getName());
            }
        }
    });

    if (partials == null) {
        return Collections.emptyList();
    }

    LinkedList<File> unexploredDirs = new LinkedList<File>();
    List<File> nondirFiles = new ArrayList<File>();

    // copy the starting set into a queue of unexploredDirs
    // and a list of files to be sync'd
    for (int i = 0; i < partials.length; ++i) {
        if (partials[i].isDirectory()) {
            unexploredDirs.add(partials[i]);
        } else {
            nondirFiles.add(partials[i]);
        }
    }

    while (!unexploredDirs.isEmpty()) {
        File exploring = unexploredDirs.removeFirst();
        File[] files = exploring.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                // we'll need to explore it
                unexploredDirs.add(f);
            } else {
                // we'll add it to our list of files.
                nondirFiles.add(f);
            }
        }
    }

    List<String> relativePaths = new ArrayList<String>();
    // we want the relative path, so drop the necessary bets.
    for (File f : nondirFiles) {
        // +1 to exclude the separator.
        relativePaths.add(ODKFileUtils.asRelativePath(appName, f));
    }
    return relativePaths;
}

From source file:net.sf.zekr.common.config.ApplicationConfig.java

/**
 * This method extracts translation properties from the corresponding node in the config file.<br>
 * Will first look inside global translations, and then user-specific ones, overwriting global translations with user-defined
 * ones if duplicates found./*from ww w . ja  v a2s  .  c  o  m*/
 */
@SuppressWarnings("unchecked")
private void extractTransProps() {
    String def = props.getString("trans.default");
    logger.info("Default translation is: " + def);

    String[] paths = { ApplicationPath.TRANSLATION_DIR, Naming.getTransDir() };
    for (int pathIndex = 0; pathIndex < paths.length; pathIndex++) {
        File transDir = new File(paths[pathIndex]);
        if (!transDir.exists()) {
            continue;
        }

        logger.info("Loading translation files info from: " + transDir);
        FileFilter filter = new FileFilter() { // accept zip files
            public boolean accept(File pathname) {
                if (pathname.getName().toLowerCase().endsWith(ApplicationPath.TRANS_PACK_SUFFIX)) {
                    return true;
                }
                return false;
            }
        };
        File[] trans = transDir.listFiles(filter);

        TranslationData td;

        for (int transIndex = 0; transIndex < trans.length; transIndex++) {
            ZipFile zipFile = null;
            try {
                td = loadTranslationData(trans[transIndex]);
                if (td == null) {
                    continue;
                }
                translation.add(td);
                if (td.id.equals(def)) {
                    try {
                        td.load();
                        logger.info("Default translation is: " + td);
                        translation.setDefault(td);
                    } catch (TranslationException e) {
                        logger.warn("Cannot load default translation: " + e);
                    }
                }

            } catch (Exception e) {
                logger.warn("Can not load translation pack \"" + zipFile
                        + "\" properly because of the following exception:");
                logger.log(e);
            }
        }
    }
    if (translation.getDefault() == null) {
        logger.error(new ZekrBaseException("Could not find default translation: " + def));
        logger.warn("Will use any English or other translations found.");
        for (TranslationData translationData : translation.getAllTranslation()) {
            if (translationData.locale.getLanguage().equalsIgnoreCase("en")) {
                logger.info("Trying to set default translation to: " + translationData.getId());
                try {
                    translationData.load();
                    translation.setDefault(translationData);
                    props.setProperty("trans.default", translation.getDefault().id);
                    break;
                } catch (TranslationException e) {
                    logger.warn("Cannot load default translation: " + e);
                }
            }
        }
        if (translation.getDefault() == null) {
            logger.warn("No default translation found! Will start without any translation. "
                    + "As a result some features will be disabled.");
            Iterator<TranslationData> iter = translation.getAllTranslation().iterator();
            if (iter.hasNext()) {
                TranslationData td = iter.next();
                try {
                    td.load();
                    translation.setDefault(td);
                    props.setProperty("trans.default", translation.getDefault().id);
                    logger.info("Default translation set to: " + translation.getDefault().getId());
                } catch (TranslationException e) {
                    logger.warn("Cannot load default translation: " + e);
                }
            }
        }
    }

    if (translation.getDefault() != null) {
        // load custom translation list
        logger.info("Load custom translation list.");
        List<TranslationData> customList = translation.getCustomGroup();
        List<String> customs = props.getList("trans.custom");
        for (int i = 0; i < customs.size(); i++) {
            String tid = customs.get(i);
            if (tid == null || "".equals(tid.trim())) {
                logger.info("No custom translation list to load.");
                continue;
            }
            TranslationData td = translation.get(tid);
            if (td == null) {
                logger.error("No such translation: " + tid);
                continue;
            }
            try {
                td.load();
                customList.add(td);
            } catch (TranslationException e) {
                logger.warn("Invalid translation will be removed from the multi-translation list: " + e);
                customs.remove(i);
            }
        }
    } else {
        logger.warn("No translation found!");
    }
}