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:com.temetra.vroomapi.RouteController.java

@RequestMapping(value = "/route", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public JsonNode route(@RequestParam(value = "loc") String[] locs,
        @RequestParam(value = "startAtFirst", defaultValue = "true") boolean startAtFirst,
        @RequestParam(value = "endAtLast", defaultValue = "false") boolean endAtLast,
        @RequestParam(value = "includeGeometry", defaultValue = "false") boolean includeGeometry)
        throws Exception {
    long millis = System.currentTimeMillis();

    File vroomBinFile = new File(vroomBinary);
    if (!vroomBinFile.exists()) {
        log.error("Vroom binary file doesn't exist");
        throw new Exception("Vroom binary file doesn't exist");
    }//from www. ja v a 2s  . c  om

    if (!vroomBinFile.canExecute()) {
        log.error("Cannot execute Vroom binary file");
        throw new Exception("Cannot execute Vroom binary file");
    }

    if (locs.length < 2) {
        log.error("Zero or one location sent");
        throw new Exception("Must send more than one location");
    }

    List<String> progArgs = new ArrayList<>();
    progArgs.add("./" + vroomBinFile.getName());
    if (startAtFirst) {
        progArgs.add("-s");
    }
    if (endAtLast) {
        progArgs.add("-e");
    }
    if (includeGeometry) {
        progArgs.add("-g");
    }

    progArgs.add("loc=" + Joiner.on("&loc=").join(locs) + "");
    log.info("Run (" + millis + "): " + Joiner.on(' ').join(progArgs));

    StringBuilder output = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder(progArgs);
    builder.directory(vroomBinFile.getParentFile());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        process.waitFor();
    }

    log.info("Output (" + millis + "): " + output.toString());
    return jsonMapper.readTree(output.toString());
}

From source file:cc.arduino.packages.uploaders.SSHUploader.java

private boolean canUploadWWWFiles(File sourcePath, SSH ssh, List<String> warningsAccumulator)
        throws IOException, JSchException {
    File www = new File(sourcePath, "www");
    if (!www.exists() || !www.isDirectory()) {
        return false;
    }/*w w w  .  j  a  v a 2 s.com*/
    if (!www.canExecute()) {
        warningsAccumulator.add(I18n.format(tr("Problem accessing files in folder \"{0}\""), www));
        return false;
    }
    if (!ssh.execSyncCommand("special-storage-available")) {
        warningsAccumulator.add(tr("Problem accessing board folder /www/sd"));
        return false;
    }
    return true;
}

From source file:net.przemkovv.sphinx.compiler.MSVCCompiler.java

public MSVCCompiler() throws InvalidCompilerException, CompilerNonAvailableException {
    Configuration config;/*w ww . j  a  v a 2  s.c  om*/
    try {
        config = new PropertiesConfiguration("net/przemkovv/sphinx/compiler/msvc_compiler.properties");
        String cmds[] = config.getStringArray("net.przemkovv.sphinx.compiler.msvc.cmd");
        String prepare_envs[] = config.getStringArray("net.przemkovv.sphinx.compiler.msvc.prepare_env");
        msvc = null;
        prepare_env = null;
        for (int i = 0; i < cmds.length; i++) {
            File temp_cmd = new File(cmds[i]);
            File temp_prepare_env = new File(prepare_envs[i]);
            if (temp_cmd.exists() && temp_cmd.canExecute()) {
                msvc = temp_cmd;
                prepare_env = temp_prepare_env;
                break;
            }

        }
        if (msvc == null) {
            throw new CompilerNonAvailableException("Compiler MS VC++ is not available.");
        }
        CompilerInfo info = getCompilerInfo();
        if (info != null) {
            logger.debug("Found MS VC++ Compiler. Version: {}, Arch: {}", info.version, info.architecture);
        }
        tmp_dir = System.getProperty("java.io.tmpdir");
        logger.debug("Temporary directory: {}", tmp_dir);
    } catch (ConfigurationException ex) {
        throw new CompilerNonAvailableException("Couldn't find configuration for compiler MS VC++.", ex);
    }

}

From source file:com.ingby.socbox.bischeck.configuration.DocManager.java

/**
 * Check if the output directory is valid to create output in. If it does 
 * not exists it will be created.//w  w  w  . ja  va2  s  .c  om
 * @param dirname
 * @return the File to the directory
 * @throws IOException if the directory can not be written to, if it can
 * not be created.
 */
private File checkDir(String dirname) throws IOException {

    File outputdir = new File(dirname);

    if (outputdir.isDirectory()) {
        if (outputdir.canWrite() && outputdir.canExecute()) {
            return outputdir;
        } else {
            throw new IOException("Directory " + dirname + " is not writable.");
        }
    } else {
        File parent = outputdir.getParentFile();

        if (parent == null) {
            // absolute name from .
            parent = new File(".");
        }

        if (parent.isDirectory() && parent.canWrite()) {
            outputdir.mkdir();
            return outputdir;
        } else {
            throw new IOException(
                    "Parent directory " + parent.getPath() + " does not exist or is not writable.");
        }
    }
}

From source file:com.twosigma.beakerx.kernel.magic.command.MavenJarResolver.java

public String findMvn() {
    if (mavenLocation == null) {

        if (System.getenv("M2_HOME") != null) {
            mavenLocation = System.getenv("M2_HOME") + "/bin/mvn";
            return mavenLocation;
        }//  w w w  .  j a va 2  s  .  c  o  m

        for (String dirname : System.getenv("PATH").split(File.pathSeparator)) {
            File file = new File(dirname, "mvn");
            if (file.isFile() && file.canExecute()) {
                mavenLocation = file.getAbsolutePath();
                return mavenLocation;
            }
        }
        throw new RuntimeException(
                "No mvn found, please install mvn by 'conda install maven' or setup M2_HOME");
    }
    return mavenLocation;
}

From source file:org.nanoko.playframework.mojo.Play2InstallPlayMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (StringUtils.isEmpty(play2version)) {
        throw new MojoExecutionException("play2version configuration parameter is not set");
    }//from w  w  w  . j a v  a 2 s. co m
    String debugLogPrefix = "AutoInstall - Play! " + play2version + ' ';
    File play2basedirFile = new File(play2basedir);
    File play2home = new File(play2basedirFile, "play-" + play2version);
    File play2 = new File(play2home, AbstractPlay2Mojo.isWindows() ? "play.bat" : "play");

    // Is the requested Play! version already installed?
    if (play2.isFile() && play2.canExecute()) {

        getLog().info(debugLogPrefix + "is already installed in " + play2home);
        return;

    }

    getLog().info("Play! " + play2version + " download and installation, please be patient ...");
    File zipFile = new File(play2basedirFile, "play-" + play2version + ".zip");

    try {

        // New download URL pattern starting from 2.1.0, the 2.1-RC* versions use the old URL pattern.
        // See https://groups.google.com/forum/#!topic/play-framework/SKOXG1YRKa8
        URL zipUrl;
        if (play2version.startsWith("2.0") || play2version.startsWith("2.1-RC")) {
            zipUrl = new URL("http://downloads.typesafe.com/releases/play-" + play2version + ".zip");
        } else {
            zipUrl = new URL(
                    "http://downloads.typesafe.com/play/" + play2version + "/play-" + play2version + ".zip");
        }
        FileUtils.forceMkdir(play2basedirFile);

        // Download
        getLog().debug(debugLogPrefix + "is downloading to " + zipFile);
        FileUtils.copyURLToFile(zipUrl, zipFile);

        // Extract
        getLog().debug(debugLogPrefix + "is extracting to " + play2basedir);
        UnArchiver unarchiver = archiverManager.getUnArchiver(zipFile);
        unarchiver.setSourceFile(zipFile);
        unarchiver.setDestDirectory(play2basedirFile);
        unarchiver.extract();

        // Prepare
        File framework = new File(play2home, "framework");
        File build = new File(framework, AbstractPlay2Mojo.isWindows() ? "build.bat" : "build");
        if (!build.canExecute() && !build.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + build + " execution bit");
        }
        if (!play2.canExecute() && !play2.setExecutable(true)) {
            throw new MojoExecutionException("Can't set " + play2 + " execution bit");
        }

        getLog().debug(debugLogPrefix + "is now installed in " + play2home);

    } catch (NoSuchArchiverException ex) {
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (IOException ex) {
        try {
            if (play2home.exists()) {
                // Clean extracted data
                FileUtils.forceDelete(play2home);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete extracted Play! distribution after error: " + play2home);
        }
        throw new MojoExecutionException("Can't auto install Play! " + play2version + " in " + play2basedir,
                ex);
    } catch (ArchiverException e) {
        throw new MojoExecutionException("Cannot unzip Play " + play2version + " in " + play2basedir, e);
    } finally {
        try {
            if (zipFile.exists()) {
                // Clean downloaded data
                FileUtils.forceDelete(zipFile);
            }
        } catch (IOException ignored) {
            getLog().warn("Unable to delete downloaded Play! distribution: " + zipFile);
        }
    }
}

From source file:org.openspaces.launcher.JettyLauncher.java

@Override
public void launch(WebLauncherConfig config) throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(config.getPort());
    //GS-12102, fix for 10.1, added possibility to define host address
    if (config.getHostAddress() != null) {
        connector.setHost(config.getHostAddress());
    }//from w  w  w  .  j  av  a 2 s  .c o m
    connector.setReuseAddress(false);
    server.setConnectors(new Connector[] { connector });

    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/");
    webAppContext.setWar(config.getWarFilePath());

    File tempDir = new File(config.getTempDirPath());
    boolean createdDirs = tempDir.mkdirs();

    if (logger.isDebugEnabled()) {
        boolean canRead = tempDir.canRead();
        boolean canWrite = tempDir.canWrite();
        boolean canExecute = tempDir.canExecute();

        logger.debug("Temp dir:" + tempDir.getName() + ", canRead=" + canRead + ", canWrite=" + canWrite
                + ", canExecute=" + canExecute + ", exists=" + tempDir.exists() + ", createdDirs=" + createdDirs
                + ", path=" + config.getTempDirPath());
    }

    webAppContext.setTempDirectory(tempDir);
    webAppContext.setCopyWebDir(false);
    webAppContext.setParentLoaderPriority(true);

    String sessionManager = System.getProperty("org.openspaces.launcher.jetty.session.manager");
    if (sessionManager != null) {
        //change default session manager implementation ( in order to change "JSESSIONID" )
        //GS-10830
        try {
            Class sessionManagerClass = Class.forName(sessionManager);
            SessionManager sessionManagerImpl = (SessionManager) sessionManagerClass.newInstance();
            webAppContext.getSessionHandler().setSessionManager(sessionManagerImpl);
        } catch (Throwable t) {
            System.out.println("Session Manager [" + sessionManager + "] was not set cause following exception:"
                    + t.toString());
            t.printStackTrace();
        }
    } else {
        System.out.println("Session Manager was not provided");
    }

    server.setHandler(webAppContext);

    server.start();
    webAppContext.start();
}

From source file:net.erdfelt.android.sdkfido.local.LocalAndroidPlatforms.java

public File getBin(String binname) throws FetchException {
    String paths[] = { "tools", "platform-tools" };

    String binosname = binname;//w  w  w.  jav  a  2 s  .  c  o m
    if (SystemUtils.IS_OS_WINDOWS) {
        binosname += ".exe";
    }

    for (String searchPath : paths) {
        File bindir = new File(this.homeDir, searchPath);
        if (!bindir.exists()) {
            continue; // skip, dir does not exist.
        }
        File bin = new File(bindir, binosname);
        if (bin.exists() && bin.isFile() && bin.canExecute()) {
            return bin;
        }
    }
    throw new FetchException("Android Binary Not Found: " + binname);
}

From source file:org.docwhat.iated.ui.PreferencesDialog.java

private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Please select your editor");

    chooser.setCurrentDirectory(new File(getDefaultAppDirectory()));

    chooser.setFileFilter(new FileFilter() {
        public boolean accept(File f) {
            if (OS.isFamilyMac() && f.isDirectory() && f.getName().toLowerCase().endsWith(".app")) {
                return (true);
            }//from w w w  .ja va  2  s. co m
            return f.canExecute();
        }

        public String getDescription() {
            return "Applications";
        }
    });

    int result = chooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        editorField.setText(chooser.getSelectedFile().getPath());
    }
}

From source file:org.n0pe.ruby.AbstractRubyMojo.java

protected File getJavaExecutable() throws MojoExecutionException {
    final String javaHome = System.getenv("JAVA_HOME");
    if (StringUtils.isEmpty(javaHome)) {
        throw new MojoExecutionException("JAVA_HOME is not set, cannot continue");
    }/*w ww  .j  a  va  2  s . co m*/
    final File java = new File(javaHome + File.separator + "bin" + File.separator + "java");
    if (!java.exists()) {
        throw new MojoExecutionException("Cannot find the java executable at: " + java.getAbsolutePath());
    }
    if (!java.canExecute()) {
        throw new MojoExecutionException("Found java executable is not executable, cannot continue");
    }
    return java;
}