List of usage examples for java.io FilenameFilter FilenameFilter
FilenameFilter
From source file:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java
/** * Replace the instrument configuration file if needed Delete the result database and files * @throws Exception//from w ww . j a v a 2 s . co m */ protected void deleteDeviceData() { // Overwrite the CardioSoft configuration file overwriteIniFile(getSettingsFileName()); overwriteIniFile(getWinSettingsFileName()); // Initialize the CardioSoft database FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".BTR")); } }; try { File[] backupDatabaseFiles = new File(getInitPath()).listFiles(filter); if (backupDatabaseFiles.length > 0) { for (int i = 0; i < backupDatabaseFiles.length; i++) { FileUtil.copyFile(backupDatabaseFiles[i], new File(getDatabasePath(), backupDatabaseFiles[i].getName())); } } else { File[] databaseFiles = new File(getDatabasePath()).listFiles(filter); for (int i = 0; i < databaseFiles.length; i++) { FileUtil.copyFile(databaseFiles[i], new File(getInitPath(), databaseFiles[i].getName())); } } } catch (Exception couldNotInitDbs) { throw new RuntimeException("Error initializing ECG database files", couldNotInitDbs); } // Delete BTrieve record file. File btrRecordFile = new File(getDatabasePath(), getBtrRecordFileName()); if (!btrRecordFile.delete()) { log.warn("Could not delete BTrieve record file."); } File reportFile = new File(getExportPath(), getXmlFileName()); if (!reportFile.delete()) { log.warn("Could not delete Cardiosoft XML output file!"); } reportFile = new File(getExportPath(), getPdfFileNameRestingEcg()); if (!reportFile.delete()) { log.warn("Could not delete Resting Ecg PDF output file!"); } reportFile = new File(getExportPath(), getPdfFileNameFullEcg()); if (!reportFile.delete()) { log.warn("Could not delete Full Ecg PDF output file!"); } }
From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java
@Before public void setup() throws Exception { File folder = new File("/tmp"); File[] files = folder.listFiles(new FilenameFilter() { @Override//from ww w .j a v a 2 s .c o m public boolean accept(final File dir, final String name) { return name.startsWith("test.db"); } }); for (final File file : files) { if (!file.delete()) { System.out.println("Failed to remove " + file.getAbsolutePath()); } } mongo.dropDatabase(DB_NAME); mongo.dropDatabase("local"); mongo.dropDatabase("admin"); mongo.dropDatabase("mongo"); mongo.getDB(DB_NAME).dropDatabase(); mongo.getDB("local").dropDatabase(); mongo.getDB("admin").dropDatabase(); mongo.getDB("mongo").dropDatabase(); db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).remove(new BasicDBObject()); mongo.getDB("mongo").getCollection("metadata").remove(new BasicDBObject()); db.createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null); BasicDBObject index = new BasicDBObject("name", 1); index.put("version.value", 1); db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).ensureIndex(index, "name", true); if (notRegistered) { notRegistered = false; try { // Create initial context System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory"); InitialContext ic = new InitialContext(); ic.createSubcontext("java:"); ic.createSubcontext("java:/comp"); ic.createSubcontext("java:/comp/env"); ic.createSubcontext("java:/comp/env/jdbc"); JdbcConnectionPool ds = JdbcConnectionPool.create( "jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa"); ic.bind("java:/mydatasource", ds); } catch (NamingException ex) { throw new IllegalStateException(ex); } } else { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); stmt.execute("DROP ALL OBJECTS "); stmt.close(); } }
From source file:eu.crowdrec.contest.sender.RequestSenderORP.java
/** * read logFile then sends line by line to server. * /* w ww .j a v a 2s .c om*/ * @param inLogFileName * path to log file. That can be a zip file or text file. * @param outLogFile * path to outLog file. The outLog file should be analyzed by the evaluator. * if the filename is null; no output will be generated * @param serverURL * URL of the server */ public static void sender(final String inLogFileName, final String outLogFile, final String serverURL) { // handle the log file // check type of file // try to read the defined logFile BufferedReader br = null; BufferedWriter bw = null; try { // if outLogFile name is not null, create an output file if (outLogFile != null && outLogFile.length() > 0) { bw = new BufferedWriter(new FileWriter(new File(outLogFile), false)); } // support a list of files in a directory File inLogFile = new File(inLogFileName); InputStream is; if (inLogFile.isFile()) { is = new FileInputStream(inLogFileName); // support gZip files if (inLogFile.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } } else { // if the input is a directory, consider all files based on a pattern File[] childs = inLogFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { final String fileName = name.toLowerCase(); return fileName.startsWith("contest.log"); } }); if (childs == null || childs.length == 0) { throw new IOException("invalid inLogFileName or empty directory"); } Arrays.sort(childs, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); Vector<InputStream> isChilds = new Vector<InputStream>(); for (int i = 0; i < childs.length; i++) { InputStream tmpIS = new FileInputStream(childs[i]); // support gZip files if (childs[i].getName().toLowerCase().endsWith(".gz")) { tmpIS = new GZIPInputStream(tmpIS); } isChilds.add(tmpIS); } is = new SequenceInputStream(isChilds.elements()); } // read the log file line by line br = new BufferedReader(new InputStreamReader(is)); try { for (String line = br.readLine(); line != null; line = br.readLine()) { // ignore invalid lines and header if (line.startsWith("null") || line.startsWith("#")) { continue; } String[] token = parseLogLine(line); if (token == null) { System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println(line); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); System.err.println( "HHHHHHHHHHHHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEEEELLLLLLLLLLLLLLLLPPPPPPPPPPPPPPP"); continue; } // use a threadPool RequestSenderThread t = new RequestSenderThread(token[0], token[1], token[2], serverURL, bw); try { // try to limit the speed of sending requests if (Thread.activeCount() > 1000) { if (logger.isDebugEnabled()) { logger.debug("Thread.activeCount() = " + Thread.activeCount()); } Thread.sleep(200); } } catch (Exception e) { logger.info(e.toString()); } t.start(); } } catch (IOException e) { logger.warn(e.toString(), e); } } catch (FileNotFoundException e) { logger.error("logFile not found e:" + e.toString()); } catch (IOException e) { logger.error("reading the logFile failed e:" + e.toString()); } finally { if (br != null) { try { br.close(); } catch (IOException e) { logger.debug("close read-log file failed"); } } if (bw != null) { try { // wait for ensuring that all request are finished // this simplifies the management of thread and worked fine for all test machines Thread.sleep(5000); bw.flush(); } catch (Exception e) { logger.debug("close write-log file failed"); } } } }
From source file:com.impetus.ankush.agent.service.ServiceMonitor.java
/** * Method to collect service status by technology * /*from w ww. ja v a2 s . c om*/ * @return */ private Map<String, Map<String, Boolean>> collectServiceStatus() { // Service Conf directory String serviceConfDir = conf.getStringValue(Constant.PROP_SERVICE_CONF_DIR); // ServiceConf directory file object. File serviceConfigDir = new File(serviceConfDir); LOGGER.info("ServiceConfDirectory:" + serviceConfDir); // Getting list of files whose name ends with XML extension in agent // services folder. File[] files = serviceConfigDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // file name ends with XML extension. return name.endsWith(Constant.File_Extension.XML); } }); Map<String, Map<String, Boolean>> serviceStatus = new HashMap<String, Map<String, Boolean>>(); // Add agent status Map<String, Boolean> agentStatus = new HashMap<String, Boolean>(); agentStatus.put(Constant.AGENT, true); serviceStatus.put(Constant.AGENT, agentStatus); // iterate over the files. for (File file : files) { LOGGER.info("Service File:" + file.getName()); String componentName = FilenameUtils.getBaseName(file.getName()); try { // java XML context object. JAXBContext jc = JAXBContext.newInstance(ServiceConfiguration.class); // Input stream reader. InputStream inputStream = new FileInputStream(file); // Buffered reader BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); // Creating un marshaller Unmarshaller unmarshaller = jc.createUnmarshaller(); // Getting component services ServiceConfiguration services = (ServiceConfiguration) unmarshaller.unmarshal(br); // Adding component service status against component. serviceStatus.put(componentName, getServiceStatus(services.getTypeServices())); LOGGER.info("Service Status Object:" + serviceStatus); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage(), e); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } return serviceStatus; }
From source file:com.qmetry.qaf.automation.util.FileUtil.java
public static FilenameFilter getFileFilterFor(final StringComparator c, final String... qnames) { FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { for (String qname : qnames) { if (StringUtil.isNotBlank(qname) && c.compareIgnoreCase(name, qname)) return true; }//from ww w . ja v a 2s. com return false; } }; return filter; }
From source file:com.crosstreelabs.cognitio.common.ExtensionLoader.java
protected void handlePath(final String path) throws MalformedURLException { if (path == null || path.isEmpty()) { return;/*ww w. j a v a 2s.co m*/ } if (!path.trim().toLowerCase().endsWith(File.separator)) { addJar(path); return; } // We're dealing with a directory, so let's find all jars File dir = new File(path); File[] files = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File file, String name) { return name.endsWith(".jar"); } }); for (File file : files) { addJar(file.getAbsolutePath()); } }
From source file:org.taverna.server.master.localworker.LocalWorkerState.java
private static String guessWorkflowScript() { File utilDir = new File(DEFAULT_WORKER_JAR).getParentFile(); File[] dirs = utilDir.listFiles(new FilenameFilter() { @Override/*from ww w. j a v a 2 s . c o m*/ public boolean accept(File dir, String name) { return name.startsWith("taverna-commandline-"); } }); assert dirs.length > 0; return new File(dirs[0], "executeworkflow.sh").toString(); }
From source file:com.momock.util.Logger.java
public static void open(Context context, final String name, int maxLogFiles, int level) { if (!enabled) return;//ww w.ja v a 2s . c o m appName = context.getPackageName(); logName = name; logFileName = logName + "[" + new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date()) + "].log"; if (logStream == System.out) { File logDir = null; try { if (getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { logDir = Environment.getExternalStorageDirectory(); } else if (context != null) { logDir = context.getCacheDir(); } if (logDir != null) { android.util.Log.d("Logger", logDir.getAbsolutePath()); String[] fs = logDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return filename.startsWith(logName + "[") && filename.endsWith("].log"); } }); List<String> allLogs = new ArrayList<String>(); for (int i = 0; fs != null && i < fs.length; i++) allLogs.add(fs[i]); Collections.sort(allLogs); for (int i = 0; i < allLogs.size() - maxLogFiles + 1; i++) new File(logDir, allLogs.get(i)).delete(); logStream = new PrintStream(new FileOutputStream(new File(logDir, logFileName), false)); } } catch (IOException e) { android.util.Log.e("Logger", "Fails to create log file!", e); } } logLevel = level; logStream.println("========== Logger Begin =========="); logStream.flush(); }
From source file:istata.service.StataService.java
/** * obtain the list of potetial matches in the file system for a given input * /*w w w .j av a 2 s . co m*/ * @param filter * @param pos * @param from * @param to * @return */ public List<ContentLine> filteredFiles(String filter, int pos, int from, int to) { int p = (pos == -1 || pos > filter.length()) ? filter.length() : pos; String before = filter.substring(0, p); List<ContentLine> result = new ArrayList<ContentLine>(); /* * check for a dangling " before the position */ int count = StataUtils.countChar(before, "\""); if (count % 2 != 0) { int beginquote = before.lastIndexOf('"'); String orgtoken = before.substring(beginquote + 1); String token = expandPath(orgtoken); // potential matching files (might be large?) List<File> potentials = new ArrayList<File>(); File absFile = new File(token); final String endname; if (absFile.getName().equals("")) { endname = token; } else { endname = absFile.getName(); } FilenameFilter fnf = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(endname); } }; FilenameFilter all = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !name.startsWith("."); } }; if (!token.equals("") || absFile.isDirectory()) { // absolute file File parent = null; if (absFile.isDirectory()) { parent = absFile; fnf = all; } else { parent = absFile.getParentFile(); } if (parent != null) { File[] fs = parent.listFiles(fnf); if (fs != null) potentials.addAll(Arrays.asList(fs)); } } // work out if rest needs to be trimmed String after = filter.substring(p); int endquote = p; // check whether we are in an existing string int aftercount = StataUtils.countChar(after, "\""); if (aftercount % 2 != 0) { int firstquote = after.indexOf('"'); endquote += firstquote + 1; } int i = 0; for (File f : potentials) { ContentLine srl = new ContentLine(); Map<String, Object> model = new HashMap<String, Object>(); char s = (orgtoken.length() > 0) ? orgtoken.charAt(0) : 'x'; String filename = reducePath(s, f); String repltext = filter.substring(0, beginquote + 1) + filename + "\"" + filter.substring(endquote); try { model.put("text", URLEncoder.encode(repltext, "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } model.put("filename", filename); model.put("pos", beginquote + filename.length() + 1); model.put("from", from); model.put("to", to); String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "items/file.vm", "UTF-8", model); srl.setContent(text); srl.setLine(i++); result.add(srl); } } return result; }
From source file:org.openmeetings.app.documents.GeneratePDF.java
/** * Generates PDF using JOD Library (external library) *//*from w w w . j av a 2 s . c om*/ public HashMap<String, String> doJodConvert(String current_dir, String fileFullPath, String destinationFolder, String outputfile) { try { String jodPath = cfgManagement.getConfValue("jod.path", String.class, "./jod"); String officePath = cfgManagement.getConfValue("office.path", String.class, ""); File jodFolder = new File(jodPath); if (!jodFolder.exists() || !jodFolder.isDirectory()) { throw new Exception("Path to JOD Library folder does not exist"); } ArrayList<String> argv = new ArrayList<String>(); argv.add("java"); if (officePath.trim().length() > 0) { argv.add("-Doffice.home=" + officePath); } String jodConverterJar = ""; for (String jarFiles : jodFolder.list(new FilenameFilter() { public boolean accept(File file1, String name) { return name.endsWith(".jar"); } })) { argv.add("-cp"); if (jarFiles.startsWith("jodconverter")) { jodConverterJar = jarFiles; } argv.add(jodFolder.getAbsolutePath() + File.separatorChar + jarFiles); } if (jodConverterJar.length() == 0) { throw new Exception("Could not find jodConverter JAR file in JOD folder"); } argv.add("-jar"); argv.add(jodFolder.getAbsolutePath() + File.separatorChar + jodConverterJar); argv.add(fileFullPath); argv.add(destinationFolder + outputfile + ".pdf"); return ProcessHelper.executeScript("doJodConvert", argv.toArray(new String[argv.size()])); } catch (Exception ex) { log.error("doJodConvert", ex); return buildErrorMessage("doJodConvert", ex.getMessage(), ex); } }