Example usage for java.nio.file Files isWritable

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

Introduction

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

Prototype

public static boolean isWritable(Path path) 

Source Link

Document

Tests whether a file is writable.

Usage

From source file:nl.salp.warcraft4j.casc.cdn.util.CascFileExtractor.java

private boolean isWritableFile(Path file) {
    return Files.notExists(file) || (Files.isRegularFile(file) && Files.isWritable(file));
}

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  .ja v  a2 s  . co  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.config.PropertyWarcraft4jConfig.java

/**
 * Initialise the instance from a configuration.
 *
 * @param configuration The configuration.
 *
 * @throws Warcraft4jConfigException When the configuration is invalid.
 *///  w  w  w . ja  v a 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: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.");
    }// www.j a v  a 2s.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.apache.nifi.controller.repository.FileSystemRepository.java

@Override
public void purge() {
    // delete all content from repositories
    for (final Path path : containers.values()) {
        FileUtils.deleteFilesInDir(path.toFile(), null, LOG, true);
    }//from  ww w.  j a  va2 s  . c  om

    for (final Path path : containers.values()) {
        if (!Files.exists(path)) {
            throw new RepositoryPurgeException("File " + path.toFile().getAbsolutePath() + " does not exist");
        }

        // Try up to 10 times to see if the directory is writable, in case another process (like a
        // virus scanner) has the directory temporarily locked
        boolean writable = false;
        for (int i = 0; i < 10; i++) {
            if (Files.isWritable(path)) {
                writable = true;
                break;
            } else {
                try {
                    Thread.sleep(100L);
                } catch (final Exception e) {
                }
            }
        }
        if (!writable) {
            throw new RepositoryPurgeException("File " + path.toFile().getAbsolutePath() + " is not writable");
        }
    }

    resourceClaimManager.purge();
}

From source file:org.apache.nifi.controller.repository.StandardProcessSession.java

@Override
public FlowFile importFrom(final Path source, final boolean keepSourceFile, final FlowFile destination) {
    validateRecordState(destination);/*from   w w  w  .  j  a v a  2  s .  com*/
    // TODO: find a better solution. With Windows 7 and Java 7 (very early update, at least), Files.isWritable(source.getParent()) returns false, even when it should be true.
    if (!keepSourceFile && !Files.isWritable(source.getParent()) && !source.getParent().toFile().canWrite()) {
        // If we do NOT want to keep the file, ensure that we can delete it, or else error.
        throw new FlowFileAccessException("Cannot write to path "
                + source.getParent().toFile().getAbsolutePath() + " so cannot delete file; will not import.");
    }

    final StandardRepositoryRecord record = records.get(destination);

    final ContentClaim newClaim;
    final long claimOffset;

    try {
        newClaim = context.getContentRepository().create(context.getConnectable().isLossTolerant());
        claimLog.debug("Creating ContentClaim {} for 'importFrom' for {}", newClaim, destination);
    } catch (final IOException e) {
        throw new FlowFileAccessException("Unable to create ContentClaim due to " + e.toString(), e);
    }

    claimOffset = 0L;
    long newSize = 0L;
    try {
        newSize = context.getContentRepository().importFrom(source, newClaim);
        bytesWritten += newSize;
        bytesRead += newSize;
    } catch (final Throwable t) {
        destroyContent(newClaim);
        throw new FlowFileAccessException(
                "Failed to import data from " + source + " for " + destination + " due to " + t.toString(), t);
    }

    removeTemporaryClaim(record);

    final FlowFileRecord newFile = new StandardFlowFileRecord.Builder().fromFlowFile(record.getCurrent())
            .contentClaim(newClaim).contentClaimOffset(claimOffset).size(newSize)
            .addAttribute(CoreAttributes.FILENAME.key(), source.toFile().getName()).build();
    record.setWorking(newFile, CoreAttributes.FILENAME.key(), source.toFile().getName());

    if (!keepSourceFile) {
        deleteOnCommit.put(newFile, source);
    }

    return newFile;
}

From source file:org.apache.openaz.xacml.std.pap.StdEngine.java

private void intialize() throws PAPException, IOException {
    ////ww  w  .jav a 2s .  com
    // Sanity check the repository path
    //
    if (this.repository == null) {
        throw new PAPException("No repository specified.");
    }
    if (Files.notExists(this.repository)) {
        Files.createDirectory(repository);
    }
    if (!Files.isDirectory(this.repository)) {
        throw new PAPException("Repository is NOT a directory: " + this.repository.toAbsolutePath());
    }
    if (!Files.isWritable(this.repository)) {
        throw new PAPException("Repository is NOT writable: " + this.repository.toAbsolutePath());
    }
    //
    // Load our groups
    //
    this.loadGroups();
}

From source file:org.apache.pulsar.io.file.FileSourceConfig.java

public void validate() {
    if (StringUtils.isBlank(inputDirectory)) {
        throw new IllegalArgumentException("Required property not set.");
    } else if (Files.notExists(Paths.get(inputDirectory), LinkOption.NOFOLLOW_LINKS)) {
        throw new IllegalArgumentException("Specified input directory does not exist");
    } else if (!Files.isReadable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("Specified input directory is not readable");
    } else if (Optional.ofNullable(keepFile).orElse(false) && !Files.isWritable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("You have requested the consumed files to be deleted, but the "
                + "source directory is not writeable.");
    }//from w  ww  .j  a va2  s  .  c o m

    if (StringUtils.isNotBlank(fileFilter)) {
        try {
            Pattern.compile(fileFilter);
        } catch (final PatternSyntaxException psEx) {
            throw new IllegalArgumentException("Invalid Regex pattern provided for fileFilter");
        }
    }

    if (minimumFileAge != null && Math.signum(minimumFileAge) < 0) {
        throw new IllegalArgumentException("The property minimumFileAge must be non-negative");
    }

    if (maximumFileAge != null && Math.signum(maximumFileAge) < 0) {
        throw new IllegalArgumentException("The property maximumFileAge must be non-negative");
    }

    if (minimumSize != null && Math.signum(minimumSize) < 0) {
        throw new IllegalArgumentException("The property minimumSize must be non-negative");
    }

    if (maximumSize != null && Math.signum(maximumSize) < 0) {
        throw new IllegalArgumentException("The property maximumSize must be non-negative");
    }

    if (pollingInterval != null && pollingInterval <= 0) {
        throw new IllegalArgumentException("The property pollingInterval must be greater than zero");
    }

    if (numWorkers != null && numWorkers <= 0) {
        throw new IllegalArgumentException("The property numWorkers must be greater than zero");
    }
}

From source file:org.apache.rya.api.path.PathUtils.java

/**
 * Indicates whether file lives in a secure directory relative to the
 * program's user./*w  w  w . java 2  s  .  com*/
 * @param file {@link Path} to test.
 * @param user {@link UserPrincipal} to test. If {@code null}, defaults to
 * current user.
 * @param symlinkDepth Number of symbolic links allowed.
 * @return {@code true} if file's directory is secure.
 */
public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) {
    if (!file.isAbsolute()) {
        file = file.toAbsolutePath();
    }
    if (symlinkDepth <= 0) {
        // Too many levels of symbolic links
        return false;
    }
    // Get UserPrincipal for specified user and superuser
    final Path fileRoot = file.getRoot();
    if (fileRoot == null) {
        return false;
    }
    final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem();
    final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService();
    UserPrincipal root = null;
    try {
        if (SystemUtils.IS_OS_UNIX) {
            root = upls.lookupPrincipalByName("root");
        } else {
            root = upls.lookupPrincipalByName("Administrators");
        }
        if (user == null) {
            user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        }
        if (root == null || user == null) {
            return false;
        }
    } catch (final IOException x) {
        return false;
    }
    // If any parent dirs (from root on down) are not secure, dir is not secure
    for (int i = 1; i <= file.getNameCount(); i++) {
        final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString());
        try {
            if (Files.isSymbolicLink(partialPath)) {
                if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) {
                    // Symbolic link, linked-to dir not secure
                    return false;
                }
            } else {
                final UserPrincipal owner = Files.getOwner(partialPath);
                if (!user.equals(owner) && !root.equals(owner)) {
                    // dir owned by someone else, not secure
                    return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath);
                }
            }
        } catch (final IOException x) {
            return false;
        }
    }
    return true;
}

From source file:org.carcv.web.beans.StorageBeanIT.java

/**
 * Test method for {@link org.carcv.web.beans.StorageBean#getPrefix()}.
 *///  ww  w .j a v a2 s  .com
@Test
public void testGetPrefix() {
    String env = System.getenv(StorageBean.envname_OPENSHIFT_DATA_DIR);
    Path checkedPath;

    if (env == null) { // if test isn't on OpenShift
        String jbossData = System.getProperty("jboss.server.data.dir");
        assertEquals(jbossData, storageBean.getPrefix());

        checkedPath = Paths.get(jbossData);
    } else {
        assertEquals(env, storageBean.getPrefix());
        checkedPath = Paths.get(env);
    }

    assertNotNull(checkedPath);
    assertTrue(Files.exists(checkedPath));
    assertTrue(Files.isDirectory(checkedPath));
    assertTrue(Files.isWritable(checkedPath));
}