Search in sources :

Example 1 with CommandlineJava

use of org.apache.tools.ant.types.CommandlineJava in project ant by apache.

the class JUnitTask method executeAsForked.

/**
 * Execute a testcase by forking a new JVM. The command will block
 * until it finishes. To know if the process was destroyed or not
 * or whether the forked Java VM exited abnormally, use the
 * attributes of the returned holder object.
 * @param  test       the testcase to execute.
 * @param  watchdog   the watchdog in charge of cancelling the test if it
 * exceeds a certain amount of time. Can be <tt>null</tt>, in this case
 * the test could probably hang forever.
 * @param casesFile list of test cases to execute. Can be <tt>null</tt>,
 * in this case only one test is executed.
 * @return the test results from the JVM itself.
 * @throws BuildException in case of error creating a temporary property file,
 * or if the junit process can not be forked
 */
private TestResultHolder executeAsForked(JUnitTest test, final ExecuteWatchdog watchdog, final File casesFile) throws BuildException {
    if (perm != null) {
        log("Permissions ignored when running in forked mode!", Project.MSG_WARN);
    }
    CommandlineJava cmd;
    try {
        cmd = (CommandlineJava) getCommandline().clone();
    } catch (final CloneNotSupportedException e) {
        throw new BuildException("This shouldn't happen", e, getLocation());
    }
    if (casesFile == null) {
        cmd.createArgument().setValue(test.getName());
        if (test.getMethods() != null) {
            cmd.createArgument().setValue(Constants.METHOD_NAMES + test.getMethodsString());
        }
    } else {
        log("Running multiple tests in the same VM", Project.MSG_VERBOSE);
        cmd.createArgument().setValue(Constants.TESTSFILE + casesFile);
    }
    cmd.createArgument().setValue(Constants.SKIP_NON_TESTS + String.valueOf(test.isSkipNonTests()));
    cmd.createArgument().setValue(Constants.FILTERTRACE + test.getFiltertrace());
    cmd.createArgument().setValue(Constants.HALT_ON_ERROR + test.getHaltonerror());
    cmd.createArgument().setValue(Constants.HALT_ON_FAILURE + test.getHaltonfailure());
    checkIncludeAntRuntime(cmd);
    checkIncludeSummary(cmd);
    cmd.createArgument().setValue(Constants.SHOWOUTPUT + String.valueOf(showOutput));
    cmd.createArgument().setValue(Constants.OUTPUT_TO_FORMATTERS + String.valueOf(outputToFormatters));
    cmd.createArgument().setValue(Constants.LOG_FAILED_TESTS + String.valueOf(logFailedTests));
    cmd.createArgument().setValue(Constants.THREADID + String.valueOf(test.getThread()));
    // #31885
    cmd.createArgument().setValue(Constants.LOGTESTLISTENEREVENTS + String.valueOf(getEnableTestListenerEvents()));
    StringBuilder formatterArg = new StringBuilder(STRING_BUFFER_SIZE);
    final FormatterElement[] feArray = mergeFormatters(test);
    for (final FormatterElement fe : feArray) {
        if (fe.shouldUse(this)) {
            formatterArg.append(Constants.FORMATTER);
            formatterArg.append(fe.getClassname());
            final File outFile = getOutput(fe, test);
            if (outFile != null) {
                formatterArg.append(",");
                formatterArg.append(outFile);
            }
            cmd.createArgument().setValue(formatterArg.toString());
            formatterArg = new StringBuilder();
        }
    }
    final File vmWatcher = createTempPropertiesFile("junitvmwatcher");
    cmd.createArgument().setValue(Constants.CRASHFILE + vmWatcher.getAbsolutePath());
    final File propsFile = createTempPropertiesFile("junit");
    cmd.createArgument().setValue(Constants.PROPSFILE + propsFile.getAbsolutePath());
    final Hashtable<String, Object> p = getProject().getProperties();
    final Properties props = new Properties();
    p.forEach(props::put);
    try {
        final OutputStream outstream = Files.newOutputStream(propsFile.toPath());
        props.store(outstream, "Ant JUnitTask generated properties file");
        outstream.close();
    } catch (final IOException e) {
        FILE_UTILS.tryHardToDelete(propsFile);
        throw new BuildException("Error creating temporary properties " + "file.", e, getLocation());
    }
    final Execute execute = new Execute(new JUnitLogStreamHandler(this, Project.MSG_INFO, Project.MSG_WARN), watchdog);
    execute.setCommandline(cmd.getCommandline());
    execute.setAntRun(getProject());
    if (dir != null) {
        execute.setWorkingDirectory(dir);
    }
    final String[] environment = env.getVariables();
    if (environment != null) {
        for (String variable : environment) {
            log("Setting environment variable: " + variable, Project.MSG_VERBOSE);
        }
    }
    execute.setNewenvironment(newEnvironment);
    execute.setEnvironment(environment);
    log(cmd.describeCommand(), Project.MSG_VERBOSE);
    checkForkedPath(cmd);
    final TestResultHolder result = new TestResultHolder();
    boolean success = false;
    try {
        result.exitCode = execute.execute();
        success = true;
    } catch (final IOException e) {
        throw new BuildException("Process fork failed.", e, getLocation());
    } finally {
        String vmCrashString = "unknown";
        BufferedReader br = null;
        try {
            if (vmWatcher.exists()) {
                br = new BufferedReader(new FileReader(vmWatcher));
                vmCrashString = br.readLine();
            } else {
                vmCrashString = "Monitor file (" + vmWatcher.getAbsolutePath() + ") missing, location not writable," + " testcase not started or mixing ant versions?";
            }
        } catch (final Exception e) {
            log(StringUtils.getStackTrace(e), Project.MSG_INFO);
        // ignored.
        } finally {
            FileUtils.close(br);
            if (vmWatcher.exists()) {
                FILE_UTILS.tryHardToDelete(vmWatcher);
            }
        }
        final boolean crash = (watchdog != null && watchdog.killedProcess()) || !Constants.TERMINATED_SUCCESSFULLY.equals(vmCrashString);
        if (casesFile != null && crash) {
            test = createDummyTestForBatchTest(test);
        }
        if (watchdog != null && watchdog.killedProcess()) {
            result.timedOut = true;
            logTimeout(feArray, test, vmCrashString);
        } else if (crash) {
            result.crashed = true;
            logVmCrash(feArray, test, vmCrashString);
        }
        if (!FILE_UTILS.tryHardToDelete(propsFile)) {
            String msg = "Could not delete temporary properties file '" + propsFile.getAbsolutePath() + "'.";
            if (success) {
                // NOSONAR
                throw new BuildException(msg);
            }
            // don't hide inner exception
            log(msg, Project.MSG_ERR);
        }
    }
    return result;
}
Also used : Execute(org.apache.tools.ant.taskdefs.Execute) LogOutputStream(org.apache.tools.ant.taskdefs.LogOutputStream) OutputStream(java.io.OutputStream) CommandlineJava(org.apache.tools.ant.types.CommandlineJava) IOException(java.io.IOException) Properties(java.util.Properties) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Example 2 with CommandlineJava

use of org.apache.tools.ant.types.CommandlineJava in project ant by apache.

the class JasperC method execute.

/**
 * Our execute method.
 * @return true if successful
 * @throws BuildException on error
 */
@Override
public boolean execute() throws BuildException {
    getJspc().log("Using jasper compiler", Project.MSG_VERBOSE);
    CommandlineJava cmd = setupJasperCommand();
    try {
        // Create an instance of the compiler, redirecting output to
        // the project log
        Java java = new Java(owner);
        Path p = getClasspath();
        if (getJspc().getClasspath() != null) {
            getProject().log("using user supplied classpath: " + p, Project.MSG_DEBUG);
        } else {
            getProject().log("using system classpath: " + p, Project.MSG_DEBUG);
        }
        java.setClasspath(p);
        java.setDir(getProject().getBaseDir());
        java.setClassname("org.apache.jasper.JspC");
        // this is really irritating; we need a way to set stuff
        for (String arg : cmd.getJavaCommand().getArguments()) {
            java.createArg().setValue(arg);
        }
        java.setFailonerror(getJspc().getFailonerror());
        // we are forking here to be sure that if JspC calls
        // System.exit() it doesn't halt the build
        java.setFork(true);
        java.setTaskName("jasperc");
        java.execute();
        return true;
    } catch (Exception ex) {
        if (ex instanceof BuildException) {
            throw (BuildException) ex;
        }
        throw new BuildException("Error running jsp compiler: ", ex, getJspc().getLocation());
    } finally {
        getJspc().deleteEmptyJavaFiles();
    }
}
Also used : Path(org.apache.tools.ant.types.Path) Java(org.apache.tools.ant.taskdefs.Java) CommandlineJava(org.apache.tools.ant.types.CommandlineJava) CommandlineJava(org.apache.tools.ant.types.CommandlineJava) BuildException(org.apache.tools.ant.BuildException) BuildException(org.apache.tools.ant.BuildException)

Example 3 with CommandlineJava

use of org.apache.tools.ant.types.CommandlineJava in project ant by apache.

the class Java method run.

/**
 * Executes the given classname with the given arguments as if it
 * were a command line application.
 *
 * @param classname the name of the class to run.
 * @param args  arguments for the class.
 * @throws BuildException in case of IOException in the execution.
 */
protected void run(String classname, Vector<String> args) throws BuildException {
    CommandlineJava cmdj = new CommandlineJava();
    cmdj.setClassname(classname);
    args.forEach(arg -> cmdj.createArgument().setValue(arg));
    run(cmdj);
}
Also used : CommandlineJava(org.apache.tools.ant.types.CommandlineJava)

Example 4 with CommandlineJava

use of org.apache.tools.ant.types.CommandlineJava in project ant by apache.

the class ExecuteJava method fork.

/**
 * Run the Java command in a separate VM, this does not give you
 * the full flexibility of the Java task, but may be enough for
 * simple needs.
 * @param pc the ProjectComponent to use for logging, etc.
 * @return the exit status of the subprocess.
 * @throws BuildException on error.
 * @since Ant 1.6.3
 */
public int fork(ProjectComponent pc) throws BuildException {
    CommandlineJava cmdl = new CommandlineJava();
    cmdl.setClassname(javaCommand.getExecutable());
    for (String arg : javaCommand.getArguments()) {
        cmdl.createArgument().setValue(arg);
    }
    if (classpath != null) {
        cmdl.createClasspath(pc.getProject()).append(classpath);
    }
    if (sysProperties != null) {
        cmdl.addSysproperties(sysProperties);
    }
    Redirector redirector = new Redirector(pc);
    Execute exe = new Execute(redirector.createHandler(), timeout == null ? null : new ExecuteWatchdog(timeout));
    exe.setAntRun(pc.getProject());
    if (Os.isFamily("openvms")) {
        setupCommandLineForVMS(exe, cmdl.getCommandline());
    } else {
        exe.setCommandline(cmdl.getCommandline());
    }
    try {
        int rc = exe.execute();
        redirector.complete();
        return rc;
    } catch (IOException e) {
        throw new BuildException(e);
    } finally {
        timedOut = exe.killedProcess();
    }
}
Also used : CommandlineJava(org.apache.tools.ant.types.CommandlineJava) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException)

Example 5 with CommandlineJava

use of org.apache.tools.ant.types.CommandlineJava in project ant by apache.

the class JDependTask method execute.

/**
 * execute the task
 *
 * @exception BuildException if an error occurs
 */
@Override
public void execute() throws BuildException {
    CommandlineJava commandline = new CommandlineJava();
    if ("text".equals(format)) {
        commandline.setClassname("jdepend.textui.JDepend");
    } else if ("xml".equals(format)) {
        commandline.setClassname("jdepend.xmlui.JDepend");
    }
    if (jvm != null) {
        commandline.setVm(jvm);
    }
    if (getSourcespath() == null && getClassespath() == null) {
        throw new BuildException("Missing classespath required argument");
    }
    if (getClassespath() == null) {
        log("sourcespath is deprecated in JDepend >= 2.5 - please convert to classespath");
    }
    // execute the test and get the return code
    int exitValue;
    boolean wasKilled = false;
    if (!getFork()) {
        exitValue = executeInVM(commandline);
    } else {
        ExecuteWatchdog watchdog = createWatchdog();
        exitValue = executeAsForked(commandline, watchdog);
        // null watchdog means no timeout, you'd better not check with null
        if (watchdog != null) {
            wasKilled = watchdog.killedProcess();
        }
    }
    // if there is an error/failure and that it should halt, stop
    // everything otherwise just log a statement
    boolean errorOccurred = exitValue == JDependTask.ERRORS || wasKilled;
    if (errorOccurred) {
        String errorMessage = "JDepend FAILED" + (wasKilled ? " - Timed out" : "");
        if (getHaltonerror()) {
            throw new BuildException(errorMessage, getLocation());
        }
        log(errorMessage, Project.MSG_ERR);
    }
}
Also used : ExecuteWatchdog(org.apache.tools.ant.taskdefs.ExecuteWatchdog) CommandlineJava(org.apache.tools.ant.types.CommandlineJava) BuildException(org.apache.tools.ant.BuildException)

Aggregations

CommandlineJava (org.apache.tools.ant.types.CommandlineJava)9 BuildException (org.apache.tools.ant.BuildException)6 File (java.io.File)4 IOException (java.io.IOException)4 Assignment (com.carrotsearch.ant.tasks.junit4.SuiteBalancer.Assignment)2 RoundRobinBalancer (com.carrotsearch.ant.tasks.junit4.balancers.RoundRobinBalancer)2 SuiteHint (com.carrotsearch.ant.tasks.junit4.balancers.SuiteHint)2 BootstrapEvent (com.carrotsearch.ant.tasks.junit4.events.BootstrapEvent)2 QuitEvent (com.carrotsearch.ant.tasks.junit4.events.QuitEvent)2 AggregatedQuitEvent (com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedQuitEvent)2 AggregatedStartEvent (com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatedStartEvent)2 AggregatingListener (com.carrotsearch.ant.tasks.junit4.events.aggregated.AggregatingListener)2 ChildBootstrap (com.carrotsearch.ant.tasks.junit4.events.aggregated.ChildBootstrap)2 JvmOutputEvent (com.carrotsearch.ant.tasks.junit4.events.aggregated.JvmOutputEvent)2 AggregatedEventListener (com.carrotsearch.ant.tasks.junit4.listeners.AggregatedEventListener)2 RunListenerClass (com.carrotsearch.ant.tasks.junit4.runlisteners.RunListenerClass)2 SlaveMain (com.carrotsearch.ant.tasks.junit4.slave.SlaveMain)2 SlaveMainSafe (com.carrotsearch.ant.tasks.junit4.slave.SlaveMainSafe)2 ClassGlobFilter (com.carrotsearch.randomizedtesting.ClassGlobFilter)2 FilterExpressionParser (com.carrotsearch.randomizedtesting.FilterExpressionParser)2