You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@ant.apache.org by Ashutosh Kumar <as...@ionidea.com> on 2004/08/25 17:28:24 UTC

calling ant from java program

How can I call a ant task from java program?
Regds
Ashutosh

Re: calling ant from java program

Posted by "mail.laconiadatasystems.com" <we...@laconiadatasystems.com>.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html
runtime.GetRuntime().exec(String cmd)
but then again you already knew that .. right ??
-Martin
----- Original Message ----- 
From: "Ashutosh Kumar" <as...@ionidea.com>
To: <us...@ant.apache.org>
Sent: Wednesday, August 25, 2004 11:28 AM
Subject: calling ant from java program


> How can I call a ant task from java program?
> Regds
> Ashutosh
> 

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
I am trying to execute a Ant program  It works fine in stand alone , but
when integarted with swing GUI it does not work.What may be the
reason.??

ClientHandler t = new ClientHandler();
         ProgramMain programMain=new ProgramMain( t);
             try {
              programMain.executeBuild();
             }
             catch (Exception ex) {
               ex.printStackTrace() ;
             }
             catch (Throwable ex) {
               ex.printStackTrace();

-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Thursday, August 26, 2004 7:47 PM
To: Ant Users List
Subject: Re: calling ant from java program

Ah, that explains many things !
I thought you wanted to call build.xml's targets...

Anyway, according to your previous post, the error message you got was
related to a "name" attribute, that couldn't be set for some object.
Check that all the "setName" methods you call actually work, ie that
"name" attributes exist for each "setName"-ed objects, as it seems to be
a javabean reflection problem.

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
I have wriiten few ant tasks in java. And executing them through
project.execute. But it hangs some where between tasks and goes from one
task to another only on pressing control C.
Regds
Ashutosh 

-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Thursday, August 26, 2004 7:47 PM
To: Ant Users List
Subject: Re: calling ant from java program

Ah, that explains many things !
I thought you wanted to call build.xml's targets...

Anyway, according to your previous post, the error message you got was
related to a "name" attribute, that couldn't be set for some object.
Check that all the "setName" methods you call actually work, ie that
"name" attributes exist for each "setName"-ed objects, as it seems to be
a javabean reflection problem.

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


Re: calling ant from java program

Posted by Olivier Croisier <Ol...@thales-is.com>.
Ah, that explains many things !
I thought you wanted to call build.xml's targets...

Anyway, according to your previous post, the error message you got was related to a "name" attribute, that couldn't be set for some object.
Check that all the "setName" methods you call actually work, ie that "name" attributes exist for each "setName"-ed objects, as it seems to be a javabean reflection problem.

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
I am trying tt call ant from java program without using build.xml
If build.xml is like this 
<taskdef 
    name="wlconfig" 
     classname="weblogic.ant.taskdefs.management.WLConfig"
             classpath="${pcmjarpath}"/>
<target name="test_config" >  
  <wlserver username="weblogic" 
            password="weblogic" 
            servername="myserver"      
            domainname="pcmdomain" 
            dir="F:/beasp3/user_projects/domains/pcmdomain" 
            host="localhost" 
            port="7001"      
            generateconfig="false"/>

The java program will be like 

         Project project = new Project();
         Class wlConfigtaskDef=null;
          try {
            wlConfigtaskDef=
Class.forName("weblogic.ant.taskdefs.management.WLConfig");

          }
          catch (ClassNotFoundException ex) {

         }

          project.addTaskDefinition("wlconfig",wlConfigtaskDef);
          Target configWeblogic=new Target();
          configWeblogic.setName("test_config");
          Task t= project.createTask("wlserver");
          t.setTaskName("wlserver");
          configWeblogic.addTask(t);
          project.addTarget(configWeblogic);
          project.setNewProperty("username","weblogic");// this
setAttribute 			should be attached to task i.e wlserver,
not to project.  			I am 		not getting API
for it.



 Regds

Ashutosh        

   


-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Thursday, August 26, 2004 1:44 PM
To: Ant Users List
Subject: Re: calling ant from java program

Hi

Hummm I dont see why it doesn't work for you...
Maybe it is a matter of Ant versionning ? I use the latest stable build
(1.6.2 I think).

The error stack trace seems to point out a Sax error, as if the parser
couldn't properly manage some element in the build file. Or it may come
from the ProjectHelper class, that performs some standart initialization
of the Project object.

Again, I would recommend trying with the latest versions (parser, ant,
etc.).
Or, if you can't change, try to see how to initialize the Project
manually, ie without using the ProjectHelper ?

Please keep me informed of your problems/successes !

PS : anyone experiencing similar problems with my class ?

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
I am trying to send email from ant. It sends mail but says failed to
initialize  mime type. Even thoughI receive mail , I does not contain
message, only subject is there.
Regds
Ashutosh

-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Friday, August 27, 2004 2:26 PM
To: Ant Users List
Subject: Re: calling ant from java program

> What may be the reason of  project.executetarget throwing nullpointer
> exception?
> regds

Hi

My first idea was that this exception could get thrown if you call the
executeTarget method with a null argument, but this error seems to be
already managed by the BuildException (@see ant javadoc).

[ executeTarget ]
public void executeTarget(java.lang.String targetName) throws
BuildException
Executes the specified target and any targets it depends on.
Parameters:
	targetName - The name of the target to execute. Must not be
null.
Throws:
	BuildException - if the build failed



So... Another answer would be : your "NullPointerException" occurs if
your Project object is null (java obviously can't call the
"executeTarget" method on a null Project object). Check if your Project
is initialized.

Third clue : the "test_config" string you give as an argument is a valid
String, but its contents may cause an error somewhere in the
executeTarget process, for example if this isn't a valid target name.
Or if the target is only defined as an internal target (no "description"
for it) : I don't know if executeTarget sees them.


best regs


-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


Re: calling ant from java program

Posted by Olivier Croisier <Ol...@thales-is.com>.
> What may be the reason of  project.executetarget throwing nullpointer
> exception?
> regds

Hi

My first idea was that this exception could get thrown if you call the executeTarget method with a null argument, but this error seems to be already managed by the BuildException (@see ant javadoc).

[ executeTarget ]
public void executeTarget(java.lang.String targetName) throws BuildException
Executes the specified target and any targets it depends on.
Parameters:
	targetName - The name of the target to execute. Must not be null.
Throws:
	BuildException - if the build failed



So... Another answer would be : your "NullPointerException" occurs if your Project object is null (java obviously can't call the "executeTarget" method on a null Project object). Check if your Project is initialized.

Third clue : the "test_config" string you give as an argument is a valid String, but its contents may cause an error somewhere in the executeTarget process, for example if this isn't a valid target name.
Or if the target is only defined as an internal target (no "description" for it) : I don't know if executeTarget sees them.


best regs


-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
What may be the reason of  project.executetarget throwing nullpointer
exception?
regds

 public void execute(Project project){
         Class wlConfigtaskDef=null;
          try {
            wlConfigtaskDef=
Class.forName("weblogic.ant.taskdefs.management.WLConfig");
          }
          catch (ClassNotFoundException ex) {
          }
 
         project.addTaskDefinition("wlconfig",wlConfigtaskDef);
           Target configWeblogic=new Target();
           configWeblogic.setName("test_config");
           WLServer wlserver=new WLServer();
           wlserver.setUserName("weblogic");
           wlserver.setPassword("weblogic") ;
           wlserver.setDomainName("testdomain") ;
           wlserver.setServerName("myserver") ;
           wlserver.setDir(new
File("C:/bea/user_projects/domains/testdomain"));
           wlserver.setHost("127.0.0.1") ;
           wlserver.setPort(7001) ;
           wlserver.setGenerateConfig(false) ;
           configWeblogic.addTask(wlserver);
           project.addTarget(configWeblogic);
           project.executeTarget("test_config");

  }

-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Thursday, August 26, 2004 1:44 PM
To: Ant Users List
Subject: Re: calling ant from java program

Hi

Hummm I dont see why it doesn't work for you...
Maybe it is a matter of Ant versionning ? I use the latest stable build
(1.6.2 I think).

The error stack trace seems to point out a Sax error, as if the parser
couldn't properly manage some element in the build file. Or it may come
from the ProjectHelper class, that performs some standart initialization
of the Project object.

Again, I would recommend trying with the latest versions (parser, ant,
etc.).
Or, if you can't change, try to see how to initialize the Project
manually, ie without using the ProjectHelper ?

Please keep me informed of your problems/successes !

PS : anyone experiencing similar problems with my class ?

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


Re: calling ant from java program

Posted by Olivier Croisier <Ol...@thales-is.com>.
Hi

Hummm I dont see why it doesn't work for you...
Maybe it is a matter of Ant versionning ? I use the latest stable build (1.6.2 I think).

The error stack trace seems to point out a Sax error, as if the parser couldn't properly manage some element in the build file. Or it may come from the ProjectHelper class, that performs some standart initialization of the Project object.

Again, I would recommend trying with the latest versions (parser, ant, etc.).
Or, if you can't change, try to see how to initialize the Project manually, ie without using the ProjectHelper ?

Please keep me informed of your problems/successes !

PS : anyone experiencing similar problems with my class ?

-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


RE: calling ant from java program

Posted by Ashutosh Kumar <as...@ionidea.com>.
Oliver
Thanx for ur mail. I tried it, but it gives this error(see below),but it
works fine it I call build.xml from command line. 
Regds

ERROR

Class org.apache.tools.ant.UnknownElement doesn't support the "name"
attribute.
	at
org.apache.tools.ant.IntrospectionHelper.setAttribute(IntrospectionHelpe
r.java:422)
	at
org.apache.tools.ant.ProjectHelper.configure(ProjectHelper.java:306)
	at
org.apache.tools.ant.helper.ProjectHelperImpl$TaskHandler.init(ProjectHe
lperImpl.java:812)
	at
org.apache.tools.ant.helper.ProjectHelperImpl$ProjectHandler.handleTaskd
ef(ProjectHelperImpl.java:534)
	at
org.apache.tools.ant.helper.ProjectHelperImpl$ProjectHandler.startElemen
t(ProjectHelperImpl.java:506)
	at
weblogic.apache.xerces.parsers.AbstractSAXParser.startElement(AbstractSA
XParser.java:419)
	at
weblogic.apache.xerces.parsers.AbstractXMLDocumentParser.emptyElement(Ab
stractXMLDocumentParser.java:221)
	at
weblogic.apache.xerces.impl.XMLNamespaceBinder.emptyElement(XMLNamespace
Binder.java:595)
	at
weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElem
ent(XMLDocumentFragmentScannerImpl.java:747)
	at
weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentConte
ntDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1477)
	at
weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(
XMLDocumentFragmentScannerImpl.java:329)
	at
weblogic.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.j
ava:525)
	at
weblogic.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.j
ava:581)
	at
weblogic.apache.xerces.parsers.XMLParser.parse(XMLParser.java:152)
	at
weblogic.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser
.java:1175)
	at
weblogic.xml.jaxp.WebLogicParser.parse(WebLogicParser.java:67)
	at
weblogic.xml.jaxp.RegistryParser.parse(RegistryParser.java:144)
	at
org.apache.tools.ant.helper.ProjectHelperImpl.parse(ProjectHelperImpl.ja
va:155)
	at
org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:1
17)
	at TestBuild.main(TestBuild.java:16)
Exception in thread "main"

-----Original Message-----
From: Olivier Croisier [mailto:Olivier.Croisier@thales-is.com] 
Sent: Wednesday, August 25, 2004 9:14 PM
To: Ant Users List
Subject: Re: calling ant from java program

> How can I call a ant task from java program?
> Regds
> Ashutosh


Here is some code I wrote.
It allows you to run any ant target from within a regular Java app.
You'll need ant-launcher.jar and ant.jar for this class to compile.
Enjoy :)

BTW, any comment/idea/debug/fix welcome !



import org.apache.tools.ant.*;

import java.io.*;
import java.util.*;

/**
  * <PRE>
  *   This class is designed to call Ant targets from any Java
application.
  *   1. Initialize a new Project by calling "init"
  *   2. Feed Ant with some properties by calling "setProperties"
(optional)
  *   3. Run an Ant target by calling "runTarget"
  *
  *
  *   Example :
  *
  *   try
  *   {
  *       //init
  *       init("/home/me/build.xml","/home/me/");
  *       //properties
  *       HashMap m = new HashMap();
  *       m.put("event", "test");
  *       m.put("subject", "sujet java 3");
  *       m.put("message", "message java 3");
  *       setProperties(m, false);
  *       //run
  *       runTarget("test");
  *   } catch (Exception e) { e.printStackTrace(); }
  * </PRE>
  *
  * @author croisier
  */


public class AntRunner
{
     private Project project;


     /**
      * Initializes a new Ant Project.
      * @param _buildFile The build File to use. If none is provided, it
will be defaulted to "build.xml".
      * @param _baseDir The project's base directory. If none is
provided, will be defaulted to "." (the current directory).
      * @throws Exception Exceptions are self-explanatory (read their
Message)
      */
     public void init(String _buildFile, String _baseDir) throws
Exception
     {
         // Create a new project, and perform some default
initialization
         project = new Project();
         try { project.init(); }
         catch (BuildException e)
             { throw new Exception("The default task list could not be
loaded."); }

         // Set the base directory. If none is given, "." is used.
         if (_baseDir == null) _baseDir=new String(".");
         try { project.setBasedir(_baseDir); }
         catch (BuildException e)
             { throw new Exception("The given basedir doesn't exist, or
isn't a directory."); }

         // Parse the given buildfile. If none is given, "build.xml" is
used.
         if (_buildFile == null) _buildFile=new String("build.xml");
         try { ProjectHelper.getProjectHelper().parse(project, new
File(_buildFile)); }
         catch (BuildException e)
             { throw new Exception("Configuration file "+_buildFile+" is
invalid, or cannot be read."); }
     }



     /**
      * Sets the project's properties.
      * May be called to set project-wide properties, or just before a
target call to set target-related properties only.
      * @param _properties A map containing the properties' name/value
couples
      * @param _overridable If set, the provided properties values may
be overriden by the config file's values
      * @throws Exception Exceptions are self-explanatory (read their
Message)
      */
     public void setProperties(Map _properties, boolean _overridable)
throws Exception
     {
         // Test if the project exists
         if (project == null) throw new Exception("Properties cannot be
set because the project has not been initialized. Please call the 'init'
method first !");

         // Property hashmap is null
         if (_properties == null) throw new Exception("The provided
property map is null.");

         // Loop through the property map
         Set propertyNames = _properties.keySet();
         Iterator iter = propertyNames.iterator();
         while (iter.hasNext())
         {
             // Get the property's name and value
             String propertyName =  (String) iter.next();
             String propertyValue = (String)
_properties.get(propertyName);
             if (propertyValue == null) continue;

             // Set the properties
             if (_overridable) project.setProperty(propertyName,
propertyValue);
             else project.setUserProperty(propertyName, propertyValue);
         }
     }



      /**
      * Runs the given Target.
      * @param _target The name of the target to run. If null, the
project's default target will be used.
      * @throws Exception Exceptions are self-explanatory (read their
Message)
      */
     public void runTarget(String _target) throws Exception
     {
         // Test if the project exists
         if (project == null) throw new Exception("No target can be
launched because the project has not been initialized. Please call the
'init' method first !");

         // If no target is specified, run the default one.
         if (_target == null) _target = project.getDefaultTarget();

         // Run the target
         try { project.executeTarget(_target);  }
         catch (BuildException e)
         { throw new Exception(e.getMessage()); }
     }

}






-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


Re: calling ant from java program

Posted by Olivier Croisier <Ol...@thales-is.com>.
> How can I call a ant task from java program?
> Regds
> Ashutosh


Here is some code I wrote.
It allows you to run any ant target from within a regular Java app.
You'll need ant-launcher.jar and ant.jar for this class to compile.
Enjoy :)

BTW, any comment/idea/debug/fix welcome !



import org.apache.tools.ant.*;

import java.io.*;
import java.util.*;

/**
  * <PRE>
  *   This class is designed to call Ant targets from any Java application.
  *   1. Initialize a new Project by calling "init"
  *   2. Feed Ant with some properties by calling "setProperties" (optional)
  *   3. Run an Ant target by calling "runTarget"
  *
  *
  *   Example :
  *
  *   try
  *   {
  *       //init
  *       init("/home/me/build.xml","/home/me/");
  *       //properties
  *       HashMap m = new HashMap();
  *       m.put("event", "test");
  *       m.put("subject", "sujet java 3");
  *       m.put("message", "message java 3");
  *       setProperties(m, false);
  *       //run
  *       runTarget("test");
  *   } catch (Exception e) { e.printStackTrace(); }
  * </PRE>
  *
  * @author croisier
  */


public class AntRunner
{
     private Project project;


     /**
      * Initializes a new Ant Project.
      * @param _buildFile The build File to use. If none is provided, it will be defaulted to "build.xml".
      * @param _baseDir The project's base directory. If none is provided, will be defaulted to "." (the current directory).
      * @throws Exception Exceptions are self-explanatory (read their Message)
      */
     public void init(String _buildFile, String _baseDir) throws Exception
     {
         // Create a new project, and perform some default initialization
         project = new Project();
         try { project.init(); }
         catch (BuildException e)
             { throw new Exception("The default task list could not be loaded."); }

         // Set the base directory. If none is given, "." is used.
         if (_baseDir == null) _baseDir=new String(".");
         try { project.setBasedir(_baseDir); }
         catch (BuildException e)
             { throw new Exception("The given basedir doesn't exist, or isn't a directory."); }

         // Parse the given buildfile. If none is given, "build.xml" is used.
         if (_buildFile == null) _buildFile=new String("build.xml");
         try { ProjectHelper.getProjectHelper().parse(project, new File(_buildFile)); }
         catch (BuildException e)
             { throw new Exception("Configuration file "+_buildFile+" is invalid, or cannot be read."); }
     }



     /**
      * Sets the project's properties.
      * May be called to set project-wide properties, or just before a target call to set target-related properties only.
      * @param _properties A map containing the properties' name/value couples
      * @param _overridable If set, the provided properties values may be overriden by the config file's values
      * @throws Exception Exceptions are self-explanatory (read their Message)
      */
     public void setProperties(Map _properties, boolean _overridable) throws Exception
     {
         // Test if the project exists
         if (project == null) throw new Exception("Properties cannot be set because the project has not been initialized. Please call the 'init' method first !");

         // Property hashmap is null
         if (_properties == null) throw new Exception("The provided property map is null.");

         // Loop through the property map
         Set propertyNames = _properties.keySet();
         Iterator iter = propertyNames.iterator();
         while (iter.hasNext())
         {
             // Get the property's name and value
             String propertyName =  (String) iter.next();
             String propertyValue = (String) _properties.get(propertyName);
             if (propertyValue == null) continue;

             // Set the properties
             if (_overridable) project.setProperty(propertyName, propertyValue);
             else project.setUserProperty(propertyName, propertyValue);
         }
     }



      /**
      * Runs the given Target.
      * @param _target The name of the target to run. If null, the project's default target will be used.
      * @throws Exception Exceptions are self-explanatory (read their Message)
      */
     public void runTarget(String _target) throws Exception
     {
         // Test if the project exists
         if (project == null) throw new Exception("No target can be launched because the project has not been initialized. Please call the 'init' method first !");

         // If no target is specified, run the default one.
         if (_target == null) _target = project.getDefaultTarget();

         // Run the target
         try { project.executeTarget(_target);  }
         catch (BuildException e)
         { throw new Exception(e.getMessage()); }
     }

}






-- 
CROISIER Olivier
Software Engineer
Thales IS - ANS
olivier.croisier@thales-is.com

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org