Running Ant using Java..

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mjahabarsadiq
    New Member
    • Feb 2007
    • 38

    Running Ant using Java..

    Hi,

    I have written a java code to execute ant targets via Servlet. I have given the code below.

    Code:
    import org.apache.tools.ant.*;
    import org.apache.catalina.ant.*;
    .
    .
    .
    .
    public void antTest()
    {
    	BuildLogger logger = new DefaultLogger();
    	logger.setMessageOutputLevel(Project.MSG_INFO);
    	logger.setOutputPrintStream(System.out);
    	logger.setErrorPrintStream(System.out);
    	logger.setEmacsMode(true);
    
    	ProjectHelper ph = ProjectHelper.getProjectHelper();
    	Project p = new Project();
    	p.addBuildListener(logger);
    	p.init();
    	p.addReference("ant.projectHelper", ph);
    	ph.parse(p, new File(sctx.getRealPath("/")+"bin/build.xml"));
    	p.executeTarget("display");
    }
    The build.xml file is as follows.

    Code:
    <project name="Web Application" default="display" basedir=".">
        <property file="${user.home}/build.properties"/>
    
        <property file="build.properties"/>
    
        <target name="init">
            <tstamp/>
        </target>
    
        <target name="display" description="Deletes the Web Application's war directory and war file">
            <echo message="This line is displaying from ant target ..."/>
        </target>
    
    </project>
    When the method antTest() is invoked, I got the following output.

    Code:
    This line is displaying from ant target ...
    When I executed the build.xml using the command prompt (i.e. using the command "ant -f build.xml display"), I got the following output.

    Code:
    Buildfile: build.xml
    Trying to override old definition of datatype resources
    
    display:
         [echo] This line is displaying from ant target ...
    
    BUILD SUCCESSFUL
    Total time: 0 seconds
    I would like to have the following.

    1) I expect the output from the java code should also display the same lines as in the output from command prompt. Please let me know the way to do so.

    2) I want to log the output of the ant target to a log file when executing from java.

    3) Is there any other way to run ant targets as we are running from the command prompt. That is if we have a string variable having the value "ant -f build.xml display", we could have to make this as the command to execute ant target. Is this possible? If so please let me know the way to implement.
  • mjahabarsadiq
    New Member
    • Feb 2007
    • 38

    #2
    Is anyone having solution for this??

    Comment

    • chaarmann
      Recognized Expert Contributor
      • Nov 2007
      • 785

      #3
      If you want the exact output from Ant as if running it from command line, then why don't you run it from command line through java then?

      Here I wrote a function where you need to pass the command and working directory only and you get back the output from this command as a string result. Then you can save this result to a log file.

      In your case, call it with
      Code:
       
      executeShell("ant -f build.xml display", "c:\\myAntInstallationDirectory\\bin")
      Code:
       
       /////////////////////////////////////////////////////////////////////////////////////////// 
       public static final String executeShell(String command, String dir)
       throws Exception
       {
        Runtime runtime = Runtime.getRuntime();
        String output="";
        try 
        {
         File fileDir = new File(dir);
         Process process = runtime.exec(command, null, fileDir);
         BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        
         // Read the output
         String line = null;
         while ((line = in.readLine()) != null)
         {
          output += line + "\n";
         }
        }
        catch (Exception exception)
        {
         throw new Exception("[EXCEPTION in RuntimeUtils.executeShell()] : output of shell-command '" + command + "' = '" + output + "'. Exception=" + exception);
        }
        
        return output;
       }

      Comment

      • isomania
        New Member
        • Jun 2010
        • 1

        #4
        Hi chaarmann,

        I've tried your solution but instead I got this error:

        [EXCEPTION in RuntimeUtils.ex ecuteShell()] : output of shell-command 'ant -f build.xml display' = ''. Exception=java. io.IOException: Cannot run program "ant" (in directory "X:\build.xml") : CreateProcess error=2, The system cannot find the file specified

        The file is there and it can be run through command line. Any idea?

        Thanks

        Comment

        • mouli82
          New Member
          • Sep 2012
          • 3

          #5
          Try below

          cmd = new String[] { "sh", "-c", "PATH=/ant binaries path","ant -buildfile","You r ant build file args..."}

          p = r4.exec(cmd);

          Comment

          • mouli82
            New Member
            • Sep 2012
            • 3

            #6
            for logs use the Record option to document the Target out put

            Comment

            • mouli82
              New Member
              • Sep 2012
              • 3

              #7
              <target name="ftp_recor d" >
              <echo message="Starte d Recording .."/>

              <record name="C:\App\lo gs\${ftp.user}_ ftp_log.txt" action="start" append="no"/>
              </target>

              Comment

              Working...