List of usage examples for java.io FileFilter FileFilter
FileFilter
From source file:org.opendatakit.sync.aggregate.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.// ww w . j a va2 s . c o m * <p> * 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()) { log.e(LOGTAG, "[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:com.manydesigns.portofino.actions.admin.page.PageAdminAction.java
protected TableForm setupChildPagesForm(List<EditChildPage> childPages, File childrenDirectory, Layout layout, String prefix) {/*from ww w .j ava 2 s. com*/ TableForm childPagesForm; FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }; List<EditChildPage> unorderedChildPages = new ArrayList<EditChildPage>(); for (File dir : childrenDirectory.listFiles(filter)) { if (PageInstance.DETAIL.equals(dir.getName())) { continue; } EditChildPage childPage = null; String title; try { Page page = DispatcherLogic.getPage(dir); title = page.getTitle(); } catch (Exception e) { logger.error("Couldn't load page for " + dir, e); title = null; } for (ChildPage cp : layout.getChildPages()) { if (cp.getName().equals(dir.getName())) { childPage = new EditChildPage(); childPage.active = true; childPage.name = cp.getName(); childPage.showInNavigation = cp.isShowInNavigation(); childPage.title = title; childPage.embedded = cp.getContainer() != null; break; } } if (childPage == null) { childPage = new EditChildPage(); childPage.active = false; childPage.name = dir.getName(); childPage.title = title; } unorderedChildPages.add(childPage); } logger.debug("Adding known pages in order"); for (ChildPage cp : layout.getChildPages()) { for (EditChildPage ecp : unorderedChildPages) { if (cp.getName().equals(ecp.name)) { childPages.add(ecp); break; } } } logger.debug("Adding unknown pages"); for (EditChildPage ecp : unorderedChildPages) { if (!ecp.active) { childPages.add(ecp); } } childPagesForm = new TableFormBuilder(EditChildPage.class).configNRows(childPages.size()) .configFields(getChildPagesFormFields()).configPrefix(prefix).build(); childPagesForm.readFromObject(childPages); return childPagesForm; }
From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java
private void copyLocalNativeLibraries(final File localNativeLibrariesDirectory, final File destinationDirectory) throws MojoExecutionException { getLog().debug("Copying existing native libraries from " + localNativeLibrariesDirectory); try {// ww w.j av a2s . c o m org.apache.commons.io.FileUtils.copyDirectory(localNativeLibrariesDirectory, destinationDirectory, new FileFilter() { @Override public boolean accept(final File pathname) { return pathname.getName().endsWith(".so"); } }); } catch (IOException e) { getLog().error("Could not copy native libraries: " + e.getMessage(), e); throw new MojoExecutionException("Could not copy native dependency.", e); } }
From source file:com.ibm.amc.data.wamt.WamtAppliance.java
/** * Recursive in to directories to locate backupmanifest.xml. * /*from w w w . jav a 2 s.co m*/ * @param directory * top-level directory * @return directory containing backupmanifest.xml */ private File locateBackupDirectory(File directory) { if (new File(directory, BACKUP_MANIFEST_FILE_NAME).exists()) { return directory; } else { final File[] subdirectories = directory.listFiles(new FileFilter() { @Override public boolean accept(File path) { return path.isDirectory(); } }); for (File subdirectory : subdirectories) { File result = locateBackupDirectory(subdirectory); if (result != null) return result; } } return null; }
From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java
/** * Checks if folder has any subfolders but respects ACL and hideFolders setting from configuration. * * @param dirPath path to current folder. * @param dir current folder being checked. Represented by File object. * @param configuration configuration object. * @param resourceType name of resource type, folder is assigned to. * @param currentUserRole user role.//from w w w .ja va2s . c om * @return true if there are any allowed and non-hidden subfolders. */ public static Boolean hasChildren(String dirPath, File dir, IConfiguration configuration, String resourceType, String currentUserRole) { FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } }; File[] subDirsList = dir.listFiles(fileFilter); if (subDirsList != null) { for (File subDirsList1 : subDirsList) { String subDirName = subDirsList1.getName(); if (!FileUtils.checkIfDirIsHidden(subDirName, configuration) && AccessControlUtil.getInstance().checkFolderACL(resourceType, dirPath + subDirName, currentUserRole, AccessControlUtil.CKFINDER_CONNECTOR_ACL_FOLDER_VIEW)) { return true; } } } return false; }
From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java
/** * ??/*from w w w. ja v a 2 s . c o m*/ * @param parentDirPath * @return */ private List getDirectoryLists(String parentDirPath) { List lists = new ArrayList(); if (parentDirPath != null) { File file = new File(parentDirPath); File[] childDir = file.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory() && !StringUtil.matchPattern(pathname.getName(), CommonUtils.REGEX_ZH) && !pathname.isHidden()) return true; return false; } }); for (File dir : childDir) { TreeData treedata = new TreeData(dir.getName()); Map attr = new HashMap(); attr.put("path", dir.getPath()); treedata.setId(dir.getPath()); treedata.setAttributes(attr); lists.add(treedata); } } return lists; }
From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java
/** * Generates an intermediate apk file (actually .ap_) containing the * resources and assets./*from ww w. java2 s.c om*/ * * @throws MojoExecutionException */ private void generateIntermediateAp_() throws MojoExecutionException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); File[] overlayDirectories; if (resourceOverlayDirectories == null || resourceOverlayDirectories.length == 0) { overlayDirectories = new File[] { resourceOverlayDirectory }; } else { overlayDirectories = resourceOverlayDirectories; } if (extractedDependenciesRes.exists()) { try { getLog().info("Copying dependency resource files to combined resource directory."); if (!combinedRes.exists() && !combinedRes.mkdirs()) { throw new MojoExecutionException("Could not create directory for combined resources at " + combinedRes.getAbsolutePath()); } org.apache.commons.io.FileUtils.copyDirectory(extractedDependenciesRes, combinedRes); } catch (IOException e) { throw new MojoExecutionException("", e); } } if (resourceDirectory.exists() && combinedRes.exists()) { try { getLog().info("Copying local resource files to combined resource directory."); org.apache.commons.io.FileUtils.copyDirectory(resourceDirectory, combinedRes, new FileFilter() { /** * Excludes files matching one of the common file to * exclude. The default excludes pattern are the ones from * {org * .codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES} * * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(File file) { for (String pattern : AbstractScanner.DEFAULTEXCLUDES) { if (AbstractScanner.match(pattern, file.getAbsolutePath())) { getLog().debug("Excluding " + file.getName() + " from resource copy : matching " + pattern); return false; } } return true; } }); } catch (IOException e) { throw new MojoExecutionException("", e); } } // Must combine assets. // The aapt tools does not support several -A arguments. // We copy the assets from extracted dependencies first, and then the // local assets. // This allows redefining the assets in the current project if (extractedDependenciesAssets.exists()) { try { getLog().info("Copying dependency assets files to combined assets directory."); org.apache.commons.io.FileUtils.copyDirectory(extractedDependenciesAssets, combinedAssets, new FileFilter() { /** * Excludes files matching one of the common file to * exclude. The default excludes pattern are the ones from * {org * .codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES} * * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(File file) { for (String pattern : AbstractScanner.DEFAULTEXCLUDES) { if (AbstractScanner.match(pattern, file.getAbsolutePath())) { getLog().debug("Excluding " + file.getName() + " from asset copy : matching " + pattern); return false; } } return true; } }); } catch (IOException e) { throw new MojoExecutionException("", e); } } // Next pull APK Lib assets, reverse the order to give precedence to // libs higher up the chain List<Artifact> artifactList = new ArrayList<Artifact>(getAllRelevantDependencyArtifacts()); for (Artifact artifact : artifactList) { if (artifact.getType().equals(APKLIB)) { File apklibAsssetsDirectory = new File(getLibraryUnpackDirectory(artifact) + "/assets"); if (apklibAsssetsDirectory.exists()) { try { getLog().info("Copying dependency assets files to combined assets directory."); org.apache.commons.io.FileUtils.copyDirectory(apklibAsssetsDirectory, combinedAssets, new FileFilter() { /** * Excludes files matching one of the common file to * exclude. The default excludes pattern are the * ones from * {org.codehaus.plexus.util.AbstractScanner * #DEFAULTEXCLUDES} * * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(File file) { for (String pattern : AbstractScanner.DEFAULTEXCLUDES) { if (AbstractScanner.match(pattern, file.getAbsolutePath())) { getLog().debug("Excluding " + file.getName() + " from asset copy : matching " + pattern); return false; } } return true; } }); } catch (IOException e) { throw new MojoExecutionException("", e); } } } } if (assetsDirectory.exists()) { try { getLog().info("Copying local assets files to combined assets directory."); org.apache.commons.io.FileUtils.copyDirectory(assetsDirectory, combinedAssets, new FileFilter() { /** * Excludes files matching one of the common file to * exclude. The default excludes pattern are the ones from * {org * .codehaus.plexus.util.AbstractScanner#DEFAULTEXCLUDES} * * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(File file) { for (String pattern : AbstractScanner.DEFAULTEXCLUDES) { if (AbstractScanner.match(pattern, file.getAbsolutePath())) { getLog().debug( "Excluding " + file.getName() + " from asset copy : matching " + pattern); return false; } } return true; } }); } catch (IOException e) { throw new MojoExecutionException("", e); } } File androidJar = getAndroidSdk().getAndroidJar(); File outputFile = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_"); List<String> commands = new ArrayList<String>(); commands.add("package"); commands.add("-f"); commands.add("-M"); commands.add(androidManifestFile.getAbsolutePath()); for (File resOverlayDir : overlayDirectories) { if (resOverlayDir != null && resOverlayDir.exists()) { commands.add("-S"); commands.add(resOverlayDir.getAbsolutePath()); } } if (combinedRes.exists()) { commands.add("-S"); commands.add(combinedRes.getAbsolutePath()); } else { if (resourceDirectory.exists()) { commands.add("-S"); commands.add(resourceDirectory.getAbsolutePath()); } } for (Artifact artifact : getAllRelevantDependencyArtifacts()) { if (artifact.getType().equals(APKLIB)) { final String apkLibResDir = getLibraryUnpackDirectory(artifact) + "/res"; if (new File(apkLibResDir).exists()) { commands.add("-S"); commands.add(apkLibResDir); } } } commands.add("--auto-add-overlay"); // Use the combined assets. // Indeed, aapt does not support several -A arguments. if (combinedAssets.exists()) { commands.add("-A"); commands.add(combinedAssets.getAbsolutePath()); } if (StringUtils.isNotBlank(renameManifestPackage)) { commands.add("--rename-manifest-package"); commands.add(renameManifestPackage); } if (StringUtils.isNotBlank(renameInstrumentationTargetPackage)) { commands.add("--rename-instrumentation-target-package"); commands.add(renameInstrumentationTargetPackage); } commands.add("-I"); commands.add(androidJar.getAbsolutePath()); commands.add("-F"); commands.add(outputFile.getAbsolutePath()); if (StringUtils.isNotBlank(configurations)) { commands.add("-c"); commands.add(configurations); } for (String aaptExtraArg : aaptExtraArgs) { commands.add(aaptExtraArg); } getLog().info(getAndroidSdk().getPathForTool("aapt") + " " + commands.toString()); try { executor.executeCommand(getAndroidSdk().getPathForTool("aapt"), commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } }
From source file:net.unicon.mercury.fac.rdbms.RdbmsMessageFactory.java
private IAttachment[] getAttachments(String msgId) { List rslt = new ArrayList(); try {// w ww .j av a2s . c om File folder = getAttachFolder(msgId, false); // Only bother if the attachment folder exists. if (folder != null) { // get only the folders // files were not added by the system File[] subFolders = folder.listFiles(new FileFilter() { public boolean accept(File path) { return path.isDirectory(); } }); for (int i = 0; i < subFolders.length; i++) { // The first file is our target. File[] files = subFolders[i].listFiles(new FileFilter() { public boolean accept(File path) { return path.isFile(); } }); if (files.length > 0) rslt.add(new RdbmsAttachmentImpl(i, files[0], msgId)); } } } catch (MercuryException e) { throw new RuntimeException("Error creating attachment", e); } return (IAttachment[]) rslt.toArray(new IAttachment[rslt.size()]); }
From source file:org.apache.carbondata.sdk.file.CarbonReaderTest.java
@Test public void testTimeStampAndBadRecord() throws IOException, InterruptedException { String timestampFormat = carbonProperties.getProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, CarbonCommonConstants.CARBON_TIMESTAMP_DEFAULT_FORMAT); String badRecordAction = carbonProperties.getProperty(CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION, CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION_DEFAULT); String badRecordLoc = carbonProperties.getProperty(CarbonCommonConstants.CARBON_BADRECORDS_LOC, CarbonCommonConstants.CARBON_BADRECORDS_LOC_DEFAULT_VAL); String rootPath = new File(this.getClass().getResource("/").getPath() + "../../").getCanonicalPath(); String storeLocation = rootPath + "/target/"; carbonProperties.addProperty(CarbonCommonConstants.CARBON_BADRECORDS_LOC, storeLocation) .addProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, "yyyy-MM-dd hh:mm:ss") .addProperty(CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION, "REDIRECT"); String path = "./testWriteFiles"; FileUtils.deleteDirectory(new File(path)); Field[] fields = new Field[9]; fields[0] = new Field("stringField", DataTypes.STRING); fields[1] = new Field("intField", DataTypes.INT); fields[2] = new Field("shortField", DataTypes.SHORT); fields[3] = new Field("longField", DataTypes.LONG); fields[4] = new Field("doubleField", DataTypes.DOUBLE); fields[5] = new Field("boolField", DataTypes.BOOLEAN); fields[6] = new Field("dateField", DataTypes.DATE); fields[7] = new Field("timeField", DataTypes.TIMESTAMP); fields[8] = new Field("decimalField", DataTypes.createDecimalType(8, 2)); try {/*from www . j a v a 2 s.c o m*/ CarbonWriterBuilder builder = CarbonWriter.builder().outputPath(path); CarbonWriter writer = builder.withCsvInput(new Schema(fields)).writtenBy("CarbonReaderTest").build(); for (int i = 0; i < 100; i++) { String[] row = new String[] { "robot" + (i % 10), String.valueOf(i), String.valueOf(i), String.valueOf(Long.MAX_VALUE - i), String.valueOf((double) i / 2), String.valueOf(true), "2018-05-12", "2018-05-12", "12.345" }; writer.write(row); String[] row2 = new String[] { "robot" + (i % 10), String.valueOf(i), String.valueOf(i), String.valueOf(Long.MAX_VALUE - i), String.valueOf((double) i / 2), String.valueOf(true), "2019-03-02", "2019-02-12 03:03:34", "12.345" }; writer.write(row2); } writer.close(); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } File folder = new File(path); Assert.assertTrue(folder.exists()); File[] dataFiles = folder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(CarbonCommonConstants.FACT_FILE_EXT); } }); Assert.assertNotNull(dataFiles); Assert.assertTrue(dataFiles.length > 0); CarbonReader reader = CarbonReader.builder(path, "_temp") .projection(new String[] { "stringField", "shortField", "intField", "longField", "doubleField", "boolField", "dateField", "timeField", "decimalField" }) .build(); int i = 0; while (reader.hasNext()) { Object[] row = (Object[]) reader.readNextRow(); int id = (int) row[2]; Assert.assertEquals("robot" + (id % 10), row[0]); Assert.assertEquals(Short.parseShort(String.valueOf(id)), row[1]); Assert.assertEquals(Long.MAX_VALUE - id, row[3]); Assert.assertEquals((double) id / 2, row[4]); Assert.assertEquals(true, (boolean) row[5]); long day = 24L * 3600 * 1000; Assert.assertEquals("2019-03-02", new Date((day * ((int) row[6]))).toString()); Assert.assertEquals("2019-02-12 03:03:34.0", new Timestamp((long) row[7] / 1000).toString()); i++; } Assert.assertEquals(i, 100); reader.close(); FileUtils.deleteDirectory(new File(path)); carbonProperties.addProperty(CarbonCommonConstants.CARBON_TIMESTAMP_FORMAT, timestampFormat); carbonProperties.addProperty(CarbonCommonConstants.CARBON_BAD_RECORDS_ACTION, badRecordAction); carbonProperties.addProperty(CarbonCommonConstants.CARBON_BADRECORDS_LOC, badRecordLoc); }
From source file:au.gov.aims.atlasmapperserver.URLCache.java
/** * * @param configManager/* www . jav a 2 s . c o m*/ * @param updateDataSources Use with unit tests only. * @throws IOException * @throws JSONException */ protected static void deleteCache(ConfigManager configManager, boolean updateDataSources) throws IOException, JSONException { searchResponseCache.clear(); File applicationFolder = configManager.getApplicationFolder(); // Clear cached files if (applicationFolder == null) return; diskCacheMap = new JSONObject(); File diskCacheFolder = FileFinder.getDiskCacheFolder(applicationFolder); File[] folders = diskCacheFolder.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); // Remove the files that are not listed in the cache map for (File folder : folders) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { file.delete(); } } folder.delete(); } if (updateDataSources) { // Delete data source cached files MultiKeyHashMap<Integer, String, AbstractDataSourceConfig> dataSources = configManager .getDataSourceConfigs(); AbstractDataSourceConfig dataSource = null; for (Map.Entry<Integer, AbstractDataSourceConfig> dataSourceEntry : dataSources.entrySet()) { dataSource = dataSourceEntry.getValue(); dataSource.deleteCachedState(); } } }