Friday, May 19, 2006

How to use Ant, Maven2 and Scripting Languages together

I have used Ant tool to organize build process for a long period of time. It's pretty convenient and helps you to organize a lot of useful actions around compilation, packaging, deployment etc.

After some period of time I found that it is very convenient to use "script" task to extend basic functionality of Ant tool or dynamically customize it. For example, Javascript or Beanshell scripting languages are perfect selection for doing this.

The only one thing that Ant doesn't take care of is the project dependency resolution for libraries used within your project. Maven tool is especially designed to solve this problem.

As the result, the following architecture could cover all or the most of possible scenarios for describing build process: Ant + Maven + Some Scripting Language (Beanshell, Javascript, Groovy etc.)

Let me introduce basic steps that help you to solve the problem.


1. Ant tool should be aware of Maven. In order to achieve this, download "Maven Tasks for Ant library" (e.g. maven-artifact-ant-2.x.x-dep.jar) and install it into ${ant.home}/lib directory.


2. Once Maven Tasks for Ant are installed, we can start using them (in project.xml). First of all, describe the namespace for maven tasks:


<project name="myProject" default="run" basedir="."
         xmlns:artifact="antlib:org.apache.maven.artifact.ant">



3. Specify the location of your local Maven repository ("${repository.home}"). Usually it is ${user.home}/.m2, but you can choose any other location. Maven will download dependent libraries and save them inside this repository:

  <property name="repository.home" value="c:/local-maven-repository"/>

  <artifact:localRepository id="local.repository" location="${repository.home}" layout="default"/>



4. Load the Maven project file and assign some id for the project:


  <artifact:pom file="pom.xml" id="maven.project" />


5. Export various classpath variables from the Maven. In the following example we have access to compile-time, run-time and test-time classpath variables:


  <target name="resolve.dependencies">
    <artifact:dependencies pathId="compile.classpath" filesetId="compile.fileset" useScope="compile">
      <pom refid="maven.project"/>
    </artifact:dependencies>

    <artifact:dependencies pathId="runtime.classpath" filesetId="runtime.fileset" useScope="runtime">
      <pom refid="maven.project"/>
    </artifact:dependencies>

    <artifact:dependencies pathId="test.classpath" filesetId="test.fileset" useScope="test">
      <pom refid="maven.project"/>
    </artifact:dependencies>

  </target>



6. Now you can use Ant tasks/targets the same way as before. You don't need to build classpath manually, it will be built dynamically based on the information from "pom.xml" maven file.

You also should be aware of some commonly used properties inside Maven. For example:


${maven.project.build.sourceDirectory} -> src/main/java
${maven.project.build.directory} -> target
${maven.project.build.outputDirectory} -> target/classes
${maven.project.name} - the project name



You can find out other properties here: http://maven.apache.org/maven-model/maven.html.

Let's create basic Ant targets, like clean-compile-jar-run:


  <property name="jar.file" value="${maven.project.build.directory}/${maven.project.name}.jar"/>

  <target name="clean" description="Removes all compiled classes">
    <delete dir="${maven.project.build.directory}"/>
  </target>

   <target name="compile" depends="resolve.dependencies" description="Compiles java sources">
    <mkdir dir="${maven.project.build.outputDirectory}"/>

    <javac destdir="${maven.project.build.outputDirectory}"
           includeAntRuntime="false"
           debug="${debug}"
           optimize="${optimize}"
           deprecation ="${deprecation}">
        <classpath refid="compile.classpath"/>
        <src path="${maven.project.build.sourceDirectory}"/>
    </javac>
  </target>

  <target name="jar" depends="compile" description="Prepare packaging for the project">
    <jar destfile="${jar.file}">
      <fileset dir="${maven.project.build.outputDirectory}"/>
    </jar>
  </target>

  <target name="run" depends="jar">
    <java jar="${jar.file}" fork="true" failonerror="true" maxmemory="128m">
      <classpath>
        <path refid="runtime.classpath"/>
        <pathelement location="${jar.file}""/>
      </classpath>
     </java>
  </target>

  <target name="run.script">
    <script language="beanshell">
      print("Hello, World!");
    </script>
  </target>



7. Your dependencies for the project are expressed in the form of "pom.xml" maven file:

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>your.group.id</groupId>
  <artifactId>your.artifact.id</artifactId>
  <version>your.version</version>

  <name>YourName</name>

  <!-- Here you have to describe all your dependencies. -->
  <dependencies>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.12</version>
    </dependency>

    ...
  </dependencies>

  </repositories>

</project>


By using this approach we can build scripts of any level of complexity without introducing Java compilation at all. Such programs will contain light-weight code, related to implementation only. All heavy-weight parts of the program will be conveniently located in the repository.

59 comments:

Anonymous said...

nice article exactly what i was looking for

valerio said...

you should find this interesting:

http://jroller.com/page/vschiavoni?entry=how_to_use_some_maven2

bye,
valerio

Anonymous said...

nice article exactly what i was looking for in the official documentation

Rahimunisa Noordeen said...

This is a good article. i am using this as a basis to use antlib to integrate ant with maven for dependency management.
i was able to successfully compile my code using maven classpath references, but i am unable to add the runtime libraries in my war file. I am not sure if i have to explicitly create target to copy the runtime.classpath jar files to web-inf/lib,and then war it up.
Any ideas?

Anonymous said...

Interesting article you got here. I'd like to read something more concerning this topic.
BTW check the design I've made myself Female escorts

Anonymous said...

Interesting article you got here. I'd like to read something more concerning that matter. Thanks for posting this info.

Anonymous said...

Pretty nice blog you've got here. Thanks for it. I like such themes and everything connected to them. I would like to read a bit more soon.

Truly yours

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

Organic vitamins said...

This is a smart blog. I mean it. You’ve so much knowledge about this issue, and so much passion. You also understand how to make people rally behind it, obviously from the responses. You’ve got a style right here that’s not too flashy, but makes a statement as large as what you are saying. Great job, indeed.

Tubal Reversal said...

Actually have a very nice blog, I wish I could see everything you have all the time, I'm really entertained by your comments, and best wishes for your blog

Free Classified Ads said...

Thanks for this read mate. Well, this is my first visit to your blog! But I admire the precious time and effort you put into it, especially into interesting articles you share here!

3d ultrasounds said...

I liked the posts and cool layout you have here! I would like to thank you for sharing your experience and the time it took to post!! Two Thumbs up!

Generic Viagra said...

Excellent tool this is what we need all time to make our work easily, it's perfect so I need to know an read a bit more about it.

Cheap wedding dresses said...

Very happy to see your article, I very much to like and agree with your point of view. Thank you for sharing. At the same time,i love best pram very much .Welcome to look at my website and blog articles.Hope we can become good friends, and exchange and to help each other! Thanks!!

Levitra Verdanafil said...

I would love to write and say what a great job you did on this, as you have put a lot of work into it.Unfortunately, I'm not sure how to leave a comment....

doctor ratings and reviews said...

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.

Classified Ads Tamil Nadu said...

I will definitely post a link to this post on my website. I’m positive my followers will find this article really useful.

price per head online said...

Thank you for the post, pretty helpful info.

hosted virtual call center said...

Hey great stuff, thank you for sharing this useful information and i will let know my friends as well.

Anonymous said...

If we glance at the term the idea of really like, with comparison to its an intimate marriage with a different, nevertheless being a sensation that is certainly engendered when you have miltchmonkey a greater romantic relationship with yourself as well -- and even as the a sense of greater unity with the family or perhaps human race * it then develops into far more extra ordinary that anybody is looking to get in your life is usually really like.

Anonymous said...

Multimedia and entertainment features such as FM radio, music and video player, expandable memory up to 8GB, and extended talk time up to 4 hours make the Jupiter B305 truly feature-packed at only P2,990.. north face backpacks The content is designed for an Internet-savvy audience that seeks quality content about specific, narrow and in-depth topics, but quick production time that leverages lower costs. ghd sale Jewelry, regardless of whether fine or costume, is a part of human culture because the earliest occasions. http://www.verynorthface.com Pinterest has, in fact, been so effective for retailers, manyfashion retailersare managing Pinterest accountsin addition to Facebook and Twitter.. ugg It's a free, self-guided event with 38 participating studios, shops and galleries.

Anonymous said...

Forget parking tickets, the government would make a lot more money. ghd boho chic limited edition Go with what you feel the perfect and comfortable for you and which you can carry confidently. buy ghd Lucky for me, this little lady in the drawer keeps my head straight. http://www.verynorthface.com more in the full article here.. http://www.downuggboots.com Fashion Photography: Jessica Stam In Vogue UK November 2010 by Lina Scheynius (Photos) Fashion Photographer Advice вЂ" How to get a photography Agent or Artist rep.

Anonymous said...

It's an online community. http://www.verynorthface.com I shot the first three launches and landings of the space shuttle program, staying at the Days Inn in Cocoa Beach, and listening to Shirl the Girl at the Mousetrap with my bud Hank Morgan. ugg uk The art of preparing yourself for Christmas day categorically defines shoppers into the over-organised extremists and the last minute libertines. ugg 4) Your photo may not contain any trademarks whatsoever. ghd flat iron These photos show the beauty of the landscape and its people..

Anonymous said...

With every year comes new expenses along with the desire to grow the event. ugg canada She says her style comes out of her Caribbean roots and the and cosmopolitan dress of New Yorkers not to mention growing up as one of six fashion-savvy sisters.. north face sale However ,You have to brand yourself in this market. http://www.manyghdhair.com I just like to point out, that while Alannah Hill may be Australian, she isn actually Australia, and our country as a whole can hardly be held responsible for her actions. north face outlet It was one of the French General silky cottons.

Anonymous said...

order viagra buy cheap viagra online from us - buy cheap viagra online us

Anonymous said...

viagra price viagra xkcd - buy viagra online new zealand

Anonymous said...

viagra online without prescription buy viagra online without rx - buy viagra hujagra 2011

Anonymous said...

order soma buy soma online no prescription - what does a soma muscle relaxer look like

Anonymous said...

buy soma buy soma online in texas - soma quotes

Anonymous said...

I truly admired comprehension by causing along with your current kick off! You have a a lot of high quality compound. I will give you assistance to build up websites have sexual intercourse. Like that, receiving these kinds of virtually any appropriate site I believe you will probably record enhanced within just engines like google just like google much like the major search engines.

Anonymous said...

Thanks pal. That has been special hearing

Anonymous said...

buy soma soma online usa - how to buy somatropin

Anonymous said...

generic soma soma bras boston - soma online next day

Anonymous said...

buy tramadol online where to buy tramadol for dogs - tramadol dosage in canine

Anonymous said...

cialis 10mg cialis once daily review - cialis 5 mg best price

Anonymous said...

buy cialis online cialis kidney disease - cialis jokes

Anonymous said...

tramadol generic par 822 tramadol - tramadol purchase online no prescription

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

Hello. And Bye. Thank you very much.

Anonymous said...

cialis online cialis daily or as needed - what does generic cialis look like

Anonymous said...

buy cialis online ordering cialis online usa - generic cialis black 800mg

Anonymous said...

http://buytramadolonlinecool.com/#59473 tramadol 100 mg high - buy tramadol using mastercard

Anonymous said...

buy klonopin online klonopin withdrawal depersonalization - klonopin 2mg dosage

Anonymous said...

learn how to buy tramdadol buy tramadol 50mg net - buy tramadol order cheap tramadol online

Anonymous said...

clonazepam without prescription klonopin withdrawal fever - xanax or klonopin better for anxiety

Anonymous said...

buy tramadol tramadol generic fedex no prescription - tramadol 50 mg price

Anonymous said...

buy tramadol online tramadol addiction lawsuits - cheap tramadol no prescription

Anonymous said...

Youг current artiсle proѵіdes confiгmеd bеneficiаl tο mе
pегsоnally. It’s reallу helрful anԁ уou are cleаrly νeгy well-informeԁ
οf this typе. Yοu ρosѕess
expoѕеd mу оwn sіght for yоu tο numerοus viewѕ on thiѕ
κind of subjeсt along wіth interesting
and гeliable сontent.

my weblog viagra
My page - viagra

Anonymous said...

http://www.integrativeonc.org/adminsio/buyklonopinonline/#use buy clonazepam online pharmacy - dose of klonopin for anxiety

Anonymous said...

soma carisoprodol 5513 dan carisoprodol drug - carisoprodol overnight delivery

Anonymous said...

carisoprodol 350 mg medicine soma carisoprodol - carisoprodol 350 mg information

Anonymous said...

Veilacalk xaikalitag onertaturrito [url=http://uillumaror.com]iziananatt[/url] globiaodowl http://gusannghor.com moimevaopinge

Anonymous said...

4. 'FROM MEDICATION TO MEDITATION': generic cialis cialis,cialis online generic cialis, viagra online cialis price,viagra generic cialis
http://genericcialispricegnf.com#cialis pills http://cialisonlinepillsgkd.com#cialis http://genericviagraonlinejvrg.com#viagra http://buyviagraonlinertvr.com#buy viagra

Anonymous said...

- Register now and benefit from the early bird discount! cialis price generic cialis,cialis online generic cialis, viagra online generic cialis,buy viagra cialis
http://genericcialispricegnf.com#cialis pills http://cialisonlinepillsgkd.com#cialis http://genericviagraonlinejvrg.com#viagra online http://buyviagraonlinertvr.com#buy viagra

Anonymous said...

year. cialis generic cialis,cialis pills cialis, viagra cialis,viagra online generic cialis
http://genericcialispricegnf.com#cialis pills http://cialisonlinepillsgkd.com#cialis online http://genericviagraonlinejvrg.com#generic viagra http://buyviagraonlinertvr.com#buy viagra