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:com.hipu.bdb.util.FileUtils.java

/**
 * Ensure writeable directory.//from  ww w. j  ava2s  .c o  m
 *
 * If doesn't exist, we attempt creation.
 *
 * @param dir Directory to test for exitence and is writeable.
 *
 * @return The passed <code>dir</code>.
 *
 * @exception IOException If passed directory does not exist and is not
 * createable, or directory is not writeable or is not a directory.
 */
public static File ensureWriteableDirectory(File dir) throws IOException {
    if (!dir.exists()) {
        boolean success = dir.mkdirs();
        if (!success) {
            throw new IOException("Failed to create directory: " + dir);
        }
    } else {
        if (!dir.canWrite()) {
            throw new IOException("Dir " + dir.getAbsolutePath() + " not writeable.");
        } else if (!dir.isDirectory()) {
            throw new IOException("Dir " + dir.getAbsolutePath() + " is not a directory.");
        }
    }

    return dir;
}

From source file:com.ms.commons.test.common.FileUtil.java

private static void doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, FileFilter filter)
        throws IOException {
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }/* ww w .j a  va 2 s  .com*/
    } else {
        if (destDir.mkdirs() == false) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
        if (preserveFileDate) {
            destDir.setLastModified(srcDir.lastModified());
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    // recurse
    File[] files = srcDir.listFiles();
    if (files == null) { // null if security restricted
        throw new IOException("Failed to list contents of " + srcDir);
    }
    for (int i = 0; i < files.length; i++) {
        if (filter.accept(files[i])) {
            File copiedFile = new File(destDir, files[i].getName());
            if (files[i].isDirectory()) {
                doCopyDirectory(files[i], copiedFile, preserveFileDate, filter);
            } else {
                doCopyFile(files[i], copiedFile, preserveFileDate);
            }
        }
    }
}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 * ? ?     .//from   www  .j ava 2  s .com
 *
 * @param path ? ?  .
 * @return ? ?  true.
 * @see File#canWrite()
 */
public static boolean canWrite(String path) {
    boolean check = false;
    try {
        File checkFile = new File(path);
        if (checkFile.exists()) {
            check = checkFile.canWrite();
        }
    } catch (SecurityException e) {
        check = false;
    }
    return check;
}

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

/**
 * If the indexer file do not exists, build the indexer using the passed configuration and
 * return the corresponding properties object
 * /*w ww.ja v  a2 s .  co  m*/
 * @note: here we suppose that elevation are stored as double
 * @note: for a list of available SPI refer to:<br>
 *        geotools/trunk/modules/plugin/imagemosaic/src/main/resources/META-INF/services/org.
 *        geotools.gce.imagemosaic.properties.PropertiesCollectorSPI
 * 
 * @param indexer
 * @param configuration
 * @return 
 * @throws NullPointerException 
 * @throws IOException 
 */
protected static Properties buildIndexer(File indexer, ImageMosaicConfiguration configuration)
        throws NullPointerException, IOException {
    // ////
    // INDEXER
    // ////
    if (!indexer.exists()) {

        FileWriter outFile = null;
        PrintWriter out = null;
        try {
            indexer.createNewFile();

            if (!indexer.canWrite()) {
                final String message = "Unable to write on indexer.properties file at URL: "
                        + indexer.getAbsolutePath();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message);
                throw new IOException(message);
            }

            outFile = new FileWriter(indexer);
            out = new PrintWriter(outFile);

            File baseDir = indexer.getParentFile();

            // Write text to file
            // setting caching of file to false

            // create a private copy and fix inconsistencies in it
            configuration = configuration.clone();
            ConfigUtil.sanitize(configuration);

            // create regex files
            for (DomainAttribute domainAttr : configuration.getDomainAttributes()) {
                final File regexFile = new File(baseDir, domainAttr.getAttribName() + "regex.properties");
                ImageMosaicProperties.createRegexFile(regexFile, domainAttr.getRegEx());

                if (domainAttr.getEndRangeAttribName() != null) {
                    final File endRangeRegexFile = new File(baseDir,
                            domainAttr.getEndRangeAttribName() + "regex.properties");
                    ImageMosaicProperties.createRegexFile(endRangeRegexFile, domainAttr.getEndRangeRegEx());
                }
            }

            StringBuilder indexerSB = createIndexer(configuration);
            out.append(indexerSB);

            //                out.println(org.geotools.gce.imagemosaic.Utils.Prop.CACHING+"=false");
            //
            //                // create indexer
            //                DomainAttribute timeAttr = ConfigUtil.getTimeAttribute(configuration);
            //                DomainAttribute elevAttr = ConfigUtil.getElevationAttribute(configuration);
            //
            //                if(timeAttr != null) {
            //                    out.println(org.geotools.gce.imagemosaic.Utils.Prop.TIME_ATTRIBUTE+"="+getAttribDeclaration(timeAttr));
            //                }
            //                if(elevAttr != null) {
            //                    out.println(org.geotools.gce.imagemosaic.Utils.Prop.ELEVATION_ATTRIBUTE+"="+getAttribDeclaration(elevAttr));
            //                }
            //
            //                List<DomainAttribute> customAttribs = ConfigUtil.getCustomDimensions(configuration);
            //                if( ! customAttribs.isEmpty() ) {
            //                    out.println("AdditionalDomainAttributes");
            //                    String sep="=";
            //                    for (DomainAttribute customAttr : customAttribs) {
            //                        out.print(sep);
            //                        sep=",";
            //                        out.print(getDimensionDeclaration(customAttr));
            //                    }
            //                    out.println();
            //                }
            //
            //                out.print("Schema=*the_geom:Polygon,location:String");
            //                for (DomainAttribute attr : configuration.getDomainAttributes()) {
            //                    TYPE type = attr.getType();
            //                    printSchemaField(out, attr.getAttribName(), type);
            //                    if(attr.getEndRangeAttribName() != null)
            //                        printSchemaField(out, attr.getEndRangeAttribName(), type);
            //                }
            //                out.println();
            //
            //                String sep="";
            //                out.print("PropertyCollectors=");
            //                for (DomainAttribute attr : configuration.getDomainAttributes()) {
            //                    TYPE type = attr.getType();
            //                    out.print(sep);
            //                    sep=";";
            //                    printCollectorField(out, attr.getAttribName(), type);
            //                    if(attr.getEndRangeAttribName() != null)
            //                        printCollectorField(out, attr.getEndRangeAttribName(), type);
            //                }
            //                out.println();

        } catch (IOException e) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("Error occurred while writing indexer.properties file at URL: "
                        + indexer.getAbsolutePath(), e);
            return null;
        } finally {
            if (out != null) {
                out.flush();
                IOUtils.closeQuietly(out);
            }
            out = null;
            if (outFile != null) {
                IOUtils.closeQuietly(outFile);
            }
            outFile = null;
        }
        return getPropertyFile(indexer);
    } else {
        // file -> indexer.properties
        /**
         * get the Caching property and set it to false
         */
        Properties indexerProps = getPropertyFile(indexer);
        String caching = indexerProps.getProperty(CACHING_KEY);
        if (caching != null) {
            if (caching.equals("true")) {
                indexerProps.setProperty(CACHING_KEY, "false");
            }
        } else {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("Unable to get the " + CACHING_KEY + " property into the "
                        + indexer.getAbsolutePath() + " file.");
        }

        return indexerProps;
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 *
 * Checks if a directory already exists. If it does not exist it is created. If it already
 * exists then, its permissions are ok.// ww w. ja  v  a 2  s.c o  m
 *
 * @param aStringBuilder
 *            StringBuilder containing an error message if an exception is thrown
 * @param aDirectory
 *            String containing the directory path.
 * @return true if the variable is defined
 *
 * */

private static synchronized boolean checkFolderPermissions(StringBuilder aStringBuilder, String aDirectory) {
    File directory = new File(aDirectory);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    if (!directory.canRead()) {
        aStringBuilder.append("The directory [" + directory + "] is not readable. "
                + "Please check your permissions rights.\n");
        return false;
    }
    if (!directory.canWrite()) {
        aStringBuilder.append("The directory [" + directory + "] is not writable. "
                + "Please check your permissions rights.\n");
        return false;
    }
    return true;
}

From source file:it.geosolutions.tools.compress.file.Extract.java

public static File extract(final File inFile, File destination, final boolean remove_source) throws Exception {

    if (inFile == null) {
        throw new IllegalArgumentException("Cannot open null file.");
    } else if (!inFile.exists()) {
        throw new FileNotFoundException(
                "The path does not match to an existent file into the filesystem: " + inFile);
    }// w w  w  .  ja va 2s .  co  m
    if (destination == null || !destination.isDirectory() || !destination.canWrite()) {
        throw new IllegalArgumentException(
                "Extract: cannot write to a null or not writeable destination folder: " + destination);
    }

    // the new file-dir
    File end_file = null;

    final Matcher m = match(inFile.getName());
    if (m != null) {
        switch (getEnumType(inFile, true)) {
        case TAR:
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Input file is a tar file: " + inFile);
                LOGGER.info("Untarring...");
            }
            end_file = new File(destination, getName(m));
            if (end_file.equals(inFile)) {
                // rename inFile
                File tarFile = new File(inFile.getParent(), inFile.getName() + ".tar");
                FileUtils.moveFile(inFile, tarFile);
                TarReader.readTar(tarFile, end_file);
            } else {
                TarReader.readTar(inFile, end_file);
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("tar extracted to " + end_file);
            }

            if (remove_source) {
                inFile.delete();
            }

            break;

        case BZIP2:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a BZ2 compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractBz2(inFile, end_file);

            if (remove_source) {
                inFile.delete();
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("BZ2 uncompressed to " + end_file.getAbsolutePath());
            }

            end_file = extract(end_file, destination, true);
            break;
        case GZIP:
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a Gz compressed file.");

            // Output filename
            end_file = new File(destination, getName(m));

            // uncompress BZ2 to the tar file
            Extractor.extractGzip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("GZ extracted to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, true);

            break;
        case ZIP:

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Input file is a ZIP compressed file. UnZipping...");

            // preparing path to extract to
            end_file = new File(destination, getName(m));

            // run the unzip method
            Extractor.unZip(inFile, end_file);

            if (remove_source)
                inFile.delete();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Zip file uncompressed to " + end_file);
            }

            // recursion
            end_file = extract(end_file, destination, remove_source);
            break;
        case NORMAL:

            end_file = inFile;

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Working on a not compressed file.");
            break;
        default:
            throw new Exception("format file still not supported! Please try using bz2, gzip or zip");
        } // switch
    } // if match
    else {
        throw new Exception("File do not match regular expression");
    }

    /**
     * returning output file name
     */
    return end_file;
}

From source file:com.crte.sipstackhome.ui.preferences.PreferencesWrapper.java

/**
 * /*www.  j av a2 s . com*/
 * @param ctxt
 * @param preferCache
 * @return
 */
private static File getStorageFolder(Context ctxt, boolean preferCache) {
    File root = Environment.getExternalStorageDirectory();
    if (!root.canWrite() || preferCache) {
        root = ctxt.getCacheDir();
    }

    if (root.canWrite()) {
        File dir = new File(root.getAbsolutePath() + File.separator
                + /*CustomDistribution.getSDCardFolder()*/ "SipStackHome");
        if (!dir.exists()) {
            dir.mkdirs();
            Log.d(THIS_FILE, " " + dir.getAbsolutePath());
        }
        return dir;
    }
    return null;
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static void forceUpdate() throws IOException, VcdiffDecodeException {
    File backupFile = new File(DATA_DIR, "helios.jar.bak");
    try {//from   w w  w  . j  a va  2 s . co  m
        Files.copy(IMPL_FILE.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException exception) {
        // We're going to wrap it so end users know what went wrong
        throw new IOException(String.format("Could not back up Helios implementation (%s %s, %s %s)",
                IMPL_FILE.canRead(), IMPL_FILE.canWrite(), backupFile.canRead(), backupFile.canWrite()),
                exception);
    }
    URL latestVersion = new URL("https://ci.samczsun.com/job/Helios/lastStableBuild/buildNumber");
    HttpURLConnection connection = (HttpURLConnection) latestVersion.openConnection();
    if (connection.getResponseCode() == 200) {
        boolean aborted = false;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(connection.getInputStream(), outputStream);
        String version = new String(outputStream.toByteArray(), "UTF-8");
        System.out.println("Latest version: " + version);
        int intVersion = Integer.parseInt(version);

        loop: while (true) {
            int buildNumber = loadHelios().buildNumber;
            int oldBuildNumber = buildNumber;
            System.out.println("Current Helios version is " + buildNumber);

            if (buildNumber < intVersion) {
                while (buildNumber <= intVersion) {
                    buildNumber++;
                    URL status = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber + "/api/json");
                    HttpURLConnection con = (HttpURLConnection) status.openConnection();
                    if (con.getResponseCode() == 200) {
                        JsonObject object = Json.parse(new InputStreamReader(con.getInputStream())).asObject();
                        if (object.get("result").asString().equals("SUCCESS")) {
                            JsonArray artifacts = object.get("artifacts").asArray();
                            for (JsonValue value : artifacts.values()) {
                                JsonObject artifact = value.asObject();
                                String name = artifact.get("fileName").asString();
                                if (name.contains("helios-") && !name.contains(IMPLEMENTATION_VERSION)) {
                                    JOptionPane.showMessageDialog(null,
                                            "Bootstrapper is out of date. Patching cannot continue");
                                    aborted = true;
                                    break loop;
                                }
                            }
                            URL url = new URL("https://ci.samczsun.com/job/Helios/" + buildNumber
                                    + "/artifact/target/delta.patch");
                            con = (HttpURLConnection) url.openConnection();
                            if (con.getResponseCode() == 200) {
                                File dest = new File(DATA_DIR, "delta.patch");
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                copy(con.getInputStream(), byteArrayOutputStream);
                                FileOutputStream fileOutputStream = new FileOutputStream(dest);
                                fileOutputStream.write(byteArrayOutputStream.toByteArray());
                                fileOutputStream.close();
                                File cur = IMPL_FILE;
                                File old = new File(IMPL_FILE.getAbsolutePath() + "." + oldBuildNumber);
                                if (cur.renameTo(old)) {
                                    VcdiffDecoder.decode(old, dest, cur);
                                    old.delete();
                                    dest.delete();
                                    continue loop;
                                } else {
                                    throw new IllegalArgumentException("Could not rename");
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Server returned response code " + con.getResponseCode() + " "
                                        + con.getResponseMessage() + "\nAborting patch process",
                                null, JOptionPane.INFORMATION_MESSAGE);
                        aborted = true;
                        break loop;
                    }
                }
            } else {
                break;
            }
        }

        if (!aborted) {
            int buildNumber = loadHelios().buildNumber;
            System.out.println("Running Helios version " + buildNumber);
            JOptionPane.showMessageDialog(null, "Updated Helios to version " + buildNumber + "!");
            Runtime.getRuntime().exec(new String[] { "java", "-jar", BOOTSTRAPPER_FILE.getAbsolutePath() });
        } else {
            try {
                Files.copy(backupFile.toPath(), IMPL_FILE.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException exception) {
                // We're going to wrap it so end users know what went wrong
                throw new IOException("Critical Error! Could not restore Helios implementation to original copy"
                        + "Try relaunching the Bootstrapper. If that doesn't work open a GitHub issue with details",
                        exception);
            }
        }
        System.exit(0);
    } else {
        throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
    }
}

From source file:dk.statsbiblioteket.util.Files.java

private static void copyDirectory(File path, File toPath, boolean overwrite) throws IOException {
    log.trace("copyDirectory(" + path + ", " + toPath + ", " + overwrite + ") called");
    if (!toPath.exists()) {
        if (!toPath.mkdirs()) {
            throw new IOException("Unable to create or verify the existence" + " of the destination folder '"
                    + toPath.getAbsoluteFile() + "'");
        }/*  w  ww . ja v a 2 s .  c o m*/
    }
    if (!toPath.canWrite()) {
        throw new IOException("The destination folder '" + toPath.getAbsoluteFile() + "' is not writable");
    }

    for (String filename : path.list()) {
        File in = new File(path, filename);
        File out = new File(toPath, filename);
        innerCopy(in, out, overwrite);
    }
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

public static File sharedContextRoot(Properties configProperties, ServletContext context, Logger log) {
    File sharedContentRoot = null;

    if (configProperties.containsKey(BASE_PATH_ENV)) {
        sharedContentRoot = new File(configProperties.getProperty(BASE_PATH_ENV));
        if (!sharedContentRoot.exists() || !sharedContentRoot.canRead() || !sharedContentRoot.canWrite()) {
            if (!sharedContentRoot.mkdirs()) {
                sharedContentRoot = null;
            }/* ww  w .  j  av  a 2 s  . c o m*/
        }
    }

    if (sharedContentRoot == null) {
        log.warn("Could not access cadmium content root.  Using the tempdir.");
        sharedContentRoot = (File) context.getAttribute("javax.servlet.context.tempdir");
        configProperties.setProperty(BASE_PATH_ENV, sharedContentRoot.getAbsoluteFile().getAbsolutePath());
    }
    return sharedContentRoot;
}