FileDocCategorySizeDatePackage
Java.javaAPI DocApache Ant 1.7028816Wed Dec 13 06:16:24 GMT 2006org.apache.tools.ant.taskdefs

Java

public class Java extends org.apache.tools.ant.Task
Launcher for Java applications. Allows use of the same JVM for the called application thus resulting in much faster operation.
since
Ant 1.1
ant.task
category="java"

Fields Summary
private org.apache.tools.ant.types.CommandlineJava
cmdl
private org.apache.tools.ant.types.Environment
env
private boolean
fork
private boolean
newEnvironment
private File
dir
private boolean
failOnError
private Long
timeout
private String
inputString
private File
input
private File
output
private File
error
protected Redirector
redirector
protected org.apache.tools.ant.types.RedirectorElement
redirectorElement
private String
resultProperty
private org.apache.tools.ant.types.Permissions
perm
private boolean
spawn
private boolean
incompatibleWithSpawn
Constructors Summary
public Java()
Normal constructor


           
      
    
public Java(org.apache.tools.ant.Task owner)
create a bound task

param
owner owner

        bindToOwner(owner);
    
Methods Summary
public voidaddAssertions(org.apache.tools.ant.types.Assertions asserts)
Add assertions to enable in this program (if fork=true).

param
asserts assertion set.
since
Ant 1.6

        if (getCommandLine().getAssertions() != null) {
            throw new BuildException("Only one assertion declaration is allowed");
        }
        getCommandLine().setAssertions(asserts);
    
public voidaddConfiguredRedirector(org.apache.tools.ant.types.RedirectorElement redirectorElement)
Add a RedirectorElement to this task.

param
redirectorElement RedirectorElement.

        if (this.redirectorElement != null) {
            throw new BuildException("cannot have > 1 nested redirectors");
        }
        this.redirectorElement = redirectorElement;
        incompatibleWithSpawn = true;
    
public voidaddEnv(Environment.Variable var)
Add an environment variable.

Will be ignored if we are not forking a new VM.

param
var new environment variable.
since
Ant 1.5

        env.addVariable(var);
    
public voidaddSysproperty(Environment.Variable sysp)
Add a system property.

param
sysp system property.

        getCommandLine().addSysproperty(sysp);
    
public voidaddSyspropertyset(org.apache.tools.ant.types.PropertySet sysp)
Add a set of properties as system properties.

param
sysp set of properties to add.
since
Ant 1.6

        getCommandLine().addSyspropertyset(sysp);
    
public voidclearArgs()
Clear out the arguments to this java task.

        getCommandLine().clearJavaArgs();
    
public Commandline.ArgumentcreateArg()
Add a command-line argument.

return
created argument.

        return getCommandLine().createArgument();
    
public org.apache.tools.ant.types.PathcreateBootclasspath()
Add a path to the bootclasspath.

since
Ant 1.6
return
created bootclasspath.

        return getCommandLine().createBootclasspath(getProject()).createPath();
    
public org.apache.tools.ant.types.PathcreateClasspath()
Add a path to the classpath.

return
created classpath.

        return getCommandLine().createClasspath(getProject()).createPath();
    
public Commandline.ArgumentcreateJvmarg()
Adds a JVM argument.

return
JVM argument created.

        return getCommandLine().createVmArgument();
    
public org.apache.tools.ant.types.PermissionscreatePermissions()
Set the permissions for the application run inside the same JVM.

since
Ant 1.6
return
Permissions.

        perm = (perm == null) ? new Permissions() : perm;
        return perm;
    
protected ExecuteWatchdogcreateWatchdog()
Create the Watchdog to kill a runaway process.

return
new watchdog.
throws
BuildException under unknown circumstances.
since
Ant 1.5

        if (timeout == null) {
            return null;
        }
        return new ExecuteWatchdog(timeout.longValue());
    
public voidexecute()
Do the execution.

throws
BuildException if failOnError is set to true and the application returns a nonzero result code.

        File savedDir = dir;
        Permissions savedPermissions = perm;

        int err = -1;
        try {
            err = executeJava();
            if (err != 0) {
                if (failOnError) {
                    throw new ExitStatusException("Java returned: " + err,
                            err,
                            getLocation());
                } else {
                    log("Java Result: " + err, Project.MSG_ERR);
                }
            }
            maybeSetResultPropertyValue(err);
        } finally {
            dir = savedDir;
            perm = savedPermissions;
        }
    
public intexecuteJava()
Do the execution and return a return code.

return
the return code from the execute java class if it was executed in a separate VM (fork = "yes") or a security manager was installed that prohibits ExitVM (default).
throws
BuildException if required parameters are missing.

        String classname = getCommandLine().getClassname();
        if (classname == null && getCommandLine().getJar() == null) {
            throw new BuildException("Classname must not be null.");
        }
        if (!fork && getCommandLine().getJar() != null) {
            throw new BuildException("Cannot execute a jar in non-forked mode."
                                     + " Please set fork='true'. ");
        }
        if (spawn && !fork) {
            throw new BuildException("Cannot spawn a java process in non-forked mode."
                                     + " Please set fork='true'. ");
        }
        if (getCommandLine().getClasspath() != null
            && getCommandLine().getJar() != null) {
            log("When using 'jar' attribute classpath-settings are ignored. "
                + "See the manual for more information.", Project.MSG_VERBOSE);
        }
        if (spawn && incompatibleWithSpawn) {
            getProject().log("spawn does not allow attributes related to input, "
            + "output, error, result", Project.MSG_ERR);
            getProject().log("spawn also does not allow timeout", Project.MSG_ERR);
            getProject().log("finally, spawn is not compatible "
                + "with a nested I/O <redirector>", Project.MSG_ERR);
            throw new BuildException("You have used an attribute "
                + "or nested element which is not compatible with spawn");
        }
        if (getCommandLine().getAssertions() != null && !fork) {
            log("Assertion statements are currently ignored in non-forked mode");
        }
        if (fork) {
            if (perm != null) {
                log("Permissions can not be set this way in forked mode.", Project.MSG_WARN);
            }
            log(getCommandLine().describeCommand(), Project.MSG_VERBOSE);
        } else {
            if (getCommandLine().getVmCommand().size() > 1) {
                log("JVM args ignored when same JVM is used.",
                    Project.MSG_WARN);
            }
            if (dir != null) {
                log("Working directory ignored when same JVM is used.",
                    Project.MSG_WARN);
            }
            if (newEnvironment || null != env.getVariables()) {
                log("Changes to environment variables are ignored when same "
                    + "JVM is used.", Project.MSG_WARN);
            }
            if (getCommandLine().getBootclasspath() != null) {
                log("bootclasspath ignored when same JVM is used.",
                    Project.MSG_WARN);
            }
            if (perm == null) {
                perm = new Permissions(true);
                log("running " + this.getCommandLine().getClassname()
                    + " with default permissions (exit forbidden)", Project.MSG_VERBOSE);
            }
            log("Running in same VM " + getCommandLine().describeJavaCommand(),
                Project.MSG_VERBOSE);
        }
        setupRedirector();
        try {
            if (fork) {
                if (!spawn) {
                    return fork(getCommandLine().getCommandline());
                } else {
                    spawn(getCommandLine().getCommandline());
                    return 0;
                }
            } else {
                try {
                    run(getCommandLine());
                    return 0;
                } catch (ExitException ex) {
                    return ex.getStatus();
                }
            }
        } catch (BuildException e) {
            if (e.getLocation() == null && getLocation() != null) {
                e.setLocation(getLocation());
            }
            if (failOnError) {
                throw e;
            } else {
                log(e);
                return 0;
            }
        } catch (ThreadDeath t) {
            throw t; // cf. NB #47191
        } catch (Throwable t) {
            if (failOnError) {
                throw new BuildException(t, getLocation());
            } else {
                log(t);
                return 0;
            }
        }
    
private intfork(java.lang.String[] command)
Executes the given classname with the given arguments in a separate VM.

param
command String[] of command-line arguments.

        Execute exe
            = new Execute(redirector.createHandler(), createWatchdog());
        setupExecutable(exe, command);

        try {
            int rc = exe.execute();
            redirector.complete();
            if (exe.killedProcess()) {
                throw new BuildException("Timeout: killed the sub-process");
            }
            return rc;
        } catch (IOException e) {
            throw new BuildException(e, getLocation());
        }
    
public org.apache.tools.ant.types.CommandlineJavagetCommandLine()
Accessor to the command line.

return
the current command line.
since
1.6.3

        return cmdl;
    
public CommandlineJava.SysPropertiesgetSysProperties()
Get the system properties of the command line.

return
the current properties of this java invocation.
since
1.6.3

        return getCommandLine().getSystemProperties();
    
protected voidhandleErrorFlush(java.lang.String output)
Handle output sent to System.err and flush the stream.

param
output string of stderr.
since
Ant 1.5.2

        if (redirector.getErrorStream() != null) {
            redirector.handleErrorFlush(output);
        } else {
            super.handleErrorOutput(output);
        }
    
protected voidhandleErrorOutput(java.lang.String output)
Handle output sent to System.err.

param
output string of stderr.
since
Ant 1.5

        if (redirector.getErrorStream() != null) {
            redirector.handleErrorOutput(output);
        } else {
            super.handleErrorOutput(output);
        }
    
protected voidhandleFlush(java.lang.String output)
Pass output sent to System.out to specified output file.

param
output string of output on its way to its handlers.
since
Ant 1.5.2

        if (redirector.getOutputStream() != null) {
            redirector.handleFlush(output);
        } else {
            super.handleFlush(output);
        }
    
public inthandleInput(byte[] buffer, int offset, int length)
Handle an input request by this task.

param
buffer the buffer into which data is to be read.
param
offset the offset into the buffer at which data is stored.
param
length the amount of data to read.
return
the number of bytes read.
exception
IOException if the data cannot be read.
since
Ant 1.6

        // Should work whether or not redirector.inputStream == null:
        return redirector.handleInput(buffer, offset, length);
    
protected voidhandleOutput(java.lang.String output)
Pass output sent to System.out to specified output file.

param
output a string of output on its way to the handlers.
since
Ant 1.5

        if (redirector.getOutputStream() != null) {
            redirector.handleOutput(output);
        } else {
            super.handleOutput(output);
        }
    
private voidlog(java.lang.Throwable t)
Log the specified Throwable.

param
t the Throwable to log.
since
1.6.2

        StringWriter sw = new StringWriter();
        PrintWriter w = new PrintWriter(sw);
        t.printStackTrace(w);
        w.close();
        log(sw.toString(), Project.MSG_ERR);
    
protected voidmaybeSetResultPropertyValue(int result)
Helper method to set result property to the passed in value if appropriate.

param
result the exit code

        String res = Integer.toString(result);
        if (resultProperty != null) {
            getProject().setNewProperty(resultProperty, res);
        }
    
private voidrun(org.apache.tools.ant.types.CommandlineJava command)
Executes the given classname with the given arguments as it were a command line application.

param
command CommandlineJava.

        try {
            ExecuteJava exe = new ExecuteJava();
            exe.setJavaCommand(command.getJavaCommand());
            exe.setClasspath(command.getClasspath());
            exe.setSystemProperties(command.getSystemProperties());
            exe.setPermissions(perm);
            exe.setTimeout(timeout);
            redirector.createStreams();
            exe.execute(getProject());
            redirector.complete();
            if (exe.killedProcess()) {
                throw new BuildException("Timeout: killed the sub-process");
            }
        } catch (IOException e) {
            throw new BuildException(e);
        }
    
protected voidrun(java.lang.String classname, java.util.Vector args)
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.

        CommandlineJava cmdj = new CommandlineJava();
        cmdj.setClassname(classname);
        for (int i = 0; i < args.size(); i++) {
            cmdj.createArgument().setValue((String) args.elementAt(i));
        }
        run(cmdj);
    
public voidsetAppend(boolean append)
If true, append output to existing file.

param
append if true, append output to existing file.
since
Ant 1.5

        redirector.setAppend(append);
        incompatibleWithSpawn = true;
    
public voidsetArgs(java.lang.String s)
Deprecated: use nested arg instead. Set the command line arguments for the class.

param
s arguments.
ant.attribute
ignore="true"

        log("The args attribute is deprecated. "
            + "Please use nested arg elements.", Project.MSG_WARN);
        getCommandLine().createArgument().setLine(s);
    
public voidsetClassname(java.lang.String s)
Set the Java class to execute.

param
s the name of the main class.
throws
BuildException if the jar attribute has been set.

        if (getCommandLine().getJar() != null) {
            throw new BuildException("Cannot use 'jar' and 'classname' "
                                     + "attributes in same command");
        }
        getCommandLine().setClassname(s);
    
public voidsetClasspath(org.apache.tools.ant.types.Path s)
Set the classpath to be used when running the Java class.

param
s an Ant Path object containing the classpath.

        createClasspath().append(s);
    
public voidsetClasspathRef(org.apache.tools.ant.types.Reference r)
Set the classpath to use by reference.

param
r a reference to an existing classpath.

        createClasspath().setRefid(r);
    
public voidsetCloneVm(boolean cloneVm)
If set, system properties will be copied to the cloned VM--as well as the bootclasspath unless you have explicitly specified a bootclaspath.

Doesn't have any effect unless fork is true.

param
cloneVm if true copy system properties.
since
Ant 1.7

        getCommandLine().setCloneVm(cloneVm);
    
public voidsetDir(java.io.File d)
Set the working directory of the process.

param
d working directory.

        this.dir = d;
    
public voidsetError(java.io.File error)
Set the File to which the error stream of the process is redirected.

param
error file getting the error stream.
since
Ant 1.6

        this.error = error;
        incompatibleWithSpawn = true;
    
public voidsetErrorProperty(java.lang.String errorProperty)
Set the property name whose value should be set to the error of the process.

param
errorProperty property name.
since
Ant 1.6

        redirector.setErrorProperty(errorProperty);
        incompatibleWithSpawn = true;
    
public voidsetFailonerror(boolean fail)
If true, then fail if the command exits with a returncode other than zero.

param
fail if true fail the build when the command exits with a nonzero returncode.

        failOnError = fail;
        incompatibleWithSpawn |= fail;
    
public voidsetFork(boolean s)
If true, execute in a new VM.

param
s do you want to run Java in a new VM.

        this.fork = s;
    
public voidsetInput(java.io.File input)
Set the input to use for the task.

param
input name of the input file.

        if (inputString != null) {
            throw new BuildException("The \"input\" and \"inputstring\" "
                + "attributes cannot both be specified");
        }
        this.input = input;
        incompatibleWithSpawn = true;
    
public voidsetInputString(java.lang.String inputString)
Set the string to use as input.

param
inputString the string which is used as the input source.

        if (input != null) {
            throw new BuildException("The \"input\" and \"inputstring\" "
                + "attributes cannot both be specified");
        }
        this.inputString = inputString;
        incompatibleWithSpawn = true;
    
public voidsetJVMVersion(java.lang.String value)
Set the JVM version.

param
value JVM version.

        getCommandLine().setVmversion(value);
    
public voidsetJar(java.io.File jarfile)
Set the location of the JAR file to execute.

param
jarfile the jarfile to execute.
throws
BuildException if there is also a main class specified.

        if (getCommandLine().getClassname() != null) {
            throw new BuildException("Cannot use 'jar' and 'classname' "
                                     + "attributes in same command.");
        }
        getCommandLine().setJar(jarfile.getAbsolutePath());
    
public voidsetJvm(java.lang.String s)
Set the command used to start the VM (only if forking).

param
s command to start the VM.

        getCommandLine().setVm(s);
    
public voidsetJvmargs(java.lang.String s)
Set the command line arguments for the JVM.

param
s jvmargs.

        log("The jvmargs attribute is deprecated. "
            + "Please use nested jvmarg elements.", Project.MSG_WARN);
        getCommandLine().createVmArgument().setLine(s);
    
public voidsetLogError(boolean logError)
Set whether error output of exec is logged. This is only useful when output is being redirected and error output is desired in the Ant log.

param
logError get in the ant log the messages coming from stderr in the case that fork = true.

        redirector.setLogError(logError);
        incompatibleWithSpawn |= logError;
    
public voidsetMaxmemory(java.lang.String max)
Corresponds to -mx or -Xmx depending on VM version.

param
max max memory parameter.

        getCommandLine().setMaxmemory(max);
    
public voidsetNewenvironment(boolean newenv)
If true, use a completely new environment.

Will be ignored if we are not forking a new VM.

param
newenv if true, use a completely new environment.
since
Ant 1.5

        newEnvironment = newenv;
    
public voidsetOutput(java.io.File out)
Set the File to which the output of the process is redirected.

param
out the output File.

        this.output = out;
        incompatibleWithSpawn = true;
    
public voidsetOutputproperty(java.lang.String outputProp)
Set the property name whose value should be set to the output of the process.

param
outputProp property name.

        redirector.setOutputProperty(outputProp);
        incompatibleWithSpawn = true;
    
public voidsetResultProperty(java.lang.String resultProperty)
Set the name of the property in which the return code of the command should be stored. Only of interest if failonerror=false.

param
resultProperty name of property.
since
Ant 1.6

        this.resultProperty = resultProperty;
        incompatibleWithSpawn = true;
    
public voidsetSpawn(boolean spawn)
Set whether or not you want the process to be spawned; default is not spawned.

param
spawn if true you do not want Ant to wait for the end of the process.
since
Ant 1.6

        this.spawn = spawn;
    
public voidsetTimeout(java.lang.Long value)
Set the timeout in milliseconds after which the process will be killed.

param
value timeout in milliseconds.
since
Ant 1.5

        timeout = value;
        incompatibleWithSpawn |= timeout != null;
    
private voidsetupCommandLine(Execute exe, java.lang.String[] command)
Set the command line for the exe. On VMS, hands off to {@link #setupCommandLineForVMS(Execute, String[])}.

param
exe executable.
param
command command to execute.

        //On VMS platform, we need to create a special java options file
        //containing the arguments and classpath for the java command.
        //The special file is supported by the "-V" switch on the VMS JVM.
        if (Os.isFamily("openvms")) {
            setupCommandLineForVMS(exe, command);
        } else {
            exe.setCommandline(command);
        }
    
private voidsetupCommandLineForVMS(Execute exe, java.lang.String[] command)
On VMS platform, we need to create a special java options file containing the arguments and classpath for the java command. The special file is supported by the "-V" switch on the VMS JVM.

param
exe executable.
param
command command to execute.

        ExecuteJava.setupCommandLineForVMS(exe, command);
    
private voidsetupEnvironment(Execute exe)
Set up our environment variables.

param
exe executable.

        String[] environment = env.getVariables();
        if (environment != null) {
            for (int i = 0; i < environment.length; i++) {
                log("Setting environment variable: " + environment[i],
                    Project.MSG_VERBOSE);
            }
        }
        exe.setNewenvironment(newEnvironment);
        exe.setEnvironment(environment);
    
private voidsetupExecutable(Execute exe, java.lang.String[] command)
Do all configuration for an executable that is common across the {@link #fork(String[])} and {@link #spawn(String[])} methods.

param
exe executable.
param
command command to execute.

        exe.setAntRun(getProject());
        setupWorkingDir(exe);
        setupEnvironment(exe);
        setupCommandLine(exe, command);
    
protected voidsetupRedirector()
Set up properties on the redirector that we needed to store locally.

        redirector.setInput(input);
        redirector.setInputString(inputString);
        redirector.setOutput(output);
        redirector.setError(error);
        if (redirectorElement != null) {
            redirectorElement.configure(redirector);
        }
        if (!spawn && input == null && inputString == null) {
            // #24918: send standard input to the process by default.
            redirector.setInputStream(
                new KeepAliveInputStream(getProject().getDefaultInputStream()));
        }
    
private voidsetupWorkingDir(Execute exe)
Set the working dir of the new process.

param
exe executable.
throws
BuildException if the dir doesn't exist.

        if (dir == null) {
            dir = getProject().getBaseDir();
        } else if (!dir.exists() || !dir.isDirectory()) {
            throw new BuildException(dir.getAbsolutePath()
                                     + " is not a valid directory",
                                     getLocation());
        }
        exe.setWorkingDirectory(dir);
    
private voidspawn(java.lang.String[] command)
Executes the given classname with the given arguments in a separate VM.

param
command String[] of command-line arguments.

        Execute exe = new Execute();
        setupExecutable(exe, command);
        try {
            exe.spawn();
        } catch (IOException e) {
            throw new BuildException(e, getLocation());
        }