RSS Feed for ProgrammingCategory: Programming

Java: Debug Commons Digester Exception »

This is a exception produced by Commons Digester. After spending few hours to find out the root cause, including studying the source code, I found that I make a silly mistake. 1: java.lang.NullPointerException 2: at org.apache.commons.digester.Digester.createSAXException( 3: at org.apache.commons.digester.Digester.createSAXException( 4: at org.apache.commons.digester.Digester.startElement( 5: at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source) 6: at org.apache.xerces.parsers.AbstractXMLDocumentParser.emptyElement(Unknown Source) 7: at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source) 8: […]

Java: A Simple JSON Utility »

Here is a simple JSON utility class that I used to do the followings Convert JSON string to a Map and vice versa Convert JSON string to list of maps and vice versa This class encapsulate all the JSON string manipulation in a single Java class so that it frees you up from the actual […]

Java: Ordered Map and Set »

If you need an ordered Map or Set, meaning maintaining the original in your Map or Set in the order you insert or add them, then you should use LinkedHashMap or LinkedHashSet. Some sample code below. 1: import java.util.*; 2:  3: public class TestClass { 4:  5: public static void main(String[] args) { 6: Map<String, […]

Java: Refactor Code by Introducing NULL Object »

This is from the Refactoring book by Martin Fowler. In our code we always need to check if a object is null, and depending on it, different actions are taken. E.g. for the following code 1: if (subscriber == null) { 2: ratePlan = defaultRatePlan; 3: } else { 4: ratePlan = subscriber.getRatePlan(); 5: } […]

Java: Logger Configuration »

Normally if you want to avoid creating multiple logger in your based and derived classes, you can declare a single logger in the based class. E.g. in the following base class, a single logger is declared 1: package twit88; 2:  3: import org.apache.commons.logging.Log; 4: import org.apache.commons.logging.LogFactory; 5:  6: public class BaseLogger { 7:  8: protected […]

Java: Static Initializer Problem »

Have a look at the following code 1: public class StaticTest { 2: 3: static { 4: name = “my name”; 5: } 6:  7: public static String name = null; 8:  9:  10: public static void main(String[] args) { 11: System.out.println(; 12:  13: } 14: } The output is “null”, which may surprise some […]

Apache Tomcat Servlet Error in GenericServlet.getServletName »

Here is the error I got for one of the Java servlet 1: 2008-09-30 02:36:50,915 | ERROR | [StandardWrapperValve:260 invoke | http-8881-Processor20] – Servlet.service() for servlet myServlet threw 2: exception 3: java.lang.NullPointerException 4: at javax.servlet.GenericServlet.getServletName( 5: 6: The servlet is configured to be invoked upon certain URL pattern in web.xml. In other word, it will […]

Java: Automate Your Load Test using JMeter »

In all critical applications when response, throughput and transaction processing time are important factors to determine the success of the system, load test is definitely a must. In my projects normally I used JMeter to carry out load testing by running JMeter across multiple machines. The problem is that the server can only be load […]

Java: Automate Your Documentation Process »

In any project, documentation is definitely necessary. Problem is that software documentation is always out of sync with the software itself as software is ever evolving. Software documentation is always outdated if they are managed in a manual way. Here are some open source software that can be used to automate software documentation, and thus […]

Java Generics Summary »

A short note on Java Generics Generics are not covariant. 1: List<Integer> li = new ArrayList<Integer>(); 2: List<Number> ln = li; // illegal Construction Delays 1: public void doSomething(T param) { 2: T copy = new T(param); // illegal 3: } Constructing wildcard references 1: class Foo { 2: public void doSomething(Set<?> set) { 3: […]

Java: Check Class Version »

Here is a simple piece of code to check your Java class version, whether is it is compiled with JDK 4, JDK 5 or JDK 6, etc… 1: try { 2: String filename = “C:\\MyClass.class”; 3: DataInputStream in = new DataInputStream 4: (new FileInputStream(filename)); 5:  6: int magic = in.readInt(); 7: if (magic != 0xcafebabe) […]

Java: Coding Guidelines »

Here are some simple guidelines I followed for one of the system that I refactored. Always Program Using the Interface E.g. 1: Map<String,String> obj = new HashMap<String,String> 2:  3: List<String,String obj> = new ArrayList<String,String>   Prefer HashMap over Hashtable, ArrayList over Vector, StringBuilder over StringBuffer If you really need synchronized access, e.g. for Map, use […]

Generate Statistics Report from Source Code Repository »

Here are some tools to help generate statistics report from your source code repository. StatCVS retrieves information from a CVS repository and generates various tables and charts describing the project development, e.g. Timeline for the lines of code Lines of code for each developer Activity by Clock time Authors Activity Author activity per Module Author […]

Java: Code Analysis using Eclipse »

Code analysis is carried to normally do the followings Coding standards Code duplication Code coverage Dependency analysis Complexity monitoring These analysis areas can be uncovered using a number of the following slick Eclipse plugins: CheckStyle: For coding standards PMD’s CPD: Enables discovering code duplication Coverlipse: Measures code coverage JDepend: Provides dependency analysis Eclipse Metrics plugin: […]

Java: StringUtils.isNumeric with Decimal Point »

For the code snippet 1: System.out.println(StringUtils.isNumeric(“10.0”)); Using Apache Commons Lang, the above will return false. This is one bug I recently found in one of the existing application. As quoted from the documentation, StringUtils.isNumeric Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false. To return […]

Java: Create Immutable Object using Builder Pattern »

To create immutable Java object, we should use the Builder Pattern, as described in Effective Java. This is the pattern I normally used now for immutable class. 1: public class Person { 2: private final String name; 3: private final int age; 4: private final String email; 5: private final String mobileNo; 6:  7:  8: […]

Java: Trap in Arithmetic II »

What will you expect from the following code? 1: public static void main(String[] args) { 2: System.out.println(10.00-9.10) ; 3:  4: } Instead of printing “0.90”, it prints “0.9000000000000004” on my machine. This is a know floating point issue with all languages. To get it correctly done in Java, you need to use BigDecimal class, passing […]

Java: Always Overwrite equals, hashCode and toString in Value Object »

You should always overwrite equals, hashCode and toString in your value objects, this will let you have more control over your value objects or model classes. Also,  always overwrite hashCode and equals in pair. Consider the following code snippet 1: import java.util.Set; 2: import java.util.HashSet; 3:  4: public class EqualTest { 5: private String name; […]

Java: StringBuilder vs StringBuffer »

StringBuilder is introduced starting JDK 1.5. There are few differences for them StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized. StringBuilder has better performance than StringBuffer under most circumstances. So, use StringBuilder if it is not […]

Java: Understanding JSR14 »

During the development of the Java generics specification (and other language features added in Java 5), experimental support was added to the javac compiler to allow it to consume Java 5 language features and generate bytecode that could be run on a Java 1.4 JVM. While these features are not supported (or even documented), they […]