FileDocCategorySizeDatePackage
Commandline.javaAPI DocApache Ant 1.7020101Wed Dec 13 06:16:18 GMT 2006org.apache.tools.ant.types

Commandline

public class Commandline extends Object implements Cloneable
Commandline objects help handling command lines specifying processes to execute. The class can be used to define a command line as nested elements or as a helper to define a command line by an application.

<someelement>
  <acommandline executable="/executable/to/run">
    <argument value="argument 1" />
    <argument line="argument_1 argument_2 argument_3" />
    <argument value="argument 4" />
  </acommandline>
</someelement>
The element someelement must provide a method createAcommandline which returns an instance of this class.

Fields Summary
private static final boolean
IS_WIN_9X
win9x uses a (shudder) bat file (antRun.bat) for executing commands
private Vector
arguments
The arguments of the command
private String
executable
the program to execute
protected static final String
DISCLAIMER
Constructors Summary
public Commandline(String toProcess)
Create a command line from a string.

param
toProcess the line: the first element becomes the executable, the rest the arguments.


                              
       
        super();
        String[] tmp = translateCommandline(toProcess);
        if (tmp != null && tmp.length > 0) {
            setExecutable(tmp[0]);
            for (int i = 1; i < tmp.length; i++) {
                createArgument().setValue(tmp[i]);
            }
        }
    
public Commandline()
Create an empty command line.

        super();
    
Methods Summary
public voidaddArguments(java.lang.String[] line)
Append the arguments to the existing command.

param
line an array of arguments to append.

        for (int i = 0; i < line.length; i++) {
            createArgument().setValue(line[i]);
        }
    
public voidaddArgumentsToList(java.util.ListIterator list)
Append all the arguments to the tail of a supplied list.

param
list the list of arguments.
since
Ant 1.6

        for (int i = 0; i < arguments.size(); i++) {
            Argument arg = (Argument) arguments.elementAt(i);
            String[] s = arg.getParts();
            if (s != null) {
                for (int j = 0; j < s.length; j++) {
                    list.add(s[j]);
                }
            }
        }
    
public voidaddCommandToList(java.util.ListIterator list)
Add the entire command, including (optional) executable to a list.

param
list the list to add to.
since
Ant 1.6

        if (executable != null) {
            list.add(executable);
        }
        addArgumentsToList(list);
    
public voidclear()
Clear out the whole command line.

        executable = null;
        arguments.removeAllElements();
    
public voidclearArgs()
Clear out the arguments but leave the executable in place for another operation.

        arguments.removeAllElements();
    
public java.lang.Objectclone()
Generate a deep clone of the contained object.

return
a clone of the contained object

        try {
            Commandline c = (Commandline) super.clone();
            c.arguments = (Vector) arguments.clone();
            return c;
        } catch (CloneNotSupportedException e) {
            throw new BuildException(e);
        }
    
public org.apache.tools.ant.types.Commandline$ArgumentcreateArgument()
Create an argument object.

Each commandline object has at most one instance of the argument class. This method calls this.createArgument(false).

see
#createArgument(boolean)
return
the argument object.

        return this.createArgument(false);
    
public org.apache.tools.ant.types.Commandline$ArgumentcreateArgument(boolean insertAtStart)
Create an argument object and add it to our list of args.

Each commandline object has at most one instance of the argument class.

param
insertAtStart if true, the argument is inserted at the beginning of the list of args, otherwise it is appended.
return
an argument to be configured

        Argument argument = new Argument();
        if (insertAtStart) {
            arguments.insertElementAt(argument, 0);
        } else {
            arguments.addElement(argument);
        }
        return argument;
    
public org.apache.tools.ant.types.Commandline$MarkercreateMarker()
Return a marker.

This marker can be used to locate a position on the commandline--to insert something for example--when all parameters have been set.

return
a marker

        return new Marker(arguments.size());
    
public java.lang.StringdescribeArguments()
Return a String that describes the arguments suitable for verbose output before a call to Runtime.exec(String[]).

return
a string that describes the arguments.
since
Ant 1.5

        return describeArguments(this);
    
public static java.lang.StringdescribeArguments(org.apache.tools.ant.types.Commandline line)
Return a String that describes the arguments suitable for verbose output before a call to Runtime.exec(String[]).

param
line the Commandline whose arguments to describe.
return
a string that describes the arguments.
since
Ant 1.5

        return describeArguments(line.getArguments());
    
public static java.lang.StringdescribeArguments(java.lang.String[] args)
Return a String that describes the arguments suitable for verbose output before a call to Runtime.exec(String[]).

param
args the command line to describe as an array of strings.
return
a string that describes the arguments.
since
Ant 1.5

        return describeArguments(args, 0);
    
protected static java.lang.StringdescribeArguments(java.lang.String[] args, int offset)
Return a String that describes the arguments suitable for verbose output before a call to Runtime.exec(String[]).

param
args the command line to describe as an array of strings.
param
offset ignore entries before this index.
return
a string that describes the arguments
since
Ant 1.5

        if (args == null || args.length <= offset) {
            return "";
        }
        StringBuffer buf = new StringBuffer("argument");
        if (args.length > offset) {
            buf.append("s");
        }
        buf.append(":").append(StringUtils.LINE_SEP);
        for (int i = offset; i < args.length; i++) {
            buf.append("\'").append(args[i]).append("\'")
                .append(StringUtils.LINE_SEP);
        }
        buf.append(DISCLAIMER);
        return buf.toString();
    
public java.lang.StringdescribeCommand()
Return a String that describes the command and arguments suitable for verbose output before a call to Runtime.exec(String[]).

return
a string that describes the command and arguments.
since
Ant 1.5

        return describeCommand(this);
    
public static java.lang.StringdescribeCommand(org.apache.tools.ant.types.Commandline line)
Return a String that describes the command and arguments suitable for verbose output before a call to Runtime.exec(String[]).

param
line the Commandline to describe.
return
a string that describes the command and arguments.
since
Ant 1.5

        return describeCommand(line.getCommandline());
    
public static java.lang.StringdescribeCommand(java.lang.String[] args)
Return a String that describes the command and arguments suitable for verbose output before a call to Runtime.exec(String[]).

This method assumes that the first entry in the array is the executable to run.

param
args the command line to describe as an array of strings
return
a string that describes the command and arguments.
since
Ant 1.5

        if (args == null || args.length == 0) {
            return "";
        }
        StringBuffer buf = new StringBuffer("Executing \'");
        buf.append(args[0]);
        buf.append("\'");
        if (args.length > 1) {
            buf.append(" with ");
            buf.append(describeArguments(args, 1));
        } else {
            buf.append(DISCLAIMER);
        }
        return buf.toString();
    
public java.lang.String[]getArguments()
Returns all arguments defined by addLine, addValue or the argument object.

return
the arguments as an array of strings.

        List result = new ArrayList(arguments.size() * 2);
        addArgumentsToList(result.listIterator());
        String [] res = new String[result.size()];
        return (String[]) result.toArray(res);
    
public java.lang.String[]getCommandline()
Return the executable and all defined arguments.

return
the commandline as an array of strings.

        List commands = new LinkedList();
        ListIterator list = commands.listIterator();
        addCommandToList(list);
        final String[] result = new String[commands.size()];
        return (String[]) commands.toArray(result);
    
public java.lang.StringgetExecutable()
Get the executable.

return
the program to run--null if not yet set.

        return executable;
    
public java.util.Iteratoriterator()
Get an iterator to the arguments list.

since
Ant 1.7
return
an Iterator.

        return arguments.iterator();
    
public static java.lang.StringquoteArgument(java.lang.String argument)
Put quotes around the given String if necessary.

If the argument doesn't include spaces or quotes, return it as is. If it contains double quotes, use single quotes - else surround the argument by double quotes.

param
argument the argument to quote if necessary.
return
the quoted argument.
exception
BuildException if the argument contains both, single and double quotes.

        if (argument.indexOf("\"") > -1) {
            if (argument.indexOf("\'") > -1) {
                throw new BuildException("Can\'t handle single and double"
                        + " quotes in same argument");
            } else {
                return '\'" + argument + '\'";
            }
        } else if (argument.indexOf("\'") > -1
                   || argument.indexOf(" ") > -1
                   // WIN9x uses a bat file for executing commands
                   || (IS_WIN_9X && argument.indexOf(';") != -1)) {
            return '\"" + argument + '\"";
        } else {
            return argument;
        }
    
public voidsetExecutable(java.lang.String executable)
Set the executable to run. All file separators in the string are converted to the platform specific value.

param
executable the String executable name.

        if (executable == null || executable.length() == 0) {
            return;
        }
        this.executable = executable.replace('/", File.separatorChar)
            .replace('\\", File.separatorChar);
    
public intsize()
Size operator. This actually creates the command line, so it is not a zero cost operation.

return
number of elements in the command, including the executable.

        return getCommandline().length;
    
public java.lang.StringtoString()
Return the command line as a string.

return
the command line.

        return toString(getCommandline());
    
public static java.lang.StringtoString(java.lang.String[] line)
Quote the parts of the given array in way that makes them usable as command line arguments.

param
line the list of arguments to quote.
return
empty string for null or no command, else every argument split by spaces and quoted by quoting rules.

        // empty path return empty string
        if (line == null || line.length == 0) {
            return "";
        }
        // path containing one or more elements
        final StringBuffer result = new StringBuffer();
        for (int i = 0; i < line.length; i++) {
            if (i > 0) {
                result.append(' ");
            }
            result.append(quoteArgument(line[i]));
        }
        return result.toString();
    
public static java.lang.String[]translateCommandline(java.lang.String toProcess)
Crack a command line.

param
toProcess the command line to process.
return
the command line broken into strings. An empty or null toProcess parameter results in a zero sized array.

        if (toProcess == null || toProcess.length() == 0) {
            //no command? no string
            return new String[0];
        }
        // parse with a simple finite state machine

        final int normal = 0;
        final int inQuote = 1;
        final int inDoubleQuote = 2;
        int state = normal;
        StringTokenizer tok = new StringTokenizer(toProcess, "\"\' ", true);
        Vector v = new Vector();
        StringBuffer current = new StringBuffer();
        boolean lastTokenHasBeenQuoted = false;

        while (tok.hasMoreTokens()) {
            String nextTok = tok.nextToken();
            switch (state) {
            case inQuote:
                if ("\'".equals(nextTok)) {
                    lastTokenHasBeenQuoted = true;
                    state = normal;
                } else {
                    current.append(nextTok);
                }
                break;
            case inDoubleQuote:
                if ("\"".equals(nextTok)) {
                    lastTokenHasBeenQuoted = true;
                    state = normal;
                } else {
                    current.append(nextTok);
                }
                break;
            default:
                if ("\'".equals(nextTok)) {
                    state = inQuote;
                } else if ("\"".equals(nextTok)) {
                    state = inDoubleQuote;
                } else if (" ".equals(nextTok)) {
                    if (lastTokenHasBeenQuoted || current.length() != 0) {
                        v.addElement(current.toString());
                        current = new StringBuffer();
                    }
                } else {
                    current.append(nextTok);
                }
                lastTokenHasBeenQuoted = false;
                break;
            }
        }
        if (lastTokenHasBeenQuoted || current.length() != 0) {
            v.addElement(current.toString());
        }
        if (state == inQuote || state == inDoubleQuote) {
            throw new BuildException("unbalanced quotes in " + toProcess);
        }
        String[] args = new String[v.size()];
        v.copyInto(args);
        return args;