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:nl.salp.warcraft4j.dev.DevToolsConfig.java

private void initialise(Configuration configuration) {
    if (configuration == null || configuration.isEmpty()) {
        throw new Warcraft4jConfigException(
                "Can't create a Warcraft4J configuration from an empty configuration.");
    }/*from www. j  a v  a  2 s.c  o m*/
    online = configuration.getBoolean(USE_CDN, USE_CDN_DEFAULT);
    if (!configuration.containsKey(WOW_DIR)) {
        throw new Warcraft4jConfigException("WoW installation directory was not configured.");
    }
    wowDir = Paths.get(resolve(configuration.getString(WOW_DIR), configuration));
    if (Files.notExists(wowDir) || !Files.isDirectory(wowDir) || !Files.isReadable(wowDir)) {
        throw new Warcraft4jConfigException(
                format("WoW installation directory %s does not exist or can't be read.", wowDir));
    }
    w4jDir = Paths.get(resolve(configuration.getString(W4J_DIR), configuration));
    if (Files.notExists(w4jDir)) {
        try {
            Files.createDirectories(w4jDir);
        } catch (IOException e) {
            throw new Warcraft4jConfigException(
                    format("Unable to create Warcraft4J working directory %s.", w4jDir), e);
        }
    } else if (!Files.isDirectory(w4jDir) || !Files.isReadable(w4jDir) || !Files.isWritable(w4jDir)) {
        throw new Warcraft4jConfigException(
                format("Warcraft4J working directory %s is either not a directory or not accessible.", w4jDir));
    }

    listFile = Paths.get(resolve(configuration.getString(LISTFILE, LISTFILE_DEFAULT), configuration));
    if (Files.notExists(listFile) || !Files.isRegularFile(listFile) || !Files.isReadable(listFile)) {
        listFile = null;
    }

    if (configuration.containsKey(DATA_EXTRACTED)) {
        extractDataDir = Paths.get(resolve(configuration.getString(DATA_EXTRACTED), configuration));
        if (Files.notExists(extractDataDir)) {
            try {
                Files.createDirectories(extractDataDir);
            } catch (IOException e) {
                throw new Warcraft4jConfigException(format("Unable to create extracted directory %s.", w4jDir),
                        e);
            }
        } else if (!Files.isDirectory(w4jDir) || !Files.isReadable(w4jDir) || !Files.isWritable(w4jDir)) {
            throw new Warcraft4jConfigException(
                    format("Extracted data directory %s is either not a directory or not accessible.", w4jDir));
        }
    }

    cache = configuration.getBoolean(CDN_CACHE, CDN_CACHE_DEFAULT);
    if (cache) {
        cacheDir = Paths
                .get(resolve(configuration.getString(CDN_CACHE_PATH, CDN_CACHE_PATH_DEFAULT), configuration));
        if (Files.notExists(cacheDir)) {
            try {
                Files.createDirectories(cacheDir);
            } catch (IOException e) {
                throw new Warcraft4jConfigException(format("Unable to create cache directory %s.", cacheDir),
                        e);
            }
        } else if (!Files.isDirectory(cacheDir) || !Files.isReadable(cacheDir) || !Files.isWritable(cacheDir)) {
            throw new Warcraft4jConfigException(
                    format("Cache directory %s is either not a directory or not accessible.", cacheDir));
        }
    }
    locale = Locale
            .getLocale(resolve(configuration.getString(WOW_LOCALE, valueOf(WOW_LOCALE_DEFAULT)), configuration))
            .orElseThrow(() -> new Warcraft4jConfigException(format("Locale %s is not a valid locale.",
                    resolve(configuration.getString(WOW_LOCALE), configuration))));
    region = Region
            .getRegion(resolve(configuration.getString(WOW_REGION, valueOf(WOW_REGION_DEFAULT)), configuration))
            .orElseThrow(() -> new Warcraft4jConfigException(format("Region %s is not a valid region.",
                    resolve(configuration.getString(WOW_REGION), configuration))));
    branch = Branch
            .getBranch(resolve(configuration.getString(WOW_BRANCH, valueOf(WOW_BRANCH_DEFAULT)), configuration))
            .orElseThrow(() -> new Warcraft4jConfigException(format("Branch %s is not a valid branch.",
                    resolve(configuration.getString(WOW_BRANCH), configuration))));
    mongodbUri = configuration.getString(MONGODB_URI, null);
    mongodbUser = configuration.getString(MONGODB_USER, null);
    mongodbPassword = configuration.getString(MONGODB_PASSWORD, null);
    if (configuration.containsKey(NEO4J_DATA_PATH)) {
        neo4jDataPath = Paths.get(resolve(configuration.getString(NEO4J_DATA_PATH), configuration));
        if (Files.notExists(neo4jDataPath)) {
            try {
                Files.createDirectories(neo4jDataPath);
            } catch (IOException e) {
                throw new Warcraft4jConfigException(
                        format("Unable to create Neo4J data directory %s.", neo4jDataPath), e);
            }
        } else if (!Files.isDirectory(neo4jDataPath) || !Files.isReadable(neo4jDataPath)
                || !Files.isWritable(neo4jDataPath)) {
            throw new Warcraft4jConfigException(format(
                    "Neo4J data directory %s is either not a directory or not accessible.", neo4jDataPath));
        }
    }
    neo4jExtUri = configuration.getString(NEO4J_EXT_URI, null);
    neo4jExtUser = configuration.getString(NEO4J_EXT_USER, null);
    neo4jExtPassword = configuration.getString(NEO4J_EXT_PASSWORD, null);
}

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

@Test
public void build() 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  w ww  .j  a v  a  2  s . c  om
    builder.storeUserName = true;
    int count = builder.fileSet(new FileSet(projectDir.resolve("src/main/java")))
            .fileSet(new FileSet(projectDir.resolve("src/test/java")))
            .optionalFileSet(new FileSet(projectDir.resolve("doesNotExist")))
            .directory(new Directory("test/directory", 0x755, "root", "root", null)).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"));
    assertTarContainsDirectory(file, "org/", null, null, null);
    assertTarContainsDirectory(file, "org/savantbuild/", null, null, null);
    assertTarContainsDirectory(file, "org/savantbuild/io/", null, null, null);
    assertTarContainsDirectory(file, "test/directory/", 0x755, "root", "root");
    assertEquals(count, 33);
}

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

/**
 * Initialise the instance from a configuration.
 *
 * @param configuration The configuration.
 *
 * @throws Warcraft4jConfigException When the configuration is invalid.
 *//*from   w  w w .j a va  2  s  . c  o  m*/

private void initialise(Configuration configuration) throws Warcraft4jConfigException {
    if (configuration == null || configuration.isEmpty()) {
        throw new Warcraft4jConfigException(
                "Can't create a Warcraft4J configuration from an empty configuration.");
    }
    online = configuration.getBoolean(ONLINE_KEY, ONLINE_DEFAULT);

    wowDir = Paths.get(configuration.getString(WOW_DIR_KEY, WOW_DIR_DEFAULT));
    if (Files.notExists(wowDir) || !Files.isDirectory(wowDir) || !Files.isReadable(wowDir)) {
        throw new Warcraft4jConfigException(
                format("WoW installation directory %s does not exist or can't be read.", wowDir));
    }

    cache = configuration.getBoolean(CACHE_KEY, CACHE_DEFAULT);
    if (cache) {
        cacheDir = Paths.get(configuration.getString(CACHE_DIR_KEY, CACHE_DIR_DEFAULT));
        if (Files.notExists(cacheDir)) {
            try {
                cacheDir = Files.createDirectories(cacheDir);
            } catch (IOException e) {
                throw new Warcraft4jConfigException(format("Unable to create cache directory %s.", cacheDir),
                        e);
            }
        } else if (!Files.isDirectory(cacheDir)) {
            throw new Warcraft4jConfigException(format("Cache directory %s is not a directory.", cacheDir));
        } else if (!Files.isReadable(cacheDir) || !Files.isWritable(cacheDir)) {
            throw new Warcraft4jConfigException(format("Cache directory %s is not accessible.", cacheDir));
        }
    }
    locale = Locale.getLocale(configuration.getString(LOCALE_KEY))
            .orElseThrow(() -> new Warcraft4jConfigException(
                    format("Locale %s is not a valid locale.", configuration.getString(LOCALE_KEY))));
    region = Region.getRegion(configuration.getString(REGION_KEY))
            .orElseThrow(() -> new Warcraft4jConfigException(
                    format("Region %s is not a valid region.", configuration.getString(REGION_KEY))));
    branch = Branch.getBranch(configuration.getString(BRANCH_KEY))
            .orElseThrow(() -> new Warcraft4jConfigException(
                    format("Branch %s is not a valid branch.", configuration.getString(BRANCH_KEY))));
}

From source file:com.seleritycorp.common.base.http.client.FileHttpClient.java

@Override
protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {
    final StatusLine statusLine;
    final FileHttpClientResponse response;
    byte[] content = null;

    String uri = request.getRequestLine().getUri();
    if (uri.startsWith("file://")) {
        File file = new File(URI.create(uri));
        uri = file.getAbsolutePath();//from   ww  w.  j  a  v  a  2  s. c o m
    }
    Path path = Paths.get(uri);

    if (request instanceof HttpGet) {
        if (Files.exists(path)) {
            if (Files.isReadable(path)) {
                if (!Files.isDirectory(path)) {
                    content = Files.readAllBytes(path);
                    statusLine = createStatusLine(HttpStatus.SC_OK, "OK");
                } else {
                    // Trying to GET a directory
                    statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request");
                }
            } else {
                // User does not have sufficient privilege to access the file
                statusLine = createStatusLine(HttpStatus.SC_FORBIDDEN, "Forbidden");
            }
        } else {
            // File does not exist.
            statusLine = createStatusLine(HttpStatus.SC_NOT_FOUND, "Not Found");
        }
    } else {
        // Request is not a HttpGet request. We currently only support GET, so we flag that the
        // client sent an illegal request.
        statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request");
    }

    response = new FileHttpClientResponse(statusLine);
    if (content != null) {
        response.setEntity(new ByteArrayEntity(content));
    }

    return response;
}

From source file:io.anserini.IndexerCW09B.java

public IndexerCW09B(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 a v  a 2s . co  m
    }
}

From source file:org.cryptomator.webdav.jackrabbit.DavLocatorFactoryImpl.java

@Override
public byte[] readPathSpecificMetadata(String encryptedPath) throws IOException {
    final Path metaDataFile = fsRoot.resolve(encryptedPath);
    if (!Files.isReadable(metaDataFile)) {
        return null;
    } else {//from   ww  w . j a  v  a2s . c om
        return Files.readAllBytes(metaDataFile);
    }
}

From source file:org.exist.launcher.LauncherWrapper.java

public static PropertiesConfiguration getVMProperties() {
    final PropertiesConfiguration vmProperties = new PropertiesConfiguration();
    final java.nio.file.Path propFile = ConfigurationHelper.lookup("vm.properties");
    InputStream is = null;/*  w  w w  .  j a v a 2  s .  com*/
    try {
        if (Files.isReadable(propFile)) {
            is = Files.newInputStream(propFile);
        }
        if (is == null) {
            is = LauncherWrapper.class.getResourceAsStream("vm.properties");
        }
        if (is != null) {
            vmProperties.read(new InputStreamReader(is, "UTF-8"));
        }
    } catch (final IOException e) {
        System.err.println("vm.properties not found");
    } catch (ConfigurationException e) {
        System.err.println("exception reading vm.properties: " + e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (final IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    return vmProperties;
}

From source file:aajavafx.LoginController.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    //Disables checkbox if username and password are blank
    saveCredentials.disableProperty()/*from  ww  w . ja  v  a 2  s.  co  m*/
            .bind(Bindings.isEmpty(userID.textProperty()).or(Bindings.isEmpty(passwordID.textProperty())));
    if (Files.isReadable(savedCredentials)) {
        //reads file and autofills the textfields
        try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(savedCredentials))) {
            UserCredentials user = (UserCredentials) in.readObject();
            userID.setText(user.getUsername());
            passwordID.setText(user.getPassword());

        } catch (IOException ex) {
            System.out.println("IO Exception: " + ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ????./*from  www  .  j  ava 2 s  . com*/
 * 
 * @param metadata urlTree
 * @param ctx urlTree
 * @return ??
 */
@Override
public InputStream load(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx)
        throws BadContentException, TargetNotFoundException {
    Path f = this.generateFileObj(metadata.getAbsolutePath());

    if (!Files.exists(f) || !Files.isReadable(f)) {
        throw new TargetNotFoundException("cannot read real file");
    }

    InputStream contents;
    try {
        contents = Files.newInputStream(f);
    } catch (IOException e) {
        throw new GenericResourceException(e);
    }

    String contentType = new MimetypesFileTypeMap().getContentType(f.getFileName().toString());
    metadata.setContentType(contentType);

    return contents;
}

From source file:io.anserini.search.SearchCollection.java

@SuppressWarnings("unchecked")
public <K> int runTopics() throws IOException {
    IndexSearcher searcher = new IndexSearcher(reader);
    searcher.setSimilarity(similarity);/*  w  w  w  .ja  v a  2 s  . c  o m*/

    Path topicsFile = Paths.get(args.topics);

    if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) {
        throw new IllegalArgumentException(
                "Topics file : " + topicsFile + " does not exist or is not a (readable) file.");
    }

    TopicReader<K> tr;
    SortedMap<K, Map<String, String>> topics;
    try {
        tr = (TopicReader<K>) Class.forName("io.anserini.search.query." + args.topicReader + "TopicReader")
                .getConstructor(Path.class).newInstance(topicsFile);
        topics = tr.read();
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to load topic reader: " + args.topicReader);
    }

    final String runTag = "Anserini_" + args.topicfield + "_" + (args.keepstop ? "KeepStopwords_" : "")
            + FIELD_BODY + "_" + (args.searchtweets ? "SearchTweets_" : "") + similarity.toString();

    PrintWriter out = new PrintWriter(
            Files.newBufferedWriter(Paths.get(args.output), StandardCharsets.US_ASCII));

    for (Map.Entry<K, Map<String, String>> entry : topics.entrySet()) {
        K qid = entry.getKey();
        String queryString = entry.getValue().get(args.topicfield);

        ScoredDocuments docs;
        if (args.searchtweets) {
            docs = searchTweets(searcher, qid, queryString, Long.parseLong(entry.getValue().get("time")));
        } else {
            docs = search(searcher, qid, queryString);
        }

        /**
         * the first column is the topic number.
         * the second column is currently unused and should always be "Q0".
         * the third column is the official document identifier of the retrieved document.
         * the fourth column is the rank the document is retrieved.
         * the fifth column shows the score (integer or floating point) that generated the ranking.
         * the sixth column is called the "run tag" and should be a unique identifier for your
         */
        for (int i = 0; i < docs.documents.length; i++) {
            out.println(String.format(Locale.US, "%s Q0 %s %d %f %s", qid,
                    docs.documents[i].getField(FIELD_ID).stringValue(), (i + 1), docs.scores[i],
                    ((i == 0 || i == docs.documents.length - 1) ? runTag : "See_Line1")));
        }
    }
    out.flush();
    out.close();

    return topics.size();
}