List of usage examples for java.io FilenameFilter FilenameFilter
FilenameFilter
From source file:de.uzk.hki.da.metadata.XmpCollector.java
/** * Collect./*from w w w . j ava2s . co m*/ * * @param xmpFiles list of xmp files to collect * @param targetFile the target file * @throws IOException */ public static void collect(WorkArea wa, List<DAFile> xmpFiles, File targetFile) throws IOException { Model model = ModelFactory.createDefaultModel(); for (DAFile dafile : xmpFiles) { File file = wa.toFile(dafile); logger.debug("collecting XMP file {}", file.getAbsolutePath()); StringWriter xmpWriter = new StringWriter(); try { // preprocess xmp in order to make it RDF/XML compatible BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedWriter writer = new BufferedWriter(xmpWriter); logger.debug("Read the xmp file..."); String currentLine; while ((currentLine = reader.readLine()) != null) { String trimmedLine = currentLine.trim(); if (trimmedLine.startsWith("<?xpacket")) continue; if (trimmedLine.contains("x:xmpmeta")) continue; writer.write(currentLine); } reader.close(); writer.close(); } catch (Exception e) { throw new RuntimeException("Unable to preprocess XMP file: " + file.getAbsolutePath(), e); } final String baseName = FilenameUtils.removeExtension(file.getName()); String[] list = file.getParentFile().list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { String baseName2 = FilenameUtils.removeExtension(name); if (baseName.equals(baseName2) && !name.toLowerCase().endsWith(".xmp")) return true; else return false; } }); if (list.length > 1) { logger.warn("More than one matching file for sidecar file {}. Skipping ...", file.getName()); continue; } else if (list.length < 1) { logger.warn("No matching file for sidecar file {}. Skipping ...", file.getName()); continue; } logger.debug("found matching file {}", list[0]); // read XMP with matching file as base name // use "http://www.danrw.de/temp/" as a pseudo base URI in order to allow relative resource URIs model.read(new StringReader(xmpWriter.toString().trim().replaceFirst("^([\\W]+)<", "<")), "http://www.danrw.de/temp/" + list[0]); } FileOutputStream targetStream = null; try { targetStream = new FileOutputStream(targetFile); model.write(targetStream, "RDF/XML-ABBREV", "http://www.danrw.de/temp/"); } catch (FileNotFoundException e) { throw new RuntimeException("Could not write XMP collection file: " + targetFile.getAbsolutePath()); } finally { if (targetStream != null) { targetStream.close(); } } }
From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java
/** * Return a collection containing the resource names which passed the filter. * * @param filter// ww w.j a v a 2 s.co m * @return * @throws IOException */ public static String[] findResources(Filter filter) { Collection resources = new ArrayList(); ClassLoader cl = ClasspathResourcesUtil.class.getClassLoader(); // if the classloader is an URLClassloader we have a better method for discovering resources // whis will also fetch files from jars outside WEB-INF/lib, useful during development if (cl instanceof URLClassLoader) { // tomcat classloader is org.apache.catalina.loader.WebappClassLoader URL[] urls = ((URLClassLoader) cl).getURLs(); for (int j = 0; j < urls.length; j++) { URL url = urls[j]; File tofile = new File(url.getFile()); collectFiles(resources, tofile, filter); } } else { // no way, we have to assume a standard war structure and look in the WEB-INF/lib and WEB-INF/classes dirs // read the jars in the lib dir File dir = new File(Path.getAbsoluteFileSystemPath("WEB-INF/lib")); //$NON-NLS-1$ if (dir.exists()) { File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File file, String name) { return name.endsWith(".jar"); } }); for (int i = 0; i < files.length; i++) { collectFiles(resources, files[i], filter); } } // read files in WEB-INF/classes collectFiles(resources, new File(Path.getAbsoluteFileSystemPath("WEB-INF/classes")), filter); } return (String[]) resources.toArray(new String[resources.size()]); }
From source file:br.edimarmanica.trinity.check.CheckAttributeNotFound.java
private void readOffSets() { /**//from w w w .ja va 2 s . c o m * Lendos os Run02.NR_SHARED_PAGES primeiros elementos de cada offset */ File dir = new File(Paths.PATH_TRINITY + site.getPath() + "/offset"); for (int nrOffset = 0; nrOffset < dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".csv"); } }).length; nrOffset++) { List<Map<String, String>> offset = new ArrayList<>(); //cada arquivo um offset try (Reader in = new FileReader(dir.getAbsoluteFile() + "/result_" + nrOffset + ".csv")) { try (CSVParser parser = new CSVParser(in, CSVFormat.EXCEL)) { int nrRegistro = 0; for (CSVRecord record : parser) { for (int nrRegra = 0; nrRegra < record.size(); nrRegra++) { String value; try { value = formatValue(Preprocessing.filter(record.get(nrRegra))); } catch (InvalidValue ex) { value = ""; } if (nrRegistro == 0) { Map<String, String> regra = new HashMap<>(); regra.put(record.get(0), value); offset.add(regra); } else { offset.get(nrRegra).put(record.get(0), value); } } nrRegistro++; } } offsets.add(offset); } catch (FileNotFoundException ex) { Logger.getLogger(CheckAttributeNotFound.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CheckAttributeNotFound.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:org.red5.server.plugin.PluginLauncher.java
public void afterPropertiesSet() throws Exception { ApplicationContext common = (ApplicationContext) applicationContext.getBean("red5.common"); Server server = (Server) common.getBean("red5.server"); //server should be up and running at this point so load any plug-ins now //get the plugins dir File pluginsDir = new File(System.getProperty("red5.root"), "plugins"); File[] plugins = pluginsDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { //lower the case String tmp = name.toLowerCase(); //accept jars and zips return tmp.endsWith(".jar") || tmp.endsWith(".zip"); }/*from w w w .j av a2s. c om*/ }); if (plugins != null) { IRed5Plugin red5Plugin = null; log.debug("{} plugins to launch", plugins.length); for (File plugin : plugins) { JarFile jar = null; Manifest manifest = null; try { jar = new JarFile(plugin, false); manifest = jar.getManifest(); } catch (Exception e1) { log.warn("Error loading plugin manifest: {}", plugin); } finally { jar.close(); } if (manifest == null) { continue; } Attributes attributes = manifest.getMainAttributes(); if (attributes == null) { continue; } String pluginMainClass = attributes.getValue("Red5-Plugin-Main-Class"); if (pluginMainClass == null || pluginMainClass.length() <= 0) { continue; } // attempt to load the class; since it's in the plugins directory this should work ClassLoader loader = common.getClassLoader(); Class<?> pluginClass; String pluginMainMethod = null; try { pluginClass = Class.forName(pluginMainClass, true, loader); } catch (ClassNotFoundException e) { continue; } try { //handle plug-ins without "main" methods pluginMainMethod = attributes.getValue("Red5-Plugin-Main-Method"); if (pluginMainMethod == null || pluginMainMethod.length() <= 0) { //just get an instance of the class red5Plugin = (IRed5Plugin) pluginClass.newInstance(); } else { Method method = pluginClass.getMethod(pluginMainMethod, (Class<?>[]) null); Object o = method.invoke(null, (Object[]) null); if (o != null && o instanceof IRed5Plugin) { red5Plugin = (IRed5Plugin) o; } } //register and start if (red5Plugin != null) { //set top-level context red5Plugin.setApplicationContext(applicationContext); //set server reference red5Plugin.setServer(server); //register the plug-in to make it available for lookups PluginRegistry.register(red5Plugin); //start the plugin red5Plugin.doStart(); } log.info("Loaded plugin: {}", pluginMainClass); } catch (Throwable t) { log.warn("Error loading plugin: {}; Method: {}", pluginMainClass, pluginMainMethod); log.error("", t); } } } else { log.info("Plugins directory cannot be accessed or doesnt exist"); } }
From source file:com.u2apple.tool.dao.DeviceXmlDaoJaxbImpl.java
private void loadVids() throws JAXBException { File dir = new File(Configuration.getProperty(Constants.VID_DIR)); File[] files = dir.listFiles(new FilenameFilter() { @Override/*from w ww .j av a 2 s . co m*/ public boolean accept(File dir, String name) { return Pattern.matches(VID_FILE_NAME_PATTERN, name); } }); if (files != null) { for (File file : files) { JAXBContext jaxbContext = JAXBContext.newInstance(VID.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); VID vid = (VID) jaxbUnmarshaller.unmarshal(file); if (vid != null) { staticMapFile.getVids().add(vid); } } } }
From source file:ClassFinder.java
private static String[] addJarsInPath(String[] paths) { Set<String> fullList = new HashSet<String>(); for (final String path : paths) { fullList.add(path); // Keep the unexpanded path // TODO - allow directories to end with .jar by removing this check? if (!path.endsWith(DOT_JAR)) { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { String[] jars = dir.list(new FilenameFilter() { public boolean accept(File f, String name) { return name.endsWith(DOT_JAR); }/*from www . j av a 2s . c o m*/ }); fullList.addAll(Arrays.asList(jars)); } } } return fullList.toArray(new String[0]); }
From source file:MyFormApp.java
public static File[] getFileList(String dirPath) { // ? pdf File dir = new File(dirPath); File[] fileList = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { // return name.endsWith(".pdf"); }//from w ww.j a v a 2 s . c o m }); return fileList; }
From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java
/** * Returns snapshot at index modulo the length of the list, if index is < 0, it returns a random snapshot *//*from w w w .j a va 2s.c o m*/ private static List<WifiReading> getSnapshot(int index, Context c) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can at least read the external storage File root = c.getExternalCacheDir(); File[] snapshotFiles = root.listFiles(new FilenameFilter() { public boolean accept(File dir, String filename) { if (filename.endsWith(FILE_EXTENSION)) { return true; } else { return false; } } }); if (snapshotFiles.length > 0) { if (index < 0) { Random rand = new Random(); index = rand.nextInt(snapshotFiles.length); } else { index = index % snapshotFiles.length; } try { // read file into a string FileInputStream fstream = new FileInputStream(snapshotFiles[index]); Log.d(TAG, snapshotFiles[index].getName()); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String fileContents = ""; String strLine; while ((strLine = br.readLine()) != null) { fileContents += strLine; } // make a json array out of the string JSONArray json = new JSONArray(fileContents); // parse the json array return jsonToReadings(json); } catch (Exception e) { Log.e(TAG, "Could not read file."); return null; } } else { // there are no cached snapshots return null; } } else { // we cannot read the external storage return null; } }
From source file:jp.co.tis.gsp.tools.dba.mojo.ExecuteDdlMojo.java
@Override protected void executeMojoSpec() throws MojoExecutionException, MojoFailureException { DriverManagerUtil.registerDriver(driver); Dialect dialect = DialectFactory.getDialect(url); dialect.dropAll(user, password, adminUser, adminPassword, schema); dialect.createUser(user, password, adminUser, adminPassword); FilenameFilter sqlFileFilter = new FilenameFilter() { @Override/* ww w . j av a 2 s .c om*/ public boolean accept(File dir, String name) { return name.endsWith(".sql"); } }; // ?.sql? List<File> files = new ArrayList<File>(Arrays.asList(ddlDirectory.listFiles(sqlFileFilter))); if (extraDdlDirectory != null && extraDdlDirectory.isDirectory()) { Collections.addAll(files, extraDdlDirectory.listFiles(sqlFileFilter)); } // ?? ???? Collections.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { return f1.getName().compareTo(f2.getName()); } }); try { executeBySqlFiles(files.toArray(new File[files.size()])); } catch (Exception e) { getLog().warn(e); } }
From source file:com.shazam.fork.TestClassScanner.java
private static List<TestClass> getTestClassesFromDexFile(File dexFilesFolder) { try {//ww w .ja va2s. co m File[] dexFiles = dexFilesFolder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("classes") && name.endsWith(".dex"); } }); List<TestClass> testClasses = new ArrayList<>(); for (File file : dexFiles) { DexFile dexFile = new DexFile(file); List<ClassDefItem> items = dexFile.ClassDefsSection.getItems(); for (ClassDefItem classDefItem : items) { final String typeDescriptor = classDefItem.getClassType().getTypeDescriptor(); if (TEST_CLASS_PATTERN.matcher(typeDescriptor).matches()) { TestClass testClass = getTestClass(typeDescriptor); testClasses.add(testClass); try { collectMethods(classDefItem, testClass); visitMethodAnnotations(classDefItem, new SuppressedMethodFlagSetter(testClass)); } catch (Throwable t) { throw new RuntimeException(t); } } } } return testClasses; } catch (IOException e) { throw new RuntimeException(e); } }