Archive for May, 2008

Code to read an Xml file in DOM and SAX, respectively.

May 27, 2008

The Simple API for XML (SAX)is available with the Java API for XML Processing (JAXP). Along with the Document Object Model, SAX is one of two common ways to write software that accesses XML data
DOM and SAX can either be a validating or a non validating parser.
    A validating parser checks the XML file against the rules imposed by DTD or XML Schema.
    A non validating parser doesn’t validate the XML file against a DTD or XML Schema.
Both Validating and non validating parser checks for the well formedness of the xml document
DOM: DOM will read the entire XML file and keep it in the memory as a tree. I wouldnt recomend DOM to be used where you are parsing realy huge XML files or XML Streams. The API is easier than SAX.. but what the heck. Generally as a rule of thumb use DOM when you want to manipulate the document, traverse the document back and forth and when they are small XML files

File file = new File(“C://TestXml.xml”);
//hook up your file here… this is a bad way to do it. Specify the path in a properties file and then  read it from there. Can you make sure your code runs the same on Unix and Windows ?

   try {
    DocumentBuilder builder =
   DocumentBuilderFactory.newInstance().newDocumentBuilder();
//rings bells ? Factory design pattern…
    Document doc = builder.parse(file); // this is what will hold a handle to
all the elements in the tree.

     NodeList nodes = doc.getElementsByTagName(“person”); //the tag whose
subtags you want to read

      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        NodeList title = element.getElementsByTagName(“firstname”);
//the sub tag
        Element line = (Element) title.item(0);
     }

You can loop in this manner and walk throught the nodes available
SAX
Generally (yeah, am taking my arse to a safer stand :D), use SAX where there are no structural modification and they are huge XML files

Pretty obvious :

  XMLReader parser =
XMLReaderFactory.createXMLReader(“org.apache.xerces.parsers.SAXParser”);
 org.xml.sax.ContentHandler handler = new SaxParserClassName();
//your class name
  parser.setContentHandler(handler);   
  InputStream in = connection.getInputStream();
  InputSource source = new InputSource(in);
  parser.parse(source);
  //parser.parse(new InputSource(“C://TestXml.xml”)); either ways !!

The comments that appear below a line, are meant for that line, below which the comments appear. The Formatting is screwing up my effort. Aiway, I think the one who is looking for help will be able to figure out what I am trying to say.

Second

May 19, 2008

 

There is a plant in a pool. The circumference of the plant doubles everyday. It covers the entire pool in 20 days. In how many days does it cover half the area of the pool it is in ?

 

Obviously 19 days ! :p

Puzzles

May 19, 2008

One of the most interesting puzzles I came across.
There is a container of water of 1000 litres.
there are two other containers available. One is 5 litres and the other is 3 litres.
I want to measure exactly 4 litres. How do I do it?

Think about it, interesting…

 

Container A = 5 litres, Container B= 3 litres
First, fetch water in the 5 litres container and empty it in Container B. You are left with 2 litres in container A.
Empty the container B and pour 2 litres from Container A into B.
So now, you have an empty container A, and a container B with 2 litres in it.
Now fetch water in container A again. It has 5 litres. Fill the container B with 1 litre of water ( because it already has two litres). Guess what,
you now have your container A with 4 litres of water.
Smart… aint it.
🙂

Why should I believe in God ?

May 19, 2008

All if this is really not out of frustration, but with deligient
thinking and tons of reasoning.
Of late I have really started to ponder if there was any God
actually.

Including the millions of Gods that an Indian traditionally had,
added along with the increased number of Them, the intruders added
(forced?) onto the masses.

May be I have been thinkinh way too much about this because I really
do not see any thing happening or moving BECAUSE of God. I think
after applying certain amount of limited logic and reasoning that can
come outta my head. There are only 2 reasons why a person would
believe(or forced to) in God. One Fear of death, and being punished
for sins, Two : when logic ceases to exist ( which really happens
when we think as to : Where did this Universe come from ? who could
have designed this human body, The perfect sexual reproductive
system , digestive system…. (Although even this is not with
perfection, if we assume that God is supposed to be perfect)).
An average person when going through a low phase in life, would
generally tend to turn towards the divine beings for some help, as if
some miracle would happen. But, nothing really happens, in reality.
We have been crying for ages, thousands of years, yet nothing has
improved the fate of an average person. ( including the Indians in
the Noo Yawrk)

taking the logic a little further.
There would be two schools of thought generally on this, 1) that God
sent you to this world to perfect yourself and win over situations
and better ourself and equip your soul with various experiences.

my question: if there was any God, wherever in the skies, then why
would he put me in trouble. At the expense of my PRESENT being pissed
at. and then they say: God really wouldnt put you in shit from which
you yourself cannot come out. If I was actually to be the child of
God then, being almighty, being all powerfull and having magical
capabilities, why will he put me in shit at all ?(that too when God
already knows that I am gonna make it out of it). and think of it, If
I am actually gonna come out of this on myself, then Why pray ??

then the 2nd most famous Myth about life is 2) That, whatever you are
facing as of now is the result of your past deeds (including your
previous birth, yes, Indians knew the reincarnation theory ages ago
just that the new world is starting to accept it after some time).

I mean, this is crazy philosophy being breathed into humanity. If I
had to bear the expenses of my past deeds (which means that a person
is passing thru a low phase in life), then where exactly would God
come in to the picture and help me, becasue the cause and affect has
been already determined!!!
Do good. bcos God is watching an he will fry u in oil for bad
deeds. ??

there is no substantial evidence that God must have put, in the head
of great inventors that things have to be invented so that a man
could have a comfortable life. All of the greatest and the most
creative inventions have been done out of the sheer necessity felt
for them including the invention of Language!

“I do not believe in a God which can see a widow weep and a child cry
with hunger – Swami Vivekanada. “
No one really sees any God coming down and helping His children who
have been whipped with the lashes of poverty, for people for whom
having one Square meal is a celebration, being alive and being able
to breathe is a moment that people cherish.People still suffering
with Physical ailments.the best way to know pain, is to go through
it, i suppose/
Suffering.hunger/poverty have become the order of every breath for
an avergae Indian( there are a few who will join the BPO and simulate
themselves into being able yap like the “Dudes”) and feel elevated
and pass nasty looks, while travelling in the company cars, to people
standing in the hordes waiting for the public transport.
… there is s much more to it.

I would love to know what the people who share a similar passion
feel/think about such an issue.
or is it that we ( as in the general humanity) have accepted
ourselves to be loosers in some corner of the heart of hearts within
us?

When will I go to the US

May 15, 2008

Its been 4 years, since I am slogging being an Software Engineer. Worked with the smallest of companies and biggest of name. I dont grovel and give it back in the face. I think thats why I have not been able to go to the US so far. Sounds crazy, doesnt it. I too wanna go there and earn heaps of money. I am darn sure I am better than 60% of Indians who get a H1B visa.
Yet, the divine will doesnt let me go there. My current company, that I joined, promised a h1 and now these guys have denied it. Duh uh. …… and to top it.. two junior first class ass licking fellas are being sent there. Talk about “mysore” ?
When am I gonna get there ?

JSP Exception handling

May 15, 2008

I keep forgetting this, so I thought Id make it easier for myself and other schizophrenics like me. Huh 🙂
To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.

Form.html – Display a Form to the user to enter his or her age.
FormHandler.jsp – A JSP Page which receives this value and prints it on the user screen.
ExceptionHandler.jsp – An exception handler JSP page which is actually an error page to which control will be passed when an exception is thrown.
i. Form.html
Create a new Form.html page.

<html>
<body>

<!– HTML Form –>
<form action=”FormHandler.jsp” method=”post”>
Enter your age ( in years ) :
<input type=”text” name=”age” />
<input type=”submit” value=”Submit” />
</form>

</body>
</html>

Explanation
Form.html page simply displays a single input field Form to the user to enter his age in months (Yes, I calculate it in months.. innovative ha). The name of input field where user will enter his/her age is “age”. We will use this input field name “age” in the FormHandler.jsp page to receive it’s value.

ii. FormHandler.jsp
Create new FormHandler.jsp page. :

<%@ page errorPage=”ExceptionHandler.jsp” %> <html> <body> <%– Form Handler Code –%> <% int age; age = Integer.parseInt(request.getParameter(“age”)); %> <%– Displaying User Age –%> <p>Your age is : <%= age %> months.</p> </body> </html>

Explanation
Code above is rather simple. Notice the first line, the page directive. It specifies an errorPage ExceptionHandler.jsp, our exception handler JSP page.

<%@ page errorPage=”ExceptionHandler.jsp” %>

Then we declare an int variable “age”. Then using the static method of Integer class we parse the entered value using Integer.parseInt() method. The value is retrieved using request.getParameter() method. The argument to request.getParameter() is the name of Form field whose value we want to retrieve.

<%
int age;

age = Integer.parseInt(request.getParameter(“age”));
%>

If all goes well and user entered an int ( e.g. 666 ) value in the input field then we display that value back to the user.

<p>Your age is : <%= age %> months.</p

Now things can go wrong and exceptional events can occur. For example, if user didn’t enter a value and what if user entered his name ( e.g. “Marshall Mathers”), of String type instead of an integer ?.

These things will be handled by the ExceptionHandler.jsp JSP page.

iii. ExceptionHandler.jsp
Create a new ExceptionHandler.jsp page.

<%@ page isErrorPage=”true” import=”java.io.*” %>
<html>
<head>
<title>Exceptional Even Occurred!</title>
 </head>
<body>

<%– Exception Handler –%>
<font color=”red”>
<%= exception.toString() %><br>
</font>

<%
out.println(“<!–“);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println(“–>”);
%>

</body>
</html>

Explanation
To make a JSP page exception handler ( i.e. errorPage ), you have to specify isErrorPage attribute in the page directive at the top and set it’s value to true.

<%@ page isErrorPage=”true” %>

When a JSP page has been declared an errorPage, it is made available an object with name of “exception” of type java.lang.Throwable. We use different methods of this exception object to display useful information to the user.

<font color=”red”>
<%= exception.toString() %><br>
</font>

 

 We can put the stack trace information for debugging inside HTML comment tags. So that user only sees a useful message and the sysadmin, developers can see the entire story.

<%
out.println(“<!–“);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println(“–>”);
%>

To use the PrintWriter and StringWriter classes you’ll have to import java.io.* package in your JSP page by changing the page directive at the top to :

<%@ page isErrorPage=”true” import=”java.io.*” %>

 

Innovative way for checking if a String is null in java

May 15, 2008

Checking for null in java can be interesting. I will talk about checking null with String.

There are two innovative ways to do this, without having to check for a specific null check.

First :

 

String n = null;
  if("navnith".equalsIgnoreCase(n))
   System.out.println(" got it here ");

and this way

  if(n instanceof String && n.trim().equalsIgnoreCase("navnith") )
 

Not a lot of people know but the instanceof operator will also check for null.

Enjoy.