List of usage examples for java.nio.file Files isReadable
public static boolean isReadable(Path path)
From source file:org.opendatakit.briefcase.export.SubmissionParser.java
/** * Returns an sorted {@link List} of {@link Path} instances pointing to all the * submissions of a form that belong to the given {@link DateRange}. * <p>//from w ww . ja v a2 s.c om * Each file gets briefly parsed to obtain their submission date and use it as * the sorting criteria and for filtering. */ static List<Path> getListOfSubmissionFiles(FormDefinition formDef, DateRange dateRange, SubmissionExportErrorCallback onParsingError) { Path instancesDir = formDef.getFormDir().resolve("instances"); if (!Files.exists(instancesDir) || !Files.isReadable(instancesDir)) return Collections.emptyList(); // TODO Migrate this code to Try<Pair<Path, Option<OffsetDate>>> to be able to filter failed parsing attempts List<Pair<Path, OffsetDateTime>> paths = new ArrayList<>(); list(instancesDir).filter(UncheckedFiles::isInstanceDir).forEach(instanceDir -> { Path submissionFile = instanceDir.resolve("submission.xml"); try { Optional<OffsetDateTime> submissionDate = readSubmissionDate(submissionFile, onParsingError); paths.add(Pair.of(submissionFile, submissionDate.orElse(OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)))); } catch (Throwable t) { log.error("Can't read submission date", t); EventBus.publish(ExportEvent.failureSubmission(formDef, instanceDir.getFileName().toString(), t)); } }); return paths.parallelStream() // Filter out submissions outside the given date range .filter(pair -> dateRange.contains(pair.getRight())).map(Pair::getLeft).collect(toList()); }
From source file:uk.ac.ebi.interpro.scan.jms.main.AbstractI5Runner.java
/** * Check if a specified path exists and is readable. * @param path The full file or directory path under review (e.g. "/tmp/test_proteins.fasta") * @param checkParent Do we just check the parent path? (e.g. "/tmp") * @param checkWriteable Should we also check that the path or parent path can be written to? * @param option The user input {@link I5Option} this path relates to (or null if not applicable) * @return True if the checks succeed, otherwise false (although the system will exit if a {@link I5Option} check fails) *//*from w w w. j av a2 s. co m*/ protected static boolean checkPathExistence(final String path, final boolean checkParent, final boolean checkWriteable, final I5Option option) { String pathToCheck = path; if (checkParent) { pathToCheck = path.substring(0, path.lastIndexOf(File.separator)); } Path p = FileSystems.getDefault().getPath(pathToCheck); boolean exists = Files.isReadable(p); if (option != null && !exists) { System.out.println("For the (-" + option.getShortOpt() + ") option you specified a location which doesn't exist or is not readable:"); System.out.println(path); System.exit(2); } if (exists && checkWriteable) { boolean writable = Files.isWritable(p); if (option != null && !writable) { System.out.println("For the (-" + option.getShortOpt() + ") option you specified a location which is not writable:"); System.out.println(path); System.exit(2); } return writable; } return exists; }
From source file:nl.salp.warcraft4j.casc.neo4j.insert.Neo4jCascBulkInserter.java
@Inject public Neo4jCascBulkInserter(Neo4jConfig config) throws IllegalArgumentException, IOException { if (config == null) { throw new IllegalArgumentException("Can't create a Neo4jCascBulkInserter with a null Neo4jConfig"); }//from ww w . j av a 2 s. c o m if (config.getNeo4jDatabasePath() == null) { throw new IllegalArgumentException( "Can't create a Neo4jCascBulkInserter with no neo4j database path configured."); } this.databasePath = config.getNeo4jDatabasePath().normalize().toAbsolutePath(); if (Files.notExists(databasePath)) { Files.createDirectories(databasePath); } else if (!Files.isWritable(databasePath) || !Files.isReadable(databasePath) || !Files.isDirectory(databasePath)) { throw new IllegalArgumentException(format( "Can't create a Neo4jCascBulkInserter for database path %s, either lacking read/write rights or is not a directory.", databasePath)); } typeInsertionActions = new HashMap<>(); }
From source file:nl.salp.warcraft4j.casc.cdn.local.FileDataReaderProvider.java
/** * Get the path to the file represented by the URI. * * @param uri The URI.// w w w. jav a 2 s . c om * * @return The path to the file represented by the URI. * * @throws CascParsingException When the URI is invalid or does not point to a valid, readable file. */ private Path toPath(String uri) throws CascParsingException { if (isEmpty(uri)) { throw new CascParsingException("Can't create a file reader for an empty path."); } Path path = Paths.get(uri); if (Files.notExists(path) || !Files.isRegularFile(path)) { throw new CascParsingException( format("Can't create a file reader for %s, file either doesn't exist or is not a file.", uri)); } if (!Files.isReadable(path)) { throw new CascParsingException(format("Can't create a file reader for non-readable file %s", uri)); } return path; }
From source file:org.nira.wso2.nexus.ComponentVersion.java
/** * Loads the Dependencies and its corresponding version * * @param pomFilePath : The path to the root pom.xml * @throws ComponentException/*from www. j av a2 s .c om*/ */ private static void readPomFile(String pomFilePath) throws ComponentException { if (Files.isReadable(Paths.get(pomFilePath))) { getDependenyVersions(pomFilePath); getDependencyManagement(pomFilePath); } }
From source file:org.schedulesdirect.grabber.ProgramCache.java
/** * Is the given program id with the given md5 in the cache? * @param progId The program id to search for * @param md5 The md5 hash to search for * @return True if progId with the given md5 is in the cache or false otherwise *//* w ww. j a va 2s . co m*/ public boolean inCache(String progId, String md5) { Path prog = vfs.getPath("programs", String.format("%s.txt", progId)); if (Files.isReadable(prog)) { try (InputStream ins = Files.newInputStream(prog)) { JSONObject o = new JSONObject(IOUtils.toString(ins, ZipEpgClient.ZIP_CHARSET.toString())); return o.getString("md5").equals(md5); } catch (JSONException | IOException e) { throw new RuntimeException(e); } } else return false; }
From source file:org.talend.dataprep.encrypt.PropertiesEncryption.java
/** * Applies the specified function to the specified set of parameters contained in the input file. * * @param input The specified name of file to encrypt * @param mustBeModified the specified set of parameters * @param function the specified function to apply to the set of specified parameters *///w w w . ja va 2 s . co m private void modifyAndSave(String input, Set<String> mustBeModified, Function<String, String> function) { Path inputFilePath = Paths.get(input); if (Files.exists(inputFilePath) && Files.isRegularFile(inputFilePath) && Files.isReadable(inputFilePath)) { try { Parameters params = new Parameters(); FileBasedConfigurationBuilder<PropertiesConfiguration> builder = // new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class) // .configure(params.fileBased() // .setFile(inputFilePath.toFile())); // PropertiesConfiguration config = builder.getConfiguration(); for (String key : mustBeModified) { config.setProperty(key, function.apply(config.getString(key))); } builder.save(); } catch (ConfigurationException e) { LOGGER.error("unable to read {} {}", input, e); } } else { LOGGER.debug("No readable file at {}", input); } }
From source file:org.commonwl.view.git.GitService.java
/** * Gets a repository, cloning into a local directory or * @param gitDetails The details of the Git repository * @param reuseDir Whether the cached repository can be used * @return The git object for the repository *///from www . j a v a 2 s . co m public Git getRepository(GitDetails gitDetails, boolean reuseDir) throws GitAPIException, IOException { Git repo; if (reuseDir) { // Base dir from configuration, name from hash of repository URL String baseName = DigestUtils.sha1Hex(GitDetails.normaliseUrl(gitDetails.getRepoUrl())); // Check if folder already exists Path repoDir = gitStorage.resolve(baseName); if (Files.isReadable(repoDir) && Files.isDirectory(repoDir)) { repo = Git.open(repoDir.toFile()); repo.fetch().call(); } else { // Create a folder and clone repository into it Files.createDirectory(repoDir); repo = cloneRepo(gitDetails.getRepoUrl(), repoDir.toFile()); } } else { // Another thread is already using the existing folder // Must create another temporary one repo = cloneRepo(gitDetails.getRepoUrl(), createTempDir()); } // Checkout the specific branch or commit ID if (repo != null) { // Create a new local branch if it does not exist and not a commit ID String branchOrCommitId = gitDetails.getBranch(); final boolean isId = ObjectId.isId(branchOrCommitId); if (!isId) { branchOrCommitId = "refs/remotes/origin/" + branchOrCommitId; } try { repo.checkout().setName(branchOrCommitId).call(); } catch (Exception ex) { // Maybe it was a tag if (!isId && ex instanceof RefNotFoundException) { final String tag = gitDetails.getBranch(); try { repo.checkout().setName(tag).call(); } catch (Exception ex2) { // Throw the first exception, to keep the same behavior as before. throw ex; } } else { throw ex; } } } return repo; }
From source file:uk.co.unclealex.executable.generator.jar.JarServiceImplTest.java
@Before public void setUp() throws IOException { tempDir = Files.createTempDirectory("jar-service-"); ClassLoader classLoader = getClass().getClassLoader(); // Check none of these classes exist already. for (String className : classNames) { try {/*from ww w . j a v a 2 s .c om*/ classLoader.loadClass(className); Assert.fail("Class " + className + " already exists."); } catch (ClassNotFoundException e) { // This is good news. } } Path classDir = tempDir.resolve("classes"); for (String className : classNames) { String classFilename = className.replace('.', '/') + ".class"; Path classFile = classDir.resolve(classFilename); Files.createDirectories(classFile.getParent()); byte[] clazz = generateClass(className); Files.write(classFile, clazz); } JarService jarService = new JarServiceImpl(); jarFile = tempDir.resolve("jar").resolve("test.jar"); Files.createDirectories(jarFile.getParent()); jarService.generateJar(classDir, jarFile); Assert.assertTrue("The jar file was not created.", Files.isReadable(jarFile)); }
From source file:dk.dma.ais.track.AisTrackServiceConfiguration.java
private InputStream aisBusConfiguration() throws IOException { InputStream is = null;//from ww w . ja v a 2 s.c o m if (!StringUtils.isBlank(aisBusXmlFileName)) { LOG.debug("Application properties say that aisbus.xml can be found in " + aisBusXmlFileName); Path aisBusXmlFile = Paths.get(aisBusXmlFileName); if (Files.exists(aisBusXmlFile) && Files.isReadable(aisBusXmlFile) && Files.isRegularFile(aisBusXmlFile)) { LOG.debug(aisBusXmlFileName + " exists, is readable and regular. Using that for AisBus configuration."); LOG.info("Using " + aisBusXmlFile.toAbsolutePath().toString()); is = Files.newInputStream(aisBusXmlFile); } else { LOG.debug( "Application properties points to a file which does not exist or is not readable or regular."); } } else { LOG.debug("No location of aisbus.xml given in application properties."); } if (is == null) { LOG.info("Falling back to built-in default AisBus configuration."); is = ClassLoader.getSystemResourceAsStream("aisbus.xml"); } return is; }