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:eu.qualimaster.adaptation.platform.ToolBase.java

/**
 * Configures logging from a given file.
 * //from ww  w.  j  a v a 2 s  . c  om
 * @param file the file to be used for logging
 * @param reset whether the logging context shall be reset (may be relevant for single-step configurations)
 */
public static void configureLogging(File file, boolean reset) {
    File logDir = new File(System.getProperty("java.io.tmpdir"));
    if (SystemUtils.IS_OS_UNIX) {
        File tmp = new File("/var/log");
        if (isAccessibleDir(tmp)) {
            logDir = tmp;
        }
    }
    System.setProperty("qm.log.dir", logDir.getAbsolutePath());

    if (file.exists() && file.canRead()) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            // Call context.reset() to clear any previous configuration, e.g. default 
            // configuration. For multi-step configuration, omit calling context.reset().
            if (reset) {
                context.reset();
            }
            context.reset();
            configurator.doConfigure(file);
        } catch (JoranException je) {
            // StatusPrinter will handle this
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
    } // ignore and use default configuration
}

From source file:azkaban.common.utils.Utils.java

public static File[] ls(File dir) {
    if (!dir.exists() || !dir.isDirectory() || !dir.canRead())
        throw new IllegalArgumentException(dir + " is not a readable directory or does not exist.");

    File[] files = dir.listFiles();
    if (files == null)
        return new File[0];
    else/*from  ww  w .  ja va2  s  .c o m*/
        return files;
}

From source file:com.microsoft.applicationinsights.internal.perfcounter.JniPCConnector.java

private static File buildDllLocalPath() {
    Properties properties = PropertyHelper.getSdkVersionProperties();
    if (properties == null) {
        throw new RuntimeException("Failed to find SDK Version Properties file.");
    }/*from w ww.  ja  v a2s.  c o m*/

    String version = properties.getProperty("version");
    if (version == null) {
        throw new RuntimeException("Failed to find SDK version.");
    }

    File dllPath = LocalFileSystemUtils.getTempDir();

    dllPath = new File(dllPath.toString(), AI_BASE_FOLDER);
    dllPath = new File(dllPath.toString(), AI_NATIVE_FOLDER);
    dllPath = new File(dllPath.toString(), version);

    if (!dllPath.exists()) {
        dllPath.mkdirs();
    }

    if (!dllPath.exists() || !dllPath.canRead() || !dllPath.canWrite()) {
        throw new RuntimeException("Failed to create a read/write folder for the native dll.");
    }

    InternalLogger.INSTANCE.trace("%s folder exists", dllPath.toString());

    return dllPath;
}

From source file:br.com.manish.ahy.kernel.util.FileUtil.java

public static void copyFile(String from, String to, Boolean overwrite) {

    try {/*from www  .  ja  v  a  2s  . c o m*/
        File fromFile = new File(from);
        File toFile = new File(to);

        if (!fromFile.exists()) {
            throw new IOException("File not found: " + from);
        }
        if (!fromFile.isFile()) {
            throw new IOException("Can't copy directories: " + from);
        }
        if (!fromFile.canRead()) {
            throw new IOException("Can't read file: " + from);
        }

        if (toFile.isDirectory()) {
            toFile = new File(toFile, fromFile.getName());
        }

        if (toFile.exists() && !overwrite) {
            throw new IOException("File already exists.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("Destination directory does not exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("Destination is not a valid directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("Can't write on destination: " + parent);
            }
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {

            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } finally {
            if (from != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
            if (to != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }

    } catch (Exception e) {
        throw new OopsException(e, "Problems when copying file.");
    }
}

From source file:com.glaf.core.util.IOUtils.java

/**
 * read lines.//  w  w w .  j  a v  a2  s  . c o m
 * 
 * @param file
 *            file.
 * @return lines.
 * @throws IOException
 */
public static String[] readLines(File file) throws IOException {
    if (file == null || !file.exists() || !file.canRead())
        return new String[0];

    return readLines(new FileInputStream(file));
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

public static KeyStore createTrustStore()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    final KeyStore trustStore = createKeyStore();

    char SEP = File.separatorChar;
    final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
    final File file = new File(dir, "cacerts");
    if (file.canRead()) {
        final KeyStore ks = KeyStore.getInstance("JKS");
        final InputStream in = new FileInputStream(file);
        try {/*w  ww.ja v  a2s. c  o m*/
            ks.load(in, null);
        } finally {
            in.close();
        }
        copyCertificates(ks, trustStore);
    }
    return trustStore;
}

From source file:net.slkdev.swagger.confluence.service.impl.SwaggerToAsciiDocServiceImpl.java

private static File getSchemaFile(final String swaggerSchemaPath)
        throws FileNotFoundException, URISyntaxException {
    // First we'll try to find the file directly
    File swaggerFile = new File(swaggerSchemaPath);

    // If we can't find it, we'll check the classpath
    if (!swaggerFile.exists()) {
        final URL swaggerSchemaURL = SwaggerToAsciiDocServiceImpl.class.getResource(swaggerSchemaPath);

        if (swaggerSchemaURL == null) {
            swaggerFile = null;/*ww w .j av  a 2  s .  c o m*/
        } else {
            swaggerFile = new File(swaggerSchemaURL.toURI());
        }
    }

    if (swaggerFile == null || !swaggerFile.exists() || !swaggerFile.canRead()) {
        throw new FileNotFoundException(
                String.format("Unable to Locate Swagger Schema at Path <%s>", swaggerSchemaPath));
    }

    return swaggerFile;
}

From source file:eu.socialsensor.main.BenchmarkConfiguration.java

private static final File validateReadableFile(String fileName, String fileType) {
    File file = new File(fileName);
    if (!file.exists()) {
        throw new IllegalArgumentException(String.format("the %s does not exist", fileType));
    }/*  www.j a  va2  s.com*/

    if (!(file.isFile() && file.canRead())) {
        throw new IllegalArgumentException(
                String.format("the %s must be a file that this user can read", fileType));
    }
    return file;
}

From source file:IndexImportMediawiki_p.java

/**
 * Run conditions ://w  w w. j  a v a2 s  . c o m
 * - no MediaWiki import thread is running : allow to start a new import by filling the "file" parameter
 * - the MediaWiki import thread is running : returns monitoring information.
 * @param header servlet request header
 * @param post request parameters. Supported keys :
 *            <ul>
 *            <li>file : a dump URL or file path on this YaCy server local file system</li>
 *            <li>iffresh : when set to true, the dump file is imported only if its last modified date is unknown or after the last import trial date on this same file.  </li>
 *            <li>report : when set, display the currently running thread monitoring info, or the last import report when no one is running.
 *            Ignored when no import thread is known.</li>
 *            </ul>
 * @param env server environment
 * @return the servlet answer object
 */
public static serverObjects respond(final RequestHeader header, final serverObjects post,
        final serverSwitch env) {
    final serverObjects prop = new serverObjects();
    final Switchboard sb = (Switchboard) env;

    if (MediawikiImporter.job != null
            && (MediawikiImporter.job.isAlive() || (post != null && post.containsKey("report")))) {
        /* one import is running, or report was explicitly requested : no option to insert anything */
        prop.put("import", 1);
        /* Only refresh automatically when the job is running */
        prop.put("refresh", MediawikiImporter.job.isAlive() ? 1 : 0);
        final String jobErrorMessage = MediawikiImporter.job.status();
        if (jobErrorMessage != null && !jobErrorMessage.isEmpty()) {
            prop.put("import_status", 1);
            prop.put("import_status_message", jobErrorMessage);
        }
        prop.put("import_thread", MediawikiImporter.job.isAlive() ? 2 : 0);
        prop.put("import_dump", MediawikiImporter.job.source());
        prop.put("import_count", MediawikiImporter.job.count());
        prop.put("import_speed", MediawikiImporter.job.speed());
        prop.put("import_runningHours", (MediawikiImporter.job.runningTime() / 60) / 60);
        prop.put("import_runningMinutes", (MediawikiImporter.job.runningTime() / 60) % 60);
        prop.put("import_remainingHours", (MediawikiImporter.job.remainingTime() / 60) / 60);
        prop.put("import_remainingMinutes", (MediawikiImporter.job.remainingTime() / 60) % 60);
    } else {
        prop.put("import", 0);
        prop.put("refresh", 0);
        prop.put("import_prevReport", MediawikiImporter.job != null ? 1 : 0);
        if (post == null) {
            prop.put("import_status", 0);

            /* Acquire a transaction token for the next POST form submission */
            final String token = TransactionManager.getTransactionToken(header);
            prop.put(TransactionManager.TRANSACTION_TOKEN_PARAM, token);
            prop.put("import_" + TransactionManager.TRANSACTION_TOKEN_PARAM, token);

        } else {
            if (post.containsKey("file")) {
                /* Check the transaction is valid */
                TransactionManager.checkPostTransaction(header, post);

                String file = post.get("file");
                MultiProtocolURL sourceURL = null;
                int status = 0;
                String sourceFilePath = "";
                final Row lastExecutedCall = WorkTables.selectLastExecutedApiCall("IndexImportMediawiki_p.html",
                        post, sb);
                Date lastExecutionDate = null;
                if (lastExecutedCall != null) {
                    lastExecutionDate = lastExecutedCall.get(WorkTables.TABLE_API_COL_DATE_LAST_EXEC,
                            (Date) null);
                }
                try {
                    sourceURL = new MultiProtocolURL(file);
                    if (sourceURL.isFile()) {
                        final File sourcefile = sourceURL.getFSFile();
                        sourceFilePath = sourcefile.getAbsolutePath();
                        if (!sourcefile.exists()) {
                            status = 2;
                        } else if (!sourcefile.canRead()) {
                            status = 3;
                        } else if (sourcefile.isDirectory()) {
                            status = 4;
                        }
                    }

                    if (status == 0 && post.getBoolean("iffresh")) {
                        long lastModified = getLastModified(sourceURL);
                        if (lastExecutionDate != null && lastModified != 0L
                                && Instant.ofEpochMilli(lastModified).isBefore(lastExecutionDate.toInstant())) {
                            status = 5;
                            prop.put("import_status_lastImportDate", GenericFormatter.formatSafely(
                                    lastExecutionDate.toInstant(), GenericFormatter.FORMAT_SIMPLE));

                            /* the import is not performed, but we increase here the api call count */
                            if (sb.tables != null) {
                                byte[] lastExecutedCallPk = lastExecutedCall.getPK();
                                if (lastExecutedCallPk != null
                                        && !post.containsKey(WorkTables.TABLE_API_COL_APICALL_PK)) {
                                    post.add(WorkTables.TABLE_API_COL_APICALL_PK,
                                            UTF8.String(lastExecutedCallPk));
                                }
                                sb.tables.recordAPICall(post, "IndexImportMediawiki_p.html",
                                        WorkTables.TABLE_API_TYPE_DUMP,
                                        "MediaWiki Dump Import for " + sourceURL);
                            }
                        }
                    }
                } catch (MalformedURLException e) {
                    status = 1;
                }
                if (status == 0) {
                    /* store this call as an api call */
                    if (sb.tables != null) {
                        /* We avoid creating a duplicate of any already recorded API call with the same parameters */
                        if (lastExecutedCall != null
                                && !post.containsKey(WorkTables.TABLE_API_COL_APICALL_PK)) {
                            byte[] lastExecutedCallPk = lastExecutedCall.getPK();
                            if (lastExecutedCallPk != null) {
                                post.add(WorkTables.TABLE_API_COL_APICALL_PK, UTF8.String(lastExecutedCallPk));
                            }
                        }
                        sb.tables.recordAPICall(post, "IndexImportMediawiki_p.html",
                                WorkTables.TABLE_API_TYPE_DUMP, "MediaWiki Dump Import for " + sourceURL);
                    }

                    MediawikiImporter.job = new MediawikiImporter(sourceURL, sb.surrogatesInPath);
                    MediawikiImporter.job.start();
                    prop.put("import_dump", MediawikiImporter.job.source());
                    prop.put("import_thread", 1);
                    prop.put("import", 1);
                    prop.put("refresh", 1);
                } else {
                    prop.put("import_status", status);
                    prop.put("import_status_sourceFile", sourceFilePath);

                    /* Acquire a transaction token for the next POST form submission */
                    final String token = TransactionManager.getTransactionToken(header);
                    prop.put(TransactionManager.TRANSACTION_TOKEN_PARAM, token);
                    prop.put("import_" + TransactionManager.TRANSACTION_TOKEN_PARAM, token);
                }
                prop.put("import_count", 0);
                prop.put("import_speed", 0);
                prop.put("import_runningHours", 0);
                prop.put("import_runningMinutes", 0);
                prop.put("import_remainingHours", 0);
                prop.put("import_remainingMinutes", 0);
            }
        }
    }
    return prop;
}

From source file:com.marklogic.contentpump.ContentPump.java

private static void checkHadoopConfDir(File hdConfDir) throws IllegalArgumentException {
    if (!hdConfDir.exists()) {
        throw new IllegalArgumentException("Hadoop conf dir " + hdConfDir + " is not found.");
    } else if (!hdConfDir.isDirectory()) {
        throw new IllegalArgumentException("Hadoop conf dir " + hdConfDir + " is not a directory.");
    } else if (!hdConfDir.canRead()) {
        throw new IllegalArgumentException("Hadoop conf dir " + hdConfDir + " cannot be read.");
    }/*from ww  w.  j  av a 2  s .  com*/
}