CustomTags.java
This is the File which defines the Property of the Tag

package com.mugil.custTags;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class CustomTags extends TagSupport  
{
  private static final long serialVersionUID = 1L;
	
  public int doStartTag() throws JspException 
  {		
     StringBuffer SamBuffer = new StringBuffer();
     SamBuffer.append("Sample Message");
		
     try
     {
	pageContext.getOut().write(SamBuffer.toString());
     }
     catch (IOException e)
     {
	e.printStackTrace();
     }
		
  	return EVAL_PAGE;
   }
	
   public int doEndTag() throws JspException 
   {
      return EVAL_PAGE;
   }
}

DisplayName.tld
This xml file creates the Relation between the tag and the property of the tag as defined in the java file.

<?xml version="1.0" encoding="UTF-8"?>
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <shortname>Example TLD</shortname>
  <tag>
    <name>Hello</name>
    <tagclass>com.mugil.custTags.CustomTags</tagclass>
    <bodycontent>empty</bodycontent>
  </tag>
</taglib>

Sample.jsp
JSP File in which the custom tag is Used.

<%@taglib prefix="DisplayName" uri="/WEB-INF/tld/DisplayName.tld"%>
.
.
.
.
<body>
 <h1>
    <DisplayName:Hello/>
 </h1>
</body>
.
.
.

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
  <web-app version="3.0">
   <servlet>
     <servlet-name>TestServlet</servlet-name>
     <servlet-class>com.mugil.custTags.TestServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>TestServlet</servlet-name>
     <url-pattern>/TestServlet/</url-pattern>
   </servlet-mapping>
  </web-app>

Output

OP

c:forEach

 <body>
   <c:forEach var="i" begin="1" end="100">
     <c:out value="${i}"/><br/>
   </c:forEach>
 </body>

Accessing Value in Bean
SampleMenu.java(bean)

  public class SampleMenu
  {
    String name;
  
    public String getName()
    {
      return name;
    }
	
    public void setName(String name)
    {
      this.name = name;
    }
  }

MenuList.java

   List<SampleMenu> arrMenuList = new ArrayList<SampleMenu>();		
   SampleMenu objSampleMenu     = new SampleMenu();

   objSampleMenu.setName("Link1");
   arrMenuList.add(objSampleMenu); 

   objSampleMenu.setName("Link2");
   arrMenuList.add(objSampleMenu);

   objSampleMenu.setName("Link3");
   arrMenuList.add(objSampleMenu);

   request.setAttribute("arrMenuList", arrMenuList);
   RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
   dispatcher.forward(request, response);

Sample.java

 
   <body>
     <c:forEach	var="i" items="${arrMenuList}">
	     <c:out value="${i.name}"/>
     </c:forEach>
   </body>

Output
Link1 Link2 Link3

If Else

 
<c:if test="${user.userGender eq 1}">Male</c:if>
<c:if test="${user.userGender eq 0}">Female</c:if>

(or)

 
  <c:choose>
    <c:when test="${user.userGender eq 1}">Male</c:when>
    <c:otherwise>Female</c:otherwise>
  </c:choose>

Alternative to If Else Statement

 
 <c:out value="${user.userGender eq 1 ? 'Male': 'Female'}"/>

If Else If

<c:choose>
    <c:when test="${empty example1}"> 
        <!-- do stuff -->
    </c:when> 
    <c:otherwise> 
        <c:choose>
            <c:when test="${empty example2}"> 
                <!-- do different stuff -->
            </c:when> 
            <c:otherwise> 
                <!-- do default stuff -->
            </c:otherwise>
        </c:choose>
    </c:otherwise> 
</c:choose>

If Else If

<c:choose>
    <c:when test="${empty example1}">
    </c:when>
    <c:when test="${empty example2}">
    </c:when>
    <c:otherwise>
    </c:otherwise>              
</c:choose>

Passing a Variable from Java to JSP Page By SetAttribute

Sample.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
  request.setAttribute("Name", "Mugil Vannan");
  RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/Sample.jsp");
  dispatcher.forward(request, response);
}

Sample.jsp

  <body>
    <c:out value="${Name}"/>
  </body>

Web.xml

  <servlet>
     <servlet-name>Sample</servlet-name>
     <servlet-class>com.sponsor.infonovum.MenuList</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>Sample</servlet-name>
     <url-pattern>/Sample/</url-pattern>
  </servlet-mapping>

How to remove last element in a array and store it in same Array

 
import java.util.Arrays;

public class SimpleArray 
{
  public static void main(String[] args) 
  {
    String[] arrNames1 = {"Mugil", "Mani", "Vinu", "Shivaji", "Raman"};
    String[] arrNames2 = new String[arrNames1.length-1]; 
		
    for(int i=0;i<arrNames1.length-1;i++)
      arrNames2[i] = arrNames1[i];
		
    arrNames1 = arrNames2.clone();
		
    for (int i = 0; i < arrNames1.length; i++) 
      System.out.println(arrNames1[i]);		
  }
}

Equity financing – from fund raiser point of view
Money without the hassle of repayment or interest.

Advantages to equity financing:

  • Its less risky than a loan because you dont have to pay it back, and its a good option if you cant afford to take on debt.You tap into the investors network, which may add more credibility to your business.
  • Investors take a long-term view, and most don’t expect a return on their investment immediately.
  • You wont have to channel profits into loan repayment.
  • You will have more cash on hand for expanding the business.
  • There’s no requirement to pay back the investment if the business fails.

Disadvantages to equity financing:

  • It may require returns that could be more than the rate you would pay for a bank loan.
  • The investor will require some ownership of your company and a percentage of the profits. You may not want to give up this kind of control.
  • You will have to consult with investors before making big (or even routine) decisions — and you may disagree with your investors.
  • In the case of irreconcilable disagreements with investors, you may need to cash in your portion of the business and allow the investors to run the company without you.
  • It takes time and effort to find the right investor for your company.

Debt financing
Advantages to debt financing:

  • The bank or lending institution (such as the Small Business Administration) has no say in the way you run your company and does not have any ownership in your business.
  • The business relationship ends once the money is paid back.
  • The interest on the loan is tax deductible.
  • Loans can be short term or long term.
  • Principal and interest are known figures you can plan in a budget (provided that you don’t take a variable rate loan).

Disadvantages to debt financing:

  • Money must paid back within a fixed amount of time.
  • If you rely too much on debt and have cash flow problems, you will have trouble paying the loan back.
  • If you carry too much debt you will be seen as “high risk” by potential investors – which will limit your ability to raise capital by equity financing in the future.
  • Debt financing can leave the business vulnerable during hard times when sales take a dip.
  • Debt can make it difficult for a business to grow because of the high cost of repaying the loan.
  • Assets of the business can be held as collateral to the lender. And the owner of the company is often required to personally guarantee repayment of the loan.

Bonds
Businesses often need loans to fund operations, move into new markets, innovate and grow in general. But the amount they need often surpasses what a bank can provide. So another useful way for corporations to raise the necessary funds is to issue bonds to whoever wants to buy them.

When you buy a bond, you’re lending money to the organization that issues it. The company, in return, promises to pay interest payments to you for the length of the loan. How much and how often you get paid interest depends on the terms of the bond. The interest rate, also called the coupon, is typically higher with long-term bonds

F­or you, the lender, a bond is a kind of investment, like a stock. The difference is that stocks aren’t loans. Rather, stocks represent partial ownership in a company, and the returns represent a share in profits. For that reason, stocks are riskier and more volatile — they closely reflect the success of a company. Bonds, on the other hand, often have a fixed interest rate. Some bonds, however, are floating-rate bonds, meaning their interest rates adjust depending on market conditions.Like stocks, bonds can be traded. When someone sells a bond at a price lower than the face value, it’s said to be selling at a discount. If sold at a price higher than the face value, it’s selling at a premium.

Alternative investment
Investments other than Stocks, Bonds and Equity comes under alternative investments.

It includes tangible assets such as precious metals, art, wine, antiques, coins, or stamps and some financial assets such as commodities, private equity, hedge funds, carbon credits, venture capital, forests/timber, film production and financial derivatives.

Difficult to predict the actual cost since it primarily lack a good quality data.They are relatively illiquid. It is very hard to determine its current market value

Dividend
Corporations may pay out part of their earnings as dividends to you and other shareholders as a return on your investment. Share dividends, which are generally paid yearly, are in the form of cash.

Dividend is always calculated on this face value.

Suppose you own 100 shares of XYZ bank. The face value of shares is Rs 10 each. Then the Total face nominal value of your holding is Rs 1000. (This is independent of the purchase value of the shares).

If the dividend declared is 110%, it is calculated on the face value of shares. For example, you will get a dividend of 1100 on your shares. That means, the dividend per share is Rs 11.

Dividend payout ratio
You can calculate a dividend payout ratio by dividing the dividend a company pays per share by the company’s earnings per share.

Dividend yield
If you own dividend-paying shares, you figure the current dividend yield on your investment by dividing the dividend being paid on each share by the share’s current market price. Dividend yield, which increases as the price per share drops and drops as the share price increases, does not tell you what you’re earning based on your original investment or the income you can expect to earn in the future. However, some investors seeking current income or following a particular investment strategy look for high-yielding shares.

How to Calculate Dividend Yield?
Not all of the tools of fundamental analysis work for every investor on every stock. If you are a value investor or looking for dividend income then there are a couple of measurements that are specific to you. For dividend investors, one of the telling metrics is Dividend Yield.

This measurement tells you what percentage return a company pays out to shareholders in the form of dividends. Older, well-established companies tend to payout a higher percentage then do younger companies and their dividend history can be more consistent.

You calculate the Dividend Yield by taking the annual dividend per share and divide by the stock’s price.

Dividend Yield = Annual dividend per share / Stock’s price per share

For example, if a company’s annual dividend is Rs. 1.50 and the stock trades at Rs. 25, the Dividend Yield is 6%. (Rs. 1.50 / Rs. 25 = 0.06)

Dividend usually declared by the companies in % terms to the face value of the share. For Example, Company trading at Rs. 50 with a face value of Rs. 10 per share declares 10% dividend. That means company will pay dividend of Rs. 1 per share to its share holders. Hence in such a case, Dividend Yield is 2% (Rs. 1 / Rs. 50 = 0.02)

The below examples are specific to Junit4

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Basic Test case which Fails

import static org.junit.Assert.*;
import org.junit.Test;

public class Junit1 {	
 @Test
 public void basicTestFail()
 {
  fail("The Test Failed");
 }
}

There is No pass method in JUnit like fail method.

As long as the test doesn’t throw an exception, it passes, unless your @Test annotation specifies an expected exception. I suppose a pass() could throw a special exception that JUnit always interprets as passing, so as to short circuit the test, but that would go against the usual design of tests (i.e. assume success and only fail if an assertion fails) and, if people got the idea that it was preferable to use pass(), it would significantly slow down a large suite of passing tests (due to the overhead of exception creation). Failing tests should not be the norm, so it’s not a big deal if they have that overhead.

Tests to verify the correctness of a program’s behavior.Verifying the correctness of a program’s behaviour by inspecting the content of output statements.Its looking manually for abnormal output.

Example1

StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public static void main(String[] args)
	{
		StringHelper objStringHelper = new StringHelper();
		System.out.println(objStringHelper.wordATrimmer("PABBB"));
	}
	
	public String wordATrimmer(String pWord)
	{
  	   String pTempString = pWord.substring(0, 2);			   
           if(pTempString.contains("A")) return pWord.replace("A", "");		
 	   pTempString = pWord.substring(2);		
	   return pWord;
	}
}

StringHelperTest.java

package com.mugil.junit.tutor;

import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
	@Test
	public void test() 
        {
		StringHelper objStringHelper = new StringHelper();
		String expectedOP            = "MMG";
		String actOP                 = objStringHelper.wordATrimmer("AAMMG");
		
		assertEquals(expectedOP, actOP);
	}
}

@Test comes from org.junit.Test Package
assertEquals – helps in performing String, Boolean and Other Comparison.

As you have seen above StringHelper.java is the actual file that has the function.StringHelperTest.java is the file in which test of the functionality is to be carried out. This java file is created in a new source folder test. By using the assert equals method we are comparing whether the expected Op and actual OP are the same.

@Test annotation at the top of the test method tells the JVM to run this method

assertTrue(boolean)
assertTrue(boolean true) will return true
assertFalse(boolean false) will return true

To make sure the code is behaving the right way we can use asserttrue() and assertfalse() methods.
StringHelper.java

package com.mugil.junit.tutor;

public class StringHelper
{	
	public boolean areFirstTwoandLastTwoStringsSame(String Name)
	{
		if(Name.length() <  2) return false;		
		if(Name.length() == 2) return true;
		
		String firstChars = Name.substring(0, 2);
		String lastChars  = Name.substring(Name.length()-2);
		
		if(firstChars == lastChars)
		  return true;
		else
		  return false;
	}
}

StringHelperTest.java

 package com.mugil.junit.tutor;

import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
  @Test
  public void test() 
  {
    StringHelper objStringHelper = new StringHelper();
    assertTrue(objStringHelper.areFirstTwoandLastTwoStringsSame("AB"));
    assertFalse(objStringHelper.areFirstTwoandLastTwoStringsSame("ABAB"));
  }
}

The above code checks whether First and Last two characters are the same and return true or false based on input to method areFirstTwoandLastTwoStringsSame.

@Before and @After Annotations
The before and after methods are used to run a case before and after the actual test started.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class StringHelperTest 
{
	
  @Before
  public void before()
  {	
    System.out.println("Before Test");
  }
	
  @After
  public void after()
  {	
    System.out.println("After Test");
  }

  @Test
  public void test1() 
  {
    System.out.println("Test1");
  }
	
  @Test
  public void test2() 
  {
    System.out.println("Test2");
  }	
}

The output of the above code would be
Output

Before Test
Test1
After Test
Before Test
Test2
After Test

You can also run a test before and after the class run as below

import org.junit.AfterClass;
import org.junit.BeforeClass;

@BeforeClass
public static void beforeClass()
{	
  System.out.println("Before Test");
}
	
@AfterClass
public static void afterClass()
{	
  System.out.println("After Test");
}

@Test
public void test1() 
{
  StringHelper objStringHelper = new StringHelper(); 
  System.out.println("During Test");
}

Output

Before Test
During Test
After Test

BeforeClass and AfterClass is run only once when object for class is created.Note the static before beforeClass and afterClass methods.

Typical Example for Using before and after methods where object for class created in before method and object assigned null in after method.

public class StringHelperTest 
{	
  StringHelper objStringHelper1;
	
  @Before
  public void before()
  {	
     objStringHelper1 = new StringHelper(); 
  }
	
  @After
  public void afterClass()
  {	
    objStringHelper1 = null;
  }

  @Test
  public void test1() 
  {   
    System.out.println("Test Cases");
  }	
}

How to check expected array is returned in Output

 
import static org.junit.Assert.*;
import org.junit.Test;

public class StringHelperTest 
{
  @Test
  public void test1() 
  {
    int[] arrNums1 = {5,4,3,2,1};
    Arrays.sort(arrNums1);		
    int[] arrNums2 = {1,2,3,4,5};
		
    assertArrayEquals(arrNums1, arrNums2);
  }
}

assertArrayEquals method comes from org.junit.Assert Package

We are going to look for the expected exception is getting thrown or not

Testing for Exception

import java.util.Arrays;
import org.junit.Test;

public class StringHelperTest 
{
  @Test(expected=NullPointerException.class)
  public void test1() 
  {
    int[] arrNums1 = null;
    Arrays.sort(arrNums1);
  }
}

Testing for Performance – How Much time is taken by code block to execute the code.

In the below code we are going to estimate actual time taken by the code block to execute

 public class StringHelperTest 
 {
   @Test(timeout=100)
   public void test1() 
   {
     for (int i = 0; i < 1000000; i++) 
     {
	    int[] arrNumbs = {i-1, i, i+1};
          Arrays.sort(arrNumbs);
     }
   }
}

timeout=100 – is going to tell the code should complete the execution within 100 milliseconds.If it fails I should optimize the code by performance tweaks to boost codes performance.

When ever you deploy website into web server or application server you need to wrap it into WAR file rather than copying files as folder.

Below we will see how to deploy war file into tomcat server.There are two ways to do that.

Method 1
1.You need to export your project as war file.
2.now copy the war file to the tomcat folder.In my case D:\tomcat7\webapps\.
3.After copying the war file to webapps folder you should restart your server to make the folder dispatched in the webapps folder.
4.Now our final step is to make sure what ever we have done in working by typing the local url in browser say if i have copied a war file by name Acme.war I should able to access the folders in project by name http://localhost:8081/Acme/

Method 2
1.In this method you I will use Tomcat manager to deploy the WAR file.
2.If you have used tomcat binary version you need to configure tomcat manager user name and password
as below

  1. Open D:\tomcat7\conf\tomcat-users.xml
  2. Add the below entries in tomcat-users.xml
  3. Now the tomcat manager username and password is set to admin and secret

3.We are ready to go and access the tomcat manager now.

tomcat-users.xml

  <role rolename="manager-gui"/>
  <role rolename="manager-status"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
<user username="tomcat" password="secret" roles="manager-gui,manager-status,manager-script,manager-jmx"/> 

You can see the following browse for WAR option under Deploy Tab

War image

You need to browse for the war file and restart the server.

Posted in WAR.

How to Run a Java file from ANT Script

 <java classname="com.mugil.tutor.Sample">
   <classpath path="test/classes/"></classpath>
 </java>

Where Sample points to Sample.class which we got through compilation and test/classes/ contains the Sample.class file. Below is the whole code in build.xml file

<project name="ANT2" default="copyTarget">
  <target name="copyTarget">
  <mkdir dir="test/classes/"/>
  <javac srcdir="src/com/mugil/tutor/" destdir="test/classes/" includeantruntime="false"></javac>
    <java classname="com.mugil.tutor.Sample">
  	<classpath path="test/classes/"></classpath>
     </java>
   </target>
</project>

How to get Current time in ANT Script

 <project name="default" default="target1">
     <target name="target1">		
	<tstamp>
	   <format property="current.time" pattern="yyyyMMdd" />
	   <format property="archive.name" pattern="'MyArchive_'yyyyMMdd_hh:mmaa'.jar'" />
	</tstamp>
	<echo>${current.time}</echo>
	<echo>${archive.name}</echo>		
     </target>
</project>

ANT Script to concatenate two variables and Create directory based on that

<project name="default" default="target1">
  <property name="mugil.dir" value="D:/Mugilvannan/"/>		
     <target name="target1">		
	<tstamp>
	  <format property="current.time" pattern="yyyyMMdd" />
	  <format property="archive.name" pattern="'MyArchive_'yyyyMMdd_hhmmaa" />
	</tstamp>
	<property name="whole.dir" value="${mugil.dir}${archive.name}"/>
	  <echo>
	    ${whole.dir}
	  </echo>		
	<mkdir dir="${whole.dir}"></mkdir>
     </target>
</project>
Posted in ANT.

Error

warning: ‘includeantruntime’ was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds

Reason
It is caused by a misfeature introduced in Ant 1.8

Include attribute includeantruntime and set it to false as shown below

Solution 1

 <javac .... includeantruntime="false" .../>  

Solution 2
In case if your project contains many build.xml files which one cannot, or prefers not to, edit
Use presetdef add these lines in top of build.xml file

 <presetdef name="javac">
    <javac includeantruntime="false" />
  </presetdef>

If your projects do actually need ant runtime libraries, you can either add them explicitly to your build files OR set includeantruntime=”true”

<javac destdir="out" includeantruntime="true">
  <src path="foo.java" />
  <src path="bar.java" />
</javac>

Now all subsequent javac tasks will essentially inherit includeantruntime=”false”

For working with ant you need to first set the path of the environment variables.I am going to do this in command prompt by executing the following line in command prompt as follows

STEP 1
I should set the Path for Java Directory and for ant bin directory as above.

 C:\Users\Mugil>set PATH=D:\Java\jdk1.6.0_32\bin;D:\Mugil\apache-ant-1.9.0\bin;

STEP 2
Now I should create a build.xml file which the ant looks for deployment as follows
build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="codethataint" default="default target">
 <target name="default target">
  <echo>
   Executing Default Target
  </echo>
 </target>
</project>

STEP 3
To run the ant file use the following line in command prompt as below

 d:\Mugil\staging>ant

In build.xml is a ANT Script that starts with root node project.
Project will have set of Targets
Targets will have set of Tasks

What if I named my build file to some other name other than build.xml say build2.xml
In such case you can use the below command as follows

 d:\Mugil\staging>ant -buildfile 

What if I want to run a different target

build2.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="codethataint" default="default target">
 <target name="default target">
  <echo>
   Executing Default Target
  </echo>
 </target>
 <target name="target 2">
  <echo>
    Target 2 
  </echo>
 </target>
</project>
 d:\Mugil\staging>ant -buildfile  "target 2"

You can enforce dependency in ANT script by using depends keyword as in the following script below

<?xml version="1.0" encoding="UTF-8"?>
<project name="codethataint" default="target2">
 <target name="target1">
  <echo>
   Target 1
  </echo>
 </target>
 <target name="target2" depends="target1">
  <echo>
   Target 2
  </echo>
 </target>
</project>

When you run the ANT script you will see Target 1 and Target 2 displayed on the Screen.Though the default target is target2 since it depends on target1 both are getting displayed.

If there are two targets which depends on each other then circular dependency will occur

<?xml version="1.0" encoding="UTF-8"?>
<project name="codethataint" default="target2">
 <target name="target1" depends="target2">
 .
 .
 <target name="target2" depends="target1">
 .
 .

Creating a Folder using build.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <project name="ANT1" default="makedir"> 
 <property name="build.dir" location="D:\build"/> 
  <target name="makedir">
   <mkdir dir="${build.dir}" /> 
  </target>
 </project>

Before you are making a Folder you need to clean it as below

<?xml version="1.0" encoding="UTF-8"?>
<project name="ANT1" default="makedir"> 
 <property name="build.dir" location="D:\build"/>
 <target name="clean">
  <delete dir="${build.dir}"/>
 </target> 
 <target name="makedir" depends="clean">
  <mkdir dir="${build.dir}" /> 
  <mkdir dir="${build.dir}/classes"/>
 </target>
</project>

Below is a Simple java project which uses an ANT script and creates three folder build.The build contains classes and jar folder.The compiled class files will sit in classes folder and jar files will sit in jar folder.

<?xml version="1.0" encoding="UTF-8"?>
<project name="ANT1" default="makejar" basedir=".">
<property name="src.dir" location="src"/>
<property name="build.dir" location="D:\build"/>
<property name="project.name" value="ANT1"/>
<target name="clean">
 <delete dir="${build.dir}"/>
</target> 
<target name="makedir" depends="clean">  
 <mkdir dir="${build.dir}" />  
 <mkdir dir="${build.dir}/src/classes"/>
</target>
<target name="compile" depends="makedir">
  <javac srcdir="src" destdir="${build.dir}/src/classes" includeantruntime="false"/>
 </target>
<target name="makejar" depends="compile">
  <jar destfile="${build.dir}/jars/${project.name}.jar" basedir="${build.dir}/src/classes" />  
</target>
</project>

Project Java File – Sample.java

package com.mugil.tutor;

public class Sample 
{
  public static void main(String[] args) 
  {
    System.out.println("Its working...!"); 
  }
}

Once you run an ANT script it does the following task as below
1.Target Clean – Deletes the folder build
2.Target makedir – Creates two directory build and Classes
3.Target compile – Compiles code and puts in classes folder as specified in destdir
4.Target makejar – Creates the JAR file as specified in the jar tag

  • You can see in the above code src.dir is given location as src which takes the src folder relative to the folder in which the build.xml exists.
  • In the line above absolute path is used for build.dir as D:\build

Copying folder from one Location to Another

<target name="makecopy">	
  <copy todir="D:/build/web">
   <fileset dir="WebContent">
   </fileset> 
  </copy>
</target>

The above code copies the content in from WebContent folder to D:/build/web

Simple Copying of File from one directory to another

<project name="ANT2" default="copyTarget" basedir=".">
 <target name="copyTarget">
   <copy file="WebContent/index.jsp" tofile="D:/build/mugil/index2.jsp"/>
  </target>
</project>

Above I am copying a file index.jsp into location D:/build/mugil/ and saving it as index2.jsp

If you want to copy the file and Save it in to directory use the below code

 <copy file="WebContent/index.jsp" todir="D:/build/mugil/"/>

If there is no folder then folder will be created before copying file

Excluding certain type of files while copying
Now I want to exclude certain types of files from get copied say XML files.

 <target name="copyTarget">
  <copy todir="D:/build/web">
    <fileset dir="WebContent">
      <exclude name="*.xml"/>
    </fileset> 
  </copy>
 </target>

The above code excludes XML file in current folder from getting copied.Now what if i want the XML files in the sub folder from getting copied

 <target name="copyTarget">
  <copy todir="D:/build/web">
    <fileset dir="WebContent">
      <exclude name="**/*.xml"/>
    </fileset> 
  </copy>
 </target>

** is going to look for files in sub folder and excludes those from getting copied.

How to pack files into Zip

<zip destfile="D:/build/web/zip/Sample.zip">
 <fileset dir="WebContent"/>
</zip>

The above code creates a Zip file with contents in WebContent

Note:
Never hard code version numbers and folder location in build.xml as they are constantly updated over a period of time.You can create a separate file where you can put your version numbers and replace it as properties in build.xml file as shown below

build.properties
appversion=1.0

build.xml

 <project name="ANT2" default="copyTarget">
   <property file="build.properties"/>
     <target name="copyTarget">
   	    <echo>${appversion} </echo>
     </target>
 </project>

OP:1.0

Now I am going to add directory name in build.properties file as below

build.properties
dest.dir=D:\\NewFiles

The above code creates a folder in D drive with name NewFiles

Why Double Backward slash?
If you are not giving double backward slash then it will take absolute path and creates folder in project work space

Is there any other way I define my folder path?
Yes.you can define it by absolute path by using forward slash as below.

build.properties
dest.dir=D:/NewFiles

ANT properties are Immutable
Now consider the below code.

build.properties
appversion=1.1

<project name="ANT2" default="copyTarget">
  <property file="build.properties"/>
  <property name="appversion" value="1.0"/>
  <target name="copyTarget">
     <echo>${appversion} </echo>
  </target>
</project>

In line 2 I am getting the appversion value set to 1.1. Later I am trying to redefine the same property by setting the value of the attribute to 1.0.But if you print the value using echo statement you can see 1.1 getting printed on console

OP:1.1

Hence ANT Properties are immutable.

Now you want to dynamically make changes in build.properties file on fly.

 <project name="ANT2" default="copyTarget">
   <property   file="build.properties"/>
     <propertyfile   file="build.properties"  comment="My properties">
       <entry  key="appversion" value="1.3"/>
     </propertyfile>	
     <target name="copyTarget">
       <echo>${appversion} </echo>
     </target>
 </project>

In build.properties file appversion value is set to 1.1.But by using propertyfile tag i am resetting the value to 1.3.This Change will also be made in the original build.properties file.So next time when you open build.properties you can note the appversion value got changed to 1.3 and time of change as commented text.

Posted in ANT.