Difference between Maven and Apache Ant

Build tools are programs to manage and automate build process of your application. By build process means compiling source code, linking the packages, bundle them into an executable binary.

Maven and Apache Ant are popular build tools from Apache.

Here are key some key differences in both tools:

Apache Ant             Maven
Ant is flexible and does not impose coding conventions. You need to specify the source of code and the destination.

Maven uses conventions. It knows where your source code is automatically, as long as you follow these conventions. You don’t need to tell Maven where it is.

Ant is procedural. You have to tell Ant exactly what to do; tell it to compile, copy, then compress, etc.

Maven is declarative; All you have to do is create a pom.xml file and put your source in the default directory. Maven will take care of the rest.

Ant doesn’t have a lifecycle.

 

Maven has a lifecycle. You simply call mvn install and a series of sequential steps are executed.

In Ant, you would first have to JUnit JAR file is, then create a classpath that includes the JUnit JAR, then tell Ant where it should look for test source code, write a goal that compiles the test source and then finally execute the unit tests with JUnit.

Maven has intelligence about common project tasks. To run tests, simply execute mvn test, as long as the files are in the default location.

Ant is simply a build tool. 

Maven is more of project management tool.

Apache Ant

Maven

Apache Ant basic tasks

In the previous post, we have learned what is Apache Ant, its features and an example to create simple build file. This post will guide you other basic ant tasks that are frequently used to create and deploy packages.

Property

 Ant allows us to declare properties and assign values that can be used as variables

<property name="property_name" value="property_value"/>

And that can be used using

${property_name}

Ant predefined properties

Property

Description

ant.version

Version of apache ant

ant.java.version

Java version that apache ant is using

ant.home

Home directory where apache is installed

ant.library.dir

Path of ant library files

ant.file

Location of build file

basedir

Base directory of build

Echoing message on screen

<echo message="Version of Apache Ant ${ant.project.name}: ${ant.file}"/>

Define classpath

<path id="classpath">
    <fileset dir="directory_path" includes="*.jar" />
    <fileset dir="directory_path" includes="*.jar" />
</path>

Compiling Java code

<javac srcdir="source_path_of_java_files" classpathref="classpath" destdir="destination_of_compiled_files" />

Creating Jar

<jar jarfile="jar_name.jar" basedir="compiled_files_path" includes="**/*.class" update="true">

Create directory

<mkdir dir="directory_name" />

Delete directory

<delete dir="directory_name" />

Copy directory

<copy todir="directory_path_where_to_copy" overwrite="true">
    <fileset dir="directory_path_to_copy_files">
         <include name="**/*.*" />
     </fileset>
</copy>

Copy files

<copy file="file_to_copy" todir="directory_path_where_to_copy" overwrite="true" />

Delete files

 <delete>
     <fileset dir="directory_path_to_copy_files">
         <include name="file_name_or_wild_card"/>
         <include name="file_name_or_wild_card"/>
    </fileset>
 </delete>

File loading 

<loadfile property="defined_property_name" srcFile="file_to_load_as_string" />

Replace string in file

<replace file="file_path" token="string_to_replace" value="string_value_to_replace_with"></replace>

Set property based on condition

Based on condition property value is set to true or false.

<condition property="property_name_to_set">
     <matches string="string_data" pattern="pattern_to_match_in_string" />
 </condition>

Above code will set property if particular pattern is matched in specified string. Pattern can hold regex expression. You can specified string inline or property that holds the string file data. Detailed explanation is available on official site.

If-else

<if>
   <equals arg1="value" arg2="value"/>
   <then><echo message="if block executed"/></then>
   <else>
         <echo message="else block executed"/>
   </else>
</if>

Like if-else in any other language, based on condition task is performed. Detailed explanation is available on official site.

Call target inside a target

<antcall target="valid_target_name"/>

Add external tasks

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask" classpath="./lib/xmltask.jar" />

Xmltask : Insert data using XPath

<xmltask source="source_file_to_edit" dest="destination_to_save_file">
     <insert path="//*[local-name()='beans'][1]/*[local-name()='bean'][last()]" position="after">
           <![CDATA[
              <import xmlns="http://www.springframework.org/schema/beans" resource="MyData.xml"/>
            ]]>
     </insert>
 </xmltask>
 
 Above command will insert xml-import after the path defined using XPath.

Xmltask : Insert data based on condition using XPath

<xmltask source="source_file_to_edit" dest="destination_to_save_file">
     <copy path="//*[local-name()='beans'][1]/*[local-name()='bean'][@resource='MyData.xml']/@resource" property="ITEM_EXISTS_ALREADY" />
     <insert path="//*[local-name()='beans'][1]/*[local-name()='bean'][last()]" position="after"> position="after" unless="ITEM_EXISTS_ALREADY">
         <![CDATA[
            <import xmlns="http://www.springframework.org/schema/beans" resource="MyData.xml"/>
         ]]>
      </insert>
</xmltask>

The above code will set property ITEM_EXISTS_ALREADY if the attribute resource with value MyData.xml  exists under given XPath. Then insertion will be performed based on the ITEM_EXISTS_PROPERTY.

Xmltask : Remove xml content

<xmltask source="source_file_to_edit" dest="destination_to_save_file">
    <remove path="/beans/bean/import[@resource='MyData.xml']"/>
 </xmltask> 

The above code will remove the import with resource value MyData.xml.

Reference

https://ant.apache.org/

https://www.tutorialspoint.com/ant/index.htm

Apache Ant : Java Build Tool

Apache Ant is a Java library and command-line tool to automate the repetitive tasks and helps to build software. Ant is flexible and does not impose coding conventions. It supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications.

Other than Java applications it can also be used to build non-Java applications like C or C++ applications.

The Apache Ant project is part of the Apache Software Foundation.

Ant Features

  • Command-line tool to automate the repetitive tasks
  • A flexible tool that provides built-in tasks allowing to compile, assemble, test and run Java applications
  • Can develop custom tasks
  • Declaring properties using property element
  • Copying files or directories from one location to other
  • Delete files or directories
  • Edit files and replace/delete some content
  • Conditional tasks

Ant Setup

  • To work with apache ant JDK (Java Development Kit) must have installed on your system.
  • Set JAVA_HOME environment variable.
  • Download Apache Ant from the link.
  • Unzip the downloaded Apache zip and set the ANT_HOME environment variable.
  • To verify the installation use following command
C:\>ant -version
Apache Ant(TM) version 1.9.7 compiled on April 9 2016

Creating simple build file

Apache Ant build file is written in XML. To create a simple build file you need to create a project and at least one target using ‘project’ and ‘target’ element.

Project

<project basedir="." default="build" name="project_name">

name is the name of the project.

default attribute specifies the default target that will be executed when no target is specified with ant command.

basedir attribute defines the path of the directory from where another path will be resolved.

Target

<target depends="init" name="build-project">
   <echo message="any message here to print"/>
</target>

name is the name of target that can be used to refer/run a target.

depends attribute defines the target on which current target depends on. Dependent target will be executed first.

Example

 <project basedir="." default="init" name="project_name">
      <target name="init">
          <echo message="Init target"/>
       </target>
 </project>

Save above snippet as build.xmlTo run this use ant command.

D:\>ant
Buildfile: D:\build.xml
init:
     [echo] Init target
BUILD SUCCESSFUL
Total time: 1 second

When you simply run ant command it searches for the build.xml file and run the default target that is defined in project element.

If your build file is saved with some other name then you can use buildfile option.

 ant -buildfile file_name.xml

 If you want to run specific target then you can use

 ant -buildfiile file_name.xml target_name

Next Tutorial >> Apache Ant Basic Tasks

Schematron

A language for making assertions about the presence or absence of patterns in XML documents. 

Use of Schematron

  • Busines rule validation
  • Data reporting and general validation
  • Quality control and constraints checking
  • Naming and design rule validation

How it works?

 1) Find useful context nodes in the document based on XPath

2) Check to see of some other XPath expressions are true for each of those contexts

3) The report which asserts has failed.

 

Main Elements

 
schematron components

 

1) Schema: Schema of the Schematron

 
<?xml version=“1.0” encoding=“utf-8”?>}}
<sch:schema xmlns=“http://purl.oclc.org/dsdl/schematron”
      xmlns:sch=“http://purl.oclc.org/dsdl/schematron”
      xmlns:sh=“http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader”
      xmlns:ef=“http://www.efatura.gov.tr/envelope-namespace”>

 

2) ns (namespace): Element to provide namespace and prefix

 
<sch:ns uri=“your_schema_url” prefix=“art” />

3) Pattern : section under different rules for a context are defined

 
<sch:pattern name=“Only two paragraph tag”>
  <sch:rule context=“art:html/art:body/art:div[1]”>
     <sch:assert test=“count(//q:p) &lt;=2”>Only two p tags</sch:assert>
  </sch:rule>
 </sch:pattern>
 

4) Rule : context is defined under which assertions are verified

 
<sch:rule context=“art:html/art:body/art:div[1]”>
   <sch:assert test=“count(//q:p) &lt;=2”>Only two p tags</sch:assert>
</sch:rule>
 

5) Assert: show failed asserts

 

<sch:assert test=“count(//q:p) &lt;=2”>Only two p tags</sch:assert>
 

6) Report : show passed rules

 
<sch:report test=“not(count(//q:p) &lt;=2)”>Only two p tags</sch:report>
 

Schematron Implementation

 

There are many implementations for Schematron. Probatron is one of these and below is the link to download the jar file or source code

https://code.google.com/archive/p/schematron/downloads

 
how schematron implementation works
 

Example


Following example will use Probatron.jar to verify business rule of XML.

Xml to test : candidate_doc.xml

 
<artist xmlns=“your_schema_url” id=“123”>
    <body class=“clear”>
       <div>
          <p>
            <t>Adele -Pop Singer</t>
          </p>
          <p>
            <t>Hello</t>
          </p>
          <p>
            <t>Set fire to the rain</t>
          </p>
        </div>
    </body>
</artist>

 

Schematrn doc : schemaron_validation_doc.sch

 

<?
xml version=“1.0” encoding=“utf-8”?>
<sch:schema xmlns=“http://purl.oclc.org/dsdl/schematron”
      xmlns:sch=“http://purl.oclc.org/dsdl/schematron”
      xmlns:sh=“http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader”
      xmlns:ef=“http://www.efatura.gov.tr/envelope-namespace”>
  <sch:ns uri=“your_schema_url” prefix=“art” />
  <sch:pattern name=“Only two paragraph tag”>
     <sch:rule context=“art:html/art:body/art:div[1]”>
        <sch:assert test=“count(//q:p) &lt;=2”>Only two p tags</sch:assert>
     </sch:rule>
  </sch:pattern>
 </sch:schema>

 

Java Code: Driver.java

 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;

import org.probatron.Session;
import org.probatron.ValidationReport;

public class Driver {
 static String fixArg(String arg) {
  // user concession, if no URL scheme assume these are files
  return arg.indexOf(":") == -1 ? "file:" + arg : arg;
 }

 public static void main(String[] args) {
  Session theSession = new Session();
  OutputStream os=null;
  try {
   os = new FileOutputStream("report.xml");
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  }
  String candidate = fixArg( "candidate_doc.xml" );
  theSession.setSchemaDoc( fixArg("schematron_validation_doc.sch" ));
  try {
   ValidationReport vr = theSession.doValidation(candidate);
   byte[] data = vr.reportAsBytes();
   String strData = new String(data);
   vr.streamOut(os); // to print in file
   vr.sreamOut(System.out); // to print on console
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
  System.out.println("Done");
 }
}

 

Output : report.xml

 
<?xml version=“1.0” standalone=“yes”?>
<svrl:schematron-output title=“” schemaVersion=“”      xmlns:svrl=“http://purl.oclc.org/dsdl/svrl”>
<svrl:ns-prefix-in-attribute-values prefix=“q” uri=“your_schema_url”>
</svrl:ns-prefix-in-attribute-values>
  <svrl:failed-assert test=“count(//p) &lt;=2”         location=“/html[1]/body[1]/div[1]” line=“4” col=“22”>
      <svrl:text>Only two p tags</svrl:text>
  </svrl:failed-assert>
</svrl:schematron-output>
 

References:

 

Official WebSite:

Advantages of spring interceptor over servlet filter
Even filters can do the same things that interceptors can but interceptors can do more easily and more elegantly.
 
Interceptors are more coupled to the request/response cycle than filters.
 
Can inject other beans in the interceptor.
 
Can use more advanced mapping patterns (ant-style).
 
You have the target handler object (controller) available, as well as the result ModelAndView object.
 
It is a bean, so you can use AOP with it.

 

 
The main advantage of spring framework HanderInterceptor is – that they can intercept between Controller Handling and View Rendering and they are spring Beans so it is easy to access another spring bean.
Servlet Filter vs Spring Interceptor

Servlet Filter and Spring Interceptors are important concepts in java world. But there is always confusion between both concepts. Both serve almost the same concept but there are differences when to use and for which purpose. 

 

Servlet Filter
Spring Interceptor
A Servlet Filter is used in the web layer only, you can’t use it outside of a web context.
Interceptors can be used anywhere.
For authentication of web pages, you would use a servlet filter.
Security stuff in your business layer or logging/bug tracking (a.k.a.
independent of the web layer) you would use an Interceptor.
For the Login authentication and auditing of incoming requests from web pages, we should use a servlet filter.
While for implementing your business layer logging and auditing and many other along feature we should use an Interceptor.
Filters implement javax.servlet.Filter
 Interceptors implement org.springframework.web.servlet.HandlerInterceptor

 

Further Reading

http://array151.com/blog/servlets/

http://array151.com/blog/servlet-filter/

http://array151.com/blog/spring-interceptors/

http://array151.com/blog/advantages-of-spring-interceptor-over-servlet-filter/

en_USEnglish
en_USEnglish