Example usage for java.io File canRead

List of usage examples for java.io File canRead

Introduction

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

Prototype

public boolean canRead() 

Source Link

Document

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

Usage

From source file:com.stacksync.desktop.util.FileUtil.java

public static List<File> getRecursiveFileList(File root, boolean includeDirectories)
        throws FileNotFoundException {
    if (!root.isDirectory() || !root.canRead() || !root.exists()) {
        throw new FileNotFoundException("Invalid directory " + root);
    }/*from   w w w.j  a  va 2 s.  c  o m*/

    List<File> result = getRecursiveFileListNoSort(root, includeDirectories);
    Collections.sort(result);

    return result;
}

From source file:edu.stanford.muse.util.ThunderbirdUtils.java

/** returns list of accounts; each account has a list of properties, the order is fragile! */
private static List<List<String>> getThunderbirdAccountsNew() {
    // read all user prefs as a map
    try {/*from   www .jav a 2s.  co m*/
        String rootDir = ThunderbirdUtils.getThunderbirdProfileDir();
        String prefs = rootDir + File.separator + "prefs.js";
        File f = new File(prefs);
        if (!f.exists() || !f.canRead()) {
            EmailUtils.log.info("Thunderbird probably not installed: no prefs.js in directory: " + prefs);
            return null;
        }

        // ok, now have map. look for accounts and their information.
        List<List<String>> result = new ArrayList<List<String>>();
        Map<String, String> userPrefsMap = readUserPrefs(prefs);

        // get the account list: original line looks like: user_pref("mail.accountmanager.accounts", "account2,account1");
        String accounts = userPrefsMap.get("mail.accountmanager.accounts");

        // sometimes this is null e.g. if tbird has been installed, but the accounts have been deleted
        if (Util.nullOrEmpty(accounts))
            return result;

        StringTokenizer st = new StringTokenizer(accounts, ",");
        while (st.hasMoreTokens()) {
            String account = st.nextToken();
            String server = userPrefsMap.get("mail.account." + account + ".server");
            if (server == null)
                continue;

            // hidden is set to true for "unified folders" account
            if ("true".equals(userPrefsMap.get("mail.server." + server + ".hidden")))
                continue;

            String serverType = userPrefsMap.get("mail.server." + server + ".type");
            // ignore a/c if server type is nntp 
            if ("nntp".equals(serverType))
                continue;

            String accountName = userPrefsMap.get("mail.server." + server + ".name");
            String serverRealHostName = userPrefsMap.get("mail.server." + server + ".realhostname");
            if (serverRealHostName == null)
                serverRealHostName = userPrefsMap.get("mail.server." + server + ".hostname");

            String userName = userPrefsMap.get("mail.server." + server + ".userName"); // note: userName, not username
            String serverPort = userPrefsMap.get("mail.server." + server + ".port");

            String directoryRel = userPrefsMap.get("mail.server." + server + ".directory-rel"); // note: userName, not username
            if (directoryRel != null && directoryRel.startsWith("[ProfD]"))
                directoryRel = directoryRel.replace("[ProfD]",
                        ThunderbirdUtils.getThunderbirdProfileDir() + File.separator);
            // we'll add it later since its later in the param sequence

            String ids = userPrefsMap.get("mail.account." + account + ".identities");
            if (ids == null) {
                // must be local folders, they don't have any id's
                List<String> accountParams = new ArrayList<String>();
                accountParams.add(accountName);
                accountParams.add(serverRealHostName);
                accountParams.add(serverType);
                accountParams.add(userName);
                accountParams.add(null); // no useremail
                accountParams.add(null); // fullname
                accountParams.add(directoryRel);

                accountParams.add(null); // no fcc
                accountParams.add(null); // no port
                result.add(accountParams);

                log.info(" account: Local Folders " + " userName: " + userName + " accountName: " + accountName
                        + " hostname: " + serverRealHostName + " serverRealHostName: " + serverRealHostName
                        + " type: " + serverType + " port: " + serverPort + " directoryRel: " + directoryRel);
                continue;
            }

            // there may multiple id's under this account, we create multiple entries in the result
            StringTokenizer st1 = new StringTokenizer(ids, ",");
            while (st1.hasMoreTokens()) {
                // create a result entry for each id
                List<String> accountParams = new ArrayList<String>();
                accountParams.add(accountName);
                accountParams.add(serverRealHostName);
                accountParams.add(serverType);
                accountParams.add(userName);

                String id = st1.nextToken();
                String useremail = userPrefsMap.get("mail.identity." + id + ".useremail");
                accountParams.add(useremail);

                String fullname = userPrefsMap.get("mail.identity." + id + ".fullName");
                accountParams.add(fullname);

                accountParams.add(directoryRel);

                String fcc_folder_full = userPrefsMap.get("mail.identity." + id + ".fcc_folder");
                String fcc_folder = null;
                if (fcc_folder_full != null) {
                    // fccFolder imap://hangal@xenon.stanford.edu/Sent
                    fcc_folder = fcc_folder_full.replaceAll("[^/]*/+[^/]*/+(.*$)", "$1"); // skip the first 2 tokens, split by /
                    if (!fcc_folder_full.equals(fcc_folder)) // only if not equal is it valid
                        fcc_folder = null;
                }

                log.info(" account: " + account + " userName: " + userName + " useremail = " + useremail
                        + " id: " + id + " accountName: " + accountName + " hostname: " + serverRealHostName
                        + " serverRealHostName: " + serverRealHostName + " type: " + serverType + " port: "
                        + serverPort + " directoryRel: " + directoryRel + " fullname = " + fullname
                        + " fcc_folder_full = " + fcc_folder_full + " fcc_folder = " + fcc_folder);
                accountParams.add(fcc_folder);

                // tack on port at the end, though we're not using it right now
                accountParams.add(serverPort);

                result.add(accountParams);
            }
        }
        return result;
    } catch (Exception e) {
        Util.print_exception(e, log);
    }
    return null;
}

From source file:com.intuit.cto.selfservice.service.Util.java

/**
 * Retrieve the directory located at the given path.
 * If this does not exist, create it//from  w w w . j ava2s .  c o  m
 * If it is not a directory, or it is not readable, throw an Exception
 */
public static File getDirectory(String path) {
    File dir = new File(path);
    if (!dir.exists()) {
        try {
            FileUtils.forceMkdir(dir);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to create new directory at path: " + path, e);
        }
    }
    if (dir.getAbsolutePath().trim().length() == 0) {
        throw new IllegalArgumentException(path + " is empty");
    }
    if (!dir.isDirectory()) {
        throw new IllegalArgumentException(path + " is not a directory");
    }
    if (!dir.canRead()) {
        throw new IllegalArgumentException(path + " is not a readable directory");
    }
    return dir;
}

From source file:com.datos.vfs.provider.sftp.SftpClientFactory.java

private static void setKnownHosts(final JSch jsch, final File sshDir, File knownHostsFile)
        throws FileSystemException {
    try {/* w  w  w .  ja  v a 2  s .  c  om*/
        if (knownHostsFile != null) {
            jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
        } else {
            // Load the known hosts file
            knownHostsFile = new File(sshDir, "known_hosts");
            if (knownHostsFile.isFile() && knownHostsFile.canRead()) {
                jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
            }
        }
    } catch (final JSchException e) {
        throw new FileSystemException("vfs.provider.sftp/known-hosts.error", knownHostsFile.getAbsolutePath(),
                e);
    }

}

From source file:com.docd.purefm.test.CommandLineFileTest.java

private static void testAgainstJavaIoFile(final CommandLineFile genericFile, final File javaFile,
        final boolean testDate) throws Throwable {
    assertEquals(javaFile, genericFile.toFile());
    assertEquals(javaFile.getName(), genericFile.getName());
    assertEquals(javaFile.getAbsolutePath(), genericFile.getAbsolutePath());
    assertEquals(javaFile.exists(), genericFile.exists());
    assertEquals(javaFile.canRead(), genericFile.canRead());
    assertEquals(javaFile.canWrite(), genericFile.canWrite());
    assertEquals(javaFile.canExecute(), genericFile.canExecute());
    assertEquals(javaFile.getPath(), genericFile.getPath());
    assertEquals(javaFile.getParent(), genericFile.getParent());
    final File parentFile;
    final GenericFile genericParentFile = genericFile.getParentFile();
    if (genericParentFile == null) {
        parentFile = null;//w  w  w.  ja  va 2 s.  c  o  m
    } else {
        parentFile = genericParentFile.toFile();
    }
    assertEquals(javaFile.getParentFile(), parentFile);
    assertEquals(javaFile.length(), genericFile.length());
    try {
        assertEquals(FileUtils.isSymlink(javaFile), genericFile.isSymlink());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        assertEquals(javaFile.getCanonicalPath(), genericFile.getCanonicalPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
    assertEquals(javaFile.length(), genericFile.length());
    assertEquals(javaFile.isDirectory(), genericFile.isDirectory());
    if (genericFile.isDirectory()) {
        assertTrue(listedPathsEqual(javaFile.list(), genericFile.list()));
        assertTrue(listedFilesEqual(javaFile.listFiles(), genericFile.listFiles()));
    }

    if (testDate) {
        assertEquals(PFMTextUtils.humanReadableDate(javaFile.lastModified(), false),
                PFMTextUtils.humanReadableDate(genericFile.lastModified(), true));
    }
}

From source file:fr.gouv.culture.vitam.droid.DroidHandler.java

/**
 * Get the valid list of files/*ww  w  .  j  a va 2  s.  co m*/
 * 
 * @param resources
 * @param extensions
 * @param recursive
 * @return the valid list of files
 * @throws CommandExecutionException
 */
public static final List<File> matchedFiled(File[] resources, String[] extensions, boolean recursive)
        throws CommandExecutionException {
    List<File> matchedFiles = new ArrayList<File>(1);
    if (resources == null || resources.length == 0) {
        throw new CommandExecutionException("Resources not specified");
    }
    File dirToSearch;
    for (int i = 0; i < resources.length; i++) {
        dirToSearch = resources[i];
        if (!dirToSearch.isDirectory()) {
            if (dirToSearch.canRead()) {
                matchedFiles.add(dirToSearch);
            } else {
                throw new CommandExecutionException("Resources not found");
            }
        } else {
            matchedFiles.addAll(FileUtils.listFiles(dirToSearch, extensions, recursive));
        }
    }
    return matchedFiles;
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void copyAllContent(final String source, final String target, final boolean ignoreHidden)
        throws Exception {
    File sourceFile = new File(source);
    File targetFile = new File(target);
    if (!targetFile.exists()) {
        targetFile.mkdirs();//  w  w w .  java2  s.  c om
    }
    if (sourceFile.exists() && sourceFile.canRead() && sourceFile.isDirectory() && targetFile.exists()
            && targetFile.canWrite() && targetFile.isDirectory()) {
        List<File> copyList = new ArrayList<File>();
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File file, String name) {
                return !ignoreHidden || !name.startsWith(".");
            }

        };
        File files[] = sourceFile.listFiles(filter);
        if (files.length > 0) {
            copyList.addAll(Arrays.asList(files));
        }
        for (int index = 0; index < copyList.size(); index++) {
            File aFile = copyList.get(index);
            String relativePath = aFile.getAbsoluteFile().getAbsolutePath()
                    .replaceFirst(sourceFile.getAbsoluteFile().getAbsolutePath(), "");
            if (aFile.isDirectory()) {
                File newDir = new File(target, relativePath);
                if (newDir.mkdir()) {
                    newDir.setExecutable(aFile.canExecute(), false);
                    newDir.setReadable(aFile.canRead(), false);
                    newDir.setWritable(aFile.canWrite(), false);
                    newDir.setLastModified(aFile.lastModified());
                    files = aFile.listFiles(filter);
                    if (files.length > 0) {
                        copyList.addAll(index + 1, Arrays.asList(files));
                    }
                } else {
                    log.warn("Failed to create new subdirectory \"{}\" in the target path \"{}\".",
                            relativePath, target);
                }
            } else {
                File newFile = new File(target, relativePath);
                if (newFile.createNewFile()) {
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    try {
                        inStream = new FileInputStream(aFile);
                        outStream = new FileOutputStream(newFile);
                        streamCopy(inStream, outStream);
                    } finally {
                        if (inStream != null) {
                            try {
                                inStream.close();
                            } catch (Exception e) {
                            }
                        }
                        if (outStream != null) {
                            try {
                                outStream.flush();
                            } catch (Exception e) {
                            }
                            try {
                                outStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                    newFile.setExecutable(aFile.canExecute(), false);
                    newFile.setReadable(aFile.canRead(), false);
                    newFile.setWritable(aFile.canWrite(), false);
                    newFile.setLastModified(aFile.lastModified());
                }
            }
        }
    }
}

From source file:fr.gouv.culture.vitam.droid.DroidHandler.java

/**
 * Get the valid list of files//from   ww  w  . j  a va2 s  . com
 * 
 * @param resources
 * @param extensions
 * @param recursive
 * @return the valid list of files
 * @throws CommandExecutionException
 */
public static final List<File> matchedFiled(String[] resources, String[] extensions, boolean recursive)
        throws CommandExecutionException {
    List<File> matchedFiles = new ArrayList<File>(1);
    if (resources == null || resources.length == 0) {
        throw new CommandExecutionException("Resources not specified");
    }
    File dirToSearch;
    for (int i = 0; i < resources.length; i++) {
        dirToSearch = new File(resources[i]);
        if (!dirToSearch.isDirectory()) {
            if (dirToSearch.canRead()) {
                matchedFiles.add(dirToSearch);
            } else {
                throw new CommandExecutionException("Resources not found");
            }
        } else {
            matchedFiles.addAll(FileUtils.listFiles(dirToSearch, extensions, recursive));
        }
    }
    return matchedFiles;
}

From source file:azkaban.execapp.AzkabanExecutorServer.java

/**
 * Loads the Azkaban property file from the AZKABAN_HOME conf directory
 *
 * @return// www . j  a  v  a2 s  .  co m
 */
/* package */static Props loadConfigurationFromAzkabanHome() {
    String azkabanHome = System.getenv("AZKABAN_HOME");

    if (azkabanHome == null) {
        logger.error("AZKABAN_HOME not set. Will try default.");
        return null;
    }

    if (!new File(azkabanHome).isDirectory() || !new File(azkabanHome).canRead()) {
        logger.error(azkabanHome + " is not a readable directory.");
        return null;
    }

    File confPath = new File(azkabanHome, ServerInternals.DEFAULT_CONF_PATH);
    if (!confPath.exists() || !confPath.isDirectory() || !confPath.canRead()) {
        logger.error(azkabanHome + " does not contain a readable conf directory.");
        return null;
    }

    return loadAzkabanConfigurationFromDirectory(confPath);
}

From source file:dk.dma.ais.abnormal.analyzer.AbnormalAnalyzerAppModule.java

/** Return URL for local file /data/geomask.xml if it exists and is readable; otherwise return default embedded geomask resource. */
private static URL getGeomaskResource() {
    URL geomaskResource = null;//from  ww w .  j av a  2  s.com

    File customGeomaskFile = new File("/data/geomask.xml");
    if (customGeomaskFile.exists() && customGeomaskFile.isFile() && customGeomaskFile.canRead()) {
        try {
            geomaskResource = customGeomaskFile.toURI().toURL();
        } catch (MalformedURLException e) {
            LOG.error("Cannot load geomask.xml from file: " + customGeomaskFile.getAbsolutePath(), e);
        }
    }

    if (geomaskResource == null) {
        geomaskResource = ClassLoader.class.getResource("/geomask.xml");
    }

    return geomaskResource;
}