Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, June 24, 2011

Parsing Multiple XML Tags

How to parse XML with different multiple tags? For instance, I have a root tag element and few child tags with same name. For below is the snippet for the XML I will be providing parsers for
Multiple XML Tags
multiple-tags.xml
<?xml version="1.0" encoding="UTF-8"?>
<rootTag Name="Root">
 <ChildOne activityType="Task">
  <Name>P1</Name>
  <Incoming>0</Incoming>
  <Outgoing>P1P2</Outgoing>
 </ChildOne>
 <ChildOne activityType="Task">
  <Name>P2</Name>
  <Incoming>P1P2</Incoming>
  <Outgoing>P2G1</Outgoing>
 </ChildOne>
 <ChildOne activityType="GatewayParallel">
  <Name>G1</Name>
  <Incoming>P2G1</Incoming>
  <Outgoing>G1P3 G1P4</Outgoing>
 </ChildOne>
 <ChildTwo type="bpmn:SequenceEdge">
  <Name>P1P2</Name>
  <Source>P1</Source>
  <Destination>P2</Destination>
  <Path>P1P2</Path>
 </ChildTwo>
 <ChildTwo type="bpmn:SequenceEdge">
  <Name>P2G1</Name>
  <Source>P2</Source>
  <Destination>G1</Destination>
  <Path></Path>
 </ChildTwo>
 <ChildTwo type="bpmn:SequenceEdge">
  <Name>G1P3</Name>
  <Source>G1</Source>
  <Destination>P3</Destination>
  <Path>P2P3</Path>
 </ChildTwo>
</rootTag>

Monday, March 7, 2011

Difference in two Calendar Dates

There are many ways to calculate the difference between two Calendar dates in Year, Months, weeks or days by simply dividing them with a fixed constant. DateUtil.java below has a method for getting the difference in Days. this method can similarly be modified to get in Weeks, Months or Years.

But some times the challenge is to display the difference in two java.util.Calendar  or java.util.Date in more user friendly manner. Like in format X Years, X months, X weeks, X days. Where X is positive number greater than zero.

Example: If the number of Full Years < 1, the format should be X months, X weeks, X days. If the number of Full Years >= 1 but the number of Full Months < 1, the format should be X Years, X weeks, X days and so on. Values of 0 is not written. Like "2 months, 2 days" rather than "2 months, 0 weeks, 2 days"

Thursday, February 3, 2011

How to read file without locking in Java

In java, we can read or write to a file without acquiring locks to it. These are mostly used for log files. Recently I was tying to mimic the tail command (of Linux) in java and wrote a simple program below.

Using java.io.RandomAccesFile we can read/write to a file without obtaining locks. Let me demonstrate with example step by step how it works.

RandomAccessFile accessFile = new RandomAccessFile(file, "r");

Create an instance of the RandomAccessFile by either passing java.io.File or a path of a file. The second constructor argument is the type of access needed. In this case it is read only "r". If you want to make it read/write pass "rw". Like Buffers of java.nio package, this class also works with the pointers. it reads the bytes and move the pointer as it progresses. The current pointer gives the information about how much of the file have bean read or has to be read.

public void print(OutputStream stream) throws IOException {
    long length = accessFile.length();
    while (accessFile.getFilePointer() < length) {
        stream.write(accessFile.read());
    }
    stream.flush();
}

Tuesday, January 18, 2011

Where to use MAP and where not

Map is a collection object which contains a key - value pair. Key is unique for identification and Value is the actual object itself. For example to store employees backed with their IDs.
  • 001 - Employee One
  • 002 - Employee Two
  • 003 - Employee Three
Point I will be stressing is the uniqueness of the Key in a Map. Keys inside a java.util.Map  will be stored as a java.util.Set no matter what implementation it is. Either java.util.HashMap or java.util.LinkedHashMap (where sequence or retrieval is retained). If we are adding objects to a Map using map.put(key,value) and retrieving using key by map.get(key), then yes we are using the Map.

Let me justify it futher. When using map.put(), map will check if there is any java.util.HashMap.Entry with the key passed. If so then it will replace the value with a new one and returns the previous Value. But the process of checking of unique key is complex. it involves method like key.equals() and key.hashcode(). Imagine if we have 100 objects to be added to a map, this comparison is done that many times irrespective if there is already an entry or not.
So, when we really think that we need to get benefited by the java.util.Set (inside the Map) then yes, usage of Map is encouraged. Many times, we do not want the feature of unique keys, we know that the Map will be populated with unique data but I want to retrieve objects by their keys, for example get Employee object with the help of an employee ID or java.util.Properties would be the best example for retrieval by keys. Here we use map.get() extensively. In this scenario there is no option but to going for Map unless you have written your own framework to retreive objects by key without using a Map.
If we have a scenario where we just use flat iteration over a map where we populate map by unique data or we don't consider uniqueness and we do not use map.get() even. We just iterate over all entries and use the data from both key and value to do some kind of processing then I would not prefer java.util.Map. Yes, there is an alternate which follows.
I would use any simple Collection object like java.util.List of type like EntryData and iterate over it.
            List<EntryData> data = new ArrayList<EntryData>(1);
            data.add(new EntryData("Some key", "Some vallue"));
            for(EntryData entry: data){
                processKey(entry.key);
                processValue(entry.value);
            }

in this way, I am preparing data which has a pair of key and value. But without using a features of map.get(key) method or I would say any feature of java.util.Map. I do not have a best example right now to describe where this could actually be used in real time. But believe me we do need this. I needed this kind of approach recently and figured out that usage of java.util.Map is not always a best practice in terms of performance.

EntryData.java
    private static class EntryData {
        final Object key,value;

        public EntryData(Object key, Object value) {
            this.key= key;
            this.value= value;
        }
    }




Tuesday, November 16, 2010

Java Beans - getters and setters- how you see them

When we talk about Java Beans. Thing comes to the mind is an object having only getters and setters to access and change its instance variables. A POJO. Ever thought why do we use this or are they really useful in your project? Maybe we are using them because its a standard but not a need. Maybe we do need them. Let me dive into its depth.

If my service layer has to transfer some data between data layer and other layers. I would go for a DTO which is a class with private instance variables and respective setter and getters which will change them when needed. Some time I as a question to my self that if I am providing getter and giving the object to the caller and setter which will change the instance variable, then why do I keep it private. Don't you think I should make that object with all public fields without any setters or getters. This will also reduce the lines of code and easy to acess the instance variables.
If this is the case, then why am I providing getXXX() and setXXX (). Is it just that its a standard and I have to follow?

Thursday, September 9, 2010

java.lang.OutOfMemoryError with StringBuilder or StringBuffer

StringBuilder or StringBuffer are used for string manipulations. Yet they fail some times.
Both the final classes are the extension for packaged scoped abstract class named "java.lang.AbstractStringBuilder". These builder/buffer classes holds character array and append or manipulate this char[] each time we perform operations on it. The default char[] size is 16 although this can be specified while creating the object. When append() method is called upon StringBuilder/StringBuffer, the capacity of this char[] is checked if the String/char/any other object can be added to ongoing char[] buffer. If the character buffer size is less. I.e. not sufficient enough to append more, the capacity is doubled . Lets say its capacity was 16, and not sufficient to add more, than the the capacity is increased by doubling the size of current buffer length. This keeps happening when you keep on appending stuffs to it. Common case is while reading a file and storing it inside memory in form of a StringBuilder. You never know what the size of file could be. when size isn't sufficient for the StringBuilder, buffer size is doubled and this keeps growing. A point will reach when System is not able to

Monday, August 23, 2010

Parsing complex nested XML with SAXParser and collections

In my previous example, I have explained how to parse simple XML with on and multiple elements or objects. This is beyond that. Have you ever encountered and XML which have nested elements and the nested elements again have same nested objects and the tree grows. I happen to encounter such huge XML of size in few MBs. Sometimes collections like java.util.Stack or java.util.Map are helpful and very useful in this case. While parsing, you have to add and object as a child to another object, but it becomes difficult to determine to which parent object the child has to be added. The image below shows a basic tree structure of the XML file in this demo example.

Friday, August 20, 2010

XML parsing with SAX Parser Demo

Java provides two ways of parsing XML. Namely SAXParser and DOM Parser. With DOM Parser complete XML document object is held in emory and uses the DOM approach with DOM elements. This approach is used when you need to get hold of elements from XML in any order. But using DOM parser is costly in term of memory. When you have a XML document and want to read it once and create in memory java object (POJO), go for SAXParser approach. SAXParser parses the document(XML) from top to bottom, tag by tag.
Using Sax parser is simple. All we need to do is create a Handler class which extends DefaultHandler class of org.xml.sax.helpers package (part of JDK). In this Handler class, we define how tags are processed and stored into in memory object.
Once the Handler is developed, Create a Parser class which uses SAXParser abstract class from javax.xml.parsers package (also part of JDK). Use this Parser class and parse the document with help of the Handler class which we created. Current example demonstrate simple XML, for parsing nested XML with hierarchy, read a another article as how to parse nested XML.
Below is a snippet of simple XML file which needs to be parsed.