Wednesday, August 20, 2008

You weren't meant to have a Boss

"The average MIT graduate wants to work at Google or Microsoft, because it's a recognized brand, it's safe, and they'll get paid a good salary right away. It's the job equivalent of the pizza they had for lunch. The drawbacks will only become apprent later, and then only in a vague sense of malaise.

And founders and early employees of startups, meanwhile, are like the Birkenstock-wearing weirdos of Berkeley: though a tiny minority of the population, they're the ones living as humans are meant to. In an artificial world, only extremists live naturally."

http://www.paulgraham.com/boss.html

Monday, August 11, 2008

XStream : The simple XML Parser

XStream is an xml parsing API implemented in Java. Key things about XStream is that it is very simple, lightweight, easy-to-use and open-source.

Let me show you how to start off with XStream.

Download XStream jar file, and have it in your classpath.

Let's see how to serialize an object into xml using XStream.

We have a class 'Person'
public class Person {
private String name = "";
private String address = "";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}
Here's how we serialize an Object of Class 'Person'


public void writeAsXml() {

Person person = new Person();
person.setName("Bob");
person.setAddress("Georgia");

XStream xStream = new XStream();
try {
FileOutputStream fs = new FileOutputStream("/tmp/person.xml");
xStream.toXML(person, fs);
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

}


The xml output we get looks like this:
<Person>
<name>Bob</name>
<address>Georgia</address>
</Person>

Easy, huh?

Now going on to deserialze Objects from XML,

public void readFromXml() {

XStream xStream = new XStream(new DomDriver());

try {
FileInputStream fin = new FileInputStream("/tmp/person.xml");
Person person = (Person) xStream.fromXML(fin, new Person());
System.out.println("Hello "+person.name+", from "+person.address);
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

}

We can accomplish more complicated stuff using XStream. But for a start I guess this is enough :)

Bookmark

AddThis Social Bookmark Button