Apache Ant – String to uppercase / lowercase using ScriptDef

In Apache Ant, we can define custom task using MacroDef.

 

Other than that, Apache Ant is now shipped with a Javascript engine so we could use ScriptDef to define our own task in Javascript. The following example defines two tasks converting a string to uppercase and lowercase.

<project name="switch-case" default="run" basedir="./">

  <!-- To upper case -->
  <scriptdef language="javascript" name="upper">
    <attribute name="string" /> 
    <attribute name="to" />
    project.setProperty(attributes.get("to"),attributes.get("string").toUpperCase());
  </scriptdef>

  <!-- To lower case -->
  <scriptdef language="javascript" name="lower">
    <attribute name="string" /> 
    <attribute name="to" />
    project.setProperty(attributes.get("to"),attributes.get("string").toLowerCase());
  </scriptdef>

  <target name="run">
    <property name="input" value="HeLlo wORld!" />
    <upper string="${input}" to="upper" />
    <lower string="${input}" to="lower" />
    <echo message="input: ${input}" />
    <echo message="upper: ${upper}" />
    <echo message="lower: ${lower}" />
  </target>

</project>

 

Result:

C:\Workspaces\switch-case> ant
Buildfile: C:\Workspaces\switch-case\build.xml

run:
     [echo] input: HeLlo wORld!
     [echo] upper: HELLO WORLD!
     [echo] lower: hello world!

BUILD SUCCESSFUL
Total time: 0 seconds

 

Done =)

Reference:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s