2014-10-30 37 views
0

我有以下脚本:从另一个目标调用Ant目标与<groovy>

<target name="query"> 
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="libraries"/> 

    <groovy> 
    import groovy.sql.Sql 

    def sql = Sql.newInstance("jdbc:oracle:thin:@mydomain.com:1521:alias", "test", "test", "oracle.jdbc.pool.OracleDataSource") 

    List productNames = sql.rows("SELECT name from PRODUCT") 

    //println(productNames.count) 

    productNames.each { 
     println it["name"] 
     // HOW TO INVOKE ANT TARGET TASK HERE? TARGET TASK WILL USE it["name"] VALUE 
    } 

    properties."productNames" = productNames 
    </groovy> 
</target> 

<target name="result" depends="query"> 
    <echo message="Row count: ${productNames}"/> 
</target> 

我想从“查询”目标调用另一个Ant目标。尤其是在productNames循环中,就像上面的注释一样。

你有什么想法该怎么做?

回答

2

中有<groovy>范围(see the documentation for more details),更具体地有ant对象,它是的AntBuildersee the api here)的实例中,与该对象可以调用getProject()方法获取的org.apache.tools.ant.Project和与该实例一些绑定对象Project您可以使用executeTarget(java.lang.String targetName)方法执行通过其名称的不同目标。所有在一起的样子:ant.getProject().executeTarget("yourTargetName")并在代码:

<target name="query"> 
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="libraries"/> 
     <groovy> 
      import groovy.sql.Sql 

      def sql = Sql.newInstance("jdbc:oracle:thin:@mydomain.com:1521:alias", "test", "test", "oracle.jdbc.pool.OracleDataSource") 

      List productNames = sql.rows("SELECT name from PRODUCT") 

      //println(productNames.count) 

      productNames.each { 
       println it["name"] 
       ant.getProject().executeTarget("yourTargetName") 
      } 

      properties."productNames" = productNames 
     </groovy> 
</target> 

编辑基于评论:

将参数传递给蚂蚁调用它通过org.apache.tools.ant.Project方法是不可能的,但有另一种方式来做到这一点使用antantcall任务通过AntBuilder,使用antcall但它不是内<groovy>支持,如果你尝试使用它,你将收到此错误信息:

antcall not supported within AntBuilder, consider using 'ant.project.executeTarget('targetName')' instead 

所以你必须使用ant任务。例如,如果您有遵循Ant目标与参数在build.xml

<target name="targetTest"> 
    <echo message="param1=${param1}"/> 
</target> 

您可以从<groovy>调用它传递一个参数是这样的:

<target name="targetSample"> 
    <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="groovyLibs"/> 
     <groovy> 
     ant.ant(antfile:'build.xml'){ // you antfile name 
      target(name:'targetTest') // your targetName 
      property(name:'param1',value:'theParamValue') // your params name and values 
     } 
     <groovy> 
</target> 

如果您执行此<groovy>对象例ant targetSampe您将获得:

targetTest: 
    [echo] param1=theParamValue 

BUILD SUCCESSFUL 
Total time: 0 seconds 

希望这有助于

+0

感谢提示。你知道我怎么可以在executeTarget方法中将参数添加到“yourTargetName”任务中?我没有看到任何额外的参数。 – bontade 2014-10-31 11:12:38

+1

我会更新我的答案以适应您的新要求':)' – albciff 2014-11-04 09:48:28

相关问题