Categories
Ant Build Script Uncategorized

Ant Target

Target can be seen as module of tasks in ant configuration file. We can request ant to execute specific target, by passing command line input. Each target may have one or more tasks. Following is sample buildConfig.xml

<?xml version="1.0"?>
   <project name="AntDemo" default="hello">
   <target name="hello">
      <echo>Hello World - Welcome to Apache Ant!</echo>
   </target>
   
  <target name="stopOracle">
		<exec executable="cmd">
			<arg value="/c"/>
			<arg value="net stop OracleServiceORCLDB"/>
		</exec>
   </target>
   
	<target name="startOracle">
		<exec executable="cmd">
			<arg value="/c"/>
			<arg value="net start OracleServiceORCLDB"/>
		</exec>
    </target>
   
   
    <target name="deleteLogs" depends="stopOracle" 
		description="Clean output directories">
      <delete>
         <fileset dir="d:/logs">
            <include name="**/*.class"/>
         </fileset>
      </delete>
	</target>

	<target name="compileSource">
	<javac
    srcdir="D:/Learning/11JAVA XML/1. javax.xml.bind/workspace/01HelloWorld/src"
    destdir="D:/Learning/11JAVA XML/build/classes"/>
	
	<jar destfile="D:/deployModule/lib/util.jar"
			basedir="D:/Learning/11JAVA XML/build/classes"
			includes="*"
	>
	</jar>
	</target>
</project>

Exec as Target : please refer target named “stopOracle” having exec as task tag inside. It contains executable command to stop oracle service. if we pass this as target it will stop oracle databse service named “OracleServiceORCLDB”. Similarly we have “startOracle” to start the oracle database instance service.

Dependent Target : Target “deleteLogs” is having dependency on “stopOracle” target. Hence if we execute “deleteLogs” target, it will first invoke “stopOracle”, then its own tasks are executed.

Multiple Tasks : If we want two or more tasks to be executed together as single module, multiple tasks can be mentioned in single target. Target “compileSource” contains the two tasks compile .java files and also create the jar of compiled classes.

Categories
Ant Build Script Uncategorized

Execute Ant

It is xml based configuration file.

Following is HelloWorld configuration file “buildConfig.xml”. File can have any name. Open command prompt and copy file in current directory.

<?xml version="1.0"?>
   <project name="AntDemo" default="hello">
   <target name="hello">
      <echo>Hello World - Welcome to Apache Ant!</echo>
   </target>
</project>

Execute following Ant command

>ant -buildfile buildConfig.xml hello

As seen in command, we are invoking ant.bat having two command line parameters -buildFile and target to execute in the build file.

In the buildConfig.xml target “hello” is mentioned and invoked. Target “hello” consists of single in-built task echo to print the input message in config file.

It prints output on console by default. Each target is executed & printed on console. Here “hello:” target is executed & printed on console its output that is echo message. In the end it says “BUILD SUCCESSFUL” with return code 0.

Ant has several optional input parameters, that can be seen using following command

cmd>ant -help

Categories
Ant Build Script Uncategorized

Install Ant

  • Download Ant distribution from https://ant.apache.org/bindownload.cgi
  • Check that compatible java version is already installed on local machine & environment variable JAVA_HOME is already set. Following commands can help to check that.
  • Unzip the Ant downloaded distribution package
  • Set environment variable ANT_HOME pointing to base directory of unzipped ant distribution.
  • Add new entry in PATH environment variable, to add path of ant bin directory.
  • To check if ant is successfully installed, open command prompt and type command “ant -version”, it should show installed version of ant.
Categories
Uncategorized

Numbers

/**
 * to demonstrate the number object. Number can store integer or double.
 */

//to create number object by constructor
var valNum = new Number(1.7);
console.log("valNum ::"+valNum);

//Number.EPSILON - smallest interval between to representable number values
console.log("Number.EPSILON value ::"+Number.EPSILON);

//Number.MAX_SAFE_INTEGER - gratest safe integer in JS
console.log("Number.MAX_SAFE_INTEGER value ::"+Number.MAX_SAFE_INTEGER);

//Number.MIN_SAFE_INTEGER - lowest safe integer in JS
console.log("Number.MIN_SAFE_INTEGER value ::"+Number.MIN_SAFE_INTEGER);

//Number.MAX_VALUE - Largest possible positive number value
console.log("Number.MAX_VALUE value ::"+Number.MAX_VALUE);

//Number.MIN_VALUE - Lowest possible positive number value
console.log("Number.MIN_VALUE value ::"+Number.MIN_VALUE);

//Number.NaN - Not a Number value
console.log("Number.NaN value::"+Number.NaN);

//Number.POSITIVE_INFINITY
console.log("Number.POSITIVE_INFINITY value::"+Number.POSITIVE_INFINITY);

//Number.NEGATIVE_INFINITY
console.log("Number.NEGATIVE_INFINITY value::"+Number.NEGATIVE_INFINITY);

//Number.isNaN(value) - to check if passed parameter value is NaN-Not a Number. 
//Any value which is neither integer nor real, is NaN
console.log("null value is ::" + Number.isNaN(null));
console.log("true value is ::" + Number.isNaN(true));
console.log("10.5 value is ::" + Number.isNaN(10.5));

//Number.isFinite(value) - if passed parameter value is finite number, returns true
console.log("is Finite 10 ::" + Number.isFinite(10));
console.log("is Finite INFINITY ::" + Number.isFinite(Number.POSITIVE_INFINITY));

//Number.isInteger(value) - if passed parameter value is integer, returns true
console.log("10.5 is integer ::"+Number.isInteger(10.5));
console.log("11 is integer ::"+Number.isInteger(11));

//Number.isSafeInteger(value) - if passed parameter value is safe integer, returns true
console.log("10.5 is safe integer ::"+Number.isSafeInteger(10.5));
console.log("11 is safe integer ::"+Number.isSafeInteger(11));

//Number.parseFloat(string) - convert passed string to float value
var floatVal = Number.parseFloat("10.7");
floatVal +=1;
console.log("floatVal ::" + floatVal);

//Number.parseInteger(string) - convert passed string to integer value
var integerValue = Number.parseInt("11");
integerValue+=1;
console.log("Integer value ::"+integerValue);

//object.toExponential([fractionDigits]) - to return the exponential representation of number object, considering passed fraction digits to display if any
var numberValue = new Number(3123.456789);
console.log("exponent value ::" + numberValue.toExponential());
console.log("exponent value ::" + numberValue.toExponential(2));
console.log("exponent value ::" + numberValue.toExponential(6));

//object.toFixed([fractionDigits]) - to return fixed value
console.log("Fixed value ::" + numberValue.toFixed());
console.log("Fixed value ::" + numberValue.toFixed(2));
console.log("Fixed value ::" + numberValue.toFixed(6));

//object.toLocaleString() - convert to locale string
console.log("locale string ::" + numberValue.toLocaleString());

//object.toPrecision() - to return the value with significant precision
console.log("precision to 2 ::" + numberValue.toPrecision(2));
console.log("precision to 2 ::" + numberValue.toPrecision(6));

//object.toString() - to return the string equivalent
console.log("toString :: "+numberValue.toString());

//object.valueOf() - to return the primitive equivalent value of object.
var realVal = numberValue.valueOf();
realVal+=1;
console.log("realValue by valueOf ::" + realVal);

//binary numbers
console.log("0b001 is::" + 0b001);
console.log("0b011 is::" + 0b011);

//octal numbers
console.log("0o1230 is::"+0o1230);

//hex numbers
console.log("0x123F is ::"+0x123F);


Output

valNum ::1.7
Number.EPSILON value ::2.220446049250313e-16
Number.MAX_SAFE_INTEGER value ::9007199254740991
Number.MIN_SAFE_INTEGER value ::-9007199254740991
Number.MAX_VALUE value ::1.7976931348623157e+308
Number.MIN_VALUE value ::5e-324
Number.NaN value::NaN
Number.POSITIVE_INFINITY value::Infinity
Number.NEGATIVE_INFINITY value::-Infinity
null value is ::false
true value is ::false
10.5 value is ::false
is Finite 10 ::true
is Finite INFINITY ::false
10.5 is integer ::false
11 is integer ::true
10.5 is safe integer ::false
11 is safe integer ::true
floatVal ::11.7
Integer value ::12
exponent value ::3.123456789e+3
exponent value ::3.12e+3
exponent value ::3.123457e+3
Fixed value ::3123
Fixed value ::3123.46
Fixed value ::3123.456789
locale string ::3,123.457
precision to 2 ::3.1e+3
precision to 2 ::3123.46
toString :: 3123.456789
realValue by valueOf ::3124.456789
0b001 is::1
0b011 is::3
0o1230 is::664
0x123F is ::4671

Categories
Uncategorized

Prototype Pattern

CREATIONAL PATTERN

Prototype pattern deals with encapsulating cloning process. As the name suggests, it is used to create prototypes by cloning, not real objects from scratch. This pattern can be used in situation where creating new object of class from scratch is costly operation, so instead it is cloned from existing objects. For example, for ome process need to prepare List of all account numbers associated with bank and customer are millions. In this case, it is costly to prepare such list object by reading through database, so such list is copied from existing list object.

Account.java

public class Account 
implements Cloneable{
	

	private String accountNo;
	private String mailId;
	private String firstName,lastName;
	
	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getFirstName() {

		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Account(String accountNo, String firstName, String lastName, String mailId) {
		// TODO Auto-generated constructor stub
		this.accountNo=accountNo;
		this.firstName = firstName;
		this.lastName = lastName;
		this.mailId = mailId;
	}

	
}

AccountHolderList.java

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class AccountHolderList implements Cloneable{

	private ArrayList accounts;
	
	public ArrayList getAccountsList(){
		return accounts;
	}
	
	public AccountHolderList() {
		// TODO Auto-generated constructor stub
		accounts = new ArrayList();
	}

	public void loadListFromDatabase(){
		//load accounts data from xml based database
		
		try   
		{  
		//creating a constructor of file class and parsing an XML file  
		File file = new File("src/AccountsDatabase.xml");  
		//an instance of factory that gives a document builder  
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
		//an instance of builder to parse the specified xml file  
		DocumentBuilder db = dbf.newDocumentBuilder();  
		Document doc = db.parse(file);  
		doc.getDocumentElement().normalize();  
		System.out.println("Root element: " + doc.getDocumentElement().getNodeName());  
		NodeList nodeList = doc.getElementsByTagName("Account");  
		// nodeList is not iterable, so we are using for loop  
		for (int itr = 0; itr < nodeList.getLength(); itr++)   
		{  
		Node node = nodeList.item(itr);  
		System.out.println("\nNode Name :" + node.getNodeName());  
		if (node.getNodeType() == Node.ELEMENT_NODE)   
		{  
		Element eElement = (Element) node;
		String accountNo = eElement.getElementsByTagName("accountNo").item(0).getTextContent();
		String firstName = eElement.getElementsByTagName("firstname").item(0).getTextContent();
		String lastName  = eElement.getElementsByTagName("lastname").item(0).getTextContent();
		String mailId = eElement.getElementsByTagName("mailId").item(0).getTextContent();
		System.out.println("accountNo: "+ accountNo);  
		System.out.println("First Name: "+ firstName);  
		System.out.println("Last Name: "+ lastName);  
		System.out.println("mail Id: "+ mailId);  
		Account accountData = new Account(accountNo, firstName, lastName, mailId);
		accounts.add(accountData);
		}  
		}  
		}   
		catch (Exception e)   
		{  
		e.printStackTrace();  
		}  
		System.out.println("Loaded accounts from database ::"+accounts.size());
	}
	
	public Object clone() {
	      Object clone = null;
	      try {
	         clone = super.clone();
	      } catch (CloneNotSupportedException e) {
	         e.printStackTrace();
	      }
	      return clone;
	  }
}

PrototypePatternDemo.java

import java.util.ArrayList;
import java.util.Iterator;

public class PrototypePatternDemo {

	public static AccountHolderList accountHolderList;
	static{
		
		//load accounts from database at time of system initiliazation
		accountHolderList = new AccountHolderList();
		accountHolderList.loadListFromDatabase();
	}
	
	public PrototypePatternDemo() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		
		//clone accounts List for sending mail, instrad of reading from database
		AccountHolderList clonedList = (AccountHolderList)accountHolderList.clone();
		
		ArrayList accList =clonedList.getAccountsList(); 
		Iterator listItr = accList.iterator();
		
		Account acc;
		while(listItr.hasNext()){
			acc = (Account)listItr.next();
			System.out.println("wished Happy New year to ::" + acc.getMailId()); 
		}
		
	}

}

Output

Categories
Uncategorized

Builder Pattern

CREATIONAL PATTERN

As the name suggests, builder pattern is about encapsulating logic for building of complex composite object by composing small, simple objects. Sometimes, every real-world entity cannot be directly created as Class. For example Lunchset.

Item.java


public interface Item {

public String getName();
public String getCost();
	
}

Cola.java


public class Cola implements Item {

	public Cola() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Coca Cola";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "20 INR";
	}

}

Sprite.java


public class Sprite implements Item {

	public Sprite() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Sprite";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "30 INR";
	}

}

ChickenBurger.java


public class ChickenBurger implements Item {

	public ChickenBurger() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Chicken Burger";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "50 INR";
	}

}

VegBurger.java


public class VegBurger implements Item {

	public VegBurger() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Veg Burger";
	}

	@Override
	public String getCost() {
		// TODO Auto-generated method stub
		return "40 INR";
	}

}

LunchSet.java

import java.util.ArrayList;
import java.util.Iterator;

public class LunchSet {

	ArrayList items ;
	
	public LunchSet() {
		// TODO Auto-generated constructor stub
		items  = new ArrayList();
	}

	public void printBills(){
		if(items==null)
		{
			System.out.println("Pls make order, set is empty");
		}
		
		Iterator itr = items.iterator();
		Item item;
		while(itr.hasNext()){
			item = (Item)itr.next();
			System.out.println(item.getName() + ", cost :" + item.getCost());
		}
	}

	public void addItem(Item item){
		items.add(item);
		return;
	}
}

BuilderPatternDemo.java


public class BuilderPatternDemo {

	public BuilderPatternDemo() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//I want Chicken burger and Coke
		LunchSet set1 = new LunchSet();
		set1.addItem(new ChickenBurger());
		set1.addItem(new Cola());
		System.out.println("Here is your set, pls pay bills as below");
		set1.printBills();
		
		
		//I want Veg Burger and Sprite
		LunchSet set2 = new LunchSet();
		set2.addItem(new VegBurger());
		set2.addItem(new Sprite());
		System.out.println("Here is your set, pls pay bills as below");
		set2.printBills();
		
		
		
		
	}

}

Categories
Uncategorized

Factory Pattern

CREATIONAL PATTERN.

Factory pattern deals with encapsulating logic for creation of objects. Suppose in banking system banker want to provide the passbook to new customer. In this case surely passbooks are not created in every branch of bank but manufacturing of passbooks would be carried out by factories & dispatched to branches on request. In this business model, all operations & logistics are managed by factories for passbooks production & branches are totally unaware or not interested to know how factory manage it. In this case if want to modify construction of object, we will have to change only factory class, not other classes like banker or customer

Passbook.java

public class Passbook {

	private String color;
	private int pageSize;
	
	public Passbook(String color, int pageSize) {
		// TODO Auto-generated constructor stub
		this.color = color;
		this.pageSize=pageSize;
	}

	public String getColor() {
		return color;
	}
	public int getPageSize() {
		return pageSize;
	}


}

PassbookFactory.java

import java.util.HashMap;
import java.util.Map;

public class PassbookFactory {
	
	private static Map colorCodeMap;
	private static Map sizeCodeMap;
	
	
	public PassbookFactory() {
		
		if(colorCodeMap==null){
			colorCodeMap = new HashMap();
			colorCodeMap.put(1,"Orange");
			colorCodeMap.put(2,"brown");
			colorCodeMap.put(3,"Gray");
			colorCodeMap.put(4,"Black");
			colorCodeMap.put(5,"White");
		}
		
		if(sizeCodeMap==null){
			sizeCodeMap = new HashMap();
			sizeCodeMap.put("small",50);
			sizeCodeMap.put("medium",100);
			sizeCodeMap.put("large",200);
		}
		
	}

	public Passbook createPassbook(int colorCode, String size){
		
		String requestedColor = colorCodeMap.containsKey(colorCode)?
                                        (String)colorCodeMap.get(colorCode):
                                         (String)colorCodeMap.get(5);
		int requestedPageSize = sizeCodeMap.containsKey(size)
                                        ?(int)sizeCodeMap.get(size)
                                        :(int)sizeCodeMap.get("small");
		Passbook pbook = new Passbook(requestedColor,requestedPageSize);
		
		return pbook;
		
	}
}

Banker.java

public class Banker {

	public Banker() {
		// TODO Auto-generated constructor stub
	}

}

FactoryPatternMain.java

import java.util.Scanner;

public class FactoryPatternMain {

	public FactoryPatternMain() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner inputStream = new Scanner(System.in);
		
		PassbookFactory pbFactory = new PassbookFactory();
		
		System.out.println("enter color code (options : 1,2,3,4,5) :");
		int colorCode = inputStream.nextInt();
		System.out.println("enter passbook size (options : small, medium, large)");
		String passbookSize = inputStream.next().trim();
		
		Passbook passbookGranted = pbFactory.createPassbook(colorCode, passbookSize);
		
		System.out.println("You have been provided passbook which has color ::"+ passbookGranted.getColor()+", with pageSize::"+passbookGranted.getPageSize());
			
		
	}

}

Output

Design a site like this with WordPress.com
Get started