Configure Log4J in Eclipse IDE

•October 29, 2009 • Leave a Comment

It would be nice to see debug message when debugging code or run unit test in IDE.

I offen get this worning message when use eclipse:
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.

It seems tricky to put log4j configuration files like log4j.properties or log4j.xml to the right place.  If you have multiple projects opened in your workspace, you need to put log4j configuration file to the root of classpath for every project. It should have a better way to do it. I got some idea from this post.

Here is what I did and it worked:

  1. Create a folder in the workspace (like /projects/classpath)
  2. Put log4j.properties under that folder
  3. right_click on the project and select Build Path -> Configure Build Path…
  4. Add External Class Folder… choose the folder that contains log4j configure file
  5. Click OK to finish

That’s it :)

Experiencing Testing Days

•October 2, 2009 • Leave a Comment

It is good to dedicate some time, sit back talking and thinking about the best practice in software development. That is what our team did in the last couple of days, I am very appreciate that and I think I got a lot from it.

Our team lead Matt Stine invited Jared Richardson, an author, speaker, consultant, and mentor come to give us a three days class. I was in the class for Thursday and Friday, and also listened to his talk on Thursday night Jug meeting, it was an awesome talk. We talked a lot about testing tools and strategies, spent fair amount of time on Selenium.

Jared’s three testing strategies make a lot of sense. He was not only talked about the goals and also talked about how to get there, what are the difficulties.  From the success and non success  stories about other software shop, we learned a lot about others and our-self. Jared said “A common problem is every team think they are special or not common”.

Here are the three strategies: TDD (Test Driven Development), don’t write a single line of production code until you have a failed test; DDT (Defect Driven Test), Jared said he actually invented this term, write test code whenever you find a production bug; Blitzkrieg, a military term, here is the full definition.

Defect Driven Testing is really a good place to start. To write test for a bug, DDT make you think the test code is really doing something useful and then you are willing to spend more time on it. We actually did that even though we didn’t know the term at the time. We were using EJB2 and you know to test EJBs is not the easiest thing to do. You need to really realize the important of testing to put those effort writing test code for EJBs. We actually built a home grown testing framework for that and we had pretty good coverage for back-end APIs.  It is encourage to hear from professional that what we did was a good practice.

Selenium is a testing tool that we talked a lot these couple of days. We had a lightening talk last night by Chris Roberts and we spent the whole day today to get our hand dirty. Selenium is a very good testing tool for Web Application, can be used for unit, functional and integration testing. It is also a very good tool for demo the Web Application functionality. Selenium’s main modules are: Core, IDE, RC and Grid, new modules may added already, the project evolved very fast. One cool thing we learned from today’s practice is that after record the test case using IDE, you can export it as Java and run as Java test (the Selenium RC need to be started). We also refactored the Java test code to make it more readable so people don’t know Java can read and even write the test.  Selenium is sweet, we will definitely use it in our projects.

Everyday we spend on the earth is probably or should be unique, but a lot of people feel like today is just a repeat of yesterday. These couple of days is definitely unique in my developer life.

Use enumerated constants in Java

•September 24, 2009 • Leave a Comment

In the article “Create enumerated constants in Java” , Eric point out static final constants like this:

static final int YELLOW = 0;
static final int GREEN = 1;
static final int BLUE = 2;

had the following drawbacks:

  • The major drawback is the lack of type safety. Any integer that is calculated or read in can be used
  • Another drawback is the lack of a readable identifier. If you use a message box or console output to display the current color choice, you get a number. That makes debugging pretty difficult

And enumerated constants had the following advantages:

  • Type safe
  • Printable
  • Ordered, for use as an index
  • Linked, for looping forwards or backwards
  • Enumerable

He also showed how to create enumerated constants in Java in the old version like JDK 1.1. But the “enum” keyword in Java 5 had taken care of all of that.

Based on this article, Java 1.5 make it very easy to create enumerated constants. The keyword “enum” is a new and the only new one brought into the language in JDK 1.5. You just need a simple one line definition like this:

public enum breakfast {yellow, green, blue };

Here is the official document from Sun.

The following is a simple enumerated constants class show that you can actually add properties and behavior to it:

public enum MsgStatusConsts {
    Received    (0),
    Finished    (1),
    Processing  (2),
    Error       (-1),
    Discard     (-2);

    private final int code;    //status code
    private MsgStatusConsts(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static void main(String args[]) {
        for (MsgStatusConsts msc : MsgStatusConsts.values()) {
            System.out.printf("The code for %s is %d, string %s%n",
                msc, msc.getCode(), msc.toString());
        }
        System.out.printf("What is valueOf(Error) %s, code %d%n",
            MsgStatusConsts.valueOf("Error"),
            MsgStatusConsts.valueOf("Error").getCode());
    }
}

Eric Armstrong (1997). Create enumerated constants in Java http://www.javaworld.com/jw-07-1997/jw-07-enumerated.html

How to create a new OSGi Bundle Maven Project from scratch

•September 16, 2009 • Leave a Comment
  1. Follow the instruction to create archetypes
  2. Install the archetype: run a. mvn clean, b. mvn install in the archetype folder, this will install the archetype to .m2 folder
  3. Go to the parent project folder (make sure you have the super pom there) and run: mvn archetype:create -DarchetypeGroupId=org.stjude.srm -DarchetypeArtifactId=module-bundle-archetype -DarchetypeVersion=1.0.0 -DgroupId=org.stjude.srm -DartifactId=srm-databus-infrastructure -Dversion=1.0.0
  4. Run mvn eclipse:eclipse in the new bundle to generate the required files and folders for eclipse (like: .project, .classpath and .settings)
  5. Import the bundle into eclipse (STS) File-Import-General-Maven Projects
  6. In STS add Spring project nature and OSGi bundle project nature to the new bundle

Configure P6Spy with JBoss-4.2.1.GA

•August 28, 2009 • 2 Comments

P6Spy is a very good tool to trouble shoot application and database problem. It put all queries from application to spy.log file, here are steps to configure it in JBoss-4.2.1.GA pointing to EDB:

  1. Download P6Spy
  2. Extract the p6spy-install.jar file, it contains p6spy.jar and spy.properties
  3. Put p6spy.jar to you server lib folder, I put it in $JBOSS_HOME/server/myserver/lib
  4. Move the spy.properties file to the JBoss classpath, I put it in $JBOSS_HOME/bin
  5. Cange the xxx_ds.xml in the $JBOSS_HOME/server/myserver/deploy folder to use P6SpyDriver, <driver-class>com.p6spy.engine.spy.P6SpyDriver</driver-class>
  6. Change spy.properties file to use correct database driver, I am using EDB: realdriver=com.edb.Driver
  7. Look at queries in spy.log file, normally located at the same directory as spy.properties file

What is FreeMarker?

•August 24, 2009 • Leave a Comment

FreeMarker is a “template engine”; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates.
FreeMarker is designed to be practical for the generation of HTML Web pages, particularly by servlet-based applications following the MVC (Model View Controller) pattern.
Although FreeMarker has some programming capabilities, it is not a full-blown programming language like PHP.
FreeMarker is not a Web application framework. It is suitable as a component in a Web application framework, but the FreeMarker engine itself knows nothing about HTTP or servlets. It simply generates text.

Difference between InputStream and Reader

•July 7, 2009 • Leave a Comment

The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.

Basically there are two types of streams. Byte streams for handling stream of bytes and character streams for handling streams of characters.

In byte streams Input/Output Streams are the abstract classes at the top of hierarchy, while Writer/Reader are abstract classes at the top of character streams hierarchy.

Please read the original post for more information.

Three ways to make HashMap thread-safe

•July 7, 2009 • Leave a Comment
  • Use: Hashtable which is thread-safe;
  • Use: Hashmap objHashmap = Collections.synchronizedMap(new HashMap(….));
  • Use: Block Synchronization mechanism. Where ever you are using the HashMap put those codes into block and sysnchronise that block with respect to HashMap object that you are having.

Why do you need to override equals() method in Java?

•July 1, 2009 • Leave a Comment

Why do you need to override equals() method in Java?

The equals method of java.lang.Object acts just like the == operator in that they both check to see if two objects are identical. Two object are identical if they both refer to the same instance of a class, that is, they share the same address in memory. This is generally known as an object identity comparison, but is also referred to as a pointer comparison.

The inherent contract of the equals method for objects that extend/inherit from Object class is that it tests for object equality rather than identity. Two objects are said to to be equivalent if they are both instances of the same Type and if the value of each field of the first object is equal to the value of the same field in the second object. Essentially this means we are recursively calling the equals method for each attribute on the objects. Java provides an implementation of equals for the basic/wrapper Types of String, Boolean, Integer, Double, BigDecimal, etc… and all primitives use the == operator for comparison.

See the original post for more information.

Why does a method claim return SET over HASHSET?

•July 1, 2009 • Leave a Comment

SET is a interface, HASHSET is a implementation of SET.

1. A Set represents a mathematical set.
2. It is a Collection that, unlike List, does not allow duplicates.
3. There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2).
4. The add method of Set returns false if you try to add a duplicate element.
5. HashSet allows at most one null element.
6. HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet.

When claim return type, it is always better to use the interface type, for easier to change to a different implementation as needed.