2.17 Assignment #2: Implement a Mini Ant

due: Monday, Oct 10

The following is a basic implementation for a subset of Ant. Extend the program to cover more features, and provide it with a test XML file that employs all the implemented features.

<..SampleAnt.java..>
 import java.io.File;
 import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 import org.xml.sax.Attributes;
 import org.xml.sax.XMLReader;
 import org.xml.sax.helpers.DefaultHandler;
 
 class SampleAnt {
   static public void main(String[] args) throws Exception {
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser = factory.newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler( new AntContentHandler() );
     xmlReader.parse( new File(args[0]).toURL().toString() );
 } }
 class AntContentHandler extends DefaultHandler {
 
     String basedir;
     String todir;
 
     public void startElement(String uri,
                              String localName,
                              String qName,
                          Attributes atts      ){
      if( qName.equals( "project" ) ){
          basedir = atts.getValue( "basedir" );
      } else if( qName.equals( "mkdir" ) ){
          String dir = atts.getValue( "dir" );
          dir = basedir + "/" + dir;
          String command = "mkdir " + dir;
 
          try{
             Runtime.getRuntime().exec( command );
          } catch ( Exception e ){ System.err.println( "--- Error ---" ); }
      } else if( qName.equals( "move" ) ){
         todir = atts.getValue( "todir" );
         todir =  basedir + "/" + todir;
 
      } else if( qName.equals( "fileset" ) ){
          String file = atts.getValue( "file" );
          file =  basedir + "/" + file;
          String command = "mv " + file + " " + todir + "/." ;
 
          try{
             Runtime.getRuntime().exec( command );
          } catch ( Exception e ){ System.err.println( "--- Error ---" ); }
      } else if( qName.equals( "echo" ) ){
         String mssg = atts.getValue( "message" );
         System.out.println( mssg );
      }
     }
 }
 
-_-_-

[a fancier variant of the program: literate view, plain code]