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.pieframework.model.repository.ModelStore.java

public static Model loadModel(Configuration config, Request request, File fileRoot, String instance)
        throws IOException, NestableException {
    if (fileRoot == null || !fileRoot.isDirectory()) {
        throw new IllegalArgumentException("Cannot build Model from given directory.");
    }//from www.jav a  2 s . com

    try {
        System system = getSystem(new File(fileRoot + PATH_DELIMITER + SYSTEM_FILE_NAME));

        Repositories repos = getRepositories(new File(fileRoot + PATH_DELIMITER + REPOSITORIES_FILE_NAME));

        model = new Model().withSystem(system).withRepositories(repos).withModelDirectory(fileRoot.getPath())
                .withConfiguration(config).withRequest(request);

        File instanceFile = new File(
                fileRoot + PATH_DELIMITER + "instances" + PATH_DELIMITER + instance + ".txt");
        if (instanceFile != null && instanceFile.canRead()) {
            applyInstanceOverrides(model, instanceFile);
        }

        // replace @{expression} tags in model
        model = evaluateTemplateExpressions(model);

        // relink the system
        linkComponents(model.getSystem());

        // ////////Experiment////

        // /////////////////////

    } catch (SimpleSerializerException e) {
        Configuration.log().error("Could not parse Model. " + e.getMessage());
        throw new NestableException("Could not parse Model.", e);
    } catch (ParserConfigurationException e) {
        Configuration.log().error("Could not parse Model. " + e.getMessage());
        throw new NestableException("Could not parse Model.", e);
    } catch (SAXException e) {
        Configuration.log().error("Could not parse Model. " + e.getMessage());
        throw new NestableException("Could not parse Model.", e);
    } catch (TransformerException e) {
        Configuration.log().error("Could not parse Model. " + e.getMessage());
        throw new NestableException("Could not parse Model.", e);
    }
    return model;
}

From source file:com.heliosapm.streams.collector.ds.pool.PoolConfig.java

/**
 * Creates and deploys an ObjectPool based on the passed config props
 * @param configProps The configuration properties file
 * @return the created GenericObjectPool
 *//*  w  w  w .j av  a  2  s . c  o m*/
public static GenericObjectPool<?> deployPool(final File configProps) {
    if (configProps == null)
        throw new IllegalArgumentException("The passed file was null");
    if (!configProps.canRead())
        throw new IllegalArgumentException("The passed file [" + configProps + "] cannot be read");
    GenericObjectPool<?> pool = pools.putIfAbsent(configProps, PLACEHOLDER);
    if (pool == null || pool == PLACEHOLDER) {
        final Properties p = URLHelper.readProperties(URLHelper.toURL(configProps));
        if (!p.containsKey("name")) {
            p.setProperty("name", StringHelper.splitString(configProps.getName(), '.', true)[0]);
        }
        try {
            pool = deployPool(p);
            pools.replace(configProps, pool);
            return pool;
        } catch (Exception ex) {
            final String msg = "Failed to deploy object pool from file [" + configProps + "]";
            LOG.error(msg, ex);
            throw new RuntimeException(msg, ex);
        }
    } else {
        throw new RuntimeException(
                "The pool defined in the file [" + configProps + "] has already been deployed");
    }
}

From source file:com.liferay.ide.core.util.FileListing.java

/**
 * Directory is valid if it exists, does not represent a file, and can be read.
 *//*from  w w  w  .j av a 2s.c  o  m*/
private static void _validateDirectory(File aDirectory) throws FileNotFoundException {
    if (aDirectory == null) {
        throw new IllegalArgumentException("Directory should not be null.");
    }

    if (!aDirectory.exists()) {
        throw new FileNotFoundException("Directory does not exist: " + aDirectory);
    }

    if (!aDirectory.isDirectory()) {
        throw new IllegalArgumentException("Is not a directory: " + aDirectory);
    }

    if (!aDirectory.canRead()) {
        throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.RDFFilesLoader.java

/**
 * Create a model from all the RDF files in the specified directory.
 *///from w  ww . ja  va  2  s .  co  m
public static OntModel getModelFromDir(File dir) {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    if (dir == null) {
        log.warn("Must pass a File to getModelFromDir()");
        return model;
    }
    if (!dir.isDirectory()) {
        log.warn("Directory must be a File object for a directory");
        return model;
    }
    if (!dir.canRead()) {
        log.warn("getModelFromDir(): Directory " + " must be readable, check permissions on "
                + dir.getAbsolutePath());
        return model;
    }

    Set<Path> paths = getPaths(dir.getPath());
    for (Path p : paths) {
        readOntologyFileIntoModel(p, model);
    }
    return model;
}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static boolean setSystemPropertyToAbsoluteFile(final String property, final String fileName) {
    if (System.getProperty(property) == null) {

        if (fileName == null) {
            log.error("Cannot set property " + property + " because filename is null");

            return false;
        }//ww  w  .ja v a2 s.  co m

        final File jaasConfigFile = new File(fileName).getAbsoluteFile();

        if (jaasConfigFile.exists() && jaasConfigFile.canRead()) {
            System.setProperty(property, jaasConfigFile.getAbsolutePath());

            log.debug("Load " + fileName + " from {} ", jaasConfigFile.getAbsolutePath());
            return true;
        } else {
            log.error("Cannot read from {}, maybe the file does not exists? ",
                    jaasConfigFile.getAbsolutePath());
        }

    } else {
        log.warn("Property " + property + " already set to " + System.getProperty(property));
    }

    return false;
}

From source file:com.puppycrawl.tools.checkstyle.Main.java

/**
 * Traverses a specified node looking for files to check. Found files are added to a specified
 * list. Subdirectories are also traversed.
 * @param node/*from w  ww  .  ja  va  2 s  .  c  om*/
 *        the node to process
 * @return found files
 */
private static List<File> listFiles(File node) {
    // could be replaced with org.apache.commons.io.FileUtils.list() method
    // if only we add commons-io library
    final List<File> result = Lists.newLinkedList();

    if (node.canRead()) {
        if (node.isDirectory()) {
            final File[] files = node.listFiles();
            // listFiles() can return null, so we need to check it
            if (files != null) {
                for (File element : files) {
                    result.addAll(listFiles(element));
                }
            }
        } else if (node.isFile()) {
            result.add(node);
        }
    }
    return result;
}

From source file:dk.netarkivet.common.utils.cdx.CDXUtils.java

/**
  * Applies createCDXRecord() to all ARC/WARC files in a directory, creating
  * one CDX file per ARC/WARC file./*from   w ww .  ja v a  2 s.  com*/
  * Note, any exceptions during index generation are logged at level FINE
  * but otherwise ignored.
  * Exceptions creating any cdx file are logged at level WARNING but
  * otherwise ignored.
  * CDX files are named as the ARC/WARC files except ".(w)arc" or
  * ".(w)arc.gz" is extended with ".cdx"
  *
  * @param archiveProfile archive profile including filters, patterns, etc.
  * @param archiveFileDirectory A directory with archive files to generate
  * index for
  * @param cdxFileDirectory A directory to generate CDX files in
  * @throws ArgumentNotValid if any of directories are null or is not an
  * existing directory, or if cdxFileDirectory is not writable.
  */
public static void generateCDX(ArchiveProfile archiveProfile, File archiveFileDirectory, File cdxFileDirectory)
        throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(archiveProfile, "ArchiveProfile archiveProfile");
    ArgumentNotValid.checkNotNull(archiveFileDirectory, "File archiveFileDirectory");
    ArgumentNotValid.checkNotNull(cdxFileDirectory, "File cdxFileDirectory");
    if (!archiveFileDirectory.isDirectory() || !archiveFileDirectory.canRead()) {
        throw new ArgumentNotValid(
                "The directory for arc files '" + archiveFileDirectory + "' is not a readable directory");
    }
    if (!cdxFileDirectory.isDirectory() || !cdxFileDirectory.canWrite()) {
        throw new ArgumentNotValid(
                "The directory for cdx files '" + archiveFileDirectory + "' is not a writable directory");
    }
    Map<File, Exception> exceptions = new HashMap<File, Exception>();
    File[] filesToProcess = archiveFileDirectory.listFiles(archiveProfile.filename_filter);
    if (filesToProcess.length == 0) {
        log.warn("Found no related arcfiles to process in the archive dir '"
                + archiveFileDirectory.getAbsolutePath() + "'.");
    } else {
        log.debug("Found " + filesToProcess.length + " related arcfiles to process in the archive dir '"
                + archiveFileDirectory.getAbsolutePath() + "'.");
    }
    for (File arcfile : filesToProcess) {
        File cdxfile = new File(cdxFileDirectory, arcfile.getName() + FileUtils.CDX_EXTENSION);
        try {
            OutputStream cdxstream = null;
            try {
                cdxstream = new FileOutputStream(cdxfile);
                writeCDXInfo(arcfile, cdxstream);
            } finally {
                if (cdxstream != null) {
                    cdxstream.close();
                }
            }
        } catch (Exception e) {
            exceptions.put(cdxfile, e);
        }
    }
    // Log any errors
    if (exceptions.size() > 0) {
        StringBuilder errorMsg = new StringBuilder("Exceptions during cdx file generation:\n");
        for (Map.Entry<File, Exception> fileException : exceptions.entrySet()) {
            errorMsg.append("Could not create cdxfile '");
            errorMsg.append(fileException.getKey().getAbsolutePath());
            errorMsg.append("':\n");
            errorMsg.append(ExceptionUtils.getStackTrace(fileException.getValue()));
            errorMsg.append('\n');
        }
        log.debug(errorMsg.toString());
    }
}

From source file:com.frostwire.android.gui.Librarian.java

/**
 * Given a folder path it'll return all the files contained within it and it's subfolders
 * as a flat set of Files.//w w w . j  a v  a  2 s  . co  m
 * <p>
 * Non-recursive implementation, up to 20% faster in tests than recursive implementation. :)
 *
 * @param folder
 * @param extensions If you only need certain files filtered by their extensions, use this string array (without the "."). or set to null if you want all files. e.g. ["txt","jpg"] if you only want text files and jpegs.
 * @return The set of files.
 * @author gubatron
 */
private static Collection<File> getAllFolderFiles(File folder, String[] extensions) {
    Set<File> results = new HashSet<>();
    Stack<File> subFolders = new Stack<>();
    File currentFolder = folder;
    while (currentFolder != null && currentFolder.isDirectory() && currentFolder.canRead()) {
        File[] fs = null;
        try {
            fs = currentFolder.listFiles();
        } catch (SecurityException e) {
        }

        if (fs != null && fs.length > 0) {
            for (File f : fs) {
                if (!f.isDirectory()) {
                    if (extensions == null || FilenameUtils.isExtension(f.getName(), extensions)) {
                        results.add(f);
                    }
                } else {
                    subFolders.push(f);
                }
            }
        }

        if (!subFolders.isEmpty()) {
            currentFolder = subFolders.pop();
        } else {
            currentFolder = null;
        }
    }
    return results;
}

From source file:com.jhash.oimadmin.Utils.java

public static String readFile(String fileName, String workArea) {
    logger.trace("readFile({},{})", fileName, workArea);
    InputStream templateStream = null;
    File workAreaDirectory;//from   w w  w .  j  a v  a2 s  .  co m
    logger.trace("Trying to validate whether workarea {} exists and is a directory", workArea);
    if (workArea != null && (workAreaDirectory = new File(workArea)) != null && workAreaDirectory.exists()
            && workAreaDirectory.isDirectory()) {
        File templateFile = new File(workAreaDirectory + File.separator + fileName);
        logger.trace("Trying to validate if file {} exists", templateFile);
        if (templateFile.exists() && templateFile.canRead()) {
            try {
                logger.trace("Trying to setup {} for reading", templateFile);
                templateStream = new FileInputStream(templateFile);
                logger.trace("File can be read using {}", templateStream);
            } catch (IOException exception) {
                throw new OIMAdminException("Could not read " + templateFile.getAbsolutePath(), exception);
            }
        }
    }
    if (templateStream == null) {
        logger.trace("Trying to setup {} for reading from system classpath ", fileName);
        templateStream = ClassLoader.getSystemResourceAsStream(fileName);
    }
    byte[] readData = new byte[1000];
    StringBuilder templateString = new StringBuilder();
    try {
        int readDataSize;
        while ((readDataSize = templateStream.read(readData)) > 0) {
            templateString.append(new String(readData, 0, readDataSize, "UTF-8"));
        }
    } catch (IOException e1) {
        throw new OIMAdminException("Failed to read templates/EventHandlerConditional", e1);
    }
    return templateString.toString();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.QcliveAbstractBaseIntegrationTest.java

/**
 * Retrieves the absolute root directory path of the tcgafiles directory.
 * /*  w  w  w . ja va2 s .  c  o m*/
 * @return the absolute root directory path of the tcgafiles directory
 */
private static String getTcgaFilesRootDirPath() {
    File tcgaFilesRoot = null;
    for (final File root : File.listRoots()) {
        tcgaFilesRoot = new File(root + tcgaFilesRootDirName);
        if (tcgaFilesRoot.canRead())
            return tcgaFilesRoot.getAbsolutePath();
    }
    return null;
}