Example usage for java.nio.file Files isReadable

List of usage examples for java.nio.file Files isReadable

Introduction

In this page you can find the example usage for java.nio.file Files isReadable.

Prototype

public static boolean isReadable(Path path) 

Source Link

Document

Tests whether a file is readable.

Usage

From source file:jp.realglobe.util.uploader.DirectoryUploader.java

@Override
public void run() {
    final String token1;
    if (this.token != null) {
        token1 = this.token;
    } else {/*w w  w. j a  va2s.c  o  m*/
        try {
            token1 = getToken();
        } catch (final InterruptedException e) {
            // 
            return;
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

    LOG.info("Use token " + token1);

    (new DelayedWatcher(this.watchDirectoryPath, this.delay, this.latestOnly, path -> {
        if (!Files.isReadable(path)) {
            LOG.info("Cannot read " + path);
            return;
        }
        final File file = path.toFile();
        if (!this.targetExtensions.isEmpty()
                && !this.targetExtensions.contains(FilenameUtils.getExtension(file.getName()))) {
            LOG.info("Skip non target file " + path);
            return;
        } else if (this.minSize > 0 && file.length() < this.minSize) {
            LOG.info("Skip too small file " + path);
            return;
        } else if (this.maxSize > 0 && file.length() > this.maxSize) {
            LOG.info("Skip too large file " + path);
            return;
        }
        upload(token1, path);
    })).run();
}

From source file:org.darkware.wpman.config.ReloadableWordpressConfig.java

/**
 * Load all available plugin configuration profile fragments under the given directory. No recursion is done.
 * All profile fragments must end in {@code .yml}.
 *
 * @param themes The {@link ThemeListConfig} to override with the loaded fragments.
 * @param dir The {@link Path} of the directory to scan.
 * @throws IOException If there is an error while listing the directory contents
 *///from   w  w  w  .j  a  v a  2  s .  co  m
protected void loadThemes(final ThemeListConfig themes, final Path dir) throws IOException {
    if (!Files.exists(dir))
        return;
    if (!Files.isDirectory(dir)) {
        WPManager.log.warn("Cannot load theme overrides: {} is not a directory.", dir);
        return;
    }
    if (!Files.isReadable(dir)) {
        WPManager.log.warn("Cannot load theme overrides: {} is not readable.", dir);
        return;
    }

    Files.list(dir).filter(f -> Files.isRegularFile(f)).filter(f -> f.toString().endsWith(".yml"))
            .forEach(f -> this.loadTheme(themes, f));
}

From source file:ee.ria.xroad.common.SystemPropertiesLoader.java

/**
 * Does the actual loading of the INI files. Glob-defined files are loaded in alphabetical
 * order based on the filename./*from  ww w. j  av a 2  s . co m*/
 */
public void load() {
    if (withCommon) {
        load(new FileWithSections(SystemProperties.CONF_FILE_COMMON));
    }

    files.forEach(this::load);

    if (withAddOn) {
        try {
            Path addOnDir = Paths.get(SystemProperties.CONF_FILE_ADDON_PATH);
            loadFilesInOrder(addOnDir, ADDON_GLOB, LOADING_ORDER_COMPARATOR);
        } catch (IOException e) {
            log.error("Cannot load addon configuration", e);
        }
    }

    if (withOverrides) {
        try {
            Path overrideDir = Paths.get(SystemProperties.getConfPath(), "conf.d");
            loadFilesInOrder(overrideDir, OVERRIDE_GLOB, LOADING_ORDER_COMPARATOR);
        } catch (IOException e) {
            log.error("Cannot load override configuration", e);
        }
    }

    if (withLocal) {
        load(new FileWithSections(SystemProperties.CONF_FILE_USER_LOCAL));
    }

    optionalLocalFiles.forEach(f -> {
        if (Files.isReadable(Paths.get(f.getName()))) {
            load(f);
        }
    });

    log.debug("Loaded properties:\n{}", loadedProperties);
}

From source file:org.niord.core.batch.BatchSetService.java

/**
 * Called every minute to monitor the "batch-sets" folder. If a batch-set zip file has been
 * placed in this folder, the batch-set gets executed.
 *//*from w  w  w . j  a  v a 2 s. co m*/
@Schedule(persistent = false, second = "24", minute = "*/1", hour = "*/1")
protected void monitorBatchJobInFolderInitiation() {

    Path batchSetsFolder = batchService.getBatchJobRoot().resolve(BATCH_SETS_FOLDER);

    if (Files.isDirectory(batchSetsFolder)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(batchSetsFolder)) {
            for (Path p : stream) {
                if (Files.isReadable(p) && Files.isRegularFile(p)) {
                    try {
                        executeBatchSetFromArchiveOrFolder(p);
                    } catch (Exception e) {
                        log.error("Error executing batch set " + p, e);
                    } finally {
                        // Delete the file
                        try {
                            Files.delete(p);
                        } catch (IOException ignored) {
                        }
                    }
                }
            }
        } catch (IOException ignored) {
        }
    }
}

From source file:fr.duminy.jbackup.core.ConfigurationManagerTest.java

private void existsRW(Path configFile, boolean existsRW) {
    assertThat(Files.exists(configFile)).as("configFile exists").isEqualTo(existsRW);
    assertThat(Files.isReadable(configFile)).as("configFile is readable").isEqualTo(existsRW);
    assertThat(Files.isWritable(configFile)).as("configFile is writable").isEqualTo(existsRW);
}

From source file:io.anserini.index.IndexWebCollection.java

public IndexWebCollection(String docsPath, String indexPath, Collection collection) throws IOException {

    this.indexPath = Paths.get(indexPath);
    if (!Files.exists(this.indexPath))
        Files.createDirectories(this.indexPath);

    docDir = Paths.get(docsPath);
    if (!Files.exists(docDir) || !Files.isReadable(docDir) || !Files.isDirectory(docDir)) {
        System.out.println("Document directory '" + docDir.toString()
                + "' does not exist or is not readable, please check the path");
        System.exit(1);//from   w  w  w  .j a v  a  2  s .com
    }

    this.collection = collection;
}

From source file:io.github.robwin.swagger2markup.builder.document.DefinitionsDocument.java

/**
 * Reads a hand-written description/*from  w  w  w .jav  a 2  s  . c o  m*/
 *
 * @param descriptionFolder the name of the folder where the description file resides
 * @param descriptionFileName the name of the description file
 * @return the content of the file
 * @throws IOException
 */
private String handWrittenPathDescription(String descriptionFolder, String descriptionFileName)
        throws IOException {
    for (String fileNameExtension : markupLanguage.getFileNameExtensions()) {
        java.nio.file.Path path = Paths.get(descriptionsFolderPath, descriptionFolder,
                descriptionFileName + fileNameExtension);
        if (Files.isReadable(path)) {
            if (logger.isInfoEnabled()) {
                logger.info("Description file processed: {}", path);
            }
            return FileUtils.readFileToString(path.toFile(), StandardCharsets.UTF_8).trim();
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Description file is not readable: {}", path);
            }
        }
    }
    if (logger.isWarnEnabled()) {
        logger.info("No description file found with correct file name extension in folder: {}",
                Paths.get(descriptionsFolderPath, descriptionFolder));
    }
    return null;
}

From source file:org.apache.marmotta.platform.core.services.importer.ImportWatchServiceImpl.java

/**
 * Detect the import format of the given file (mime-type)
 * @param file the file to check/*from   w  ww .  ja  va2 s  .c o  m*/
 * @return the mime-type
 * @throws MarmottaImportException
 */
private String detectFormat(Path file) throws MarmottaImportException {
    String format = null;
    final String fileName = file.toFile().getName();

    final Path config = file.getParent()
            .resolve(configurationService.getStringConfiguration(CONFIG_KEY_CONF_FILE, "config"));
    if (Files.isReadable(config)) {
        Properties prop = loadConfigFile(file);
        final String fmt = prop.getProperty("format");
        if (fmt != null) {
            RDFFormat rdfFormat = Rio.getParserFormatForMIMEType(fmt);
            if (rdfFormat != null) {
                format = rdfFormat.getDefaultMIMEType();
                log.debug("Using format {} from config file {}", format, config);
            } else {
                log.debug("Unknown format {} in config file {}, ignoring", fmt, config);
            }
        } else {
            log.trace("No format defined in {}", config);
        }
    }

    // mimetype detection based on file-extension
    if (format == null) {
        // FIXME: Maybe use GzipUtils and BZip2Utils instead?
        RDFFormat rdfFormat = Rio.getParserFormatForFileName(fileName.replaceFirst("\\.(gz|bz2)$", ""));
        if (rdfFormat != null) {
            format = rdfFormat.getDefaultMIMEType();
            log.trace("Using format {} based on file-name {}", format, fileName);
        }
    }

    if (format == null || !importService.getAcceptTypes().contains(format)) {
        throw new MarmottaImportException("Suitable RDF parser not found");
    }

    // encoding detection
    // FIXME: is this required?
    try (BufferedInputStream bis = new BufferedInputStream(openStream(file))) {
        CharsetDetector cd = new CharsetDetector();
        cd.setText(bis);
        CharsetMatch cm = cd.detect();
        if (cm != null) {
            log.trace("Detected charset {} in {}", cm.getName(), file);
            format += "; charset=" + cm.getName();
        }
        bis.close();
    } catch (IOException e) {
        log.error("Error detecting charset for '{}': {}", fileName, e.getMessage());
    }

    return format;
}

From source file:org.savantbuild.io.tar.TarBuilderTest.java

@Test
public void buildStrings() throws Exception {
    FileTools.prune(projectDir.resolve("build/test/tars"));

    Path file = projectDir.resolve("build/test/tars/test.tar.gz");
    TarBuilder builder = new TarBuilder(file.toString());
    builder.storeGroupName = true;/*ww w  . j  av  a  2s.com*/
    builder.storeUserName = true;
    int count = builder.fileSet(projectDir.resolve("src/main/java").toString())
            .fileSet(projectDir.resolve("src/test/java").toString()).optionalFileSet("doesNotExist").build();
    assertTrue(Files.isReadable(file));
    assertTarFileEquals(file, "org/savantbuild/io/Copier.java",
            projectDir.resolve("src/main/java/org/savantbuild/io/Copier.java"));
    assertTarFileEquals(file, "org/savantbuild/io/FileSet.java",
            projectDir.resolve("src/main/java/org/savantbuild/io/FileSet.java"));
    assertEquals(count, 32);
}

From source file:org.apache.hadoop.crypto.key.RangerKMSDB.java

private void updateDBSSLURL() {
    if (conf != null && conf.get(PROPERTY_PREFIX + DB_SSL_ENABLED) != null) {
        String db_ssl_enabled = conf.get(PROPERTY_PREFIX + DB_SSL_ENABLED);
        if (StringUtils.isEmpty(db_ssl_enabled) || !"true".equalsIgnoreCase(db_ssl_enabled)) {
            db_ssl_enabled = "false";
        }//from ww  w.j  a  va  2  s. c  o  m
        db_ssl_enabled = db_ssl_enabled.toLowerCase();
        if ("true".equalsIgnoreCase(db_ssl_enabled)) {
            String db_ssl_required = conf.get(PROPERTY_PREFIX + DB_SSL_REQUIRED);
            if (StringUtils.isEmpty(db_ssl_required) || !"true".equalsIgnoreCase(db_ssl_required)) {
                db_ssl_required = "false";
            }
            db_ssl_required = db_ssl_required.toLowerCase();
            String db_ssl_verifyServerCertificate = conf.get(PROPERTY_PREFIX + DB_SSL_VerifyServerCertificate);
            if (StringUtils.isEmpty(db_ssl_verifyServerCertificate)
                    || !"true".equalsIgnoreCase(db_ssl_verifyServerCertificate)) {
                db_ssl_verifyServerCertificate = "false";
            }
            db_ssl_verifyServerCertificate = db_ssl_verifyServerCertificate.toLowerCase();
            conf.set(PROPERTY_PREFIX + DB_SSL_ENABLED, db_ssl_enabled);
            conf.set(PROPERTY_PREFIX + DB_SSL_REQUIRED, db_ssl_required);
            conf.set(PROPERTY_PREFIX + DB_SSL_VerifyServerCertificate, db_ssl_verifyServerCertificate);
            String ranger_jpa_jdbc_url = conf.get(PROPERTY_PREFIX + DB_URL);
            if (!StringUtils.isEmpty(ranger_jpa_jdbc_url)) {
                StringBuffer ranger_jpa_jdbc_url_ssl = new StringBuffer(ranger_jpa_jdbc_url);
                ranger_jpa_jdbc_url_ssl.append("?useSSL=" + db_ssl_enabled + "&requireSSL=" + db_ssl_required
                        + "&verifyServerCertificate=" + db_ssl_verifyServerCertificate);
                conf.set(PROPERTY_PREFIX + DB_URL, ranger_jpa_jdbc_url_ssl.toString());
                DB_PROPERTIES.put(JPA_DB_URL, conf.get(PROPERTY_PREFIX + DB_URL));
                logger.info(PROPERTY_PREFIX + DB_URL + "=" + ranger_jpa_jdbc_url_ssl.toString());
            }

            if ("true".equalsIgnoreCase(db_ssl_verifyServerCertificate)) {
                if (conf != null) {
                    // update system key store path with custom key store.
                    String keystore = conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE);
                    if (!StringUtils.isEmpty(keystore)) {
                        Path path = Paths.get(keystore);
                        if (Files.exists(path) && Files.isReadable(path)) {
                            System.setProperty("javax.net.ssl.keyStore",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE));
                            System.setProperty("javax.net.ssl.keyStorePassword",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE_PASSWORD));
                            System.setProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
                        } else {
                            logger.debug("Could not find or read keystore file '" + keystore + "'");
                        }
                    } else {
                        logger.debug("keystore property '" + PROPERTY_PREFIX + DB_SSL_KEYSTORE
                                + "' value not found!");
                    }
                    // update system trust store path with custom trust store.
                    String truststore = conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE);
                    if (!StringUtils.isEmpty(truststore)) {
                        Path path = Paths.get(truststore);
                        if (Files.exists(path) && Files.isReadable(path)) {
                            System.setProperty("javax.net.ssl.trustStore",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE));
                            System.setProperty("javax.net.ssl.trustStorePassword",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE_PASSWORD));
                            System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType());
                        } else {
                            logger.debug("Could not find or read truststore file '" + truststore + "'");
                        }
                    } else {
                        logger.debug("truststore property '" + PROPERTY_PREFIX + DB_SSL_TRUSTSTORE
                                + "' value not found!");
                    }
                }
            }
        }
    }
}