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:monasca.common.middleware.HttpClientPoolFactory.java

private static KeyStore loadKeystore(String type, String keyStore, String keyPass) throws Exception {
    final KeyStore ks = KeyStore.getInstance("jks");
    if ((keyStore != null) && !keyStore.isEmpty()) {
        File keystoreFile = new File(keyStore);
        if (!keystoreFile.canRead()) {
            throw new FileNotFoundException(String.format("%s '%s' is not readable", type, keyStore));
        }//w  ww .  j  a  va 2s  . c om
        try (FileInputStream is1 = new FileInputStream(keystoreFile)) {
            ks.load(is1, keyPass.toCharArray());
        } catch (Exception e) {
            String errorMessage = String.format("Unable to open %s '%s': %s", type, keyStore, e.getMessage());
            logger.error(errorMessage);
            throw new Exception(errorMessage, e);
        }
    } else {
        ks.load(null, null);
    }
    return ks;
}

From source file:com.newatlanta.appengine.junit.vfs.gae.GaeVfsTestCase.java

public static void assertEquals(File file, FileObject fileObject) throws Exception {
    assertEqualPaths(file, fileObject);//from ww  w .ja v  a  2s  .com
    assertEquals(file.canRead(), fileObject.isReadable());
    assertEquals(file.canWrite(), fileObject.isWriteable());
    assertEquals(file.exists(), fileObject.exists());
    if (file.getParentFile() == null) {
        assertNull(fileObject.getParent());
    } else {
        assertEqualPaths(file.getParentFile(), fileObject.getParent());
    }
    assertEquals(file.isDirectory(), fileObject.getType().hasChildren());
    assertEquals(file.isFile(), fileObject.getType().hasContent());
    assertEquals(file.isHidden(), fileObject.isHidden());
    if (file.isFile()) {
        assertEquals(file.length(), fileObject.getContent().getSize());
    }
    if (file.isDirectory()) { // same children
        File[] childFiles = file.listFiles();
        FileObject[] childObjects = fileObject.getChildren();
        assertEquals(childFiles.length, childObjects.length);
        for (int i = 0; i < childFiles.length; i++) {
            assertEqualPaths(childFiles[i], childObjects[i]);
        }
    }
}

From source file:eu.eubrazilcc.lvl.core.AllTests.java

@BeforeClass
public static void setup() {
    System.out.println("AllTests.setup()");
    final URL anchorURL = AllTests.class.getClassLoader().getResource(ANCHOR_FILENAME);
    File anchorFile = null;//w w  w  . ja  v  a  2 s .  co m
    try {
        anchorFile = new File(anchorURL.toURI());
    } catch (Exception e) {
        anchorFile = new File(System.getProperty("user.dir"));
    }
    TEST_RESOURCES_PATH = concat(anchorFile.getParent(), "files");
    final File resDir = new File(TEST_RESOURCES_PATH);
    if (resDir != null && resDir.isDirectory() && resDir.canRead()) {
        try {
            TEST_RESOURCES_PATH = resDir.getCanonicalPath();
        } catch (IOException e) {
            // nothing to do
        }
    } else {
        throw new IllegalStateException("Invalid test resources pathname: " + TEST_RESOURCES_PATH);
    }
    System.out.println("Test resources pathname: " + TEST_RESOURCES_PATH);
    // load logging bridges
    LOG_MANAGER.preload();
    // system pre-loading
    CLOSER_SERVICE_MOCK.preload();
}

From source file:com.afrisoftech.lib.PDF2ExcelConverter.java

public static void convertPDf2Excel(String pdfFile2Convert) throws Exception {
    if (pdfFile2Convert.length() < 3) {
        System.out.println("File to convert is mandatory!");
        javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
    } else {/* ww  w. ja v  a2 s  . c om*/

        final String apiKey = "ktxpfvf0i5se";
        final String format = "xlsx-single".toLowerCase();
        final String pdfFilename = pdfFile2Convert;

        if (!formats.contains(format)) {
            System.out.println("Invalid output format: \"" + format + "\"");
        }

        // Avoid cookie warning with default cookie configuration
        RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();

        File inputFile = new File(pdfFilename);

        if (!inputFile.canRead()) {
            System.out.println("Can't read input PDF file: \"" + pdfFilename + "\"");
            javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!");
        }

        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .build()) {
            HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey);
            FileBody fileBody = new FileBody(inputFile);

            HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build();
            httppost.setEntity(requestBody);

            System.out.println("Sending request");

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                if (response.getStatusLine().getStatusCode() != 200) {
                    System.out.println(response.getStatusLine());
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Internet connection is a must. Consult IT administrator for further assistance");
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    final String outputFilename = getOutputFilename(pdfFilename,
                            format.replaceFirst("-.*$", ""));
                    System.out.println("Writing output to " + outputFilename);

                    final File outputFile = new File(outputFilename);
                    FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile);
                    if (java.awt.Desktop.isDesktopSupported()) {
                        try {
                            java.awt.Desktop.getDesktop().open(outputFile);
                        } catch (IOException ex) {
                            javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage());
                            ex.printStackTrace(); //Exceptions.printStackTrace(ex);
                        }
                    }
                } else {
                    System.out.println("Error: file missing from response");
                    javax.swing.JOptionPane.showMessageDialog(null,
                            "Error: file missing from response! Internet connection is a must.");
                }
            }
        }
    }
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private static File searchLibrary(ApplicationInfo applicationInfo) {
    // Search for library path
    String[] libraryPaths;/*w  ww . j a v  a2 s  .  c  o m*/
    if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
        final String property = System.getProperty("java.library.path");
        libraryPaths = property.split(":");
    } else {
        libraryPaths = new String[1];
        libraryPaths[0] = applicationInfo.nativeLibraryDir;
    }
    if (libraryPaths[0] == null) {
        Log.e(TAG, "can't find library path");
        return null;
    }

    // Search for libvlcjni.so
    File lib;
    for (String libraryPath : libraryPaths) {
        lib = new File(libraryPath, "libvlcjni.so");
        if (lib.exists() && lib.canRead())
            return lib;
    }
    Log.e(TAG, "WARNING: Can't find shared library");
    return null;
}

From source file:cache.reverseproxy.CachedResponseParser.java

public static GenericHttpResponse getResponse(String fileName, boolean isSoap) throws IOException {
    String fileDir = ProxyConfig.getOutputDir(isSoap);

    File file = new File(fileDir + "/" + fileName);
    if (!file.exists() || !file.canRead() || file.isDirectory()) {
        return null;
    }//from   w w w.  ja v a  2s .c om

    GenericHttpResponse response = new GenericHttpResponse();

    BufferedReader br = new BufferedReader(new FileReader(file));
    StringBuffer fileContents = new StringBuffer();
    String line = br.readLine();
    boolean isHeadRetrieved = false;
    boolean isFirst = true;
    while (line != null) {
        if (!isFirst && !isHeadRetrieved) {
            fileContents.append("\r\n");
            if (line != null) {
                String ucaseLine = line.toUpperCase();
                if (ucaseLine.indexOf("CONTENT-TYPE") > -1 && ucaseLine.indexOf(HTTP.UTF_8) > -1) {
                    response.encoding = HTTP.UTF_8;
                }
            }
        }
        if (!isFirst || !"".equals(line)) {
            fileContents.append(line);
        }

        isFirst = false;
        line = br.readLine();
        if ("".equals(line) && !isHeadRetrieved) {
            isHeadRetrieved = true;
            response.headers = fileContents.toString();
            fileContents = new StringBuffer();
            isFirst = true;
        }
    }

    if (isHeadRetrieved) {
        response.entity = fileContents.toString();
    } else {
        response.headers = fileContents.toString();
    }

    br.close();
    /*System.out.println("FromFile:BEGIN");
    System.out.println(response.headers);
    System.out.println(response.entity);
    System.out.println("FromFile:END");*/
    return response;
}

From source file:com.BibleQuote.utils.FsUtils.java

public static void SearchByFilter(File currentFile, ArrayList<String> resultFiles, FileFilter filter)
        throws IOException {

    try {//  w  w  w . j av  a 2s. c om
        File[] files = currentFile.listFiles(filter);
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (!file.canRead()) {
                continue;
            } else if (file.isDirectory()) {
                SearchByFilter(file, resultFiles, filter);
            } else {
                resultFiles.add(file.getAbsolutePath());
            }
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("SearchByFilter(%1$s, %2$s)", currentFile.getName(), filter.toString()), e);
    }

}

From source file:com.sg2net.utilities.ListaCAP.json.JsonUtilties.java

public static Collection<Comune> deserializeFrom(File file) {
    if (file == null) {
        throw new IllegalArgumentException("File is null");
    }//from w  w  w . j a v  a  2s .c o m
    if (!file.exists() || file.isDirectory() || !file.canRead()) {
        throw new IllegalArgumentException("File " + file.getName() + " is not file or is not readable ");
    }
    try {
        return JSONMapper.readValue(file, new TypeReference<List<Comune>>() {
        });
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:me.ineson.testing.utils.GradleConfig.java

private static synchronized String readGradleConfig(String key) {
    if (GRADLE_PROPERTIES == null) {
        File filename = new File(SystemUtils.getUserHome(), ".gradle/gradle.properties");
        if (!filename.exists() || !filename.isFile() || !filename.canRead()) {
            throw new IllegalStateException("Failed to access gradle configuration: "
                    + filename.getAbsolutePath() + ", exists " + filename.exists() + ", isFile "
                    + filename.isFile() + ", canRead " + filename.canRead());
        }//from  www . j a v  a2s. c o m
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(
                    "Failed to access gradle configuration: " + filename.getAbsolutePath(), e);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Failed to access gradle configuration: " + filename.getAbsolutePath(), e);
        }
        GRADLE_PROPERTIES = properties;
    }

    String fullKey = "systemProp." + key;
    String value = GRADLE_PROPERTIES.getProperty(fullKey);

    if (value != null) {
        System.setProperty(key, value);
    }

    return value;
}

From source file:it.geosolutions.tools.io.file.reader.TextReader.java

/**
 * Get the contents of a {@link File} as a String using the specified character encoding.
 * //ww  w.  j a va 2  s . co  m
 * @param file
 *            {@link File} to read from
 * @param encoding
 *            IANA encoding
 * @return a {@link String} containig the content of the {@link File} or
 *         <code>null<code> if an error happens.
 */
public static String toString(final File file, final String encoding) {
    Objects.notNull(file);
    if (!file.isFile() || !file.canRead() || !file.exists())
        return null;
    InputStream stream = null;
    try {
        if (encoding == null)
            return org.apache.commons.io.IOUtils.toString(new FileInputStream(file));
        else
            return org.apache.commons.io.IOUtils.toString(new FileInputStream(file), encoding);
    } catch (Throwable e) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(e.getLocalizedMessage(), e);
        return null;
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (Throwable e) {
                if (LOGGER.isTraceEnabled())
                    LOGGER.trace(e.getLocalizedMessage(), e);
            }
    }
}