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:com.ontotext.s4.service.S4ServiceClient.java

/**
 * Annotates the contents of a single file with the specified MIME type. Returns an object which allows
  * for convenient access to the annotations in the annotated document.
 * /*from  ww  w  .ja  v  a 2 s  .c o  m*/
 * @param documentContent the file whose contents will be annotated
 * @param documentEncoding the encoding of the document file
 * @param documentMimeType the MIME type of the document to annotated content as well as the annotations produced
 * @throws IOException
 * @throws S4ServiceClientException
 */
public AnnotatedDocument annotateFileContents(File documentContent, Charset documentEncoding,
        SupportedMimeType documentMimeType) 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 annotateDocument(content, documentMimeType);
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private void init() {
    try {//from   w  ww. j  a v a  2s . c o m
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.error("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    Path ddfHomePath = Paths.get(System.getProperty("ddf.home"));
    if (!keyStoreFile.isAbsolute()) {
        keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
    }
    if (!trustStoreFile.isAbsolute()) {
        trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.error("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    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);
        try {
            keyStore.load(null, null);
        } catch (NoSuchAlgorithmException | CertificateException | IOException ignore) {
        }
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        trustStore.load(tfis, trustStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.error("Unable to load system trust file.", e);
        try {
            trustStore.load(null, null);
        } catch (NoSuchAlgorithmException | CertificateException | IOException ignore) {
        }
    }
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void closeBundle() throws Exception {
    Bundle bundle = Bundles.createBundle();
    Path zip = Bundles.closeBundle(bundle);
    assertTrue(Files.isReadable(zip));
    assertEquals(zip, bundle.getSource());
    checkSignature(zip);//from  www.  j a  v  a2s. c  o  m
}

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

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

    Path file = projectDir.resolve("build/test/tars/test.tar");
    TarBuilder builder = new TarBuilder(file);
    builder.storeGroupName = true;/*from   ww  w  . j a va 2s.  co  m*/
    builder.storeUserName = true;
    int count = builder.fileSet(new ArchiveFileSet(projectDir.resolve("src/main/java"), "usr/local/main"))
            .fileSet(new ArchiveFileSet(projectDir.resolve("src/test/java"), "usr/local/test"))
            .optionalFileSet(new FileSet(projectDir.resolve("doesNotExist")))
            .directory(new Directory("test/directory", 0x755, "root", "root", null)).build();
    assertTrue(Files.isReadable(file));
    assertTarFileEquals(file, "usr/local/main/org/savantbuild/io/Copier.java",
            projectDir.resolve("src/main/java/org/savantbuild/io/Copier.java"));
    assertTarFileEquals(file, "usr/local/main/org/savantbuild/io/FileSet.java",
            projectDir.resolve("src/main/java/org/savantbuild/io/FileSet.java"));
    assertTarFileEquals(file, "usr/local/test/org/savantbuild/io/FileSetTest.java",
            projectDir.resolve("src/test/java/org/savantbuild/io/FileSetTest.java"));
    assertTarContainsDirectory(file, "usr/local/main/org/", null, null, null);
    assertTarContainsDirectory(file, "usr/local/test/org/", null, null, null);
    assertTarContainsDirectory(file, "usr/local/main/org/savantbuild/", null, null, null);
    assertTarContainsDirectory(file, "usr/local/test/org/savantbuild/", null, null, null);
    assertTarContainsDirectory(file, "usr/local/main/org/savantbuild/io/", null, null, null);
    assertTarContainsDirectory(file, "usr/local/test/org/savantbuild/io/", null, null, null);
    assertTarContainsDirectory(file, "test/directory/", 0x755, "root", "root");
    assertEquals(count, 43);
}

From source file:uk.co.unclealex.executable.generator.ScripterImplTest.java

protected void checkRun(Path homeDir, Path scriptPath, String expectedStdout, String expectedStderr,
        int expectedReturnValue, String... arguments) throws IOException {
    ProcessRequestBuilder processRequestBuilder = Guice.createInjector(new ProcessRequestBuilderModule())
            .getInstance(ProcessRequestBuilder.class);
    String command = scriptPath.toAbsolutePath().toString();
    final ProcessRequest processRequest = processRequestBuilder.forCommand(command).withArguments(arguments);
    Callable<ProcessResult> callable = new Callable<ProcessResult>() {
        @Override/*from www.  j  av  a 2  s . c  om*/
        public ProcessResult call() throws IOException {
            return processRequest.execute();
        }
    };
    List<String> commandParts = Lists.newArrayList();
    commandParts.add(command);
    commandParts.addAll(Arrays.asList(arguments));
    String fullCommand = Joiner.on(' ').join(commandParts);
    try {
        ProcessResult processResult = Executors.newSingleThreadExecutor().submit(callable).get(10,
                TimeUnit.SECONDS);
        Assert.assertTrue("The executable jar was not copied.",
                Files.isReadable(homeDir.resolve(".executable").resolve("executable-999.jar")));
        Assert.assertEquals("Command " + fullCommand + " produced the wrong stderr.", expectedStderr,
                processResult.getError());
        Assert.assertEquals("Command " + fullCommand + " produced the wrong stdout.", expectedStdout,
                processResult.getOutput());
        Assert.assertEquals("Command " + fullCommand + " returned with the wrong value.", expectedReturnValue,
                processResult.getReturnValue());
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        log.error("Running command " + fullCommand + " failed.", e);
        Assert.fail("Running command " + fullCommand + " failed.");
    }
}

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

public IndexClueWeb09b(String docsPath, String indexPath) 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);/*  w w w  .j  av a  2s  . c  om*/
    }
}

From source file:nl.salp.warcraft4j.config.PropertyWarcraft4jConfigTest.java

@Test
public void shouldCreateCacheDirectoryIfNotExisting() throws Exception {
    Path dir = testDir.resolve("newCacheDir");
    if (Files.exists(dir)) {
        delete(dir);/*from w  w w  . ja  va2s  .  c o  m*/
    }
    assertTrue("Cache directory not deleted.", Files.notExists(dir));
    when(configuration.getString(eq(PropertyWarcraft4jConfig.CACHE_DIR_KEY), anyString()))
            .thenReturn(String.valueOf(dir));

    PropertyWarcraft4jConfig config = new PropertyWarcraft4jConfig(configuration);

    assertTrue("Cache directory does not exist.", Files.exists(config.getCacheDirectory()));
    assertTrue("Cache directory is not a directory.", Files.isDirectory(config.getCacheDirectory()));
    assertTrue("Cache directory is not readable.", Files.isReadable(config.getCacheDirectory()));
}

From source file:org.apache.taverna.commandline.data.InputsHandler.java

private Bundle openInputBundle(CommandLineOptions options) throws IOException {
    if (!options.hasInputBundle()) {
        return DataBundles.createBundle();
    }/*from  w ww .ja  v a 2 s  . c  om*/
    Path inputBundlePath = Paths.get(options.getInputBundle());
    if (!Files.isReadable(inputBundlePath)) {
        throw new IOException("Can't read inputbundle: " + inputBundlePath);
    }
    if (options.hasSaveResultsToBundle()
            && safeIsSameFile(inputBundlePath, Paths.get(options.getSaveResultsToBundle()))) {
        // Note: It is valid to do -bundle same.zip -inputbundle same.zip, 
        // in which case we should NOT open it as readOnly, as that
        // might make a copy unnecessarily. In case of symlinks we'll use the
        // path from -bundle to avoid double-opening later
        return DataBundles.openBundle(Paths.get(options.getSaveResultsToBundle()));
    } else {
        return DataBundles.openBundleReadOnly(inputBundlePath);
    }
}

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 plugins The {@link PluginListConfig} 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
 *//*ww w  . j a  v  a 2  s  .  c  om*/
protected void loadPlugins(final PluginListConfig plugins, final Path dir) throws IOException {
    if (!Files.exists(dir))
        return;
    if (!Files.isDirectory(dir)) {
        WPManager.log.warn("Cannot load plugin overrides: {} is not a directory.", dir);
        return;
    }
    if (!Files.isReadable(dir)) {
        WPManager.log.warn("Cannot load plugin overrides: {} is not readable.", dir);
        return;
    }

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

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

/**
 * @see org.alfresco.repo.bulkimport.DirectoryAnalyser#analyseDirectory(org.alfresco.repo.bulkimport.ImportableItem, java.nio.file.DirectoryStream.Filter)
 *//* w w  w. ja v a  2s .  co  m*/
public AnalysedDirectory analyseDirectory(ImportableItem directory, DirectoryStream.Filter<Path> filter) {
    Path directoryFile = directory.getHeadRevision().getContentFile();
    AnalysedDirectory result = new AnalysedDirectory(listFiles(directoryFile, filter));

    if (log.isDebugEnabled()) {
        log.debug("Analysing directory " + FileUtils.getFileName(directoryFile) + "...");
    }

    // Build up the list of ImportableItems from the directory listing
    for (Path file : result.getOriginalPaths()) {
        // MNT-9763 bulkimport fails when there is a very large LastModified timestamp.
        String isoDate = null;
        try {
            isoDate = ISO8601DateFormat
                    .format(new Date(Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis()));
            ISO8601DateFormat.parse(isoDate);
        } catch (PlatformRuntimeException | IOException e) {
            log.warn("Failed to convert date " + isoDate + " to string for " + file.getFileName(), e);
            importStatus.incrementNumberOfUnreadableEntries();
            continue;
        }

        if (log.isTraceEnabled()) {
            log.trace("Scanning file " + FileUtils.getFileName(file) + "...");
        }

        if (Files.isReadable(file)) {
            try {
                nameChecker.evaluate(file.getFileName().toString());
            } catch (ConstraintException e) {
                if (log.isWarnEnabled()) {
                    log.warn("Skipping file with invalid name: '" + FileUtils.getFileName(file) + "'.");
                }
                // mark file with invalid name as unreadable
                importStatus.incrementNumberOfUnreadableEntries();

                continue;
            }

            if (isVersionFile(file)) {
                addVersionFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else if (isMetadataFile(file)) {
                addMetadataFile(directory, result, file);
                importStatus.incrementNumberOfFilesScanned();
            } else {
                boolean isDirectory = addParentFile(directory, result, file);

                if (isDirectory) {
                    importStatus.incrementNumberOfFoldersScanned();
                } else {
                    importStatus.incrementNumberOfFilesScanned();
                }
            }
        } else {
            if (log.isWarnEnabled()) {
                log.warn("Skipping unreadable file '" + FileUtils.getFileName(file) + "'.");
            }

            importStatus.incrementNumberOfUnreadableEntries();
        }
    }

    // Finally, remove any items from the list that aren't valid (don't have either a
    // contentFile or a metadataFile)
    Iterator<ImportableItem> iter = result.getImportableItems().iterator();

    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid() || !isMetadataValid(importableItem)) {
            iter.remove();
        }
    }

    iter = result.getImportableDirectories().iterator();
    while (iter.hasNext()) {
        ImportableItem importableItem = iter.next();

        if (!importableItem.isValid()) {
            iter.remove();
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Finished analysing directory " + FileUtils.getFileName(directoryFile) + ".");
    }

    return result;
}