Thursday, July 15, 2010

Sample XML parsing

 package sample;  

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import com.sun.org.apache.xpath.internal.XPathAPI;

import java.io.FileNotFoundException;
import java.io.IOException;

public class XMLParser {

private static Element getRootElementFromXML() {
Element xmlRootElm = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(XML_FILE_PATH);
Document doc = builder.parse(is);
xmlRootElm = doc.getDocumentElement();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException :" + e);
} catch (IOException e) {
System.out.println("IOException :" + e);
} catch (SAXException e) {
System.out.println("SAXException :" + e);
} catch (ParserConfigurationException e) {
System.out.println("ParserConfigurationException :" + e);
}
return xmlRootElm;
}

private static Element getXmlElement(Element inRootElement, String inXpath) {
NodeList list = null;
Element element = null;
try {
list = XPathAPI.selectNodeList(inRootElement.getOwnerDocument(), inXpath);
} catch (TransformerException e) {
System.out.println("Unable to read XML : " + e);
}
if (list != null && list.getLength() > 0) {
element = (Element) list.item(0);
}
return element;
}

public static void main(String[] args) {
Element rootElement = getRootElementFromXML();
/**
* below constructed xpath : //country[@name='India']//city[@name='Chennai']
**/
String xPath = "//" + "country" + "[@name='" + "India" + "']//" + "city" +
"[@name='" + "Chennai" + "']";

Element element = getXmlElement(rootElement, xPath);
System.out.println("Code of Chennai : " + element.getAttribute("code"));
}

public static final String XML_FILE_PATH = "./src/sample/Sample.xml";
}



Sample.xml

 <?xml version="1.0" encoding="UTF-8"?>  
<countries>
<country name="India">
<city name="Delhi" code="011"/>
<city name="Mumbai" code="022"/>
<city name="Kolkata" code="033"/>
<city name="Chennai" code="044"/>
</country>
<country name="USA">
<city name="SanFrancisco" code="055"/>
<city name="Newyork" code="066"/>
<city name="Washington" code="077"/>
<city name="Florida" code="088"/>
</country>
<country name="Australia">
<city name="Sydney" code="099"/>
<city name="Melbourne" code="100"/>
<city name="Adelaide" code="111"/>
<city name="Perth" code="222"/>
</country>
</countries>

Friday, June 4, 2010

Factory pattern

Factory Pattern - a type of Creational Pattern. The creational patterns deal with the best way to create instances of objects.

Sample design

 public interface IEquipment {
String getType();
}

public abstract class Equipment implements IEquipment{
public String getNumber() {
return number;
}
protected void setNumber(String number) {
this.number = number;
}
private String number;
}


public class Container extends Equipment{
public Boolean getIsReefer() {
return isReefer;
}
protected void setIsReefer(Boolean isReefer) {
this.isReefer = isReefer;
}
public String getType() {
return "Container";
}

private Boolean isReefer;
}


public class Chassis extends Equipment {
public Boolean getIsWheeled() {
return isWheeled;
}
protected void setWheeled(Boolean isWheeled) {
this.isWheeled = isWheeled;
}
public String getType() {
return "Chassis";
}

private Boolean isWheeled;
}


public class Accessory extends Equipment {
public String getDescription() {
return description;
}
protected void setDescription(String description) {
this.description = description;
}
public String getType() {
return "Accessory";
}

private String description;
}


// Factory producing Equipments
public class EquipmentFactory {
public static IEquipment createEquipment(String inEquipmentType) {
IEquipment equipment = null;
if (CONTAINER.equals(inEquipmentType)) {
equipment = new Container();
} else if (CHASSIS.equals(inEquipmentType)) {
equipment = new Chassis();
} else if (ACCESSORY.equals(inEquipmentType)) {
equipment = new Accessory();
}
return equipment;
}

private static final String CONTAINER = Container.class.getName();
private static final String CHASSIS = Chassis.class.getName();
private static final String ACCESSORY = Accessory.class.getName();
}

Tuesday, July 7, 2009

Stack and Heap in java

Stack in java is used to store methods and local variables or stack variable.
It is useful in threading and exception handling. As per the behavior of stack (LIFO) Last In First Out, the elements in the stack depends on each other.

For example

 void test() { 
int a;
chain();
}

Here while running the above code, first test() method will get invoked. After that chain() will be called..now test() will be in the top of stack memory.
After the execution of chain() only, the test() will finish its execution (as per LIFO).

On the other hand Heap is mainly used to store Objects. Whatever objects (instance variables) that is created is stored in Heap only.

Java uses Pass-by-Value and no pass-by reference

Java uses Pass-by-Value and no pass-by reference

Java does manipulate objects by reference, and all object variables are references.
However, Java doesn't pass method arguments by reference; it passes them by value.
 public void swap1(int var, int var2) { 
int temp = var1;
var1 = var2;
var2 = temp;
}

When swap1() returns, the variables passed as arguments will still hold their original values.
The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well.
 public void swap2(Point arg1, Point arg2) { 
arg1.x = 100;
arg1.y = 100;

Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}

public static void main(String[] args) {
Point pnt1 = new Point(0, 0);
Point pnt2 = new Point(0, 0);
System.Out.printIn("X= " + pnt1.x + " Y=" + pnt1.y);
System.Out.printIn("X= " + pnt2.x + " Y=" + pnt2.y);
}

IF we execute this main() method, we see the following output:
X= 0 Y= 0
X= 0 Y= 0
X= 100 Y= 100
x= 0 y= 0

Sunday, June 28, 2009

Sort a list of Objects based on their names

 List sortSubPanelBasedOnNames(List subPanels) { 
Collections.sort(subPanels, new Comparator() {
public int compare(TestPanel panel1, TestPanel panel2) {
return (panel1.getInspectorName()).compareTo(panel2.getInspectorName());
}
});
return subPanels;
}

Wednesday, May 21, 2008

What are Immutable and Mutable Objects (String vs StringBuffer)

 public static void main(String[] arg) { 
/* String */

String a = "abc";
String b = "def";
String c = "def";

System.out.println(a.hashCode());
a += "xyz";
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
System.out.println(a);

/* StringBuffer */

StringBuffer sb = new StringBuffer("wer");
System.out.println(sb.hashCode());
sb.append("ert");
System.out.println(sb.hashCode());
}


Output:
-------

96354
-1424366089
99333
99333
abcxyz
17523401
17523401

Explanation:
------------

Mutable and Immutable objects :
The objects whose values can be changed in the same address, are Mutable objects.
The objects whose values cannot be changes in the same address, are Immutable objects.

Example : String and StringBuffer

The main difference, String is Immutable whereas StringBuffer is Mutable.
String is Notsynchronized whereas StringBuffer is Synchronized.
String doesnt have an append method whereas StringBuffer has.


Important Note:
In the code above, when a String "def" is assigned to 'b', it is stored at address "99333".
Again, if I assign the same String "def" to "c", it points to the same address "99333".

Wednesday, April 9, 2008

Converting a substring to Integer in C++

#include < iostream >
#include < sstream >
#include < cctype >

int main()
{
std::string s = "dsdhjsahdk dsdjdsaj 36782367 sdjdhak";

int j = 0;
std::stringstream cstr;
cstr << s;
int i = 0;
char ch;

while( cstr >> ch )
{
if( std::isdigit(ch) )
{
cstr.putback(ch);
break;
}

if( ( j = s.find(" ", j) )== std::string::npos )
{
cstr.seekg(-1);
break;
}

cstr.seekg(++j, std::ios::beg);

}

if(cstr)
{
cstr >> i;
}
std::cout << i;

return 0;

}