Example usage for java.io File canExecute

List of usage examples for java.io File canExecute

Introduction

In this page you can find the example usage for java.io File canExecute.

Prototype

public boolean canExecute() 

Source Link

Document

Tests whether the application can execute the file denoted by this abstract pathname.

Usage

From source file:org.scantegrity.scanner.Scanner.java

/**
 * Reads all the output directories in the configuration, creates a list
 * of every directory, and sets up any output directories if needed.
 * // w w  w  .j a v a2  s  .  c  om
 * @return
 */
private static void createOutputDirectories() {
    Vector<String> l_locs = c_config.getOutputDirNames();
    c_outDirs = new Vector<String>();

    //WE want to avoid failures at all costs in this function.
    if (l_locs == null) {
        System.err.println("Invalid output directory option! Using" + " default /media.");
        l_locs = new Vector<String>();
        l_locs.add("/media");
    }
    //Go through each directory name.
    for (String l_loc : l_locs) {
        if (l_loc == null)
            continue;
        File l_d = new File(l_loc);
        int l_c = 0;
        try {
            if (l_d.exists() && l_d.canExecute() && l_d.canRead() && l_d.isDirectory()) {
                //Get a directory listing.
                File[] l_subds = l_d.listFiles();
                for (File l_subd : l_subds) {
                    try {
                        if (l_subd.canExecute() && l_subd.canRead() && l_subd.canWrite()
                                && l_subd.isDirectory()) {
                            if (!(new File(l_subd.getAbsolutePath() + File.separator + "scantegrity-scanner")
                                    .exists())) {
                                FileUtils.forceMkdir(new File(
                                        l_subd.getAbsolutePath() + File.separator + "scantegrity-scanner"));
                            }

                            if (!(new File(l_subd.getAbsolutePath() + File.separator + "scantegrity-scanner"
                                    + File.separator + c_errDir).exists())) {
                                FileUtils.forceMkdir(new File(l_subd.getAbsolutePath() + File.separator
                                        + "scantegrity-scanner" + File.separator + c_errDir));
                            }

                            c_outDirs.add(l_subd.getAbsolutePath() + File.separator + "scantegrity-scanner");
                            l_c++;
                        }
                    } catch (Exception l_e) {
                        l_e.printStackTrace();
                        //ignore.
                    }
                }
                if (l_c == 0 && l_d.canWrite()) {
                    if (!(new File(l_d.getAbsolutePath() + File.separator + "scantegrity-scanner/").exists())) {
                        FileUtils.forceMkdir(
                                new File(l_d.getAbsolutePath() + File.separator + "scantegrity-scanner"));
                    }

                    if (!(new File(l_d.getAbsolutePath() + File.separator + "scantegrity-scanner"
                            + File.separator + c_errDir).exists())) {
                        FileUtils.forceMkdir(new File(l_d.getAbsolutePath() + File.separator
                                + "scantegrity-scanner" + File.separator + c_errDir));
                    }

                    c_outDirs.add(l_d.getAbsolutePath() + File.separator + "scantegrity-scanner");
                } else if (l_c == 0) {
                    System.err.println("Permissions error: could not use " + l_d.getAbsolutePath());
                }
            }
        } catch (Exception l_e) {
            System.err.println("Could not read " + l_d.getAbsolutePath() + "\n Reason:" + l_e.getMessage());
        }
    }
    //If all else fails..
    if (c_outDirs.size() <= 0) {
        System.err.println("Unable to use an output directory!");
        try {
            if (!(new File("scantegrity-scanner").exists())) {
                FileUtils.forceMkdir(new File("scantegrity-scanner"));
            }

            if (!(new File("scantegrity-scanner" + File.separator + c_errDir).exists())) {
                FileUtils.forceMkdir(new File("scantegrity-scanner" + File.separator + c_errDir));
            }
            c_outDirs.add("scantegrity-scanner");
        } catch (Exception l_e) {
            System.err.println("Exiting.. could not create an output directory!");
            criticalExit(15);
        }
    }
}

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

/**
 * Make the given URL available as an executable file. A temporary file is created and deleted
 * upon a regular shutdown of the JVM. If the parameter {@code aCache} is {@code true}, the
 * temporary file is remembered in a cache and if a file is requested for the same URL at a
 * later time, the same file is returned again. If the previously created file has been deleted
 * meanwhile, it is recreated from the URL.
 *
 * @param aUrl// w w  w .j ava 2  s .  c  o  m
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @return an executable file created from the given URL.
 * @throws IOException
 *             if the file has permissions issues.
 */

public static synchronized File getUrlAsExecutable(URL aUrl, boolean aCache) throws IOException {

    File file;
    synchronized (urlFileCache) {

        file = urlFileCache.get(aUrl.toString());
        if (!aCache || (file == null) || !file.exists()) {

            String name = FilenameUtils.getBaseName(aUrl.getPath());
            file = File.createTempFile(name, ".temp");
            file.setExecutable(true);
            if (!file.canExecute()) {
                StringBuilder errorMessage = new StringBuilder(128);
                errorMessage.append("Tried to use temporary folder, but seems it is not "
                        + "executable. Please check the permissions rights from your " + "temporary folder.\n");

                if (isEnvironmentVariableDefined(XDG_RUNTIME_DIR_ENV_VAR, errorMessage)
                        && checkFolderPermissions(errorMessage, System.getenv(XDG_RUNTIME_DIR_ENV_VAR))) {
                    file = getFileAsExecutable(aUrl, System.getenv(XDG_RUNTIME_DIR_ENV_VAR));
                } else if (isEnvironmentVariableDefined(DKPRO_HOME_ENV_VAR, errorMessage)
                        && checkFolderPermissions(errorMessage,
                                System.getenv(DKPRO_HOME_ENV_VAR) + File.separator + "temp")) {
                    file = getFileAsExecutable(aUrl,
                            System.getenv(DKPRO_HOME_ENV_VAR) + File.separator + "temp");
                } else {
                    if (!isUserHomeDefined(errorMessage)
                            || !checkFolderPermissions(errorMessage, System.getProperty("user.home")
                                    + File.separator + ".dkpro" + File.separator + "temp")) {
                        throw new IOException(errorMessage.toString());
                    }
                    file = getFileAsExecutable(aUrl, System.getProperty("user.home") + File.separator + ".dkpro"
                            + File.separator + "temp");
                }

            }
            file.deleteOnExit();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = aUrl.openStream();
                outputStream = new FileOutputStream(file);
                copy(inputStream, outputStream);
            } finally {
                closeQuietly(inputStream);
                closeQuietly(outputStream);
            }
            if (aCache) {
                urlFileCache.put(aUrl.toString(), file);
            }
        }
    }
    return file;
}

From source file:io.vertx.config.vault.utils.VaultDownloader.java

public static File download() {
    File out = new File("target/vault/vault");

    if (SystemUtils.IS_OS_WINDOWS) {
        out = new File("target/vault/vault.exe");
    }//from  w  w w  . j a  v a 2  s  .  com

    if (out.isFile()) {
        return out;
    }

    File zip = new File("target/vault.zip");

    try {
        FileUtils.copyURLToFile(getURL(VaultProcess.VAULT_VERSION), zip);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    assert zip.isFile();

    System.out.println(zip.getAbsolutePath() + " has been downloaded, unzipping");
    try {
        unzip(zip, out.getParentFile());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    System.out.println("Vault: " + out.getAbsolutePath());
    assert out.isFile();
    out.setExecutable(true);
    assert out.canExecute();
    return out;
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

/**
 * Computes the default Hadoop command path.
 * @param environmentVariables the current environment variables
 * @return the detected command path, or {@code null} if the command path is not found
 * @since 0.6.0// w  w w  .j av  a2s. c o m
 */
public static File findHadoopCommand(Map<String, String> environmentVariables) {
    assert environmentVariables != null;
    File command = getExplicitHadoopCommand(environmentVariables);
    if (command != null) {
        return command;
    }
    File home = getExplicitHadoopDirectory(environmentVariables);
    if (home != null && home.isDirectory()) {
        command = new File(home, PATH_HADOOP_COMMAND);
    } else {
        command = findHadoopCommandFromPath(environmentVariables);
    }
    if (command == null || command.canExecute() == false) {
        return null;
    }
    return command;
}

From source file:org.geotools.gce.imagepyramid.Utils.java

/**
 * Prepares a message with the status of the provided file.
 * @param sourceFile The {@link File} to provided the status message for
 * @return a status message for the provided {@link File} or a {@link NullPointerException} in case the {@link File}is <code>null</code>.
 *///www  . j a  v a 2  s.c  o  m
private static String fileStatus(File sourceFile) {
    if (sourceFile == null) {
        throw new NullPointerException("Provided null input to fileStatus method");
    }
    final StringBuilder builder = new StringBuilder();
    builder.append("Checking file:").append(FilenameUtils.getFullPath(sourceFile.getAbsolutePath()))
            .append("\n");
    builder.append("exists").append(sourceFile.exists()).append("\n");
    builder.append("isFile").append(sourceFile.isFile()).append("\n");
    builder.append("canRead:").append(sourceFile.canRead()).append("\n");
    builder.append("canWrite").append(sourceFile.canWrite()).append("\n");
    builder.append("canExecute").append(sourceFile.canExecute()).append("\n");
    builder.append("isHidden:").append(sourceFile.isHidden()).append("\n");
    builder.append("lastModified").append(sourceFile.lastModified()).append("\n");

    return builder.toString();
}

From source file:org.kalypso.kalypsosimulationmodel.ui.calccore.CalcCoreUtils.java

public static File findExecutable(final String version, final String pattern, final String searchPattern,
        final COMPATIBILITY_MODE compatibilityMode) throws CoreException {
    if (StringUtils.isBlank(version)) {
        final File latestExecutable = getLatestExecutable(searchPattern);
        if (latestExecutable == null) {
            // Version des Rechenkerns nicht angegeben. Die Version muss in den Steuerparametern gesetzt werden.
            final String msg = Messages.getString("org.kalypso.ogc.gml.featureview.control.ChooseExeControl.1"); //$NON-NLS-1$
            final IStatus status = new Status(IStatus.ERROR, KalypsoModelSimulationBase.PLUGIN_ID, msg);
            throw new CoreException(status);
        }/* w w  w .jav a  2s .co  m*/

        return latestExecutable;
    }

    switch (compatibilityMode) {
    case NA:
        /*
         * for backward compatibility, strings "neueste" or "latest" will be considered as well
         */
        if (VERSION_NEUESTE.equals(version) || VERSION_LATEST.equals(version))
            return getLatestExecutable(searchPattern);
        break;
    case NONE:
    case WSPM:
    case RMA:
        break;
    }

    /* Always call this in order to provoke the download error message */
    getAvailableExecuteablesChecked(searchPattern);

    // REMARK: This is OS dependent; we use should use a pattern according to OS
    final String exeName = String.format(pattern, version);
    final File exeFile = new File(getExecutablesDirectory(), exeName);

    if (!exeFile.exists()) {
        final String msg = Messages.getString("org.kalypso.ogc.gml.featureview.control.ChooseExeControl.6", //$NON-NLS-1$
                exeFile.getAbsolutePath());
        final IStatus status = new Status(IStatus.ERROR, KalypsoModelSimulationBase.PLUGIN_ID, msg);
        throw new CoreException(status);
    }

    if (!exeFile.isFile()) {
        final String msg = Messages.getString("org.kalypso.ogc.gml.featureview.control.ChooseExeControl.2", //$NON-NLS-1$
                exeFile.getAbsolutePath());
        final IStatus status = new Status(IStatus.ERROR, KalypsoModelSimulationBase.PLUGIN_ID, msg);
        throw new CoreException(status);
    }

    if (!exeFile.canExecute()) {
        final String msg = Messages.getString("org.kalypso.ogc.gml.featureview.control.ChooseExeControl.5", //$NON-NLS-1$
                exeFile.getAbsolutePath());
        final IStatus status = new Status(IStatus.ERROR, KalypsoModelSimulationBase.PLUGIN_ID, msg);
        throw new CoreException(status);
    }

    return exeFile;
}

From source file:net.opentsdb.tsd.GraphHandler.java

/**
 * Iterate through the class path and look for the Gnuplot helper script.
 * @return The path to the wrapper script.
 *//*from ww w .  j a  v a2s. c om*/
private static String findGnuplotHelperScript() {
    final URL url = GraphHandler.class.getClassLoader().getResource(WRAPPER);
    if (url == null) {
        throw new RuntimeException("Couldn't find " + WRAPPER + " on the" + " CLASSPATH: "
                + System.getProperty("java.class.path"));
    }
    final String path = url.getFile();
    LOG.debug("Using Gnuplot wrapper at {}", path);
    final File file = new File(path);
    final String error;
    if (!file.exists()) {
        error = "non-existent";
    } else if (!file.canExecute()) {
        error = "non-executable";
    } else if (!file.canRead()) {
        error = "unreadable";
    } else {
        return path;
    }
    throw new RuntimeException("The " + WRAPPER + " found on the" + " CLASSPATH (" + path + ") is a " + error
            + " file...  WTF?" + "  CLASSPATH=" + System.getProperty("java.class.path"));
}

From source file:com.gas.common.ui.util.ExecutableFileFilter.java

@Override
public boolean accept(File f) {
    boolean canExe = f.canExecute();
    if (Utilities.isWindows()) {
        String ext = FilenameUtils.getExtension(f.getAbsolutePath());
        return canExe && "exe".equalsIgnoreCase(ext);
    } else if (Utilities.isMac()) {
        return canExe;
    }// w  w  w . j  a  va 2s  .c om

    return canExe;
}

From source file:au.org.ala.layers.intersect.IntersectConfig.java

private static void isValidPathGDAL(String path, String desc) {
    File f = new File(path);

    if (!f.exists()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\" is not a valid local file path.  It does not exist.");
    } else if (!f.isDirectory()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  It is not a directory.");
    } else if (!f.canRead()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  Not permitted to READ.");
    }/*from www.  ja  v a 2  s  .  co  m*/

    //look for GDAL file "gdalwarp"
    File g = new File(path + File.separator + "gdalwarp");
    if (!f.exists()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  gdalwarp does not exist.");
    } else if (!g.canExecute()) {
        logger.error("Config error. Property \"" + desc + "\" with value \"" + path
                + "\"  is not a valid local file path.  gdalwarp not permitted to EXECUTE.");
    }
}

From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java

/**
 * Copy a file from one place to another, providing progress along the way.
 *//*from   w  ww . j  a  v  a 2 s.co  m*/
public static void copyFile(File fromFile, File toFile, IProgressMonitor monitor) throws IOException {

    byte[] data = new byte[4096];

    InputStream in = new FileInputStream(fromFile);

    toFile.delete();

    OutputStream out = new FileOutputStream(toFile);

    int count = in.read(data);

    while (count != -1) {
        out.write(data, 0, count);
        count = in.read(data);
    }

    in.close();
    out.close();

    toFile.setLastModified(fromFile.lastModified());
    if (fromFile.canExecute()) {
        toFile.setExecutable(true);
    }

    monitor.worked(1);

}