Tuesday, July 1, 2008

Book Review: Effective Java, Second Edition

Effective Java, Second Edition by Joshua Bloch is certainly the best Java book I have read in a long time. As a disclaimer, I never read the first edition and I am thus unable to compare the two editions. Effective Java, Second Edition is a mostly easy and fun read providing you with many insights and best practices on how to use Java effectively. It certainly is not a book for the beginner just starting out learning Java. For that purpose you may want to take a look at Thinking in Java by Bruce Eckel instead. Nevertheless, Effective Java would serve as an excellent follow-up.

In Effective Java, Joshua Bloch does a great job describing best practices that you as developer will find useful on a daily basis. For example, I really found his description of the builder pattern (Item 2, page 11) quite interesting. Another Item that fascinated me, was Item 15 (page 73) - "Minimize mutability". Both items are part of a broader theme throughout the book that promotes creating code that is as immutable as possible. In that regard, reading the book will enable you to simply write better and safer code. The book also leads the way towards promoting functional programming techniques which will come in quite handily when developing multithreaded applications. Therefore, as a next book I may recommend reading Java Concurrency in Practice by Brian Goetz.

Even for the experienced Java developer, Effective Java contains quite a few little eye openers. I for example was previously unaware of how static factory methods can simplify the creation of parameterized type instances using "type inference". This example is described on page 9 (Item 1). In the past I had always used something like this:

List users = new ArrayList();

But by using a static factory method you can do:

List users = Helper.newArrayList();

I thought that this was a pretty nifty example that may help making code a bit cleaner. What I also very much liked about Effective Java was that Joshua points out certain short-comings of the Java language itself and its APIs whenever applicable. For example, page 64 describes the inconsistent behavior between BigDecimal's 'equals' method and its 'compareTo' method, and in item 41 (page 194) Joshua details the shortcomings of the List interface when using Autoboxing.

While the vast majority of the book was very easy to read and to understand, I found that the chapter about bounded wildcards using generics (item 28) was a little difficult to grasp and I wished it were a bit more extensive. On the other side, the provided mnemonic is quite helpful: PECS - Producer-extends, Consumer-super.

Overall, I highly recommend Effective Java, Second Edition which will continue to serve me, and likely you too, as an excellent reference resource.

Wednesday, June 18, 2008

TED - Ideas and Inspirations

On the Java Posse they mentioned a presentation by Jill Bolte, a brain researcher, about her experiences having suffered a stroke - It was an amazing presentation! I also have to explore more of TED. There seems to be a ton of good stuff...

Wednesday, June 4, 2008

NFJS Atlanta 2008 Report

I just realized that I started writing a blog entry about attending the No Fluff Just Stuff conference here in Atlanta (May 16-18) - but never finished it...Oh well - Anyway, it was a great conference and the provided backpack will certainly serve me well :-)

Here are the sessions I attended:

Friday
  1. Developing Rich Internet Applications by Richard Monson-Haefel
  2. Java Memory, Performance and the Garbage Collector by Ken Sipe
  3. Architecture and Scaling by Ken Sipe
Saturday
  1. Tactical Continuous Integration with Hudson by Andrew Glover
  2. SOA's Challenges by Ken Sipe
  3. Dojo: Getting Started by Nathaniel Schutta
  4. Configuring Spring with Annotations by Mark Fisher
Sunday
  1. Enterprise Integration Patterns with Spring by Mark Fisher Part I
  2. Enterprise Integration Patterns with Spring by Mark Fisher Part II
  3. Introduction to Tapestry 5 by Howard Lewis Ship
  4. Pragmatic Patterns with Tapestry 5 IoC by Howard Lewis Ship
For me the best presentation was the second part of the Enterprise Integration Patterns talk by Mark Fisher. It was basically all about Spring Integration - This project looks way cool! It basically allows to componentize your application, similar to how you work with JMS. But Spring Integration is working on a lower level. It also has features that are typically found in ESBs such as adapters for mail, JMS, FTP etc. Mark Fisher hinted that in the future Spring Integration may also evolve into a workflow solution.

In terms of speakers - Ken Sipe was simply terrific. I did not expect an overly exciting presentation when listening to "Java Memory, Performance and the Garbage Collector" but I was very impressed. Great talk and very informative.

Lastly it is always nice to listen to Howard Lewis Ship - Tapestry looks good and I really need to play with it at some point - if only the day had 48 hours...

Can't wait for the next conference - Jay, job well done.

Wednesday, May 28, 2008

Addicted to YSlow and what Jawr can do to help

At the No Fluff Just Stuff (NFJS) conference I attended 2 weeks ago, somebody mentioned YSlow, which is a tool for analyzing websites in regards to performance and is a plugin for Firebug. Hence, this week I spent some time using it and fixing the issues YSlow found on my project.

It is really nice and almost addictive...YSlow grades the performance of your website in a number of categories. There is a good site at yahoo explaining those categories called: "Best Practices for Speeding Up Your Web Site".

For example, you should always put CSS at the top of your web pages and JavaScript files should be at the bottom. While this is easy to fix, the recommendation to reduce HTTP request is a bit trickier to fix.

Well, let's assume you implemented a typical Web 2.0 website using a few Javascript libraries such as Prototype, Scriptaculous as well as your own Javascript files. Furthermore, you broke your CSS into multiple files because otherwise you would simply lose control over it entirely.

That of course causes a lot of HTTP requests when loading the files and thus leads to a degradation of your website's performance.

But luckily if you write Java based web applications there is a really cool library out there called Jawr that let's you bundle up (combine) your Javascript and CSS files. Not only that, Jawr also minifies your Javascript and CSS files plus it is able to GZip the files as well. Jawr also provides a nice quickstart tutorial and lastly Jawr also has a tutorial that explains how to use it with the big JavaScript libraries such as jQuery, Prototype, Scriptaculous and Yahoo! UI library.

Wednesday, May 21, 2008

RSS Feed Aggregators

For the Atlanta Java User Group I have been looking into providing an RSS feed aggregation service for blogs of AJUG members. Since AJUG is running its own server, I wanted to provide a server-based solution. Interestingly, it seems the choices are rather slim when looking for something that is OSS. Pratik mentioned groovyblogs. It looks interesting, got it running very quickly, but I saw one too many stacktraces when clicking through the application. Maybe just bad luck...Once I find the time to dive deeper into Groovy and Grails, I may return to groovyblogs, though. The source code is available here.

Barry Hawkins pointed me to Planet, a Python-based feed aggregator. To see it in action, take a look at http://planet.python.org/. Well, after looking at it, I found Planet Venus its successor. Compared to the original Planet, Planet Venus actually has some documentation (I like documentation!) and a fairly active mailing list. Furthermore, nature.com is using Planet Venus. You can find it at http://planet.nature.com/. There is also blog entry by Sam Ruby that provides a little more background information regarding Planet Venus.

Anyway, the actual installation has been trivial - it is basically just a command line script, that parses RSS feeds, applies a template and than spits out html pages. Thus, adding the script's execution to your crontab is all that is needed to feed your aggregator with new data.

Monday, May 19, 2008

Spring Security 2.0

For my home project, I updated ACEGI security to Spring Security 2.0.1. My experience was similar to Matt Raible's - positive. I was able to cut down the XML configuration quite substantially. At the end only 49 lines remained (Including XML namespace declarations).

The migration was very easy except for 2 smaller issues (See further below). First, I updated web.xml to rename the security filter to Spring Security's one:

springSecurityFilterChain

org.springframework.web.filter.DelegatingFilterProxy

...

springSecurityFilterChain
/*



Also, since I am using my own "user service" to pull users and roles from the database, I had to rename a few imports in my classes to reflect the package names of Spring Security 2.0.

The biggest configuration change was updating the bean definition in my context configuration file which contains all the necessary XML to wire all the beans together. Spring Security 2.0 is now providing its own XML Namespaces, which drastically simplifies configuration.

Thsu, here is the final application context configuration file for Spring Security 2.0 as used by my project:














































As mentioned above, I encountered two smaller issues. First, I am using the Jasypt library which I am using for digesting passwords. It provides a password encoder that plugs into ACEGI security. Unfortunately, it has not yet been updated to also work in conjunction of Spring Security 2.0. The aforementioned implemented password still uses the old package structure. Thanks to open source this is an easy fix :-)

Thus, I checked out Jasypt into my Eclipse Ide, updated the package reference and the pom to pull in the Spring Security 2.0 jars. I also created a ticked on the Jasypt project website and submitted a patch with the changes. Let's see whether it will find its way into the prokject soon.

My second problem had to do with the rolePrefix of Spring Security. Spring Security by default pre-fixes roles names with "ROLE_". Since my project does not use prefixes for role names I had created rolevoter bean that set the rolePrefix property.

Interestingly you can't do this configuration using namespaces. With the current version you need to fall back to the traditional bean configuration support which involves creating 3 additional beans:

  • roleVoter

  • accessDecisionManager

  • authenticatedVoter
There is a little more information available on the Spring forums about this. Hopefully this maybe be simplified in the future - thus, I opened a ticket for this on the Spring Jira.

Wednesday, May 14, 2008

If Tomcat is Running out of Memory...

If your Tomcat is running out of memory, take a look at the following issue posted by Atlassian. It affects basically all Tomcat versions including Tomcat 6.

The fix is to set the following JVM parameter:

-Dorg.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true

And, just for completeness - if you need to specifiy JVM parameters for Tomcat, create a file called setenv.sh in your Tomcat's bin directory.

e.g.

#!/bin/sh

CATALINA_OPTS=" \
-Xms512m -Xmx512m \
-XX:PermSize=128m -XX:MaxPermSize=256m \
-server \
-Djava.awt.headless=true \
-Dorg.apache.jasper.runtime.BodyContentImpl.LIMIT_BUFFER=true"

export CATALINA_OPTS

Tomcat will pick up the file automatically when it starts up. Regarding Permspace issues, there was a good discussion about it over at Matt Raible's Blog.

Wednesday, April 30, 2008

Lightbox gone crazy...

If you think there are too many Java web-frameworks out there - check out the market for JavaScript Lightbox libraries:

http://planetozh.com/projects/lightbox-clones/

Tuesday, April 22, 2008

Learning Spanish

I started reading my second Spanish book: Pueblos del Caribe y la Amazonia. The book describes the life and customs of the indigenous people in pre-hispanic times. So far it seems to be a relatively easy informative read and I like to learn more about Latin-American history anyway. My next Spanish book is already waiting - Diarios de Motocicleta...Good ol' Che. I have been taking Spanish classes for the last one and a half years and finally things start making more and more sense. 

Which reminds me - my last level (12) at the Latin American Association here in Atlanta starts this week.

Monday, April 21, 2008

Converting Daos from Hibernate to JPA

Over the weekend I converted the Daos of my pet project jRecruiter from Hibernate to the Java Persistence API (JPA) using Hibernate as persistence provider. The project is using the latest Spring version (2.5.3) and I also incorporated Spring's latest annotation features. This allowed me to remove all the Dao-related Spring bean declarations in my context.xml file. The actual conversion from pure Hibernate to JPA was quite straight forward. I was struggling a bit with the Spring configuration of the entityManagerFactory but got it to work eventually.

Here is my Spring context file with the JPA setup.































${hibernate.dialect}
true 'Y', false 'N'
true
org.hibernate.cache.EhCacheProvider
true
true









The modifications to the daos itself were rather modest. One difference I noticed is that executing a query using query.getSingleResult(); throws a NoResultException. I prefer returning null - therefore I had to do the following:


try {
user = (User) query.getSingleResult();
} catch(NoResultException e) {
user = null;
}


Also, the Dao classes are annotated with @Repository e.g.:


...
@Repository("userDao")
public class UserDaoJpa extends GenericDaoJpa<>
implements UserDao {
...


Also, I use some of the new Spring features that allow me to get rid of quite a bit of XML:







Using context:component-scan Spring will auto-detect my daos and registered them with the context without any XML necessary. I think this is kind of neat especially for smaller projects.

Lastly, in case you need to access Hibernatenate's SessionFactory directly:

Session session = (Session)entityManager.getDelegate();