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.indeed.imhotep.builder.tsv.KerberosUtils.java

public static void loginFromKeytab(@Nullable String principal, @Nullable String keytabPath) throws IOException {
    // if one of these is set, then assume they meant to set both
    if (!Strings.isNullOrEmpty(principal) || !Strings.isNullOrEmpty(keytabPath)) {
        log.info("Using properties from configuration file");
        with(principal, keytabPath);/*ww  w . jav  a  2  s .  c om*/
    } else {
        // look for the file to be readable for this user
        final String username = StandardSystemProperty.USER_NAME.value();
        final File keytabFile = new File(String.format("/etc/local_keytabs/%1$s/%1$s.keytab", username));
        log.info("Checking for user " + username + " keytab, settings at " + keytabFile.getAbsolutePath());
        if (keytabFile.exists() && keytabFile.canRead()) {
            with(username + "/_HOST@INDEED.NET", keytabFile.getAbsolutePath());
        } else {
            log.warn("Unable to find user keytab, maybe the keytab is in ticket from klist");
        }
    }
}

From source file:com.nineteendrops.tracdrops.client.core.Utils.java

public static byte[] getBinaryData(String fullFileName, TracProperties tracProperties) {

    File file = new File(fullFileName);
    if (!file.exists()) {
        throw new TracException(MessageUtils.getFullFileNameNotFoundMessage(fullFileName));
    }/*  w  ww .  j a  v a  2  s .  c om*/

    if (!file.canRead()) {
        throw new TracException(MessageUtils.getFullFileNameNotFoundMessage(fullFileName));
    }

    if (!file.isFile()) {
        throw new TracException(MessageUtils.getFullFileNameNotFoundMessage(fullFileName));
    }

    int maxUploadSize = tracProperties.getIntegerProperty(TracProperties.ATTACHMENT_UPLOAD_MAX_SIZE);
    if (file.length() > maxUploadSize) {
        throw new TracException(MessageUtils.getMessage("core.file.size.exceeded", fullFileName,
                String.valueOf(maxUploadSize)));
    }

    byte[] binaryData;
    try {
        binaryData = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(binaryData);
        fis.close();
    } catch (IOException e) {
        throw new TracException(MessageUtils.registerErrorLog(log, "core.unexpected.exception", e.getMessage()),
                e);
    }
    return binaryData;
}

From source file:com.orange.ocara.model.export.docx.DocxWriterTest.java

/**
 * Determine whether a file is a ZIP File.
 *//*from www . ja  v  a2  s  . c o  m*/
private static boolean isZipFile(File file) throws IOException {
    if (file.isDirectory()) {
        return false;
    }
    if (!file.canRead()) {
        throw new IOException("Cannot read file " + file.getAbsolutePath());
    }
    if (file.length() < 4) {
        return false;
    }
    DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
    int test = in.readInt();
    in.close();
    return test == 0x504b0304;
}

From source file:edu.cornell.mannlib.vitro.webapp.auth.identifier.common.IsBlacklisted.java

/**
 * Runs the SPARQL query in the file with the uri of the individual
 * substituted in./*from ww  w  .j  a va  2 s  .  c  o  m*/
 * 
 * The URI of ind will be substituted into the query where ever the token
 * "?individualURI" is found.
 * 
 * If there are any solution sets, then the URI of the variable named
 * "cause" will be returned. Make sure that it is a resource with a URI.
 * Otherwise null will be returned.
 */
private static String runSparqlFileForBlacklist(File file, Individual ind, ServletContext context) {
    if (!file.canRead()) {
        log.debug("cannot read blacklisting SPARQL file " + file.getName());
        return NOT_BLACKLISTED;
    }

    String queryString = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
        byte b[] = new byte[fis.available()];
        fis.read(b);
        queryString = new String(b);
    } catch (IOException ioe) {
        log.debug(ioe);
        return NOT_BLACKLISTED;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.warn("could not close file", e);
            }
        }
    }

    if (StringUtils.isEmpty(queryString)) {
        log.debug(file.getName() + " is empty");
        return NOT_BLACKLISTED;
    }

    OntModel model = ModelAccess.on(context).getOntModel();

    queryString = queryString.replaceAll("\\?individualURI", "<" + ind.getURI() + ">");
    log.debug(queryString);

    Query query = QueryFactory.create(queryString);
    QueryExecution qexec = QueryExecutionFactory.create(query, model);
    try {
        ResultSet results = qexec.execSelect();
        while (results.hasNext()) {
            QuerySolution solution = results.nextSolution();
            if (solution.contains("cause")) {
                RDFNode node = solution.get("cause");
                if (node.isResource()) {
                    return node.asResource().getURI();
                } else if (node.isLiteral()) {
                    return node.asLiteral().getString();
                }
            } else {
                log.error("Query solution must contain a variable " + "\"cause\" of type Resource or Literal.");
                return NOT_BLACKLISTED;
            }
        }
    } finally {
        qexec.close();
    }
    return NOT_BLACKLISTED;
}

From source file:forge.properties.ForgeProfileProperties.java

public static void load() {
    final Properties props = new Properties();
    final File propFile = new File(ForgeConstants.PROFILE_FILE);
    try {// www  .j  a v a  2s.  c  o  m
        if (propFile.canRead()) {
            props.load(new FileInputStream(propFile));
        }
    } catch (final IOException e) {
        System.err.println("error while reading from profile properties file");
    }

    final Pair<String, String> defaults = getDefaultDirs();
    userDir = getDir(props, USER_DIR_KEY, defaults.getLeft());
    cacheDir = getDir(props, CACHE_DIR_KEY, defaults.getRight());
    cardPicsDir = getDir(props, CARD_PICS_DIR_KEY,
            cacheDir + "pics" + File.separator + "cards" + File.separator);
    cardPicsSubDirs = getMap(props, CARD_PICS_SUB_DIRS_KEY);
    serverPort = getInt(props, SERVER_PORT_KEY, 36743); // "Forge" using phone keypad

    //ensure directories exist
    FileUtil.ensureDirectoryExists(userDir);
    FileUtil.ensureDirectoryExists(cacheDir);
    FileUtil.ensureDirectoryExists(cardPicsDir);
}

From source file:morphy.Morphy.java

private static File ensureConfigFileExistsAndReadable(String filePath) {
    File configFile = new File(filePath);
    if (!configFile.exists()) {
        System.err.println("Configuration file does not exist.");
        System.exit(1);/*from  ww w.  j  av a 2 s. c om*/
    }

    if (!configFile.canRead()) {
        System.err.println("Unable to read configuration file.");
        System.exit(1);
    }
    return configFile;
}

From source file:com.thoughtworks.go.util.FileUtil.java

public static boolean isDirectoryReadable(File directory) {
    return directory.canRead() && directory.canExecute() && directory.listFiles() != null;
}

From source file:Main.java

/**
 * Reads the given file, translating {@link IOException} to a
 * {@link RuntimeException} of some sort.
 *
 * @param file {@code non-null;} the file to read
 * @return {@code non-null;} contents of the file
 *//*from  ww w  . j  a v a 2s .  co  m*/
public static byte[] readFile(File file) {
    if (!file.exists()) {
        throw new RuntimeException(file + ": file not found");
    }

    if (!file.isFile()) {
        throw new RuntimeException(file + ": not a file");
    }

    if (!file.canRead()) {
        throw new RuntimeException(file + ": file not readable");
    }

    long longLength = file.length();
    int length = (int) longLength;
    if (length != longLength) {
        throw new RuntimeException(file + ": file too long");
    }

    byte[] result = new byte[length];

    try {
        FileInputStream in = new FileInputStream(file);
        int at = 0;
        while (length > 0) {
            int amt = in.read(result, at, length);
            if (amt == -1) {
                throw new RuntimeException(file + ": unexpected EOF");
            }
            at += amt;
            length -= amt;
        }
        in.close();
    } catch (IOException ex) {
        throw new RuntimeException(file + ": trouble reading", ex);
    }

    return result;
}

From source file:FileTableHTML.java

public static String makeHTMLTable(String dirname) {
    // Look up the contents of the directory
    File dir = new File(dirname);
    String[] entries = dir.list();

    // Set up an output stream we can print the table to.
    // This is easier than concatenating strings all the time.
    StringWriter sout = new StringWriter();
    PrintWriter out = new PrintWriter(sout);

    // Print the directory name as the page title
    out.println("<H1>" + dirname + "</H1>");

    // Print an "up" link, unless we're already at the root
    String parent = dir.getParent();
    if ((parent != null) && (parent.length() > 0))
        out.println("<A HREF=\"" + parent + "\">Up to parent directory</A><P>");

    // Print out the table
    out.print("<TABLE BORDER=2 WIDTH=600><TR>");
    out.print("<TH>Name</TH><TH>Size</TH><TH>Modified</TH>");
    out.println("<TH>Readable?</TH><TH>Writable?</TH></TR>");
    for (int i = 0; i < entries.length; i++) {
        File f = new File(dir, entries[i]);
        out.println("<TR><TD>" + (f.isDirectory() ? "<a href=\"" + f + "\">" + entries[i] + "</a>" : entries[i])
                + "</TD><TD>" + f.length() + "</TD><TD>" + new Date(f.lastModified()) + "</TD><TD align=center>"
                + (f.canRead() ? "x" : " ") + "</TD><TD align=center>" + (f.canWrite() ? "x" : " ")
                + "</TD></TR>");
    }//w  w  w.j  av  a 2  s  .com
    out.println("</TABLE>");
    out.close();

    // Get the string of HTML from the StringWriter and return it.
    return sout.toString();
}

From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * Returns the contents of '/etc/lsb-release' (and/or others).
 *//*from  ww  w . jav a2s . c  o  m*/
private static String getLinuxDescription() {
    StringBuilder result = new StringBuilder();
    if (EnvironmentUtils.IS_LINUX) {
        String[] files = new String[] { "/etc/lsb-release", //$NON-NLS-1$
                "/etc/lsb_release", "/etc/system-release", //$NON-NLS-1$ //$NON-NLS-2$
                "/etc/fedora-release", "/etc/SuSE-release", //$NON-NLS-1$ //$NON-NLS-2$
                "/etc/redhat-release", "/etc/release", //$NON-NLS-1$ //$NON-NLS-2$
                "/proc/version_signature", "/proc/version", "/etc/issue", }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        for (int i = 0; i < files.length; i++) {
            File file = new File(files[i]);
            if (file.exists() && file.canRead()) {
                try {
                    String version = IOUtils2.readString(file).trim();
                    if (version != null && result.indexOf(version) == -1) {
                        result.append(version);
                        result.append("\n"); //$NON-NLS-1$
                    }
                } catch (IOException e) {
                    JSSCommunityActivator.getDefault()
                            .logError(MessageFormat.format(Messages.CommunityAPIUtils_ErrorMsgReadingFile,
                                    new Object[] { file.getAbsolutePath() }), e);
                }
            }
        }
    }
    return result.toString();
}