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.waarp.gateway.kernel.exec.ExecuteExecutor.java

public void run() throws Reply421Exception {
    // Check if the execution will be done through LocalExec daemon
    if (AbstractExecutor.useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(arg, delay, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }//  www . j  ava  2s .  co  m
    // Execution is done internally
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + args[0]);
            throw new Reply421Exception("Pre Exec command is not executable");
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error("System Exception: " + e.getMessage() + "\n    Exec cannot execute command "
                        + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            } catch (IOException e2) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e1) {
                }
                logger.error(
                        "Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
                throw new Reply421Exception("Cannot execute Pre command");
            }
            logger.info("System Exception: " + e.getMessage() + " but finally get the command executed "
                    + commandLine.toString());
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e1) {
            }
            logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
            throw new Reply421Exception("Cannot execute Pre command");
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e1) {
        }
        logger.error("Exception: " + e.getMessage() + "\n    Exec in error with " + commandLine.toString());
        throw new Reply421Exception("Cannot execute Pre command");
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e1) {
    }
    if (watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        futureCompletion.setSuccess();
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with {}", commandLine);
        futureCompletion.setSuccess();
    } else {
        logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with "
                + commandLine.toString());
        throw new Reply421Exception("Pre command executed in error");
    }
}

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

public GXXCompiler() throws InvalidCompilerException, CompilerNonAvailableException {
    tmp_dir_prefix = "gxx_";
    try {//w  w  w  .  j av  a  2 s . co m

        Configuration config = new PropertiesConfiguration(
                "net/przemkovv/sphinx/compiler/gxx_compiler.properties");
        String cmds[] = config.getStringArray("net.przemkovv.sphinx.compiler.gxx.cmd");
        String prepare_envs[] = config.getStringArray("net.przemkovv.sphinx.compiler.gxx.prepare_env");

        compiler_cmd = null;
        prepare_env_cmd = null;

        for (int i = 0; i < cmds.length; i++) {
            File temp_cmd = new File(cmds[i]);

            if (temp_cmd.exists() && temp_cmd.canExecute()) {
                compiler_cmd = temp_cmd;
                if (!prepare_envs[i].isEmpty()) {
                    prepare_env_cmd = new File(prepare_envs[i]);
                }
                break;
            }
        }
        if (compiler_cmd == null) {
            throw new CompilerNonAvailableException("Compiler G++ is not available.");
        }

        CompilerInfo info = getCompilerInfo();
        if (info != null) {
            logger.debug("Found g++ Compiler. Version: {}, Vendor: {}", info.version, info.vendor);
        }
        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 compiler G++.", ex);
    }

}

From source file:com.thoughtworks.go.util.FileUtilTest.java

@Test
void shouldReturnTrueIfDirectoryIsReadable() {
    File readableDirectory = mock(File.class);
    when(readableDirectory.canRead()).thenReturn(true);
    when(readableDirectory.canExecute()).thenReturn(true);
    when(readableDirectory.listFiles()).thenReturn(new File[] {});
    assertThat(FileUtil.isDirectoryReadable(readableDirectory)).isTrue();

    File unreadableDirectory = mock(File.class);
    when(readableDirectory.canRead()).thenReturn(false);
    when(readableDirectory.canExecute()).thenReturn(false);
    assertThat(FileUtil.isDirectoryReadable(unreadableDirectory)).isFalse();

    verify(readableDirectory).canRead();
    verify(readableDirectory).canExecute();
    verify(readableDirectory).listFiles();
    verify(unreadableDirectory).canRead();
    verify(unreadableDirectory, never()).canExecute();
}

From source file:org.alfresco.util.OpenOfficeVariant.java

private File canExecute(File file) {
    File fullyQualifiedExecutable = null;
    File dir = file.getParentFile();
    String name = file.getName();
    for (String ext : EXTENSIONS) {
        file = new File(dir, name + ext);
        if (file.canExecute()) {
            fullyQualifiedExecutable = file;
            break;
        }/*from  w w  w.ja v a  2  s . c  o m*/
        if (!windows) {
            break;
        }
    }
    return fullyQualifiedExecutable;
}

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

private void recursiveSCP(File from, SCP scp) throws IOException {
    File[] files = from.listFiles();
    if (files == null) {
        return;/*from  ww  w  . jav  a  2s .  co m*/
    }

    for (File file : files) {
        if (!FILES_NOT_TO_COPY.contains(file.getName())) {
            if (file.isDirectory() && file.canExecute()) {
                scp.startFolder(file.getName());
                recursiveSCP(file, scp);
                scp.endFolder();
            } else if (file.isFile() && file.canRead()) {
                scp.sendFile(file);
            }
        }
    }
}

From source file:com.jpmorgan.cakeshop.bean.QuorumConfigBean.java

private void initQuorumBean() {

    // setup needed paths
    String baseResourcePath = System.getProperty("eth.geth.dir");
    if (StringUtils.isBlank(baseResourcePath)) {
        baseResourcePath = FileUtils.getClasspathName("geth");
    }/*from  ww  w .j a v  a2s  .com*/

    if (SystemUtils.IS_OS_LINUX) {
        LOG.debug("Using quorum for linux");
        setQuorumPath(expandPath(baseResourcePath, QUORUM_LINUX_COMMAND));
        setConstellationPath(expandPath(baseResourcePath, CONSTELLATION_LINUX_COMMAND));
        setKeyGen(expandPath(baseResourcePath, CONSTELLATION_LINUX_KEYGEN));
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        LOG.debug("Using quorum for mac");
        setQuorumPath(expandPath(baseResourcePath, QUORUM_MAC_COMMAND));
        setConstellationPath(expandPath(baseResourcePath, CONSTELLATION_MAC_COMMAND));
        setKeyGen(expandPath(baseResourcePath, CONSTELLATION_MAC_KEYGEN));

    } else {
        LOG.error("Running on unsupported OS! Only  Linux and Mac OS X are currently supported");
        throw new IllegalArgumentException(
                "Running on unsupported OS! Only Linux and Mac OS X are currently supported");
    }

    File quorumExec = new File(getQuorumPath());
    if (!quorumExec.canExecute()) {
        quorumExec.setExecutable(true);
    }
    File constExec = new File(getConstellationPath());
    if (!constExec.canExecute()) {
        constExec.setExecutable(true);
    }
    File keyGenExec = new File(getKeyGen());
    if (!keyGenExec.canExecute()) {
        keyGenExec.setExecutable(true);
    }

}

From source file:net.orpiske.sdm.lib.io.support.ShieldAwareCopier.java

@Override
protected void handleFile(File file, int depth, Collection results) throws IOException {
    File destinationFile = new File(destination, file.getName());

    if (!ShieldUtils.isShielded(destinationFile)) {
        FileUtils.copyFile(file, destinationFile);

        destinationFile.setExecutable(file.canExecute());
        destinationFile.setReadable(file.canRead());
        destinationFile.setWritable(file.canWrite());
    } else {/*  w w w.  ja v  a 2 s  . com*/
        System.out.println("Ignoring shielded file " + file.getPath());
    }
}

From source file:de.akquinet.innovation.play.maven.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  .  ja  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 {

        URL zipUrl = new URL("http://download.playframework.org/releases/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.waarp.openr66.context.task.ExecTask.java

@Override
public void run() {
    /*//from   w w w.  ja v a 2 s.co  m
     * First apply all replacements and format to argRule from context and argTransfer. Will
     * call exec (from first element of resulting string) with arguments as the following value
     * from the replacements. Return 0 if OK, else 1 for a warning else as an error. No change
     * should be done in the FILENAME
     */
    logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Check if the execution will be done through LocalExec daemon
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    // Execution is done internally
    String[] args = finalname.split(" ");
    File exec = new File(args[0]);
    if (exec.isAbsolute()) {
        if (!exec.canExecute()) {
            logger.error("Exec command is not executable: " + finalname);
            R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner());
            futureCompletion.setResult(result);
            futureCompletion.cancel();
            return;
        }
    }
    CommandLine commandLine = new CommandLine(args[0]);
    for (int i = 1; i < args.length; i++) {
        commandLine.addArgument(args[i]);
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0 && waitForValidation) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    if (!waitForValidation) {
        // Do not wait for validation
        futureCompletion.setSuccess();
        logger.info("Exec will start but no WAIT with {}", commandLine);
    }
    int status = -1;
    try {
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(Configuration.RETRYINMS);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                if (waitForValidation) {
                    futureCompletion.setFailure(e);
                }
                return;
            } catch (IOException e1) {
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
                if (waitForValidation) {
                    futureCompletion.setFailure(e);
                }
                return;
            }
        } else {
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
            if (waitForValidation) {
                futureCompletion.setFailure(e);
            }
            return;
        }
    } catch (IOException e) {
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.setFailure(e);
        }
        return;
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        logger.error("Exec is in Time Out");
        status = -1;
    }
    if (status == 0) {
        if (waitForValidation) {
            futureCompletion.setSuccess();
        }
        logger.info("Exec OK with {}", commandLine);
    } else if (status == 1) {
        logger.warn("Exec in warning with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.setSuccess();
        }
    } else {
        logger.error("Status: " + status + " Exec in error with " + commandLine.toString());
        if (waitForValidation) {
            futureCompletion.cancel();
        }
    }
}

From source file:com.pawelniewiadomski.devs.jira.automat.AutomatListener.java

private void executeCommand(String executableName, String baseUrl, String issueKey, String user) {
    final File commandPath = new File(EventUtils.getExecutablesDir(applicationProperties), executableName);
    if (!commandPath.exists()) {
        log.debug(String.format("%s doesn't exist", commandPath));
        return;/*from  ww w.ja va 2 s . co m*/
    }
    if (!commandPath.canExecute()) {
        log.warn(String.format("%s is not executable", commandPath));
        return;
    }
    try {
        Runtime.getRuntime().exec(new String[] { commandPath.toString(), baseUrl, issueKey, user });
    } catch (IOException e) {
        log.error("Unable to execute command " + commandPath, e);
    }
}