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:org.geoserver.wps.gs.GeorectifyConfiguration.java

/**
 * Load the configured parameters through the properties file. TODO: Move to XML instead of
 * properties file// ww w  . ja va  2 s  .  co  m
 * 
 * @throws IOException
 */
private void loadConfig() throws IOException {
    final boolean hasPropertiesFile = configFile != null && configFile.getType() == Type.RESOURCE;

    if (hasPropertiesFile) {
        Properties props = new Properties();
        InputStream fis = null;
        try {
            fis = configFile.in();
            props.load(fis);
            Iterator<Object> keys = props.keySet().iterator();
            envVariables = Maps.newHashMap();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equalsIgnoreCase(GRKeys.GDAL_CACHEMAX)) {
                    // Setting GDAL_CACHE_MAX Environment variable if available
                    String cacheMax = null;
                    try {
                        cacheMax = (String) props.get(GRKeys.GDAL_CACHEMAX);
                        if (cacheMax != null) {
                            int gdalCacheMaxMemory = Integer.parseInt(cacheMax); // Only for validation
                            envVariables.put(GRKeys.GDAL_CACHEMAX, cacheMax);
                        }
                    } catch (NumberFormatException nfe) {
                        if (LOGGER.isLoggable(Level.WARNING)) {
                            LOGGER.log(Level.WARNING,
                                    "Unable to parse the specified property as a number: " + cacheMax, nfe);
                        }
                    }
                } else if (key.equalsIgnoreCase(GRKeys.GDAL_DATA)
                        || key.equalsIgnoreCase(GRKeys.GDAL_LOGGING_DIR)
                        || key.equalsIgnoreCase(GRKeys.TEMP_DIR)) {
                    // Parsing specified folder path
                    String path = (String) props.get(key);
                    if (path != null) {
                        final File directory = new File(path);
                        if (directory.exists() && directory.isDirectory()
                                && ((key.equalsIgnoreCase(GRKeys.GDAL_DATA) && directory.canRead())
                                        || directory.canWrite())) {
                            envVariables.put(key, path);
                        } else {
                            if (LOGGER.isLoggable(Level.WARNING)) {
                                LOGGER.log(Level.WARNING, "The specified folder for " + key
                                        + " variable isn't valid, "
                                        + "or it doesn't exist or it isn't a readable directory or it is a "
                                        + "destination folder which can't be written: " + path);
                            }
                        }
                    }
                } else if (key.equalsIgnoreCase(GRKeys.EXECUTION_TIMEOUT)) {
                    // Parsing execution timeout
                    String timeout = null;
                    try {
                        timeout = (String) props.get(GRKeys.EXECUTION_TIMEOUT);
                        if (timeout != null) {
                            executionTimeout = Long.parseLong(timeout); // Only for validation
                        }
                    } catch (NumberFormatException nfe) {
                        if (LOGGER.isLoggable(Level.WARNING)) {
                            LOGGER.log(Level.WARNING,
                                    "Unable to parse the specified property as a number: " + timeout, nfe);
                        }
                    }
                } else if (key.equalsIgnoreCase(GRKeys.GDAL_WARP_PARAMS)
                        || key.equalsIgnoreCase(GRKeys.GDAL_TRANSLATE_PARAMS)) {
                    // Parsing gdal operations custom option parameters
                    String param = (String) props.get(key);
                    if (param != null) {
                        if (key.equalsIgnoreCase(GRKeys.GDAL_WARP_PARAMS)) {
                            gdalWarpingParameters = param.trim();
                        } else {
                            gdalTranslateParameters = param.trim();
                        }
                    }
                } else if (key.endsWith("PATH")) {
                    // Dealing with properties like LD_LIBRARY_PATH, PATH, ...
                    String param = (String) props.get(key);
                    if (param != null) {
                        envVariables.put(key, param);
                    }
                }
            }

        } catch (FileNotFoundException e) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, "Unable to parse the config file: " + configFile.path(), e);
            }

        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, "Unable to parse the config file: " + configFile.path(), e);
            }
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Throwable t) {
                    // Does nothing
                }
            }
        }
    }
}

From source file:com.aurel.track.admin.server.siteConfig.SiteConfigBL.java

public static String createAndCheckDirectory(String directoryName,
        /*List<ControlError> errors, List<String> controlPath,*/ Locale locale) {
    String keyBase = "admin.server.config.err.directory";
    if (directoryName == null || directoryName.trim().length() == 0) {
        /*errors.add(new ControlError(controlPath, getText(keyBase+".DirectoryRequired", locale)));
        return errors;*/// www . ja va2 s.co  m
        return getText(keyBase + ".DirIsRequired", locale);
    }

    File f = new File(directoryName);

    if (f.isFile()) {
        /*errors.add(new ControlError(controlPath, getText(keyBase+".DirIsFile", locale)));
        return errors;*/
        return getText(keyBase + ".DirIsFile", locale);
    }

    if (!f.isAbsolute()) {
        /*errors.add(new ControlError(controlPath, getText(keyBase+".DirIsRelative", locale)));
        return errors;*/
        return getText(keyBase + ".DirIsRelative", locale);
    }

    // if the directory does not exist, create it
    if (!f.exists()) {
        LOGGER.info("Creating directory " + directoryName);
        try {
            f.mkdir();
        } catch (Exception e) {
            /*errors.add(new ControlError(controlPath, getText(keyBase+".CantWrite", locale)));
            return errors;*/
            return getText(keyBase + ".CantWrite", locale);
        }
    }

    if (!f.canWrite() || !f.canRead()) {
        /*errors.add(new ControlError(controlPath, getText(keyBase+".CantAccess", locale)));
        return errors;*/
        return getText(keyBase + ".CantAccess", locale);
    }
    //return errors;
    return null;
}

From source file:ru.org.linux.topic.AddTopicController.java

private String processUploadImage(HttpServletRequest request) throws IOException, ScriptErrorException {
    if (request instanceof MultipartHttpServletRequest) {
        MultipartFile multipartFile = ((MultipartRequest) request).getFile("image");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            File uploadedFile = File.createTempFile("preview", "",
                    new File(configuration.getPathPrefix() + "/linux-storage/tmp/"));
            String image = uploadedFile.getPath();
            if ((uploadedFile.canWrite() || uploadedFile.createNewFile())) {
                try {
                    logger.debug("Transfering upload to: " + image);
                    multipartFile.transferTo(uploadedFile);
                    return image;
                } catch (Exception e) {
                    throw new ScriptErrorException("Failed to write uploaded file", e);
                }/*w  w w . ja va2  s .c o m*/
            } else {
                logger.info("Bad target file name: " + image);
            }
        }
    }

    return null;
}

From source file:com.aurel.track.dbase.HandleHome.java

/**
 * Returns the path to the TRACKPLUS_HOME directory, where
 * configuration data is being kept./*  www .j a  v a2s  .  co m*/
 * @return
 */
public static String getTrackplus_Home() {
    if (Trackplus_Home == null) {
        Connection con = null;
        Trackplus_Home = ""; // block  further processing from here by null length path
        // initialize from environment
        if (System.getProperty(TRACKPLUS_HOME) != null) { // first look at -DTRACKPLUS_HOME
            Trackplus_Home = System.getProperty(TRACKPLUS_HOME);
            LOGGER.info(
                    "Taking initial TRACKPLUS_HOME from Java VM argument -DTRACKPLUS_HOME=" + Trackplus_Home);
        } else if (System.getenv(TRACKPLUS_HOME) != null) {
            Trackplus_Home = System.getenv(TRACKPLUS_HOME); // then look at environ. variable
            LOGGER.info("Taking TRACKPLUS_HOME from environment variable as " + Trackplus_Home);
        } else {
            try {
                PropertiesConfiguration tcfg = loadServletContextPropFile(TORQUE_FILE,
                        ApplicationBean.getInstance().getServletContext());
                Class.forName(tcfg.getString("torque.dsfactory.track.connection.driver"));
                con = DriverManager.getConnection(tcfg.getString("torque.dsfactory.track.connection.url"),
                        tcfg.getString("torque.dsfactory.track.connection.user"),
                        tcfg.getString("torque.dsfactory.track.connection.password"));
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT ATTACHMENTROOTDIR FROM TSITE");
                while (rs.next()) {
                    Trackplus_Home = rs.getString(1);
                }
            } catch (Exception e) {
                LOGGER.error("Cannot access database table TSITE");
            } finally {
                if (con != null) {
                    try {
                        con.close();
                    } catch (SQLException e) {
                        LOGGER.info("Closing the connection failed with " + e.getMessage());
                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                    }
                }
            }
        }
        if (Trackplus_Home != null && !"".equals(Trackplus_Home)) {
            File tph = new File(Trackplus_Home);
            if (!tph.exists()) { // try to create it
                try {
                    tph.mkdirs();
                } catch (Exception e) {
                    LOGGER.debug("We could not create directory " + Trackplus_Home + ".");
                }
            }
            if (!tph.isDirectory() || !tph.canWrite()) { // we need to be able to write to this directory
                LOGGER.error("We cannot write to the given TRACKPLUS_HOME directory at " + Trackplus_Home
                        + ". Ignoring environment.");
                Trackplus_Home = ""; // block again by null length path
            }
        }

        if (Trackplus_Home == null || "".equals(Trackplus_Home)) {
            Trackplus_Home = System.getProperty("user.home") + File.separator + "trackplus";
            LOGGER.info("Creating TRACKPLUS_HOME at " + Trackplus_Home);
        }
    }
    return Trackplus_Home;
}

From source file:jfs.sync.encrypted.EncryptedFileStorageAccess.java

@Override
public FileInfo getFileInfo(String rootPath, String relativePath) {
    FileInfo result = new FileInfo();
    String name = getLastPathElement(relativePath, relativePath);
    result.setName(name);/*from   www  . j a v  a2  s  .  c  o  m*/
    result.setPath(rootPath + relativePath);
    File file = getFile(rootPath, relativePath);
    result.setDirectory(file.isDirectory());
    result.setExists(file.exists());
    result.setCanRead(true);
    result.setCanWrite(true);
    if (log.isDebugEnabled()) {
        log.debug("getFileInfo() " + result.getPath() + " e[" + result.isExists() + "] d["
                + result.isDirectory() + "]");
    } // if
    if (result.isExists()) {
        result.setCanRead(file.canRead());
        result.setCanWrite(file.canWrite());
        if (!result.isDirectory()) {
            result.setModificationDate(file.lastModified());
            result.setSize(-1);
        } else {
            result.setSize(0);
        } // if
    } else {
        if (log.isDebugEnabled()) {
            log.debug("getFileInfo() could not detect file for " + result.getPath());
        } // if
    } // if
    return result;
}

From source file:io.github.eternalbits.compactvd.CompactVD.java

private void copy(File from, int options, File to, String type) throws IOException {
    long mtime = to.lastModified();
    task = DiskImageProgress.COPY;/*from w  w w.ja va 2 s.  com*/
    File copy = null;
    try (RandomAccessFile check = new RandomAccessFile(from, "r")) { // is file?
        // If writable, source is open in write mode for an exclusive file lock
        String mode = from.canWrite() ? "rw" : "r";
        try (DiskImage image = DiskImages.open(from, mode)) {
            if (type == null)
                type = image.getType();
            try (DiskImage clone = DiskImages.create(type, to, image.getDiskSize())) {
                copy = to; // copy open by DiskImage
                FileLock source = null;
                if (mode.equals("rw"))
                    source = image.tryLock();
                verboseProgress(SEARCHING_SPACE);
                image.addObserver(this, false);
                image.optimize(options);
                image.removeObserver(this);
                if (!isCancelled()) {
                    verboseProgress("Copying " + from.getName() + " to " + to.getName());
                    FileLock fileLock = clone.tryLock();
                    clone.addObserver(this, false);
                    clone.copy(image);
                    clone.removeObserver(this);
                    fileLock.release();
                }
                if (source != null)
                    source.release();
                if (!isCancelled()) {
                    copy = null;
                }
            }
        }
    } finally {
        if (copy != null && copy.isFile())
            copy.delete();
        System.out.println(mtime != to.lastModified()
                ? String.format(IMAGE_CREATED, to.getName(), to.getAbsoluteFile().getParent())
                : IMAGE_NOT_CREATED);
    }
}

From source file:com.iyonger.apm.web.model.Home2.java

/**
 * Constructor.// w  w  w  . jav a 2 s .c om
 *
 * @param directory home directory ${NGRINDER_HOME}
 * @param create    create the directory if not exists
 */
public Home2(File directory, boolean create) {
    checkNotNull(directory, "directory should not be null");
    if (create) {
        if (directory.mkdir()) {
            LOGGER.info("{} is created.", directory.getPath());
        }
    }
    if (directory.exists() && !directory.canWrite()) {
        throw new ConfigurationException(
                String.format(" ngrinder home directory %s is not writable.", directory), null);
    }
    this.directory = directory;
}

From source file:com.iyonger.apm.web.model.Home.java

/**
 * Constructor./*from w  ww  . j a v a2s  . c  om*/
 *
 * @param directory home directory ${NGRINDER_HOME}
 * @param create    create the directory if not exists
 */
public Home(File directory, boolean create) {
    checkNotNull(directory, "directory should not be null");
    if (create) {
        if (directory.mkdir()) {
            LOGGER.info("{} is created.", directory.getPath());
        }
    }
    if (directory.exists() && !directory.canWrite()) {
        throw new ConfigurationException(
                String.format(" ngrinder home directory %s is not writable.", directory), null);
    }
    this.directory = directory;
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePrivateKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPrivateKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPrivateKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();//  ww  w  .j  a  v  a  2  s .c  o  m

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(file);

        try {
            provider.getEncryptedPrivateKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestFilePublicKeyDataProvider.java

@Test
@Ignore("canRead()/canWrite() do not work on Win; setReadable()/setWritable() do not work on some Macs.")
public void testGetEncryptedPublicKeyData02() throws IOException {
    final String fileName = "testGetEncryptedPublicKeyData02.key";
    File file = new File(fileName);
    file = file.getCanonicalFile();//  w ww. ja  v a  2  s .c  om

    if (file.exists())
        FileUtils.forceDelete(file);

    byte[] data = new byte[] { 0x01, 0x71, 0x33 };

    FileUtils.writeByteArrayToFile(file, data);

    try {
        assertTrue("Setting the file to not-readable should have succeeded.", file.setReadable(false, false));
        assertFalse("The file should not be readable.", file.canRead());
        assertTrue("The file should still be writable.", file.canWrite());

        FilePublicKeyDataProvider provider = new FilePublicKeyDataProvider(file);

        try {
            provider.getEncryptedPublicKeyData();
            fail("Expected exception KeyNotFoundException.");
        } catch (KeyNotFoundException e) {
            assertNotNull("The cause should not be null.", e.getCause());
        }
    } finally {
        FileUtils.forceDelete(file);
    }
}