List of usage examples for java.io File isFile
public boolean isFile()
From source file:adalid.jaas.google.GoogleRecaptcha.java
private static String secretKey() { logger.log(Level.INFO, VALIDATOR_KEY + " = {0}", GoogleRecaptcha.class.getName()); String secretKey = System.getProperties().getProperty(SECRET_KEY_PROPERTY_KEY); if (secretKey == null || secretKey.isEmpty()) { String path = secretKeyFilePath(); File file = new File(path); if (file.isFile()) { logger.log(TRACE, SECRET_KEY_FILE_PROPERTY_KEY + " = {0}", path); try { secretKey = new Scanner(file).useDelimiter("\\Z").next(); } catch (FileNotFoundException ex) { logger.log(Level.WARNING, SECRET_KEY_FILE_PROPERTY_KEY + " {0} is missing", path); }/* w ww. ja va 2 s. co m*/ } else { logger.log(Level.WARNING, SECRET_KEY_FILE_PROPERTY_KEY + " {0} is missing or invalid", path); } } if (secretKey == null || secretKey.isEmpty()) { logger.log(Level.WARNING, MISSING_SECRET_KEY); return DEFAULT_SECRET_KEY; } return secretKey; }
From source file:de.shadowhunt.sonar.plugins.ignorecode.batch.IgnoreCoverageDecorator.java
static List<CoveragePattern> loadPatterns(final Configuration configuration) { if (configuration == null) { return Collections.emptyList(); }/* w w w.j av a 2 s . c o m*/ final String fileLocation = configuration.getString(CONFIG_FILE); if (StringUtils.isBlank(fileLocation)) { LOGGER.info("no ignore file configured for property: {}", CONFIG_FILE); return Collections.emptyList(); } final File ignoreFile = new File(fileLocation); if (!ignoreFile.isFile()) { LOGGER.error("could not find ignore file: {}", ignoreFile); return Collections.emptyList(); } FileInputStream fis = null; try { fis = new FileInputStream(ignoreFile); final List<CoveragePattern> patterns = CoveragePattern.parse(fis); LOGGER.info("loaded {} coverage ignores from {}", patterns.size(), ignoreFile); return patterns; } catch (final Exception e) { throw new SonarException("could not load ignores for file: " + ignoreFile, e); } finally { IOUtils.closeQuietly(fis); } }
From source file:org.apiwatch.util.IO.java
public static APIScope getAPIData(String source, String format, String encoding, String username, String password) throws IOException, SerializationError, HttpException { File file = new File(source); APIScope scope = null;/* www . j a v a 2 s . com*/ if (file.isFile()) { if (format == null) { /* get format from file extension */ format = source.substring(source.lastIndexOf('.') + 1); } InputStream in = new FileInputStream(file); Reader reader = new InputStreamReader(in, encoding); scope = Serializers.loadAPIScope(reader, format); reader.close(); in.close(); } else { /* maybe source is a URL */ DefaultHttpClient client = new DefaultHttpClient(); if (username != null && password != null) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username, password)); } HttpResponse response = client.execute(new HttpGet(source)); if (response.getStatusLine().getStatusCode() >= 400) { throw new HttpException(response.getStatusLine().getReasonPhrase()); } HttpEntity entity = response.getEntity(); ContentType contentType = ContentType.fromHeader(entity.getContentType().getValue()); if (entity.getContentEncoding() != null) { encoding = entity.getContentEncoding().getValue(); } else if (contentType.charset != null) { encoding = contentType.charset; } if (format == null) { format = contentType.type; } InputStream in = entity.getContent(); Reader reader = new InputStreamReader(in, encoding); scope = Serializers.loadAPIScope(reader, format); reader.close(); in.close(); client.getConnectionManager().shutdown(); } return scope; }
From source file:edu.usc.polar.OpenNLP.java
public static void dir(String path, String[] args) { try {/*w ww . j av a2 s.co m*/ File root = new File(path); if (root.isFile()) { if (counter >= 1000 || file == null) { counter = 0; jsonCount++; file = new File("C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\OpenNLP\\NER_" + jsonCount + ".json"); if (jsonFile != null) { jsonFile.write("{\"NER_OpenNLP\":"); jsonFile.write(jsonArray.toJSONString()); jsonFile.write("}"); System.out.println(jsonArray.toJSONString()); jsonFile.close(); } jsonFile = new FileWriter(file); jsonArray = new JSONArray(); } if (!root.getName().equals((".DS_Store"))) { ApacheOpenNLP(root.getAbsolutePath(), args); counter++; } } else { File[] list = root.listFiles(); if (list == null) { return; } for (File f : list) { if (f.isDirectory()) { dir(f.getAbsolutePath(), args); System.out.println("Dir:" + f.getAbsoluteFile()); } else { if (counter >= 1000 || file == null) { counter = 0; jsonCount++; file = new File("C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\OpenNLP\\NER_" + jsonCount + ".json"); // System.out.print("check"+jsonArray.toJSONString()); if (jsonFile != null) { jsonFile.write("{\"NER_OpenNLP\":"); jsonFile.write(jsonArray.toJSONString()); jsonFile.write("}"); System.out.println(jsonArray.toJSONString()); jsonFile.close(); } jsonFile = new FileWriter(file); jsonArray = new JSONArray(); } if (!f.getName().equals((".DS_Store"))) { ApacheOpenNLP(f.getAbsolutePath(), args); counter++; // add json } } } } } catch (Exception e) { e.toString(); } }
From source file:net.idlesoft.android.apps.github.utils.GravatarCache.java
/** * Returns a Gravatar ID associated with the provided name * /*from www.j a va2 s .c om*/ * @param name * @return the gravatar ID associated with the name */ public static String getGravatarID(final String name) { String id = ""; try { final File gravatars = ensure_directory(ROOT_DIR); final File gravatar_id = new File(gravatars, name + ".id"); if (gravatar_id.isFile()) { final FileReader fr = new FileReader(gravatar_id); final BufferedReader in = new BufferedReader(fr); id = in.readLine(); in.close(); } else { id = getGravatarIdFromGithub(name); if (!id.equals("")) { final FileWriter fw = new FileWriter(gravatar_id); final BufferedWriter bw = new BufferedWriter(fw); bw.write(id); bw.flush(); bw.close(); } } } catch (final IOException e) { e.printStackTrace(); } return id; }
From source file:key.secretkey.utils.PasswordStorage.java
/** * Gets the passwords (PasswordItem) in a directory * @param path the directory path//from w w w. ja va 2 s. c o m * @return a list of password items */ public static ArrayList<PasswordItem> getPasswords(File path, File rootDir) { //We need to recover the passwords then parse the files ArrayList<File> passList = getFilesList(path); if (passList.size() == 0) return new ArrayList<PasswordItem>(); ArrayList<PasswordItem> passwordList = new ArrayList<PasswordItem>(); for (File file : passList) { if (file.isFile()) { passwordList.add(PasswordItem.newPassword(file.getName(), file, rootDir)); } else { // ignore .git directory if (file.getName().equals(".git")) continue; passwordList.add(PasswordItem.newCategory(file.getName(), file, rootDir)); } } sort(passwordList); return passwordList; }
From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java
public static File generateNgrams(File src_dir, AbstractStringProvider prvdr, int from_cardinality, int to_cardinality, boolean overwrite) { final File ngram_file = new File(src_dir, String.format("%s.%s", src_dir.getName(), "ngrams.txt.gz")); int n_b = from_cardinality, n_e = to_cardinality; if (ngram_file.exists()) { LOG.info("Output file already exists: '{}'.", ngram_file.getAbsolutePath()); if (overwrite) { ngram_file.delete();//from w w w .j a va 2s . co m LOG.info("Overwriting file: '{}'.", ngram_file.getAbsolutePath()); } else return ngram_file; } File[] src_files = src_dir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile() && f.getName().endsWith(".txt") && (!f.equals(ngram_file)); } }); String[] basenames = new String[src_files.length]; for (int i = 0; i < basenames.length; i++) basenames[i] = src_files[i].getName(); LOG.info(String.format("Reading txt files from dir: '%s'; Files: %s.", src_dir.getAbsolutePath(), StringUtils.abbreviate(Arrays.toString(basenames), 200))); LOG.info(String.format("Writing ngrams to file: '%s'.", ngram_file.getAbsolutePath())); PrintWriter pw = null; try { pw = new PrintWriter( new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(ngram_file)), "UTF-8")); } catch (IOException e) { LOG.error("Could not open writer for file: '{}'.", ngram_file.getAbsolutePath(), e); return null; } long num_ngrams = 0l; List<String>[] ngrams = null; for (int i = 0; i < src_files.length; i++) { File src_file = src_files[i]; LOG.info("Processing file {} / {} ('{}')", i + 1, src_files.length, src_file.getAbsolutePath()); long num_ngrams_f = 0l; try { LineIterator liter = new LineIterator( new BufferedReader(new InputStreamReader(new FileInputStream(src_file), "UTF-8"))); int lc = 0; while (liter.hasNext()) { if (++lc % 1000 == 0) LOG.debug("Processing line {} ({})", lc, src_file); String line = liter.next(); for (String sentence : prvdr.splitSentences(line)) { for (int n = n_b; n <= n_e; n++) { ngrams = null; try { List<String> tokens = prvdr.tokenizeSentence(sentence); if (tokens.isEmpty()) continue; ngrams = AbstractLanguageModel.getNgramSequence(tokens, n); } catch (Exception e) { LOG.warn( "Could not get ngram of cardinality {} from String '{}' in line '{}' from file '{}'.", n, StringUtils.abbreviate(line, 100), lc, src_file.getAbsolutePath()); continue; } for (List<String> ngram : ngrams) pw.println(StringUtils.join(ngram, " ")); pw.flush(); num_ngrams_f += ngrams.length; } } } liter.close(); } catch (Exception e) { LOG.warn("Could not read file '{}'.", src_file.getAbsolutePath(), e); } LOG.debug("Generated {} ngrams from file {}.", num_ngrams_f, src_file); num_ngrams += num_ngrams_f; } if (pw != null) pw.close(); LOG.info("Generated {} ngrams.", num_ngrams); return ngram_file; }
From source file:eu.eubrazilcc.lvl.core.conf.ConfigurationFinder.java
public final static boolean testConfigurationFiles(final String baseDir, final String[] filenames) { boolean passed = (isNotEmpty(baseDir) && filenames != null && filenames.length > 0 ? true : false); for (int i = 0; i < filenames.length && passed; i++) { try {//w w w .j av a 2 s . c om final File file = new File(concat(baseDir, filenames[i])); if (!file.isFile() || !file.canRead()) { passed = false; } } catch (Exception ignore) { passed = false; } } return passed; }
From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java
private static void zipFile(ZipArchiveOutputStream out, File file, String parentInZip) { ZipArchiveEntry entry = null;/* w w w . jav a 2s .c o m*/ try { if (file.isFile()) { // out String name = FileUtil.removeFirstIfIsSparator(parentInZip + File.separator + file.getName()); entry = new ZipArchiveEntry(name); logger.info("zip file : " + name); out.putArchiveEntry(entry); FileUtil.copyFile(file, out); out.closeArchiveEntry(); } else {// ??out // ? File[] children = file.listFiles(); if (children != null) { for (int i = 0; i < children.length; i++) { zipFile(out, children[i], parentInZip + File.separator + file.getName()); } } } } catch (Exception e) { e.printStackTrace(); } }
From source file:fr.logfiletoes.Main.java
/** * Get config file and check if existe//from w w w.j ava2 s .c o m * @return */ public static String getConfigFilePath() { String configFile = System.getProperty("fr.logfiletoes.config.file"); if (configFile == null) { LOG.severe("-Dfr.logfiletoes.config.file is required for config file"); System.exit(1); } else { File config = new File(configFile); if (!config.exists()) { LOG.severe("\"" + config.getAbsolutePath() + "\" not found"); System.exit(2); } if (!config.isFile()) { LOG.severe("\"" + config.getAbsolutePath() + "\" is not file"); System.exit(3); } } return configFile; }