Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

In this page you can find the example usage for java.io File canWrite.

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:cz.cas.lib.proarc.common.config.AppConfiguration.java

/**
 * checks file/folder parameters/*from   www.j a v  a2  s . com*/
 * @return {@code true} iff {@code f} exists
 */
private static boolean checkFile(File f, boolean mustExist, Boolean expectDirectory, Boolean expectCanRead,
        Boolean expextCanWrite) throws IOException {

    if (f.exists()) {
        if (expectDirectory != null) {
            if (expectDirectory && !f.isDirectory()) {
                throw new IOException(String.format("Not a folder: '%s'!", f));
            } else if (!expectDirectory && f.isDirectory()) {
                throw new IOException(String.format("Not a file: '%s'!", f));
            }
        }
        if (expectCanRead != null) {
            if (expectCanRead != f.canRead()) {
                throw new IOException(
                        String.format("Invalid read permission (=%s) for: '%s'!", !expectCanRead, f));
            }
        }
        if (expextCanWrite != null) {
            if (expextCanWrite != f.canWrite()) {
                throw new IOException(
                        String.format("Invalid write permission (=%s) for: '%s'!", !expextCanWrite, f));
            }
        }
        return true;
    } else if (mustExist) {
        if (expectDirectory != null && expectDirectory) {
            throw new FileNotFoundException(String.format("Folder '%s' not founf!", f));
        } else {
            throw new FileNotFoundException(String.format("File '%s' not founf!", f));
        }
    }
    return false;
}

From source file:com.xse.eclipseui.widgets.validators.PathValidator.java

@Override
public IStatus validate(final String value) {
    final IStatus validationStatus = super.validate(value);

    if (validationStatus.isOK()) {
        if (!this.isMandatory() && StringUtils.isEmpty(value)) {
            return Status.OK_STATUS;
        }//from w ww  .  j  ava  2 s. co  m

        final File file = new File(value);
        if (this.isDirectory) {
            if (file.exists() && file.isDirectory() && file.canWrite()) {
                return Status.OK_STATUS;
            }
        } else {
            if (this.exists) {
                if (file.exists() && file.isFile() && file.canRead()) {
                    return Status.OK_STATUS;
                }
            } else {
                final String fullPathNoEndSeparator = FilenameUtils.getFullPathNoEndSeparator(value);
                if (fullPathNoEndSeparator != null) {
                    final File parentPath = new File(fullPathNoEndSeparator);
                    if (parentPath.exists() && parentPath.isDirectory() && parentPath.canExecute()
                            && parentPath.canWrite()) {
                        return Status.OK_STATUS;
                    }
                }
            }
        }

        return new Status(this.errorLevel, this.pluginId, this.getMessage());
    }

    return validationStatus;
}

From source file:de.iew.stagediver.fx.database.provider.impl.HSQLDBProvider.java

/**
 * Validates the configured database file system path. Does not have any effect if a path is not configured. If
 * configured the path must be a writeable directory.
 *
 * @throws DBProviderConfigurationException if the validation failed
 *///ww w. j  a v a  2 s  .  co m
public void validateConfiguredDatabasePath() throws DBProviderConfigurationException {
    // The database path could also be reused for the res-backend but then requires a backend specific validation
    // which is not yet implemented.
    if (StringUtils.isNotBlank(this.databasePath)) {
        File databasePathTest = new File(this.databasePath);

        if (!(databasePathTest.isDirectory() && databasePathTest.canWrite())) {
            throw new DBProviderConfigurationException(DATABASE_PATH,
                    "The path is not a directory or not writeable");
        }
    }
}

From source file:ch.astina.hesperid.installer.web.services.InstallationManager.java

public boolean hasWriteableHomeDirectory() {
    String installDir = getApplicationHomeDirectoryPath();

    if (installDir == null || installDir.isEmpty()) {
        return false;
    }//from   w  w  w .  j a  v  a2s . co m

    File dir = new File(installDir);

    return (dir.isDirectory() && dir.canWrite());
}

From source file:it.geosolutions.mariss.wps.ppio.OutputResourcesPPIO.java

@Override
public void encode(Object value, OutputStream os) throws Exception {

    ZipOutputStream zos = null;/*  www.ja  va2  s.co  m*/
    try {
        OutputResource or = (OutputResource) value;

        zos = new ZipOutputStream(os);
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.DEFAULT_COMPRESSION);

        Iterator<File> iter = or.getDeletableResourcesIterator();
        while (iter.hasNext()) {

            File tmp = iter.next();
            if (!tmp.exists() || !tmp.canRead() || !tmp.canWrite()) {
                LOGGER.warning("Skip Deletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

            if (!tmp.delete()) {
                LOGGER.warning("File '" + tmp.getName() + "' cannot be deleted...");
            }
        }
        iter = null;

        Iterator<File> iter2 = or.getUndeletableResourcesIterator();
        while (iter2.hasNext()) {

            File tmp = iter2.next();
            if (!tmp.exists() || !tmp.canRead()) {
                LOGGER.warning("Skip Undeletable file '" + tmp.getName() + "' some problems occurred...");
                continue;
            }

            addToZip(tmp, zos);

        }
    } finally {
        try {
            zos.close();
        } catch (IOException e) {
            LOGGER.severe(e.getMessage());
        }
    }
}

From source file:com.legstar.codegen.CodeGenUtil.java

/**
 * Check that a directory is valid./*from   ww  w  .jav  a2 s  . c om*/
 * 
 * @param fdir the directory to check
 * @param create true if directory should be created when not found
 */
public static void checkDirectory(final File fdir, final boolean create) {

    if (fdir == null) {
        throw (new IllegalArgumentException("No directory name was specified"));
    }

    if (!fdir.exists()) {
        if (!create) {
            throw (new IllegalArgumentException(fdir.getName() + " does not exist"));
        } else {
            if (!fdir.mkdirs()) {
                throw (new IllegalArgumentException("Could not create directory " + fdir.getName()));
            } else {
                return;
            }
        }
    }
    if (!fdir.isDirectory()) {
        throw (new IllegalArgumentException(fdir.getName() + " is not a directory"));
    }
    if (!fdir.canWrite()) {
        throw (new IllegalArgumentException("Directory " + fdir.getName() + " is not writable"));
    }
}

From source file:MainClass.java

public void setFileStats(File dir) {
    String files[] = dir.list();//  www .  j a  va2 s. c  om
    data = new Object[files.length][titles.length];

    for (int i = 0; i < files.length; i++) {
        File tmp = new File(files[i]);
        data[i][0] = new Boolean(tmp.isDirectory());
        data[i][1] = tmp.getName();
        data[i][2] = new Boolean(tmp.canRead());
        data[i][3] = new Boolean(tmp.canWrite());
        data[i][4] = new Long(tmp.length());
        data[i][5] = new Date(tmp.lastModified());
    }

    fireTableDataChanged();
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicUpdater.java

/**
 * Method to backup granules that have been removed from the index.
 * /* w  w w  .  ja  va 2 s  .com*/
 * <P>
 * The provided backup dire must exist and be writable for the process.
 * 
 * @param filesToBackup {@link List} of files to backup, that is move to the backup directory
 * @param backUpDirectory target directory for the process
 * @return <code>false</code> in case we manage to move the files, <code>false</code> otherwise.
 */
static boolean backUpGranulesFiles(final List<File> filesToBackup, final File backUpDirectory) {

    //checks on dir
    if (backUpDirectory == null) {
        throw new IllegalArgumentException("Provided null back up directory");
    }
    if (!backUpDirectory.exists() || !backUpDirectory.isDirectory() || !backUpDirectory.canWrite()) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Provided directory does not exist or it is not writable");
        }
        return false;
    }

    if (filesToBackup == null || filesToBackup.size() == 0) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Provided list of files to backup is empty");
        }
        return true;
    }

    // now the magic
    boolean retValue = true;
    for (File granule : filesToBackup) {

        // move
        try {
            FileUtils.moveFileToDirectory(granule, backUpDirectory, false);
        } catch (IOException e) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(e.getLocalizedMessage(), e);
            }
            // if we fail we try to remove the afterwards
            retValue = false;
        }
    }
    return retValue;
}

From source file:com.netflix.lipstick.Main.java

private static String validateLogFile(String logFileName, String scriptName) {
    String strippedDownScriptName = null;

    if (scriptName != null) {
        File scriptFile = new File(scriptName);
        if (!scriptFile.isDirectory()) {
            String scriptFileAbsPath;
            try {
                scriptFileAbsPath = scriptFile.getCanonicalPath();
                strippedDownScriptName = getFileFromCanonicalPath(scriptFileAbsPath);
            } catch (IOException ioe) {
                log.warn("Could not compute canonical path to the script file " + ioe.getMessage());
                strippedDownScriptName = null;
            }/*from  w ww .  ja va2s . com*/
        }
    }

    String defaultLogFileName = (strippedDownScriptName == null ? "pig_" : strippedDownScriptName)
            + new Date().getTime() + ".log";
    File logFile;

    if (logFileName != null) {
        logFile = new File(logFileName);

        // Check if the file name is a directory
        // append the default file name to the file
        if (logFile.isDirectory()) {
            if (logFile.canWrite()) {
                try {
                    logFileName = logFile.getCanonicalPath() + File.separator + defaultLogFileName;
                } catch (IOException ioe) {
                    log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                    return null;
                }
                return logFileName;
            } else {
                log.warn("Need write permission in the directory: " + logFileName + " to create log file.");
                return null;
            }
        } else {
            // we have a relative path or an absolute path to the log file
            // check if we can write to the directory where this file
            // is/will be stored

            if (logFile.exists()) {
                if (logFile.canWrite()) {
                    try {
                        logFileName = new File(logFileName).getCanonicalPath();
                    } catch (IOException ioe) {
                        log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                        return null;
                    }
                    return logFileName;
                } else {
                    // do not have write permissions for the log file
                    // bail out with an error message
                    log.warn("Cannot write to file: " + logFileName + ". Need write permission.");
                    return logFileName;
                }
            } else {
                logFile = logFile.getParentFile();

                if (logFile != null) {
                    // if the directory is writable we are good to go
                    if (logFile.canWrite()) {
                        try {
                            logFileName = new File(logFileName).getCanonicalPath();
                        } catch (IOException ioe) {
                            log.warn("Could not compute canonical path to the log file " + ioe.getMessage());
                            return null;
                        }
                        return logFileName;
                    } else {
                        log.warn("Need write permission in the directory: " + logFile + " to create log file.");
                        return logFileName;
                    }
                } // end if logFile != null else is the default in fall
                  // through
            } // end else part of logFile.exists()
        } // end else part of logFile.isDirectory()
    } // end if logFileName != null

    // file name is null or its in the current working directory
    // revert to the current working directory
    String currDir = System.getProperty("user.dir");
    logFile = new File(currDir);
    logFileName = currDir + File.separator + (logFileName == null ? defaultLogFileName : logFileName);
    if (logFile.canWrite()) {
        return logFileName;
    }
    log.warn("Cannot write to log file: " + logFileName);
    return null;
}

From source file:com.sap.prd.mobile.ios.mios.UpdateVersionInPomMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from  w  w  w.ja va  2s .  co m*/

        String version = getXCodeVersion();

        if (version == null || version.isEmpty())
            throw new MojoExecutionException("No xcode version found. Could not update version in pom.");

        if (appendSnapshot)
            version += "-SNAPSHOT";

        final File pom = new File("pom.xml").getAbsoluteFile();

        if (!pom.canWrite())
            throw new MojoExecutionException(
                    "Pom file '" + pom + "' is readonly. Cannot update version in this file.");

        Model model = readPom(pom);

        String oldVersion = model.getVersion();

        if (oldVersion != null && oldVersion.equals(version)) {
            getLog().info("! XCode version matches pom version. No update needed.");
            return;
        }
        model.setVersion(version);

        writePom(pom, model);

        getLog().info(
                "! Version in pom file (" + pom + ") updated from '" + oldVersion + "' to " + version + ".");
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (XmlPullParserException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (XCodeException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}