Need Ant condition example

coolgokul picture coolgokul · Jul 18, 2012 · Viewed 10.7k times · Source

Can someone please explain me with Example of Ant condition property with "if", "and", "not" and "istrue" with the code??

I'm new to Ant and need help on this.

Basically i need to download file using FTP. I have code to download it. but there are few condition i need to check before downloading.

  1. Before downloading check the Downloadstatusvariable value (usually its true or false value")
  2. check whether file is already downloaded or available in the path
  3. if both the conditions fails then exec the FTP download code.

Thanks in advance.

Answer

choover picture choover · Jul 19, 2012

ant-contrib is widely-used library and the if/else/for/foreach tasks will not only make it easier to write complex ant scripts, they'll make your ant scripts much more readable.

But, since you insist :)

The way I've handled this in the past is to set up a task A that only executes if property X is set, and make task A depend on some task B that checks the conditions and sets property X if they are true. For example:

<target name="get-ftp-file" depends="check-need-ftp-file" if="ftp.call.required">
  <ftp ... />
</target>

<target name="check-need-ftp-file">
  <condition property="ftp.call.required">
    <and>
      <not>
        <!-- Checks if Downloadstatusvariable variable is true -->
        <istrue value="${Downloadstatusvariable}"/>
      </not>
      <not>
        <!-- Checks if file is present in filesystem -->
        <available file="${my.file}"/>
      </not>
    </and>
  </condition>
</target>

EDIT:

coolgokul, the <and> and <not> tasks are standard logical operators. The <available> condition in the example above evaluates to true if the file exists on the local machine. But we want to download the file only if the file does NOT exist on the local machine, so we wrap it up in the <not> task. Similar for the ${Downloadstatusvariable} check--we want to make sure it is not true, so we use <istrue> and then wrap it up in <not>.

Finally, we want to make sure that that the variable is not true AND the file does not exist, so we wrap up both those conditions in <and>. Translated to English, we're asking "Is Downloadstatusvariable not true, and is the downloaded file not available?"

Recommend you read more about conditional operators @ http://ant.apache.org/manual/Tasks/conditions.html

Hope that helps.