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.openkm.servlet.RepositoryStartupServlet.java

/**
 * Close OpenKM and free resources/*from w ww  .j  a v  a 2 s  .  c om*/
 */
public static synchronized void stop(GenericServlet gs) {
    if (!running) {
        throw new IllegalStateException("OpenKM not started");
    }

    // Shutdown plugin framework
    ExtensionManager.getInstance().shutdown();

    try {
        if (Config.REMOTE_CONVERSION_SERVER.equals("")) {
            if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) {
                log.info("*** Shutting down OpenOffice manager ***");
                DocConverter.getInstance().stop();
            }
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    log.info("*** Shutting down UI Notification... ***");
    uin.cancel();

    log.info("*** Shutting down cron... ***");
    cron.cancel();

    if (Config.UPDATE_INFO) {
        log.info("*** Shutting down update info... ***");
        ui.cancel();
    }

    // Cancel timers
    cronTimer.cancel();
    uinTimer.cancel();
    uiTimer.cancel();

    // Shutdown pending task executor
    log.info("*** Shutting pending task executor... ***");
    PendingTaskExecutor.shutdown();

    log.info("*** Shutting down repository... ***");

    try {
        // Preserve system user config
        if (!Config.REPOSITORY_NATIVE) {
            JcrRepositoryModule.shutdown();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    log.info("*** Repository shutted down ***");

    try {
        log.info("*** Execute stop script ***");
        File script = new File(Config.HOME_DIR + File.separatorChar + Config.STOP_SCRIPT);
        ExecutionUtils.runScript(script);
        File jar = new File(Config.HOME_DIR + File.separatorChar + Config.STOP_JAR);
        ExecutionUtils.getInstance().runJar(jar);
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    try {
        log.info("*** Execute stop SQL ***");
        File sql = new File(Config.HOME_DIR + File.separatorChar + Config.STOP_SQL);

        if (sql.exists() && sql.canRead()) {
            FileReader fr = new FileReader(sql);
            HibernateUtil.executeSentences(fr);
            IOUtils.closeQuietly(fr);
        } else {
            log.warn("Unable to read sql: {}", sql.getPath());
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    log.info("*** Shutting down workflow engine... ***");
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    jbpmContext.getJbpmConfiguration().getJobExecutor().stop();
    jbpmContext.getJbpmConfiguration().close();
    jbpmContext.close();

    // OpenKM is stopped
    running = false;
}

From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java

public static void copyFileAttributes(@Nonnull final File from, @Nonnull final File to) {
    to.setExecutable(from.canExecute());
    to.setReadable(from.canRead());
    to.setWritable(from.canWrite());//from w w  w.j av a 2 s  .c o  m
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

private static boolean generateAppfromXML(String fn) {

    long starttime = System.currentTimeMillis();

    // fn must not be null or empty
    if (fn == null || fn.isEmpty()) {
        log.error("Empty filename!");
        return false;
    }/*from   ww  w .  j  a  v  a  2 s  .c o  m*/
    // fn must be a valid file and readable
    File runnableitem = new File(fn);
    if (!runnableitem.exists() || !runnableitem.canRead()) {
        log.error("{} doesn't exists or can't be read! ", fn);
        return false;
    }
    // load as xml file, validate it, and ...
    Document doc;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        //dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(runnableitem);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("{} occured: {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }
    // extract project id, name  and version from it.
    String projectid = doc.getDocumentElement().getAttribute("id");
    if ((projectid == null) || projectid.isEmpty()) {
        log.error("Missing project id in description file!");
        return false;
    }
    String projectname;
    try {
        projectname = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "name").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.error("Missing project name in description file!");
        return false;
    }

    String projectversion = "unknown";
    try {
        projectversion = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "version").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.warn("Missing project version in description file!");

    }

    File projectdir = new File(
            config.getProperty("project.dir", config.getProperty("target.dir") + "/" + projectid));

    mkdirs(projectdir + "/src/main/java");
    mkdirs(projectdir + "/src/main/config");
    mkdirs(projectdir + "/src/main/libs");
    mkdirs(projectdir + "/src/main/pages");
    mkdirs(projectdir + "/src/main/resources");
    mkdirs(projectdir + "/src/main/downloads");

    // place runnableitem in config dir
    try {
        Files.copy(runnableitem.toPath(), new File(projectdir + "/src/main/config/runnableitem.xml").toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error("{} occurred : {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }

    // copy files from SKELETON to projectdir and replace wildcard expression
    String[] SKELETON_INPUT_ARRAY = { "/pom.xml", "/src/main/config/log4j-tool.properties" };
    String SKELETON_INPUT = null;
    try {
        for (int c = 0; c < SKELETON_INPUT_ARRAY.length; c++) {
            SKELETON_INPUT = SKELETON_INPUT_ARRAY[c];

            InputStream in = Main.class.getResourceAsStream("/SKELETON" + SKELETON_INPUT);
            if (in == null) {
                throw new IOException();
            }

            CopyAndReplace(in, new FileOutputStream(new File(projectdir, SKELETON_INPUT)), projectid,
                    projectname, projectversion);
        }

    } catch (IOException e) {
        log.error("Exception occurred while calling 'copyAndReplace(/SKELETON{},{}/{},{},{},{})'",
                SKELETON_INPUT, projectdir, SKELETON_INPUT, projectid, projectname, projectversion);
        return false;
    }

    log.info("Empty project created! ");

    try {
        // _base 

        generate(CodeGen_Implementation.class, runnableitem, projectdir);
        log.info("Implementation generated!");

        generate(CodeGen_Implementation_Threadworker.class, runnableitem, projectdir);
        log.info("Implementation_Threadworker generated!");

        generate(CodeGen_Utilities.class, runnableitem, projectdir);
        log.info("Utilities generated!");

        generate(CodeGen_Common.class, runnableitem, projectdir, "/templates/common", RESOURCETYPE.isDirectory);

        log.info("Common generated!");

        // _REST
        generate(CodeGen_REST.class, runnableitem, projectdir);
        generate(CodeGen_REST_general.class, runnableitem, projectdir);

        log.info("REST generated!");

        //_HTML
        generate(CodeGen_WebSubmissionPage.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Visualization.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Formatchooser.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Function.class, runnableitem, projectdir);
        generate(CodeGen_Session_Reset.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Controller.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_Webstart.class, runnableitem, projectdir); // can be removed ???
        generate(CodeGen_WebToolBeanContextConfig.class, runnableitem, projectdir);
        generate(CodeGen_WebManual.class, runnableitem, projectdir);
        generate(CodeGen_WebPage.class, runnableitem, projectdir, "/templates/pages", RESOURCETYPE.isDirectory);

        log.info("XHTML pages generated!");

        long time = (System.currentTimeMillis() - starttime) / 1000;

        log.info("Project \"{}\" (id:{}, version:{}) created at '{}' in {} seconds.", projectname, projectid,
                projectversion, projectdir, time);

    } catch (CodeGenParserException e) {
        log.error("CodeGenParserException occurred :", e);
        return false;
    }
    return true;
}

From source file:fr.gouv.culture.vitam.digest.DigestCompute.java

public static int createDigest(File src, File dst, File ftar, File fglobal, boolean oneDigestPerFile,
        String[] extensions, String mask, boolean prefix) {
    if (mask == null) {
        return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, extensions);
    }/*from  w  w  w . j  a va 2 s  . co  m*/
    try {
        if (prefix) {
            // fix mask
            List<File> filesToScan = new ArrayList<File>();
            File dirToSearch = src;
            if (!dirToSearch.isDirectory()) {
                if (dirToSearch.canRead() && dirToSearch.getName().startsWith(mask)) {
                    filesToScan.add(dirToSearch);
                } else {
                    throw new CommandExecutionException("Resources not found");
                }
            } else {
                Collection<File> temp = FileUtils.listFiles(dirToSearch, extensions,
                        StaticValues.config.argument.recursive);
                for (File file : temp) {
                    if (file.getName().startsWith(mask)) {
                        filesToScan.add(file);
                    }
                }
                temp.clear();
            }
            return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, filesToScan);
        } else {
            // RegEx mask
            File dirToSearch = src;
            if (!dirToSearch.isDirectory()) {
                List<File> filesToScan = new ArrayList<File>();
                if (dirToSearch.canRead() && dirToSearch.getName().matches(mask + ".*")) {
                    filesToScan.add(dirToSearch);
                    String global = dirToSearch.getName().replaceAll("[^" + mask + "].*", "")
                            + "_all_digests.xml";
                    fglobal = new File(fglobal, global);
                } else {
                    throw new CommandExecutionException("Resources not found");
                }
                return createDigest(src, dst, ftar, fglobal, oneDigestPerFile, filesToScan);
            } else {
                HashMap<String, List<File>> hashmap = new HashMap<String, List<File>>();
                Collection<File> temp = FileUtils.listFiles(dirToSearch, extensions,
                        StaticValues.config.argument.recursive);
                List<File> filesToScan = null;
                Pattern pattern = Pattern.compile(mask + ".*");
                Pattern pattern2 = Pattern.compile(mask);
                for (File file : temp) {
                    String filename = file.getName();
                    Matcher matcher = pattern.matcher(filename);
                    if (matcher.matches()) {
                        String end = pattern2.matcher(filename).replaceFirst("");
                        int pos = filename.indexOf(end);
                        if (pos <= 0) {
                            System.err.println("Cannot find : " + end + " in " + filename);
                            continue;
                        }
                        String global = filename.substring(0, pos);
                        if (global.charAt(global.length() - 1) != '_') {
                            global += "_";
                        }
                        global += "all_digests.xml";
                        filesToScan = hashmap.get(global);
                        if (filesToScan == null) {
                            filesToScan = new ArrayList<File>();
                            hashmap.put(global, filesToScan);
                        }
                        filesToScan.add(file);
                    }
                }
                temp.clear();
                int res = 0;
                for (String global : hashmap.keySet()) {
                    File fglobalnew = new File(fglobal, global);
                    res += createDigest(src, dst, ftar, fglobalnew, oneDigestPerFile, hashmap.get(global));
                }
                hashmap.clear();
                return res;
            }
        }
    } catch (CommandExecutionException e1) {
        System.err.println(StaticValues.LBL.error_error.get() + " " + e1.toString());
        return -1;
    }
}

From source file:com.themodernway.server.core.io.IO.java

public static final boolean isReadable(final File file) {
    return file.canRead();
}

From source file:ffx.autoparm.Keyword_poltype.java

/**
 * This method sets up configuration properties in the following precedence
 * order: 1.) Java system properties a.) -Dkey=value from the Java command
 * line b.) System.setProperty("key","value") within Java code.
 *
 * 2.) Structure specific properties (for example pdbname.properties)
 *
 * 3.) User specific properties (~/.ffx/ffx.properties)
 *
 * 4.) System wide properties (file defined by environment variable
 * FFX_PROPERTIES)/*from ww w.j  av a2 s  . c  o  m*/
 *
 * 5.) Internal force field definition.
 *
 * @since 1.0
 * @param file a {@link java.io.File} object.
 * @return a {@link org.apache.commons.configuration.CompositeConfiguration}
 * object.
 */
public static CompositeConfiguration loadProperties(File file) {
    /**
     * Command line options take precedences.
     */
    CompositeConfiguration properties = new CompositeConfiguration();
    properties.addConfiguration(new SystemConfiguration());

    /**
     * Structure specific options are 2nd.
     */
    if (file != null && file.exists() && file.canRead()) {

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String prmfilename = br.readLine().split(" +")[1];
            File prmfile = new File(prmfilename);
            if (prmfile.exists() && prmfile.canRead()) {
                properties.addConfiguration(new PropertiesConfiguration(prmfile));
                properties.addProperty("propertyFile", prmfile.getCanonicalPath());
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    //      /**
    //       * User specific options are 3rd.
    //       */
    //      String filename = System.getProperty("user.home") + File.separator
    //            + ".ffx/ffx.properties";
    //      File userPropFile = new File(filename);
    //      if (userPropFile.exists() && userPropFile.canRead()) {
    //         try {
    //            properties.addConfiguration(new PropertiesConfiguration(
    //                  userPropFile));
    //         } catch (Exception e) {
    //            logger.info("Error loading " + filename + ".");
    //         }
    //      }
    //
    //      /**
    //       * System wide options are 2nd to last.
    //       */
    //      filename = System.getenv("FFX_PROPERTIES");
    //      if (filename != null) {
    //         File systemPropFile = new File(filename);
    //         if (systemPropFile.exists() && systemPropFile.canRead()) {
    //            try {
    //               properties.addConfiguration(new PropertiesConfiguration(
    //                     systemPropFile));
    //            } catch (Exception e) {
    //               logger.info("Error loading " + filename + ".");
    //            }
    //         }
    //      }
    /**
     * Echo the interpolated configuration.
     */
    if (logger.isLoggable(Level.FINE)) {
        Configuration config = properties.interpolatedConfiguration();
        Iterator<String> i = config.getKeys();
        while (i.hasNext()) {
            String s = i.next();
            logger.fine("Key: " + s + ", Value: " + Arrays.toString(config.getList(s).toArray()));
        }
    }

    return properties;
}

From source file:it.geosolutions.tools.io.file.Copy.java

/**
 * Copy the input file onto the output file using the specified buffer size.
 * /*from  w  w w. j  a v a  2s  .  com*/
 * @param sourceFile
 *            the {@link File} to copy from.
 * @param destinationFile
 *            the {@link File} to copy to.
 * @param size
 *            buffer size.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyFile(File sourceFile, File destinationFile, int size) throws IOException {
    Objects.notNull(sourceFile, destinationFile);
    if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile())
        throw new IllegalStateException("Source is not in a legal state.");
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }
    if (destinationFile.getAbsolutePath().equalsIgnoreCase(sourceFile.getAbsolutePath()))
        throw new IllegalArgumentException("Cannot copy a file on itself");

    RandomAccessFile s = null, d = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        s = new RandomAccessFile(sourceFile, "r");
        source = s.getChannel();
        d = new RandomAccessFile(destinationFile, "rw");
        destination = d.getChannel();
        IOUtils.copyFileChannel(size, source, destination);
    } finally {
        if (source != null) {
            try {
                source.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
        if (s != null) {
            try {
                s.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (destination != null) {
            try {
                destination.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }

        if (d != null) {
            try {
                d.close();
            } catch (Throwable t) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(t.getLocalizedMessage(), t);
            }
        }
    }
}

From source file:FileCopy.java

/**
 * The static method that actually performs the file copy. Before copying the
 * file, however, it performs a lot of tests to make sure everything is as it
 * should be./*from w w  w. ja va  2 s. c  om*/
 */
public static void copy(String from_name, String to_name) throws IOException {
    File from_file = new File(from_name); // Get File objects from Strings
    File to_file = new File(to_name);

    // First make sure the source file exists, is a file, and is readable.
    // These tests are also performed by the FileInputStream constructor
    // which throws a FileNotFoundException if they fail.
    if (!from_file.exists())
        abort("no such source file: " + from_name);
    if (!from_file.isFile())
        abort("can't copy directory: " + from_name);
    if (!from_file.canRead())
        abort("source file is unreadable: " + from_name);

    // If the destination is a directory, use the source file name
    // as the destination file name
    if (to_file.isDirectory())
        to_file = new File(to_file, from_file.getName());

    // If the destination exists, make sure it is a writeable file
    // and ask before overwriting it. If the destination doesn't
    // exist, make sure the directory exists and is writeable.
    if (to_file.exists()) {
        if (!to_file.canWrite())
            abort("destination file is unwriteable: " + to_name);
        // Ask whether to overwrite it
        System.out.print("Overwrite existing file " + to_file.getName() + "? (Y/N): ");
        System.out.flush();
        // Get the user's response.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String response = in.readLine();
        // Check the response. If not a Yes, abort the copy.
        if (!response.equals("Y") && !response.equals("y"))
            abort("existing file was not overwritten.");
    } else {
        // If file doesn't exist, check if directory exists and is
        // writeable. If getParent() returns null, then the directory is
        // the current dir. so look up the user.dir system property to
        // find out what that is.
        String parent = to_file.getParent(); // The destination directory
        if (parent == null) // If none, use the current directory
            parent = System.getProperty("user.dir");
        File dir = new File(parent); // Convert it to a file.
        if (!dir.exists())
            abort("destination directory doesn't exist: " + parent);
        if (dir.isFile())
            abort("destination is not a directory: " + parent);
        if (!dir.canWrite())
            abort("destination directory is unwriteable: " + parent);
    }

    // If we've gotten this far, then everything is okay.
    // So we copy the file, a buffer of bytes at a time.
    FileInputStream from = null; // Stream to read from source
    FileOutputStream to = null; // Stream to write to destination
    try {
        from = new FileInputStream(from_file); // Create input stream
        to = new FileOutputStream(to_file); // Create output stream
        byte[] buffer = new byte[4096]; // To hold file contents
        int bytes_read; // How many bytes in buffer

        // Read a chunk of bytes into the buffer, then write them out,
        // looping until we reach the end of the file (when read() returns
        // -1). Note the combination of assignment and comparison in this
        // while loop. This is a common I/O programming idiom.
        while ((bytes_read = from.read(buffer)) != -1)
            // Read until EOF
            to.write(buffer, 0, bytes_read); // write
    }
    // Always close the streams, even if exceptions were thrown
    finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
                ;
            }
        if (to != null)
            try {
                to.close();
            } catch (IOException e) {
                ;
            }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java

/**
 *
 * Checks if a directory already exists. If it does not exist it is created. If it already
 * exists then, its permissions are ok.//  w w  w. ja  va  2s.c  o m
 *
 * @param aStringBuilder
 *            StringBuilder containing an error message if an exception is thrown
 * @param aDirectory
 *            String containing the directory path.
 * @return true if the variable is defined
 *
 * */

private static synchronized boolean checkFolderPermissions(StringBuilder aStringBuilder, String aDirectory) {
    File directory = new File(aDirectory);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    if (!directory.canRead()) {
        aStringBuilder.append("The directory [" + directory + "] is not readable. "
                + "Please check your permissions rights.\n");
        return false;
    }
    if (!directory.canWrite()) {
        aStringBuilder.append("The directory [" + directory + "] is not writable. "
                + "Please check your permissions rights.\n");
        return false;
    }
    return true;
}

From source file:com.dnielfe.manager.utils.SimpleUtils.java

public static void deleteTarget(Activity activity, String path, String dir) {
    File target = new File(path);

    if (!target.exists()) {
        return;/*from   w w w  .  j a va  2  s  .c  o m*/
    } else if (target.isFile() && target.canWrite()) {
        target.delete();
        requestMediaScanner(activity, target);
        return;
    } else if (target.isDirectory() && target.canRead()) {
        String[] file_list = target.list();

        if (file_list != null && file_list.length == 0) {
            target.delete();
            return;
        } else if (file_list != null && file_list.length > 0) {

            for (int i = 0; i < file_list.length; i++) {
                File temp_f = new File(target.getAbsolutePath() + "/" + file_list[i]);

                if (temp_f.isDirectory())
                    deleteTarget(activity, temp_f.getAbsolutePath(), dir);
                else if (temp_f.isFile()) {
                    temp_f.delete();
                    requestMediaScanner(activity, temp_f);
                }
            }
        }

        if (target.exists())
            if (target.delete())
                return;
    } else if (target.exists() && !target.delete()) {
        RootCommands.DeleteFileRoot(path, dir);
    }
    return;
}