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:com.door43.translationstudio.core.TargetTranslationMigrator.java

/**
 * Merges invalid chunks found in the target translation with a valid sibling chunk in order
 * to preserve translation data. Merged chunks are marked as not finished to force
 * translators to review the changes.//ww w. j a  v a  2s.c om
 * @param library
 * @param manifestFile
 * @param sourceTranslation
 * @param chapterDir
 * @return
 */
private static boolean mergeInvalidChunksInChapter(final Library library, File manifestFile,
        final SourceTranslation sourceTranslation, final File chapterDir) {
    JSONObject manifest;
    try {
        manifest = new JSONObject(FileUtils.readFileToString(manifestFile));
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    final String chunkMergeMarker = "\n----------\n";
    File[] frameFiles = chapterDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return !pathname.getName().equals("title.txt") && !pathname.getName().equals("reference.txt");
        }
    });
    String invalidChunks = "";
    File lastValidFrameFile = null;
    String chapterId = chapterDir.getName();
    for (File frameFile : frameFiles) {
        String frameId = frameFile.getName();
        Frame frame = library.getFrame(sourceTranslation, chapterId, frameId);
        String frameBody = "";
        try {
            frameBody = FileUtils.readFileToString(frameFile).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (frame != null) {
            lastValidFrameFile = frameFile;
            // merge invalid frames into the existing frame
            if (!invalidChunks.isEmpty()) {
                try {
                    FileUtils.writeStringToFile(frameFile, invalidChunks + frameBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                invalidChunks = "";
                try {
                    Manifest.removeValue(manifest.getJSONArray("finished_frames"), chapterId + "-" + frameId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else if (!frameBody.isEmpty()) {
            // collect invalid frame
            if (lastValidFrameFile == null) {
                invalidChunks += frameBody + chunkMergeMarker;
            } else {
                // append to last valid frame
                String lastValidFrameBody = "";
                try {
                    lastValidFrameBody = FileUtils.readFileToString(lastValidFrameFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    FileUtils.writeStringToFile(lastValidFrameFile,
                            lastValidFrameBody + chunkMergeMarker + frameBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    Manifest.removeValue(manifest.getJSONArray("finished_frames"),
                            chapterId + "-" + lastValidFrameFile.getName());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            // delete invalid frame
            FileUtils.deleteQuietly(frameFile);
        }
    }
    // clean up remaining invalid chunks
    if (!invalidChunks.isEmpty()) {
        // grab updated list of frames
        frameFiles = chapterDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return !pathname.getName().equals("title.txt") && !pathname.getName().equals("reference.txt");
            }
        });
        if (frameFiles != null && frameFiles.length > 0) {
            String frameBody = "";
            try {
                frameBody = FileUtils.readFileToString(frameFiles[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                FileUtils.writeStringToFile(frameFiles[0], invalidChunks + chunkMergeMarker + frameBody);
                try {
                    Manifest.removeValue(manifest.getJSONArray("finished_frames"),
                            chapterId + "-" + frameFiles[0].getName());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}

From source file:net.sf.maltcms.chromaui.project.spi.project.ChromAUIProject.java

public Map<String, Map<File, List<File>>> getImportDirectoryFiles() {
    File importDir = getImportDirectory();
    File[] toolFiles = importDir.listFiles(new FileFilter() {
        @Override/*from  ww  w. java2s .c  o  m*/
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    Map<String, Map<File, List<File>>> importDirectoryFiles = new LinkedHashMap<>();
    for (File tool : toolFiles) {
        importDirectoryFiles.put(tool.getName(), getToolFiles(tool));
    }
    return importDirectoryFiles;
}

From source file:net.sf.maltcms.chromaui.project.spi.project.ChromAUIProject.java

private Map<File, List<File>> getToolFiles(File tool) {
    File[] dates = tool.listFiles(new FileFilter() {
        @Override/*w  ww.j a v  a2s  .  co  m*/
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });
    Map<File, List<File>> instanceFiles = new LinkedHashMap<>();
    for (File date : dates) {
        instanceFiles.put(date, new ArrayList<>(FileUtils.listFiles(date, null, true)));
    }
    return instanceFiles;
}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowHelper.java

/**
 * Internal method for recursive substition within pTargetPath.
 *
 * @param pTask The task whose working directory should be checked for
 * substitution.//  ww w  . java2s  .  c  o  m
 * @param pTargetPath The target path.
 *
 * @throws IOException If the replacement operation fails for some reason.
 * @throws URISyntaxException If any of the URLs in the task (input, output,
 * temp or working dir URL) is invalid.
 */
private static void substituteVariablesRecursive(DataWorkflowTask pTask, File pTargetPath)
        throws IOException, URISyntaxException {
    if (pTargetPath == null || !pTargetPath.exists()) {
        LOGGER.warn("Argument pTargetPath must not be 'null' and must exist");
        return;
    }
    LOGGER.info("Checking directory '" + pTargetPath.getPath() + "'");

    //get a list of relevant files
    File[] relevantFileList = pTargetPath.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            //accept a file only if it is a directory or
            //if it is a file called "replace_vars", which marks directories that should be affected by replacements
            return (pathname.isDirectory()
                    || (pathname.isFile() && pathname.getName().equals("dataworkflow_substitution")));
        }
    });

    //go through all listed files within pTargetPath
    for (File relevantFile : relevantFileList) {
        if (relevantFile.isDirectory()) {
            //continue recursively
            substituteVariablesRecursive(pTask, relevantFile);
        } else {
            //due to the filtering we have now a replace_var file. Therefore we have to replace variables in all files within its parent directory.
            performSubstitution(pTask, relevantFile.getParentFile());
        }
    }
}

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

private void loadBookmarkSetGroup() {
    File bookmarkDir = new File(Naming.getBookmarkDir());
    File origBookmarkDir = new File(res.getString("bookmark.baseDir"));

    FileFilter xmlFilter = new FileFilter() { // accept .xml files
        public boolean accept(File pathname) {
            if (pathname.getName().toLowerCase().endsWith(".xml")) {
                return true;
            }/*from w  w  w. jav  a 2 s.  com*/
            return false;
        }
    };

    // bookmarks
    try {
        if (!bookmarkDir.exists() || !bookmarkDir.isDirectory()) {
            logger.info("Copy all bookmarks to " + Naming.getBookmarkDir());
            FileUtils.copyDirectory(origBookmarkDir, bookmarkDir);
        } else {
            File bookmarkFolderAlreadyCopied = new File(Naming.getBookmarkDir() + "/.DONOTDELETE");
            if (!bookmarkFolderAlreadyCopied.exists()) {
                File[] origs = origBookmarkDir.listFiles(xmlFilter);
                for (int i = 0; i < origs.length; i++) {
                    File destFile = new File(bookmarkDir + "/" + origs[i].getName());
                    if (!destFile.exists()) {
                        logger.info("Copy bookmark " + origs[i] + " to " + Naming.getBookmarkDir());
                        FileUtils.copyFile(origs[i], destFile);
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.log(e);
    }

    String def = props.getString("bookmark.default");
    File[] bookmarkSets = bookmarkDir.listFiles(xmlFilter);
    for (int i = 0; i < bookmarkSets.length; i++) {
        // bookmarks should be lazily loaded
        BookmarkSet bms = new BookmarkSet(Naming.getBookmarkDir() + "/" + bookmarkSets[i].getName());
        bookmarkSetGroup.addBookmarkSet(bms);
        if (bms.getId().equals(def)) {
            bookmarkSetGroup.setAsDefault(bms);
        }
    }
    if (bookmarkSetGroup.getDefault() == null) {
        logger.doFatal(new BookmarkException(
                "No default bookmark set, or cannot load the default bookmark set: " + def));
    }
    bookmarkSetGroup.getDefault().load();
}

From source file:com.aliyun.odps.local.common.WareHouse.java

public List<String> getProjectNames() {
    File warehouseDir = getWarehouseDir();
    if (!warehouseDir.exists()) {
        return null;
    }/*from www. j  av  a  2 s  .  co  m*/
    List<String> result = new ArrayList<String>();
    File[] projects = warehouseDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && !pathname.isHidden();

        }
    });
    for (File p : projects) {
        if (p.isDirectory()) {
            result.add(p.getName());
        }
    }
    return result;
}

From source file:com.taobao.android.tpatch.utils.PatchUtils.java

public static void getTpatchClassDef(File tpatchFile, Map<String, Map<String, ClassDef>> bundleMap)
        throws IOException {
    if (tpatchFile == null || !tpatchFile.exists()) {
        return;//from  ww w  . j  a v  a  2s  .  c  o m
    }
    File unZipFolder = new File(tpatchFile.getParentFile(), tpatchFile.getName().split("\\.")[0]);
    unZipFolder.mkdirs();
    ZipUtils.unzip(tpatchFile, unZipFolder.getAbsolutePath());
    File[] bundleFolder = unZipFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && pathname.getName().startsWith("lib");
        }
    });

    for (File file : bundleFolder) {
        Map<String, ClassDef> dexClasses = getBundleClassDef(file);
        bundleMap.put(file.getName(), dexClasses);

    }

    FileUtils.deleteDirectory(tpatchFile.getParentFile());
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

/**
 * List {@link QualifiedResource} from an input directory.
 * @param from// w  w w .  java2s  .  c o  m
 * @param extension
 * @return
 */
private Collection<QualifiedResource> listQualifiedResources(final File from, final String extension) {
    Preconditions.checkNotNull(extension);
    final Collection<QualifiedResource> resources = new ArrayList<>();
    if (from.isDirectory()) {
        for (File f : from.listFiles(new FileFilter() {
            public boolean accept(File file) {
                if (file.isFile()
                        && extension.equalsIgnoreCase(FilenameUtils.getExtension(file.getAbsolutePath()))) {
                    try {
                        resources.add(QualifiedResource.fromFile(file));
                        return true;
                    } catch (Exception e) {
                        getLog().error(e);
                    }
                    getLog().warn("Invalid " + extension + " file : " + file.getAbsolutePath());
                } else {
                    getLog().debug("+ skipping " + file.getAbsolutePath());
                }
                return false;
            }
        })) {
            // log matching svgmask inputs
            getLog().debug("+ found " + extension + " file : " + f.getAbsolutePath());
        }
    } else {
        throw new RuntimeException(from.getAbsolutePath() + " is not a directory");
    }
    return resources;
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

/** Called when the activity is first created. */
@Override/* w w w . j  a v  a  2  s . c  o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // must be at the beginning of any activity that can be called from an
    // external intent
    try {
        Collect.createODKDirs();
    } catch (RuntimeException e) {
        createErrorDialog(e.getMessage(), EXIT);
        return;
    }
    Log.i("Activity", "Created");
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences
            .registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
                public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                    compressImage = mSharedPreferences
                            .getBoolean(PreferencesActivity.KEY_ENABLE_IMAGE_COMPRESSION, false);
                }
            });
    setContentView(R.layout.form_entry);
    /*      setTitle(getString(R.string.app_name) + " > "
    + getString(R.string.loading_form));*/
    setTitle(getString(R.string.app_name));

    Log.i("Entry", "Form");
    mErrorMessage = null;
    //progressBar = (ProgressBar) findViewById(R.id.progress);
    //progressBar.setVisibility(ProgressBar.VISIBLE);
    //progressBar.setProgress(0);

    mBeenSwiped = false;
    mAlertDialog = null;
    mCurrentView = null;
    mInAnimation = null;
    mOutAnimation = null;
    mGestureDetector = new GestureDetector(this, this);
    mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder);

    // get admin preference settings
    mAdminPreferences = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0);

    mNextButton = (ImageButton) findViewById(R.id.form_forward_button);
    mNextButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mBeenSwiped = true;
            showNextView();
        }
    });

    mBackButton = (ImageButton) findViewById(R.id.form_back_button);
    mBackButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mBeenSwiped = true;
            showPreviousView();
        }
    });

    needLocation = mSharedPreferences.getBoolean(PreferencesActivity.KEY_GPS_FIX, false);
    if (needLocation) {

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, this);
    }

    // Load JavaRosa modules. needed to restore forms.
    new XFormsModule().registerModule();

    // needed to override rms property manager
    org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager(getApplicationContext()));

    String startingXPath = null;
    String waitingXPath = null;
    String instancePath = null;
    Boolean newForm = true;
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_FORMPATH)) {
            mFormPath = savedInstanceState.getString(KEY_FORMPATH);
        }
        if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
            instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
        }
        if (savedInstanceState.containsKey(KEY_XPATH)) {
            startingXPath = savedInstanceState.getString(KEY_XPATH);
            Log.i(t, "startingXPath is: " + startingXPath);
        }
        if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
            waitingXPath = savedInstanceState.getString(KEY_XPATH_WAITING_FOR_DATA);
            Log.i(t, "waitingXPath is: " + waitingXPath);
        }
        if (savedInstanceState.containsKey(NEWFORM)) {
            newForm = savedInstanceState.getBoolean(NEWFORM, true);
        }
        if (savedInstanceState.containsKey(KEY_ERROR)) {
            mErrorMessage = savedInstanceState.getString(KEY_ERROR);
        }
    }

    // If a parse error message is showing then nothing else is loaded
    // Dialogs mid form just disappear on rotation.
    if (mErrorMessage != null) {
        createErrorDialog(mErrorMessage, EXIT);
        return;
    }

    // Check to see if this is a screen flip or a new form load.
    Object data = getLastNonConfigurationInstance();
    if (data instanceof FormLoaderTask) {
        mFormLoaderTask = (FormLoaderTask) data;
    } else if (data instanceof SaveToDiskTask) {
        mSaveToDiskTask = (SaveToDiskTask) data;
    } else if (data == null) {
        if (!newForm) {
            if (Collect.getInstance().getFormController() != null) {
                refreshCurrentView();
            } else {
                Log.w(t, "Reloading form and restoring state.");
                // we need to launch the form loader to load the form
                // controller...
                mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath);
                Collect.getInstance().getActivityLogger().logAction(this, "formReloaded", mFormPath);
                // TODO: this doesn' work (dialog does not get removed):
                // showDialog(PROGRESS_DIALOG);
                // show dialog before we execute...
                Log.i("Loader", "Executing");
                mFormLoaderTask.execute(mFormPath);
            }
            return;
        }

        // Not a restart from a screen orientation change (or other).
        Collect.getInstance().setFormController(null);
        CompatibilityUtils.invalidateOptionsMenu(this);

        Intent intent = getIntent();
        if (intent != null) {
            Uri uri = intent.getData();

            if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
                // get the formId and version for this instance...
                String jrFormId = null;
                String jrVersion = null;
                {
                    Cursor instanceCursor = null;
                    try {
                        instanceCursor = getContentResolver().query(uri, null, null, null, null);
                        if (instanceCursor.getCount() != 1) {
                            this.createErrorDialog("Bad URI: " + uri, EXIT);
                            return;
                        } else {
                            instanceCursor.moveToFirst();
                            instancePath = instanceCursor.getString(
                                    instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                            Collect.getInstance().getActivityLogger().logAction(this, "instanceLoaded",
                                    instancePath);

                            jrFormId = instanceCursor
                                    .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                            int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);

                            jrVersion = instanceCursor.isNull(idxJrVersion) ? null
                                    : instanceCursor.getString(idxJrVersion);
                        }
                    } finally {
                        if (instanceCursor != null) {
                            instanceCursor.close();
                        }
                    }
                }

                String[] selectionArgs;
                String selection;

                if (jrVersion == null) {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL";
                } else {
                    selectionArgs = new String[] { jrFormId, jrVersion };
                    selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?";
                }

                {
                    Cursor formCursor = null;
                    try {
                        formCursor = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection,
                                selectionArgs, null);
                        if (formCursor.getCount() == 1) {
                            formCursor.moveToFirst();
                            mFormPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        } else if (formCursor.getCount() < 1) {
                            this.createErrorDialog(
                                    getString(R.string.parent_form_not_present, jrFormId)
                                            + ((jrVersion == null) ? ""
                                                    : "\n" + getString(R.string.version) + " " + jrVersion),
                                    EXIT);
                            return;
                        } else if (formCursor.getCount() > 1) {
                            // still take the first entry, but warn that
                            // there are multiple rows.
                            // user will need to hand-edit the SQLite
                            // database to fix it.
                            formCursor.moveToFirst();
                            mFormPath = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                            this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT);
                            return;
                        }
                    } finally {
                        if (formCursor != null) {
                            formCursor.close();
                        }
                    }
                }
            } else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
                Cursor c = null;
                try {
                    c = getContentResolver().query(uri, null, null, null, null);
                    if (c.getCount() != 1) {
                        this.createErrorDialog("Bad URI: " + uri, EXIT);
                        return;
                    } else {
                        c.moveToFirst();
                        mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
                        // This is the fill-blank-form code path.
                        // See if there is a savepoint for this form that
                        // has never been
                        // explicitly saved
                        // by the user. If there is, open this savepoint
                        // (resume this filled-in
                        // form).
                        // Savepoints for forms that were explicitly saved
                        // will be recovered
                        // when that
                        // explicitly saved instance is edited via
                        // edit-saved-form.
                        final String filePrefix = mFormPath.substring(mFormPath.lastIndexOf('/') + 1,
                                mFormPath.lastIndexOf('.')) + "_";
                        final String fileSuffix = ".xml.save";
                        File cacheDir = new File(Collect.CACHE_PATH);
                        File[] files = cacheDir.listFiles(new FileFilter() {
                            @Override
                            public boolean accept(File pathname) {
                                String name = pathname.getName();
                                return name.startsWith(filePrefix) && name.endsWith(fileSuffix);
                            }
                        });
                        // see if any of these savepoints are for a
                        // filled-in form that has never been
                        // explicitly saved by the user...
                        for (int i = 0; i < files.length; ++i) {
                            File candidate = files[i];
                            String instanceDirName = candidate.getName().substring(0,
                                    candidate.getName().length() - fileSuffix.length());
                            File instanceDir = new File(
                                    Collect.INSTANCES_PATH + File.separator + instanceDirName);
                            File instanceFile = new File(instanceDir, instanceDirName + ".xml");
                            if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) {
                                // yes! -- use this savepoint file
                                instancePath = instanceFile.getAbsolutePath();
                                break;
                            }
                        }
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
            } else {
                Log.e(t, "unrecognized URI");
                this.createErrorDialog("Unrecognized URI: " + uri, EXIT);
                return;
            }

            mFormLoaderTask = new FormLoaderTask(instancePath, null, null);
            Collect.getInstance().getActivityLogger().logAction(this, "formLoaded", mFormPath);
            showDialog(PROGRESS_DIALOG);
            // show dialog before we execute...
            Log.i("Loader", "Executing");
            mFormLoaderTask.execute(mFormPath);
        }
    }

}

From source file:com.aliyun.odps.local.common.WareHouse.java

public List<TableMeta> getTableMetas(String projName) throws IOException {
    File projectDir = getProjectDir(projName);
    if (!projectDir.exists()) {
        return null;
    }/*from w  ww .  j av  a2s .c o  m*/

    List<TableMeta> result = new ArrayList<TableMeta>();
    File[] tables = projectDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && !pathname.isHidden()
                    && !pathname.getName().equals(Constants.RESOURCES_DIR);
        }
    });
    // old version
    for (File t : tables) {
        if (!existsTable(projName, t.getName())) {
            continue;
        }

        TableMeta tableMeta = getTableMeta(projName, t.getName());
        if (tableMeta != null) {
            result.add(tableMeta);
        }
    }

    // new version >=0.14
    File tableBaseDir = new File(projectDir, Constants.TABLES_DIR);
    if (!tableBaseDir.exists()) {
        return result;
    }
    tables = tableBaseDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && !pathname.isHidden();
        }
    });
    for (File t : tables) {
        if (!existsTable(projName, t.getName())) {
            continue;
        }

        TableMeta tableMeta = getTableMeta(projName, t.getName());
        if (tableMeta != null) {
            result.add(tableMeta);
        }
    }

    return result;
}