List of usage examples for java.io FileFilter FileFilter
FileFilter
From source file:com.opendoorlogistics.studio.scripts.list.ScriptsPanel.java
@Override public void onDirectoryChanged(File directory) { // set new directory this.directory = directory; PreferencesManager.getSingleton().setDirectory(PrefKey.SCRIPTS_DIR, directory); // check to see if watcher is pointing at wrong one if (watcher != null && watcher.getDirectory().equals(directory) == false) { shutdownDirectoryWatcher();// ww w .ja va 2 s. com } ScriptNode selected = scriptsTree.getSelectedValue(); if (isOkDirectory()) { scriptsTree.setEnabled(true); final File[] files = directory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && FilenameUtils.isExtension(pathname.getAbsolutePath(), ScriptConstants.FILE_EXT); } }); scriptsTree.setFiles(files); // reselect if (selected != null) { scriptsTree.setSelected(selected); } // init watcher if (watcher == null) { watcher = WatchSingleDirectory.launch(directory, new SwingFriendlyDirectoryChangedListener(this)); } } else { shutdownDirectoryWatcher(); // set list to empty scriptsTree.setFiles(new File[] {}); scriptsTree.setEnabled(false); } updateAppearance(); }
From source file:edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageImpl.java
/** * {@inheritDoc}/*from w w w. j av a 2s . co m*/ * <p> * For a non-null result, a directory must exist for the ID, and it must * contain a file (it may or may not contain other directories). * </p> */ @Override public String getFilename(String id) throws IOException { File dir = FileStorageHelper.getPathToIdDirectory(id, this.namespacesMap, this.rootDir); log.debug("ID '" + id + "' translates to this directory path: '" + dir + "'"); if ((!dir.exists()) || (!dir.isDirectory())) { return null; } File[] files = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile(); } }); if (files.length == 0) { return null; } if (files.length > 1) { throw new IllegalStateException( "More than one file associated with ID: '" + id + "', directory location '" + dir + "'"); } return FileStorageHelper.decodeName(files[0].getName()); }
From source file:com.amalto.workbench.dialogs.SelectImportedModulesDialog.java
@Override protected Control createDialogArea(Composite parent) { parent.getShell().setText(this.title); Composite composite = (Composite) super.createDialogArea(parent); GridLayout layout = (GridLayout) composite.getLayout(); layout.numColumns = 2;/* w w w .j av a 2s .co m*/ SashForm form = new SashForm(composite, SWT.HORIZONTAL); GridData data = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1); data.widthHint = 400; data.heightHint = 300; form.setLayoutData(data); entityViewer = createTableViewer(form, "Entities", entityprovider, new XSDTreeLabelProvider()); typeViewer = createTableViewer(form, "Types", typeprovider, new TypesLabelProvider()); form.setWeights(new int[] { 3, 5 }); Composite compositeBtn = new Composite(composite, SWT.FILL); compositeBtn.setLayoutData(new GridData(SWT.FILL, SWT.NONE, false, false, 1, 1)); compositeBtn.setLayout(new GridLayout(1, false)); Button addXSDFromLocal = new Button(compositeBtn, SWT.PUSH | SWT.FILL); addXSDFromLocal.setLayoutData(new GridData(SWT.FILL, SWT.NONE, false, false, 1, 1)); addXSDFromLocal.setText(Messages.AddXsdFromlocal); addXSDFromLocal.setToolTipText(Messages.AddXsdSchemaFromlocal); addXSDFromLocal.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { FileDialog fd = new FileDialog(shell.getShell(), SWT.SAVE); fd.setFilterExtensions(new String[] { "*.xsd" });//$NON-NLS-1$ fd.setText(Messages.ImportXSDSchema); String filename = fd.open(); if (filename == null) { return; } URL url = getSourceURL("file:///" + filename); addSchema(url, true); } }); if (exAdapter != null) { exAdapter.createDialogArea(compositeBtn); } Button impXSDFromExchange = new Button(compositeBtn, SWT.PUSH | SWT.FILL); impXSDFromExchange.setLayoutData(new GridData(SWT.FILL, SWT.NONE, false, false, 1, 1)); impXSDFromExchange.setText(Messages.ImportFromExchangeServer); impXSDFromExchange.setToolTipText(Messages.ImportSchemaFromServer); impXSDFromExchange.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { StringBuffer repository = new StringBuffer(); ImportExchangeOptionsDialog dlg = new ImportExchangeOptionsDialog(shell.getShell(), null, false, repository); dlg.setBlockOnOpen(true); int ret = dlg.open(); if (ret == Window.OK) { File dir = new File(repository.toString()); File[] fs = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".xsd"); } }); if (null == fs || fs.length == 0) { MessageDialog.openWarning(getShell(), Messages.import_schema_failed, Messages.no_schema_available); return; } for (File file : fs) { URL url = getSourceURL("file:///" + file.getPath()); addSchema(url, true); } } } }); Button addXSDFromInputDlg = new Button(compositeBtn, SWT.PUSH | SWT.FILL); addXSDFromInputDlg.setLayoutData(new GridData(SWT.FILL, SWT.NONE, false, false, 1, 1)); addXSDFromInputDlg.setText(Messages.AddXsdFromOther); addXSDFromInputDlg.setToolTipText(Messages.AddFromOtherSite); addXSDFromInputDlg.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { InputDialog id = new InputDialog(shell.getShell(), Messages.AddXsdFromOther, Messages.EnterTextUrl, "", new IInputValidator() { //$NON-NLS-1$ public String isValid(String newText) { if ((newText == null) || "".equals(newText)) { return Messages.NameNotEmpty; } return null; }; }); id.setBlockOnOpen(true); int ret = id.open(); if (ret == Window.CANCEL) { return; } URL url = getSourceURL(id.getValue()); addSchema(url, true); } }); entityViewer.setInput(addContent); typeViewer.setInput(addContent); return composite; }
From source file:com.photon.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.java
private void generateR() throws MojoExecutionException { getLog().debug("Generating R file for " + project.getPackaging()); genDirectory.mkdirs();/*ww w.java2 s . c o m*/ 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) */ 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); } } CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); List<String> commands = new ArrayList<String>(); commands.add("package"); commands.add("-m"); commands.add("-J"); commands.add(genDirectory.getAbsolutePath()); commands.add("-M"); commands.add(androidManifestFile.getAbsolutePath()); if (StringUtils.isNotBlank(customPackage)) { commands.add("--custom-package"); commands.add(customPackage); } 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)) { commands.add("-S"); commands.add(getLibraryUnpackDirectory(artifact) + File.separator + "res"); } } commands.add("--auto-add-overlay"); if (assetsDirectory.exists()) { commands.add("-A"); commands.add(assetsDirectory.getAbsolutePath()); } if (extractedDependenciesAssets.exists()) { commands.add("-A"); commands.add(extractedDependenciesAssets.getAbsolutePath()); } commands.add("-I"); commands.add(getAndroidSdk().getAndroidJar().getAbsolutePath()); if (StringUtils.isNotBlank(configurations)) { commands.add("-c"); commands.add(configurations); } getLog().info(getAndroidSdk().getPathForTool("aapt") + " " + commands.toString()); try { executor.executeCommand(getAndroidSdk().getPathForTool("aapt"), commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } project.addCompileSourceRoot(genDirectory.getAbsolutePath()); }
From source file:com.symbian.driver.core.controller.utils.ModelUtils.java
/** * Utility class that checks any PCPath, and subsitutes variables and * wildcards as appropriate./* w ww.j ava 2s.c o m*/ * * Please make certain that any corresponding Symbian Path is also changed * when using wildcards. * * @param aPCPath * The orginal IBM compatible PC Path. * @param aWildcardSupported * <code>true</code> if wildcards should be supported, * <code>false</code> otherwise. * @return The validated absaloute file paths, if * <code>aWildcardVariable</code> is <code>false</code>, or set * of files if <code>aWildcardVariable</code> is * <code>false</code>. * * @throws IOException * If there was an error accessing the files or directories. */ public static final File[] checkPCPath(final String aPCPath, final boolean aWildcardSupported) throws IOException { String lPCPathLiteral = subsituteVariables(aPCPath); File lPCPathFile = new File(lPCPathLiteral); if (aWildcardSupported && lPCPathLiteral.indexOf("*") >= 0) { File lParentDir = lPCPathFile.getParentFile(); // Setup the regular expression String lRegExpName = lPCPathFile.getName().replaceAll("\\.", "\\\\.").replaceAll("\\*", ".\\*"); lRegExpName = "^" + lRegExpName + "$"; final Pattern lFileNamePattern = Pattern.compile(lRegExpName); return lParentDir.listFiles(new FileFilter() { public boolean accept(File aPathname) { Matcher lMatcher = lFileNamePattern.matcher(aPathname.getName()); if (lMatcher.find()) { return true; } return false; } }); } // Regular file support if (lPCPathFile == null || !lPCPathFile.exists()) { ControllerUtils.LOGGER.warning("Cannot find file: " + lPCPathLiteral + ". Please use absolute paths, using the variables: ${epocroot}, ${sourceroot}, ${xmlroot}, ${build} and ${platform}."); TDConfig CONFIG = TDConfig.getInstance(); try { // Source Root support lPCPathFile = new File(TDConfig.getInstance().getPreferenceFile(TDConfig.SOURCE_ROOT) + File.separator + lPCPathLiteral); if (lPCPathFile == null || !lPCPathFile.exists()) { // XML Root support lPCPathFile = new File(TDConfig.getInstance().getPreferenceFile(TDConfig.XML_ROOT) + File.separator + lPCPathLiteral); if (lPCPathFile == null || !lPCPathFile.exists()) { // EPOC Root support lPCPathFile = new File(TDConfig.getInstance().getPreferenceFile(TDConfig.EPOC_ROOT) + File.separator + lPCPathLiteral); if (lPCPathFile == null || !lPCPathFile.exists()) { // Can't find file throw new IOException("The PC path is incorrect: " + lPCPathLiteral); } } } } catch (ParseException lParseException) { ControllerUtils.LOGGER.log(Level.WARNING, lParseException.getMessage(), lParseException); } catch (IOException lIOException) { ControllerUtils.LOGGER.log(Level.WARNING, lIOException.getMessage(), lIOException); } } // Return the one correct file return new File[] { lPCPathFile }; }
From source file:org.opendatakit.utilities.ODKFileUtils.java
/** * This routine clears all the marker files used by the various tools to * avoid re-running the initialization task. * <p>/* w ww . j a v a2 s .c o m*/ * Used in services.preferences.activities.ClearAppPropertiesActivity * * @param appName the app name */ @SuppressWarnings("unused") public static void clearConfiguredToolFiles(String appName) { File dataDir = new File(ODKFileUtils.getDataFolder(appName)); File[] filesToDelete = dataDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.isDirectory()) { return false; } String name = pathname.getName(); int idx = name.lastIndexOf('.'); if (idx == -1) { return false; } String type = name.substring(idx + 1); return "version".equals(type); } }); for (File f : filesToDelete) { if (!f.delete()) { throw new RuntimeException("Could not delete file " + f.getAbsolutePath()); } } }
From source file:net.unicon.demetrius.fac.filesystem.FsResourceFactory.java
/** * Returns the contents of a given folder. * @param f/*from w w w . j a v a 2 s. c om*/ * The <code>IFolder</code> for which the contents will be returned. * @param rt * The <code>ResourceType[]</code> denotes types of resources to return. * @return * An array of <code>IResource</code> objects for the given folder. */ public IResource[] getContents(IFolder f, ResourceType[] rt) throws DemetriusException { // Assertions. if (f == null) { String msg = "Argument 'f [IFolder]' cannot be null."; throw new IllegalArgumentException(msg); } if (rt == null) { String msg = "Argument 'rt' cannot be null."; throw new IllegalArgumentException(msg); } IResource[] contents = new IResource[0]; File[] files = null; File[] fileTypes = null; File[] folderTypes = null; File dir = new File(evaluateFsPath(dataSource, f)); for (int i = 0; i < rt.length; i++) { if (rt[i].equals(ResourceType.FOLDER)) { folderTypes = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory(); } }); if (folderTypes != null) { files = folderTypes; } else { throw new DemetriusException("The abstract pathname does not denote a directory."); } } if (rt[i].equals(ResourceType.FILE)) { fileTypes = dir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile(); } }); files = fileTypes; } } if (rt.length > 1) { files = new File[folderTypes.length + fileTypes.length]; System.arraycopy(folderTypes, 0, files, 0, folderTypes.length); System.arraycopy(fileTypes, 0, files, folderTypes.length, fileTypes.length); } contents = new IResource[files.length]; File curr = null; for (int i = 0; i < files.length; i++) { curr = files[i]; if (curr.isDirectory()) { IResource resource = new FolderImpl(curr.getName(), this, 0, new Date(curr.lastModified()), f, curr.isHidden()); contents[i] = resource; } else { IResource resource = new FileImpl(curr.getName(), this, curr.length(), new Date(curr.lastModified()), f, curr.isHidden(), null); contents[i] = resource; } } return contents; }
From source file:org.apache.directory.server.jndi.ServerContextFactory.java
private void loadLdifs(DirectoryService service) throws NamingException { ServerStartupConfiguration cfg = (ServerStartupConfiguration) service.getConfiguration() .getStartupConfiguration();// w w w. j a v a2s. c o m // log and bail if property not set if (cfg.getLdifDirectory() == null) { log.info("LDIF load directory not specified. No LDIF files will be loaded."); return; } // log and bail if LDIF directory does not exists if (!cfg.getLdifDirectory().exists()) { log.warn("LDIF load directory '" + getCanonical(cfg.getLdifDirectory()) + "' does not exist. No LDIF files will be loaded."); return; } // get an initial context to the rootDSE for creating the LDIF entries Hashtable env = (Hashtable) service.getConfiguration().getEnvironment().clone(); env.put(Context.PROVIDER_URL, ""); DirContext root = (DirContext) this.getInitialContext(env); // make sure the configuration area for loaded ldif files is present ensureLdifFileBase(root); // if ldif directory is a file try to load it if (!cfg.getLdifDirectory().isDirectory()) { if (log.isInfoEnabled()) { log.info("LDIF load directory '" + getCanonical(cfg.getLdifDirectory()) + "' is a file. Will attempt to load as LDIF."); } Attributes fileEntry = getLdifFileEntry(root, cfg.getLdifDirectory()); if (fileEntry != null) { String time = (String) fileEntry.get("createTimestamp").get(); if (log.isInfoEnabled()) { log.info("Load of LDIF file '" + getCanonical(cfg.getLdifDirectory()) + "' skipped. It has already been loaded on " + time + "."); } return; } LdifFileLoader loader = new LdifFileLoader(root, cfg.getLdifDirectory(), cfg.getLdifFilters()); loader.execute(); addFileEntry(root, cfg.getLdifDirectory()); return; } // get all the ldif files within the directory (should be sorted alphabetically) File[] ldifFiles = cfg.getLdifDirectory().listFiles(new FileFilter() { public boolean accept(File pathname) { boolean isLdif = pathname.getName().toLowerCase().endsWith(".ldif"); return pathname.isFile() && pathname.canRead() && isLdif; } }); // log and bail if we could not find any LDIF files if (ldifFiles == null || ldifFiles.length == 0) { log.warn("LDIF load directory '" + getCanonical(cfg.getLdifDirectory()) + "' does not contain any LDIF files. No LDIF files will be loaded."); return; } // load all the ldif files and load each one that is loaded for (int ii = 0; ii < ldifFiles.length; ii++) { Attributes fileEntry = getLdifFileEntry(root, ldifFiles[ii]); if (fileEntry != null) { String time = (String) fileEntry.get("createTimestamp").get(); log.info("Load of LDIF file '" + getCanonical(ldifFiles[ii]) + "' skipped. It has already been loaded on " + time + "."); continue; } LdifFileLoader loader = new LdifFileLoader(root, ldifFiles[ii], cfg.getLdifFilters()); int count = loader.execute(); log.info("Loaded " + count + " entries from LDIF file '" + getCanonical(ldifFiles[ii]) + "'"); if (fileEntry == null) { addFileEntry(root, ldifFiles[ii]); } } }
From source file:eu.qualimaster.easy.extension.modelop.ModelModifier.java
/** * Creates a copy of the build model and place the files parallel to the copied variability model files. * @return The root folder of the copied model files. *///from w w w. j a va 2 s . c o m private File copyBuildModel() { File srcFolder = new File(baseLocation, "EASy"); File vilFolder = new File(targetFolder, COPIED_MODELS_LOCATION); vilFolder.mkdirs(); try { FileUtils.copyDirectory(srcFolder, vilFolder, new FileFilter() { @Override public boolean accept(File pathname) { String fileName = pathname.getName(); return pathname.isDirectory() || fileName.endsWith("vil") || fileName.endsWith("vtl") || fileName.endsWith("rtvtl"); } }); } catch (IOException e) { Bundle.getLogger(ModelModifier.class).exception(e); } return vilFolder; }
From source file:es.uvigo.ei.sing.adops.datatypes.ProjectExperiment.java
@Override public void clear() { final FileFilter filter = new FileFilter() { @Override//from w w w .ja v a 2 s.com public boolean accept(File pathname) { if (pathname.equals(ProjectExperiment.this.getNotesFile()) || pathname.equals(ProjectExperiment.this.getPropertiesFile()) || pathname.equals(ProjectExperiment.this.getFastaFile()) || pathname.equals(ProjectExperiment.this.getNamesFile()) || pathname.equals(ProjectExperiment.this.getFilesFolder())) { return false; } return true; } }; for (File file : this.getFolder().listFiles(filter)) { if (file.isFile()) file.delete(); else if (file.isDirectory()) try { FileUtils.deleteDirectory(file); } catch (IOException e) { } } try { FileUtils.cleanDirectory(this.getFilesFolder()); } catch (IOException e) { } new File(this.getFilesFolder(), TCoffeeOutput.OUTPUT_FOLDER_NAME).mkdirs(); new File(this.getFilesFolder(), MrBayesOutput.OUTPUT_FOLDER_NAME).mkdirs(); new File(this.getFilesFolder(), CodeMLOutput.OUTPUT_FOLDER_NAME).mkdirs(); this.result = null; this.setChanged(); this.notifyObservers(); }