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.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing non-emulated command.
 *//*w w w  .j a v a  2 s  . c  o  m*/
@Test
public void executeCommand_delegate() {
    Assume.assumeTrue("not unix-like", SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_LINUX);

    File touch = new File("/usr/bin/touch");
    Assume.assumeTrue("no 'touch' command", touch.isFile() && touch.canExecute());

    AtomicBoolean call = new AtomicBoolean();
    MockCommandEmulator.callback(args -> call.set(true));
    File target = new File(framework.getWork("working"), "target");
    Assume.assumeFalse(target.exists());

    // exec: touch .../target
    TestExecutionPlan.Command command = command("generic", touch.getPath(), target.getAbsolutePath());
    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(command, Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(target.exists(), is(true));
    assertThat(call.get(), is(false));
}

From source file:ch.zhaw.iamp.rct.Controller.java

private void verifyBinaryState() throws InterruptedException {
    File binary = new File(mainWindow.getExecutableFilePath());

    if (!binary.exists() || !binary.canExecute()) {
        throw new InterruptedException(
                "The binary at '" + binary.getAbsolutePath() + "' has to be existing and executable.");
    } else {/*  w w  w .ja  v  a2  s .c om*/
        System.out.println("[J] The binary at '" + binary.getAbsolutePath() + "' seems to be executable.");
    }
}

From source file:org.waarp.openr66.context.task.ExecOutputTask.java

@Override
public void run() {
    /*//w w  w  . j  av a 2  s .  com
     * 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. In case of
     * an error (> 0), all the line from output will be send back to the partner with the Error
     * code. No change is made to the file.
     */
    logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            finalize(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    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();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;
    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    AllLineReader allLineReader = new AllLineReader(inputStream);
    Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    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) {
                finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                        commandLine);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.flush();
                } catch (IOException e2) {
                }
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status,
                    commandLine);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = allLineReader.getLastLine().toString();
    }
    finalize(status, newname, commandLine.toString());
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Gets information about a File//from   www .ja  v  a 2s .  c o m
 * @param file File to get information about
 * @return Information about a file
 */
@Action(aliases = { "getFileInformations", "fileInformations", "informations" })
public TreeMap<String, Object> getFileInformations(final String file) {
    final TreeMap<String, Object> fileInformations = new TreeMap<String, Object>();
    final File file_ = new File(file);
    if (file_.exists()) {
        fileInformations.put("Name", file_.getName());
        fileInformations.put("Path", file_.getPath());
        fileInformations.put("Size", file_.length());
        fileInformations.put("Execute", file_.canExecute());
        fileInformations.put("Read", file_.canRead());
        fileInformations.put("Write", file_.canWrite());
        fileInformations.put("IsDirectory", file_.isDirectory());
        fileInformations.put("IsFile", file_.isFile());
        fileInformations.put("IsHidden", file_.isHidden());
        final FileNameMap fileNameMap = URLConnection.getFileNameMap();
        fileInformations.put("Mime", fileNameMap.getContentTypeFor("file://" + file_.getPath()));
        return fileInformations;
    }
    return new TreeMap<String, Object>();
}

From source file:org.waarp.openr66.context.task.ExecMoveTask.java

@Override
public void run() {
    /*//from   w ww .ja  v a  2s . 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. The last
     * line of stdout will be the new name given to the R66File in case of status 0. The
     * previous file should be deleted by the script or will be deleted in case of status 0. If
     * the status is 1, no change is made to the file.
     */
    logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session);
    String finalname = argRule;
    finalname = getReplacedValue(finalname, argTransfer.split(" "));
    // Force the WaitForValidation
    waitForValidation = true;
    if (Configuration.configuration.isUseLocalExec() && useLocalExec) {
        LocalExecClient localExecClient = new LocalExecClient();
        if (localExecClient.connect()) {
            localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
            LocalExecResult result = localExecClient.getLocalExecResult();
            move(result.getStatus(), result.getResult(), finalname);
            localExecClient.disconnect();
            return;
        } // else continue
    }
    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();
    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = null;
    try {
        outputStream = new PipedOutputStream(inputStream);
    } catch (IOException e1) {
        try {
            inputStream.close();
        } catch (IOException e) {
        }
        logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1);
        futureCompletion.setFailure(e1);
        return;
    }
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null);
    defaultExecutor.setStreamHandler(pumpStreamHandler);
    int[] correctValues = { 0, 1 };
    defaultExecutor.setExitValues(correctValues);
    ExecuteWatchdog watchdog = null;

    if (delay > 0) {
        watchdog = new ExecuteWatchdog(delay);
        defaultExecutor.setWatchdog(watchdog);
    }
    LastLineReader lastLineReader = new LastLineReader(inputStream);
    Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId());
    thread.setDaemon(true);
    Configuration.configuration.getExecutorService().execute(thread);
    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 {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with "
                        + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            } catch (IOException e1) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                thread.interrupt();
                try {
                    inputStream.close();
                } catch (IOException e2) {
                }
                try {
                    pumpStreamHandler.stop();
                } catch (IOException e2) {
                }
                logger.error(
                        "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
                futureCompletion.setFailure(e);
                return;
            }
        } else {
            try {
                outputStream.close();
            } catch (IOException e1) {
            }
            thread.interrupt();
            try {
                inputStream.close();
            } catch (IOException e1) {
            }
            try {
                pumpStreamHandler.stop();
            } catch (IOException e2) {
            }
            logger.error(
                    "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
            futureCompletion.setFailure(e);
            return;
        }
    } catch (IOException e) {
        try {
            outputStream.close();
        } catch (IOException e1) {
        }
        thread.interrupt();
        try {
            inputStream.close();
        } catch (IOException e1) {
        }
        try {
            pumpStreamHandler.stop();
        } catch (IOException e2) {
        }
        logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString());
        futureCompletion.setFailure(e);
        return;
    }
    try {
        outputStream.flush();
    } catch (IOException e) {
    }
    try {
        outputStream.close();
    } catch (IOException e) {
    }
    try {
        pumpStreamHandler.stop();
    } catch (IOException e2) {
    }
    try {
        if (delay > 0) {
            thread.join(delay);
        } else {
            thread.join();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    try {
        inputStream.close();
    } catch (IOException e1) {
    }
    String newname = null;
    if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) {
        // kill by the watchdoc (time out)
        status = -1;
        newname = "TimeOut";
    } else {
        newname = lastLineReader.getLastLine();
        if (status == 0 && (newname == null || newname.isEmpty())) {
            status = 1;
        }
    }
    move(status, newname, commandLine.toString());
}

From source file:com.commercehub.bamboo.plugins.grailswrapper.GrailsWrapperTask.java

@NotNull
@Override// w  w w . jav a2 s  .  c  o m
public TaskResult execute(@NotNull TaskContext taskContext) throws TaskException {
    TaskResultBuilder taskResultBuilder = TaskResultBuilder.newBuilder(taskContext);
    BuildLogger buildLogger = taskContext.getBuildLogger();
    Map<String, String> environment = buildEnvironment(taskContext);
    File workingDirectory = taskContext.getWorkingDirectory();
    if (!workingDirectory.isDirectory()) {
        buildLogger.addErrorLogEntry("Working directory " + workingDirectory.getPath() + " does not exist.");
        return taskResultBuilder.failedWithError().build();
    }
    String wrapperExecutable = SystemUtils.IS_OS_WINDOWS ? "grailsw.bat" : "./grailsw";
    File wrapperExecutableFile = new File(workingDirectory, wrapperExecutable);
    if (!wrapperExecutableFile.isFile()) {
        buildLogger.addErrorLogEntry("Could not locate " + wrapperExecutable + " in working directory "
                + workingDirectory.getPath());
        return taskResultBuilder.failedWithError().build();
    }
    if (!wrapperExecutableFile.canExecute()) {
        buildLogger.addErrorLogEntry(wrapperExecutable + " in working directory " + workingDirectory.getPath()
                + " is not executable");
        return taskResultBuilder.failedWithError().build();
    }
    Joiner commandJoiner = Joiner.on(" ");
    for (List<String> command : parseCommands(taskContext)) {
        command.add(0, wrapperExecutable);
        ExternalProcessBuilder processBuilder = new ExternalProcessBuilder().workingDirectory(workingDirectory)
                .env(environment).command(command);
        ExternalProcess process = processService.executeExternalProcess(taskContext, processBuilder);
        taskResultBuilder.checkReturnCode(process);
        ProcessHandler handler = process.getHandler();
        if (!handler.succeeded() || handler.getExitCode() != 0) {
            buildLogger.addErrorLogEntry("Grails wrapper command '" + commandJoiner.join(command)
                    + "' failed; skipping any subsequent commands");
            break;
        }
    }
    return taskResultBuilder.build();
}

From source file:com.sios.stc.coseng.util.TestParam.java

public synchronized Boolean isValid(final LocalParam localParam) throws IOException {
    Boolean isValid = true;/*from w  w  w .j ava2 s .  c o m*/
    // Warning items that don't necessarily invalidate the config
    if ((baseUrl == null) || baseUrl.isEmpty()) {
        TestParam.log.log(Level.WARNING, logDetails("A baseUrl was not provided; some tests may fail"));
    }
    if (verbosity == null) {
        TestParam.log.log(Level.INFO, logDetails("A verbosity was not provided; assuming level (0)"));
        verbosity = 0;
    }
    if (spot == null) {
        TestParam.log.log(Level.INFO, logDetails("A spot was not provided; assuming LOCAL"));
        spot = Spot.LOCAL;
    }
    // True|False validation parameters
    if (platform == null) {
        TestParam.log.log(Level.SEVERE, logDetails(
                "No platform was provided; a platform of (" + getPlatformOptions() + ") is REQUIRED"));
        isValid = false;
    }
    if (browser == null) {
        TestParam.log.log(Level.SEVERE,
                logDetails("No browser was provided; a browser of (" + getBrowserOptions() + ") is REQUIRED"));
        isValid = false;
    }
    // Special; chromeDriver|ieDriver when Spot.LOCAL and !Browser.FIREFOX
    if ((browser != null) && (spot == Spot.LOCAL)) {
        if (browser == Browser.CHROME) {
            // If can't find chromeDriver; bail
            final File chromeDriver = localParam.getChromeDriver();
            if ((chromeDriver == null) || !chromeDriver.exists() || !chromeDriver.canExecute()) {
                TestParam.log.log(Level.SEVERE,
                        logDetails(
                                "Testing with browser (" + browser.toString() + ") at spot (" + spot.toString()
                                        + ") REQUIRES chromeDriver. Could not find executable chromeDriver ("
                                        + chromeDriver + ")"));
                isValid = false;
            }
        } else if (browser != Browser.FIREFOX) {
            // Must be IE*
            final File ieDriver = localParam.getIeDriver();
            // If can't find ieDriver; bail
            if ((ieDriver == null) || !ieDriver.exists() || !ieDriver.canExecute()) {
                TestParam.log.log(Level.SEVERE,
                        logDetails("Testing with browser (" + browser.toString() + ") at spot ("
                                + spot.toString() + ") REQUIRES ieDriver. Could not find executable ieDriver ("
                                + ieDriver + ")"));
                isValid = false;
            }
        }
    }
    // If !windows but browser is IE*; bail
    if ((browser != null) && (platform != null)) {
        if (platform != Platform.WINDOWS) {
            if ((browser != Browser.FIREFOX) && (browser != Browser.CHROME)) {
                TestParam.log.log(Level.SEVERE,
                        logDetails("Internet Explorer IE*, any version; REQUIRES platform WINDOWS"));
                isValid = false;
            }
        }
    }
    if ((suite == null) || suite.isEmpty()) {
        TestParam.log.log(Level.SEVERE, logDetails("No suite provided; at least one suite XML REQUIRED"));
        isValid = false;
    } else {
        // jarSuiteTempDirectory is checked in findTestSuite
        if (!findTestSuite(localParam)) {
            TestParam.log.log(Level.SEVERE, logDetails("Could not find ALL suite (" + suite.toString() + ")"));
            isValid = false;
        }
    }
    if ((spot == Spot.GRID) && ((gridUrl == null) || gridUrl.isEmpty())) {
        TestParam.log.log(Level.SEVERE,
                logDetails("A gridUrl was not provided; spot (" + spot.toString() + ") REQUIRES gridUrl"));
        isValid = false;
    }
    if (!setTestReportDirectory(localParam)) {
        TestParam.log.log(Level.SEVERE, logDetails(
                "Could not create testReportDirectory (" + testReportDirectory.getCanonicalPath() + ")"));
        isValid = false;
    }
    if ((verbosity < 0) || (verbosity > 10)) {
        TestParam.log.log(Level.SEVERE, logDetails("Invalid verbosity; must be 0-10"));
        isValid = false;
    }
    setIsValid(isValid);
    return isValid;
}

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

/**
 * search for hadoop command from HADOOP_HOME.
 *///from www.  j a  v a 2s  .  co  m
@Test
public void findHadoopCommand_explicit() {
    putExec("bin/hadoop");

    Map<String, String> envp = new HashMap<>();
    envp.put("HADOOP_HOME", folder.getRoot().getAbsolutePath());

    File file = ConfigurationProvider.findHadoopCommand(envp);
    assertThat(file, is(notNullValue()));
    assertThat(file.toString(), file.canExecute(), is(true));
}

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

/**
 * search for hadoop command from PATH.//from  w  w w .  j av a  2 s . com
 */
@Test
public void findHadoopCommand_path() {
    putExec("bin/hadoop");

    Map<String, String> envp = new HashMap<>();
    envp.put("PATH", new File(folder.getRoot(), "bin").getAbsolutePath());

    File file = ConfigurationProvider.findHadoopCommand(envp);
    assertThat(file, is(notNullValue()));
    assertThat(file.toString(), file.canExecute(), is(true));
}

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

/**
 * search for hadoop command from HADOOP_HOME.
 *//*from  ww  w . ja  v a2s.co  m*/
@Test
public void findHadoopCommand_both() {
    putExec("home/bin/hadoop");
    putExec("path/hadoop");

    Map<String, String> envp = new HashMap<>();
    envp.put("HADOOP_HOME", new File(folder.getRoot(), "home").getAbsolutePath());
    envp.put("PATH", new File(folder.getRoot(), "path").getAbsolutePath());

    File file = ConfigurationProvider.findHadoopCommand(envp);
    assertThat(file, is(notNullValue()));
    assertThat(file.toString(), file.canExecute(), is(true));
    assertThat(file.toString(), file.getParentFile().getName(), is("bin"));
}