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:io.github.robwin.swagger2markup.builder.document.DefinitionsDocument.java

private void schema(String title, String schemasFolderPath, String schemaName, String language)
        throws IOException {
    java.nio.file.Path path = Paths.get(schemasFolderPath, schemaName);
    if (Files.isReadable(path)) {
        this.markupDocBuilder.sectionTitleLevel3(title);
        this.markupDocBuilder.source(FileUtils.readFileToString(path.toFile(), StandardCharsets.UTF_8).trim(),
                language);/*w w w .  ja va2s  . co m*/
        if (logger.isInfoEnabled()) {
            logger.info("Schema file processed: {}", path);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Schema file is not readable: {}", path);
        }
    }
}

From source file:io.anserini.rerank.lib.AxiomReranker.java

/**
 * If the result is deterministic we can cache all the docids. All queries can share this
 * cache.// w  ww.  ja va2 s  .  c  om
 */
private ScoreDoc[] buildInternalDocidsCache(SearchArgs args) throws IOException {
    String index = args.axiom_index == null ? args.index : args.axiom_index;
    Path indexPath = Paths.get(index);
    if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) {
        throw new IllegalArgumentException(index + " does not exist or is not a directory.");
    }
    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexPath));
    IndexSearcher searcher = new IndexSearcher(reader);
    if (args.searchtweets) {
        return searcher.search(new FieldValueQuery(TweetGenerator.StatusField.ID_LONG.name), reader.maxDoc(),
                BREAK_SCORE_TIES_BY_TWEETID).scoreDocs;
    }
    return searcher.search(new FieldValueQuery(LuceneDocumentGenerator.FIELD_ID), reader.maxDoc(),
            BREAK_SCORE_TIES_BY_DOCID).scoreDocs;
}

From source file:misc.FileHandler.java

/**
 * Returns a <code>MESSAGE_DIGEST</code> checksum of the given file.
 * //from  w  w w.  j  av  a 2s  .  c  om
 * @param file
 *            the file to checksum.
 * @return the checksum of the given file or <code>null</code>, if an error
 *         occurs.
 */
public static byte[] getChecksum(Path file) {
    if ((file == null) || !Files.isReadable(file)) {
        throw new IllegalArgumentException("file must exist and be readable!");
    }

    byte[] checksum = null;

    try (FileInputStream in = new FileInputStream(file.toFile());) {
        checksum = getChecksum(in, Files.size(file));
    } catch (IOException | NoSuchAlgorithmException e) {
        Logger.logError(e);
    }

    return checksum;
}

From source file:org.codice.ddf.security.common.Security.java

private KeyStore getSystemKeyStore() {
    KeyStore keyStore;/*from  ww w . j a v  a2 s  . co  m*/

    try {
        keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));

    } catch (KeyStoreException e) {
        LOGGER.error("Unable to create keystore instance of type {}",
                System.getProperty("javax.net.ssl.keyStoreType"), e);
        return null;
    }

    Path keyStoreFile = new File(System.getProperty("javax.net.ssl.keyStore")).toPath();
    Path ddfHomePath = Paths.get(System.getProperty("ddf.home"));

    if (!keyStoreFile.isAbsolute()) {
        keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
    }

    String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

    if (!Files.isReadable(keyStoreFile)) {
        LOGGER.error("Unable to read system key/trust store files: [ {} ] ", keyStoreFile);
        return null;
    }

    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        keyStore.load(kfis, keyStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.error("Unable to load system key file.", e);
    }

    return keyStore;
}

From source file:io.anserini.rerank.lib.AxiomReranker.java

/**
 * If the external reranking context is not null we will first search against the external
 * index and return the top ranked documents.
 *
 * @param docs The initial ranking results against target index. We will return them if external
 *             index is null.//from w ww  . j a v  a2 s. co m
 *
 * @return Top ranked ScoredDocuments from searching external index
 */
private ScoredDocuments processExternalContext(ScoredDocuments docs, RerankerContext<T> context)
        throws IOException {
    if (externalIndexPath != null) {
        Path indexPath = Paths.get(this.externalIndexPath);
        if (!Files.exists(indexPath) || !Files.isDirectory(indexPath) || !Files.isReadable(indexPath)) {
            throw new IllegalArgumentException(
                    this.externalIndexPath + " does not exist or is not a directory.");
        }
        IndexReader reader = DirectoryReader.open(FSDirectory.open(indexPath));
        IndexSearcher searcher = new IndexSearcher(reader);
        searcher.setSimilarity(context.getIndexSearcher().getSimilarity(true));

        SearchArgs args = new SearchArgs();
        args.hits = this.R;
        args.arbitraryScoreTieBreak = context.getSearchArgs().arbitraryScoreTieBreak;
        args.searchtweets = context.getSearchArgs().searchtweets;

        RerankerContext<T> externalContext = new RerankerContext<>(searcher, context.getQueryId(),
                context.getQuery(), context.getQueryText(), context.getQueryTokens(), context.getFilter(),
                args);

        return searchTopDocs(null, externalContext);
    } else {
        return docs;
    }
}

From source file:org.wso2.carbon.uuf.internal.io.StaticResolver.java

private ZonedDateTime getLastModifiedDate(Path resourcePath) {
    if (!Files.isReadable(resourcePath)) {
        throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' is not readable.");
    }//from ww  w.  j  a  v  a 2 s. c o  m

    BasicFileAttributes fileAttributes;
    try {
        fileAttributes = Files.readAttributes(resourcePath, BasicFileAttributes.class);
    } catch (NoSuchFileException | FileNotFoundException e) {
        // This shouldn't be happening because we checked the file's readability before. But just in case.
        throw new ResourceNotFoundException("Static resource file '" + resourcePath + "' does not exists.", e);
    } catch (Exception e) {
        // UnsupportedOperationException, IOException or any other Exception that might occur.
        throw new FileOperationException(
                "Cannot read file attributes from static resource file '" + resourcePath + "'.", e);
    }
    if (fileAttributes.isRegularFile()) {
        return ZonedDateTime.ofInstant(fileAttributes.lastModifiedTime().toInstant(), GMT_TIME_ZONE);
    } else {
        /*
         * From book "OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide" page 478:
         *      Java defines a regular file as one that contains content, as opposed to a symbolic link,
         *      directory, resource (e.g. port, pipe), or other non-regular files that may be present in some
         *      operating systems. [...] It is possible for isRegularFile() to return true for a symbolic link,
         *      as long as the link resolves to a regular file.
         * Hence, checking 'isRegularFile' of a file is enough to determine its existence and not being a directory.
         */
        throw new ResourceNotFoundException(
                "Static resource file '" + resourcePath + "' is not a regular file.");
    }
}

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

private Properties loadConfigFile(Path importFile) {
    // Check for a configFile
    final Path config = importFile.getParent()
            .resolve(configurationService.getStringConfiguration(CONFIG_KEY_CONF_FILE, "config"));
    if (Files.isReadable(config)) {
        try {// w  ww  . ja v a  2 s . c  o m
            Properties prop = new Properties();
            final FileInputStream inStream = new FileInputStream(config.toFile());
            prop.load(inStream);
            inStream.close();
            return prop;
        } catch (IOException e) {
            log.warn("could not read dirConfigFile {}: {}", config, e.getMessage());
        }
    }
    return null;
}

From source file:com.ontotext.s4.service.S4ServiceClient.java

/**
 * Annotates the contents of a single file returning an
 * {@link InputStream} from which the annotated content can be read
 * // ww  w.j ava 2s .  co m
 * @param documentContent the file which will be annotated
 * @param documentEncoding the encoding of the file which will be annotated
 * @param documentMimeType the MIME type of the file which will be annotated
 * @param serializationFormat the serialization format used for the annotated content
  *
 * @throws IOException if there are problems reading the contents of the file
 * @throws S4ServiceClientException
 */
public InputStream annotateFileContentsAsStream(File documentContent, Charset documentEncoding,
        SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        throws IOException, S4ServiceClientException {

    Path documentPath = documentContent.toPath();
    if (!Files.isReadable(documentPath)) {
        throw new IOException("File " + documentPath.toString() + " is not readable.");
    }
    ByteBuffer buff;
    buff = ByteBuffer.wrap(Files.readAllBytes(documentPath));
    String content = documentEncoding.decode(buff).toString();

    return annotateDocumentAsStream(content, documentMimeType, serializationFormat);
}

From source file:business.services.FileService.java

public HttpEntity<InputStreamResource> downloadAccessLog(String filename,
        boolean writeContentDispositionHeader) {
    try {//from w w w  .  ja  va2 s.  c o  m
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath(accessLogsPath).normalize();
        filename = filename.replace(fileSystem.getSeparator(), "_");
        filename = URLEncoder.encode(filename, "utf-8");

        Path f = fileSystem.getPath(accessLogsPath, filename).normalize();
        // filter path names that point to places outside the logs path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            log.error("Invalid filename: " + filename);
            throw new FileDownloadError("Invalid file name");
        }
        if (!Files.isReadable(f)) {
            log.error("File does not exist: " + filename);
            throw new FileDownloadError("File does not exist");
        }

        InputStream input = new FileInputStream(f.toFile());
        InputStreamResource resource = new InputStreamResource(input);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        if (writeContentDispositionHeader) {
            headers.set("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_"));
        }
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:misc.FileHandler.java

/**
 * Encrypts the given file using the newest key found in the respective
 * access bundle and protects the metadata with a message authentication
 * code using the respective integrity key, if desired. Otherwise, the file
 * stays as is and no message authentication code is computed.
 * /*from   ww w. j a  v  a  2  s . c  o m*/
 * @param prefix
 *            the path to the client's root directory. May not be
 *            <code>null</code>.
 * @param file
 *            the relative path to the client's root directory of the
 *            original file to protect. May not be <code>null</code>.
 * @param isDiff
 *            <code>true</code>, if the <code>file</code> is a binary diff.
 *            </code>false</code>, otherwise.
 * @param diff
 *            the complete path to the diff file. If <code>isDiff</code> is
 *            <code>true</code>, this parameter may not be <code>null</code>
 *            .
 * @return the complete path of the file, the metadata of the file as well
 *         as the MAC of the protected data (if applicable).
 *         <code>null</code>, if an error occurs (for example, if the access
 *         bundle is not found).
 */
public static Triple<Path, ProtectedData, byte[]> getData(Path prefix, Path file, boolean isDiff, Path diff) {
    if (prefix == null) {
        throw new NullPointerException("prefix may not be null!");
    }
    if (file == null) {
        throw new NullPointerException("file may not be null!");
    }
    if (isDiff && (diff == null)) {
        throw new IllegalArgumentException("if isDiff is true, diff must not be null!");
    }

    Path completePath = isDiff ? diff : Paths.get(prefix.toString(), file.toString());

    if (!Files.isReadable(completePath)) {
        Logger.logError(String.format("file %s must exist and be readable!", completePath.toString()));
        return null;
    }

    Triple<Path, ProtectedData, byte[]> result = null;
    Path accessBundleDirectory = FileHandler.getAccessBundleDirectory(prefix, file);
    AccessBundle bundle = FileHandler.getAccessBundle(prefix, accessBundleDirectory);

    if (bundle != null) {
        if ((bundle.getHighestContentKey() != null)) {
            PreparationProvider provider = PreparationProviderFactory.getInstance(
                    bundle.getHighestContentKey().getAlgorithm(),
                    bundle.getHighestIntegrityKey().getAlgorithm());
            result = provider.prepareSend(completePath, bundle.getHighestContentKey(),
                    bundle.getHighestIntegrityKey(), isDiff);
        } else if ((bundle.getHighestContentKey() == null) && (bundle.getHighestIntegrityKey() == null)) {
            PreparationProvider provider = PreparationProviderFactory.getInstance(null, null);
            result = provider.prepareSend(completePath, null, null, isDiff);
        } else {
            Logger.logError(String.format("Invalid access bundle in %s", accessBundleDirectory.toString()));
        }
    } else {
        Logger.logError(
                String.format("No or invalid access bundle present in %s", accessBundleDirectory.toString()));
    }

    return result;
}