List of usage examples for java.io FileFilter FileFilter
FileFilter
From source file:com.door43.translationstudio.core.TargetTranslationMigrator.java
/** * major restructuring of the manifest to provide better support for future front/back matter, drafts, rendering, * and resolves issues between desktop and android platforms. * @param path// w ww . ja v a2 s . c om * @return */ private static File v4(File path) throws Exception { File manifestFile = new File(path, MANIFEST_FILE); JSONObject manifest = new JSONObject(FileUtils.readFileToString(manifestFile)); // type { String typeId = "text"; if (manifest.has("project")) { try { JSONObject projectJson = manifest.getJSONObject("project"); typeId = projectJson.getString("type"); projectJson.remove("type"); manifest.put("project", projectJson); } catch (JSONException e) { e.printStackTrace(); } } JSONObject typeJson = new JSONObject(); TranslationType translationType = TranslationType.get(typeId); typeJson.put("id", typeId); if (translationType != null) { typeJson.put("name", translationType.getName()); } else { typeJson.put("name", ""); } manifest.put("type", typeJson); } // update project // NOTE: this was actually in v3 but we missed it so we need to catch it here if (manifest.has("project_id")) { String projectId = manifest.getString("project_id"); manifest.remove("project_id"); JSONObject projectJson = new JSONObject(); projectJson.put("id", projectId); projectJson.put("name", projectId.toUpperCase()); // we don't know the full name at this point manifest.put("project", projectJson); } // update resource if (manifest.getJSONObject("type").getString("id").equals("text")) { if (manifest.has("resource_id")) { String resourceId = manifest.getString("resource_id"); manifest.remove("resource_id"); JSONObject resourceJson = new JSONObject(); // TRICKY: supported resource id's (or now types) are "reg", "obs", "ulb", and "udb". if (resourceId.equals("ulb")) { resourceJson.put("name", "Unlocked Literal Bible"); } else if (resourceId.equals("udb")) { resourceJson.put("name", "Unlocked Dynamic Bible"); } else if (resourceId.equals("obs")) { resourceJson.put("name", "Open Bible Stories"); } else { // everything else changes to "reg" resourceId = "reg"; resourceJson.put("name", "Regular"); } resourceJson.put("id", resourceId); manifest.put("resource", resourceJson); } else if (!manifest.has("resource")) { // add missing resource JSONObject resourceJson = new JSONObject(); JSONObject projectJson = manifest.getJSONObject("project"); JSONObject typeJson = manifest.getJSONObject("type"); if (typeJson.getString("id").equals("text")) { String resourceId = projectJson.getString("id"); if (resourceId.equals("obs")) { resourceJson.put("id", "obs"); resourceJson.put("name", "Open Bible Stories"); } else { // everything else changes to reg resourceJson.put("id", "reg"); resourceJson.put("name", "Regular"); } manifest.put("resource", resourceJson); } } } else { // non-text translation types do not have resources manifest.remove("resource_id"); manifest.remove("resource"); } // update source translations if (manifest.has("source_translations")) { JSONObject oldSourceTranslationsJson = manifest.getJSONObject("source_translations"); manifest.remove("source_translations"); JSONArray newSourceTranslationsJson = new JSONArray(); Iterator<String> keys = oldSourceTranslationsJson.keys(); while (keys.hasNext()) { try { String key = keys.next(); JSONObject oldObj = oldSourceTranslationsJson.getJSONObject(key); JSONObject sourceTranslation = new JSONObject(); String[] parts = key.split("-", 2); if (parts.length == 2) { String languageResourceId = parts[1]; String[] pieces = languageResourceId.split("-"); if (pieces.length > 0) { String resId = pieces[pieces.length - 1]; sourceTranslation.put("resource_id", resId); sourceTranslation.put("language_id", languageResourceId.substring(0, languageResourceId.length() - resId.length() - 1)); sourceTranslation.put("checking_level", oldObj.getString("checking_level")); sourceTranslation.put("date_modified", oldObj.getInt("date_modified")); sourceTranslation.put("version", oldObj.getString("version")); newSourceTranslationsJson.put(sourceTranslation); } } } catch (Exception e) { // don't fail migration just because a source translation was invalid e.printStackTrace(); } } manifest.put("source_translations", newSourceTranslationsJson); } // update parent draft if (manifest.has("parent_draft_resource_id")) { JSONObject draftStatus = new JSONObject(); draftStatus.put("resource_id", manifest.getString("parent_draft_resource_id")); draftStatus.put("checking_entity", ""); draftStatus.put("checking_level", ""); draftStatus.put("comments", "The parent draft is unknown"); draftStatus.put("contributors", ""); draftStatus.put("publish_date", ""); draftStatus.put("source_text", ""); draftStatus.put("source_text_version", ""); draftStatus.put("version", ""); manifest.put("parent_draft", draftStatus); manifest.remove("parent_draft_resource_id"); } // update finished chunks if (manifest.has("finished_frames")) { JSONArray finishedFrames = manifest.getJSONArray("finished_frames"); manifest.remove("finished_frames"); manifest.put("finished_chunks", finishedFrames); } // remove finished titles if (manifest.has("finished_titles")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedTitles = manifest.getJSONArray("finished_titles"); manifest.remove("finished_titles"); for (int i = 0; i < finishedTitles.length(); i++) { String chapterId = finishedTitles.getString(i); finishedChunks.put(chapterId + "-title"); } manifest.put("finished_chunks", finishedChunks); } // remove finished references if (manifest.has("finished_references")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedReferences = manifest.getJSONArray("finished_references"); manifest.remove("finished_references"); for (int i = 0; i < finishedReferences.length(); i++) { String chapterId = finishedReferences.getString(i); finishedChunks.put(chapterId + "-reference"); } manifest.put("finished_chunks", finishedChunks); } // remove project components // NOTE: this was never quite official, just in android if (manifest.has("finished_project_components")) { JSONArray finishedChunks = manifest.getJSONArray("finished_chunks"); JSONArray finishedProjectComponents = manifest.getJSONArray("finished_project_components"); manifest.remove("finished_project_components"); for (int i = 0; i < finishedProjectComponents.length(); i++) { String component = finishedProjectComponents.getString(i); finishedChunks.put("00-" + component); } manifest.put("finished_chunks", finishedChunks); } // add format if (!Manifest.valueExists(manifest, "format") || manifest.getString("format").equals("usx") || manifest.getString("format").equals("default")) { String typeId = manifest.getJSONObject("type").getString("id"); String projectId = manifest.getJSONObject("project").getString("id"); if (!typeId.equals("text") || projectId.equals("obs")) { manifest.put("format", "markdown"); } else { manifest.put("format", "usfm"); } } // update where project title is saved. File oldProjectTitle = new File(path, "title.txt"); File newProjectTitle = new File(path, "00/title.txt"); if (oldProjectTitle.exists()) { newProjectTitle.getParentFile().mkdirs(); FileUtils.moveFile(oldProjectTitle, newProjectTitle); } // update package version manifest.put("package_version", 5); FileUtils.write(manifestFile, manifest.toString(2)); // migrate usx to usfm String format = manifest.getString("format"); // TRICKY: we just added the new format field, anything marked as usfm may have residual usx and needs to be migrated if (format.equals("usfm")) { File[] chapterDirs = path.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() && !pathname.getName().equals(".git"); } }); for (File cDir : chapterDirs) { File[] chunkFiles = cDir.listFiles(); for (File chunkFile : chunkFiles) { try { String usx = FileUtils.readFileToString(chunkFile); String usfm = USXtoUSFMConverter.doConversion(usx).toString(); FileUtils.writeStringToFile(chunkFile, usfm); } catch (IOException e) { // this conversion may have failed but don't stop the rest of the migration e.printStackTrace(); } } } } return path; }
From source file:com.owncloud.android.ui.activity.SyncedFoldersActivity.java
private File[] getFileList(File localFolder) { File[] files = localFolder.listFiles(new FileFilter() { @Override/* w w w. j a v a 2s . c o m*/ public boolean accept(File pathname) { return !pathname.isDirectory(); } }); if (files != null) { Arrays.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } }); } else { files = new File[] {}; } return files; }
From source file:com.taobao.android.builder.tasks.app.databinding.AwbDataBindingRenameTask.java
/** * ?so/*w w w . java2 s .co m*/ */ @TaskAction void createAwbPackages() throws ExecutionException, InterruptedException { AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(getVariantName()); if (null == atlasDependencyTree) { return; } ExecutorServicesHelper executorServicesHelper = new ExecutorServicesHelper(taskName, getLogger(), 0); List<Runnable> runnables = new ArrayList<>(); for (final AwbBundle awbBundle : atlasDependencyTree.getAwbBundles()) { if (!awbBundle.isDataBindEnabled()) { continue; } runnables.add(new Runnable() { @Override public void run() { try { File dataBindingClazzFolder = appVariantOutputContext.getVariantContext() .getJAwbavaOutputDir(awbBundle); String packageName = awbBundle.getPackageName(); String appName = awbBundle.getPackageName() + "._bundleapp_"; //? File dataMapperClazz = new File(dataBindingClazzFolder, "android/databinding/DataBinderMapper.class"); if (!dataMapperClazz.exists()) { throw new GradleException("missing datamapper class"); } rewriteDataBinderMapper(dataBindingClazzFolder, packageName, dataMapperClazz); //FileUtils.deleteDirectory(new File(dataBindingClazzFolder, packageName.replace(".", "/") + // "/_bundleapp_" )); File appDir = new File(dataBindingClazzFolder, appName.replace(".", "/")); if (appDir.exists()) { File[] files = appDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && !pathname.isDirectory(); } }); for (File tmp : files) { FileUtils.forceDelete(tmp); } } //rename DataBindUtils AwbTransform awbTransform = appVariantOutputContext.getAwbTransformMap() .get(awbBundle.getName()); List<File> files = awbTransform.getInputLibraries(); Map<String, String> replaceMap = new HashMap<>(); replaceMap.put("android/databinding/DataBindingUtil", "android/databinding/AtlasDataBindingUtil"); List<File> newLibrarys = new ArrayList<>(); for (File inputJar : files) { File outputJar = new File(appVariantContext.getAwbLibraryDirForDataBinding(awbBundle), FileNameUtils.getUniqueJarName(inputJar) + ".jar"); outputJar.delete(); outputJar.getParentFile().mkdirs(); outputJar.createNewFile(); new ClazzReplacer(inputJar, outputJar, replaceMap).execute(); newLibrarys.add(outputJar); } awbTransform.setInputLibraries(newLibrarys); } catch (Throwable e) { e.printStackTrace(); throw new GradleException("databinding awb failed", e); } } }); } executorServicesHelper.execute(runnables); }
From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java
/** * helper method to parse cashbox simulation files or directories containing multiple simulation files * @param inputFileOrDirectory simulation input file/simulation input directory * @return simulation package used to run the cashbox simulation *//*from ww w .ja v a 2 s .c o m*/ public static List<CashBoxSimulation> readCashBoxSimulationFromFile(File inputFileOrDirectory) { List<CashBoxSimulation> cashBoxSimulationList = new ArrayList<>(); try { if (inputFileOrDirectory.isDirectory()) { File[] inputFileList = inputFileOrDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".testrun"); } }); for (File simulationFile : inputFileList) { cashBoxSimulationList.addAll(readCashBoxSimulationFromFile(simulationFile)); } } else { BufferedInputStream bIn = new BufferedInputStream(new FileInputStream(inputFileOrDirectory)); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); IOUtils.copy(bIn, bOut); CashBoxSimulation cashBoxSimulation = (CashBoxSimulation) gson .fromJson(new String(bOut.toByteArray()), CashBoxSimulation.class); cashBoxSimulationList.add(cashBoxSimulation); } } catch (IOException e) { e.printStackTrace(); System.exit(0); } return cashBoxSimulationList; }
From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java
private void autoSearch() { new Thread(() -> { File[] files = filechooser.getInitialDirectory().listFiles(new FileFilter() { @Override//from www. j a va2 s . com public boolean accept(File pathname) { String x = FilenameUtils.getExtension(pathname.getAbsolutePath()); return x.compareToIgnoreCase("tsv") == 0; } }); File mostRecent = Arrays.stream(files).max((x, y) -> Long.compare(x.lastModified(), y.lastModified())) .orElse(null); if (mostRecent == null) { return; } Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setContentText("We found the following TSV file in your default location:\n\"" + mostRecent.getName() + "\"\n" + "Modified: " + new Date(mostRecent.lastModified()) + "\n\n" + "Would you like load this file?"); Optional<ButtonType> answer = alert.showAndWait(); if (answer.isPresent() && answer.get().getButtonData().equals(ButtonData.OK_DONE)) { System.out.println(answer.get()); setInputFile(mostRecent); //setting the input file is enough to trigger the load! // loadInInfo(mostRecent); //not safe, just load the file in for you. // onBtnGo(null); } else { } }); }).start(); }
From source file:com.enjoyxstudy.selenium.htmlsuite.MultiHTMLSuiteRunner.java
/** * @param suiteDir//from w ww . j a v a2 s.co m * @return suiteFiles * @throws IOException */ private File[] collectSuiteFiles(File suiteDir) throws IOException { if (!suiteDir.exists() || !suiteDir.isDirectory()) { throw new IOException("Can't find HTML Suite dir:" + suiteDir.getAbsolutePath()); } return suiteDir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && TEST_SUITE_REGEXP.matcher(pathname.getName()).matches(); } }); }
From source file:com.depas.utils.FileUtils.java
public static File[] getFilesInDirectory(String path) { File dir = new File(path); FileFilter fileFilter = new FileFilter() { @Override// w w w . j a va 2s . co m public boolean accept(File file) { return !file.isDirectory(); } }; return dir.listFiles(fileFilter); }
From source file:de.blizzy.documentr.page.PageStore.java
@Override public List<String> listPageAttachments(String projectName, String branchName, String pagePath) throws IOException { Assert.hasLength(projectName);//from w w w .j a v a2 s .c om Assert.hasLength(branchName); Assert.hasLength(pagePath); // check if page exists by trying to load it getPage(projectName, branchName, pagePath, false); ILockedRepository repo = null; try { repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); File attachmentsDir = new File(workingDir, DocumentrConstants.ATTACHMENTS_DIR_NAME); File pageAttachmentsDir = Util.toFile(attachmentsDir, pagePath); List<String> names = Collections.emptyList(); if (pageAttachmentsDir.isDirectory()) { FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && file.getName().endsWith(DocumentrConstants.META_SUFFIX); } }; List<File> files = Lists.newArrayList(pageAttachmentsDir.listFiles(filter)); Function<File, String> function = new Function<File, String>() { @Override public String apply(File file) { return StringUtils.substringBeforeLast(file.getName(), DocumentrConstants.META_SUFFIX); } }; names = Lists.newArrayList(Lists.transform(files, function)); Collections.sort(names); } return names; } catch (GitAPIException e) { throw new IOException(e); } finally { Closeables.closeQuietly(repo); } }
From source file:net.dmulloy2.ultimatearena.UltimateArena.java
private void loadClasses() { File folder = new File(getDataFolder(), "classes"); FileFilter filter = new FileFilter() { @Override// w ww . jav a 2 s . co m public boolean accept(File file) { return file.getName().contains(".yml"); } }; File[] files = folder.listFiles(filter); if (files == null || files.length == 0) { generateStockClasses(); files = folder.listFiles(filter); } int total = 0; files: for (File file : files) { // Make sure it isn't already loaded for (ArenaClass loaded : classes) { if (loaded.getFile().equals(file)) continue files; } ArenaClass ac = new ArenaClass(this, file); if (ac.isLoaded()) { classes.add(ac); total++; if (ac.isNeedsPermission()) { // Fully qualified names, conflicts with UA permissions PluginManager pm = getServer().getPluginManager(); org.bukkit.permissions.Permission perm = pm.getPermission(ac.getPermissionNode()); if (perm == null) { perm = new org.bukkit.permissions.Permission(ac.getPermissionNode(), PermissionDefault.OP); pm.addPermission(perm); } } } } log("Loaded {0} classes.", total); }
From source file:com.geoodk.collect.android.tasks.FormLoaderTask.java
@SuppressWarnings("unchecked") private void loadExternalData(File mediaFolder) { //SCTO-594/*from w w w. java2 s .c o m*/ File[] zipFiles = mediaFolder.listFiles(new FileFilter() { @Override public boolean accept(File file) { return file.getName().toLowerCase().endsWith(".zip"); } }); if (zipFiles != null) { ZipUtils.unzip(zipFiles); for (File zipFile : zipFiles) { boolean deleted = zipFile.delete(); if (!deleted) { Log.w(t, "Cannot delete " + zipFile + ". It will be re-unzipped next time. :("); } } } File[] csvFiles = mediaFolder.listFiles(new FileFilter() { @Override public boolean accept(File file) { String lowerCaseName = file.getName().toLowerCase(); return lowerCaseName.endsWith(".csv") && !lowerCaseName.equalsIgnoreCase(ITEMSETS_CSV); } }); Map<String, File> externalDataMap = new HashMap<String, File>(); if (csvFiles != null) { for (File csvFile : csvFiles) { String dataSetName = csvFile.getName().substring(0, csvFile.getName().lastIndexOf(".")); externalDataMap.put(dataSetName, csvFile); } if (externalDataMap.size() > 0) { publishProgress(Collect.getInstance().getString(R.string.survey_loading_reading_csv_message)); ExternalDataReader externalDataReader = new ExternalDataReaderImpl(this); externalDataReader.doImport(externalDataMap); } } }