Jeff Kunkle

XML
20071231 Monday December 31, 2007
Use Caution when Mixing JUnit 3 and 4

Quick quiz, what is the output from the following JUnit test?

    1 package com.nearinfinity.sandbox;
    2 
    3 import junit.framework.TestCase;
    4 
    5 import org.junit.After;
    6 import org.junit.Before;
    7 import org.junit.Test;
    8 
    9 public class ModelTest extends TestCase {
   10 
   11     @Before
   12     public void setUp() {
   13         System.out.println("Setup called.");
   14     }
   15 
   16     @After
   17     public void teardown() {
   18         System.out.println("Teardown called.");
   19     }
   20 
   21     @Test
   22     public void testSomething() {
   23         assertTrue(true);
   24     }
   25 
   26 }

If you said

Setup has been called.
Teardown has been called.

you’d be wrong. Don’t feel bad though, I spent about two hours staring at a similar test until I finally figured out what was going on. So, what’s the problem?

The problem lies in the mixed use of JUnit 3 and 4 concepts. The astute reader will notice that this test extends the JUnit 3 junit.framework.TestCase while also using JUnit 4 annotations. So which wins, the base class methods, the annotations, or both? Well, it turns out that the JUnit 3 base class conventions win out and the annotations are ignored. With that said, can you now guess what the test output is? Did you guess

Setup has been called.

If not, don’t feel bad. It’s not immediately obvious. It turns out that the testSomething test method runs because it starts with the word test, not because it’s decorated with the org.junit.Test annotation. The setUp method runs because it overrides junit.framework.TestCase’s setUp method, not because it has a org.junit.Before annotation. Lastly, the teardown method doesn’t run at all because it does not override the base class tearDown method due to the lowercase “d” and as we’ve seen, the org.junit.After annotation has no effect.

That lower case “d” cost me two hours of my life, which I now consider time well spent. It made me realize that my test’s inheritance chain ultimately led to junit.framework.TestCase. The fact that the test had worked in the past was a textbook case of dumb luck.

So, if your JUnit 4 test classes start acting strange, make sure that base class you’re extending doesn’t ultimately lead to a junit.framework.TestCase.

Posted by jkunkle Dec 31 2007, 07:30:00 AM EST
20071126 Monday November 26, 2007
Application Versus Database Security

The merits of placing security in the application layer versus the database is a debate I seem to find myself in regularly. As an application developer, I've historically argued for application-level security. It was something I understood well and felt like I had some control over. Over time, I've come to understand the debate from many perspectives and have adjusted my convictions accordingly.

For the record, I don't believe there is any absolutely correct answer. There are valid arguments for each side of the debate. My perspective has mostly been shaped through experience developing custom software for clients. I have little experience developing commercial software and surmise that your thoughts on the subject may differ if that's your day job.

In my experience, most customers view their data as the most important aspect of any system, not the application. They want to be sure their data is safe at all times. What if someone accesses the database through a different application, a third-party data broker or directly via a SQL client? How do you protect the data in those situations if all the restrictions are resident in the application? I hear these questions all the time.

The rebuttal to this argument that I hear most often is that nobody will ever access the data outside of the application. This seems like an obviously shortsighted statement to me and I don't think anyone actually believes it. It's more of a synonym for saying that you'd rather not worry about security at the database layer because it's out of your control, too hard, etc. Pick your favorite excuse. I've probably used them all myself.

What it all boils down to is that the database is very likely to outlive your application. In fact, it'll probably outlive your application and several subsequent ones. Why would a customer want to pay someone to rebuild the security logic each time? It's tedious, expensive, and error prone. Additionally, you're application may not be the only one accessing the database. What are the odds that two development teams implement security constraints the same exact way in each application? Not good, I promise.

As I stated in the beginning, I've definitely changed my perspectives on application versus database-level security. I was certainly an application-level security bigot before, but I find it difficult to continue my unwavering ways when looking at the problem more critically. I just hope my fellow colleagues don't renounce me for siding with the DBAs on this one.

Posted by jkunkle Nov 26 2007, 07:30:00 AM EST
20070815 Wednesday August 15, 2007
Review of The Definitive Guide to Grails

I’ve found myself a bit bored with web application development lately. I’ve been itching to do something significant with Ruby on Rails for quite some time but always find myself working on Java projects for various clients. At the recommendation of some colleagues I’ve decided to take a peak at Grails and I have to say that I’ve shed my boredom and am once again excited about web development.

The following is my review of The Definitive Guide to Grails, written by Graeme Keith Rocher. Prior to reading this book I considered myself to know a lot about Java, a little about Ruby and Ruby on Rails, very little about Groovy, and nothing about Grails. After one speed reading of The Definitive Guide to Grails I have to admit that I’m quite excited at the prospect of starting a new project with Grails.

Conclusion

Yes, that’s right, I’m placing the conclusion at the front of the review. Why? Because the reviews of each chapter ended up being much longer than I’d anticipated and I fear few readers will hang on until the end. If you’re interested in some of the finer grained details of each chapter please read the following sections that I spent way too much time writing.

I found The Definitive Guide to Grails to be one of the best technical books I’ve read recently. The book appears to be targeted at the Grails newbie, which would suit just about everyone at this point in time. I never felt the content was over my head nor was I bored with long-winded explanations. I was looking for a book that would introduce me to as many core Grails concepts as possible within a short page count, and Graeme’s book certainly delivered.

If you learn best by following along with examples, you’re likely to enjoy this book. All eleven chapters are filled with plenty of code examples that not only bolstered my understanding of Grails, but also helped me comprehend some of the finer points of the Groovy language. I found the examples to be straightforward, numerous, and relatively short. I’m not a big fan of the long multi-page examples you sometimes find in technical books. I want enough just enough code to understand the topic and then move on. In my opinion, this is where The Definitive Guide to Grails excels. If you’re coming from a Java background, you should be able to pick up on the examples with minimal effort.

Also being new to Groovy, I appreciated the fact that Graeme sprinkled the use of some advanced Groovy features into the code examples. In wasn’t a windfall of features mind you, but it was enough to convince me of the power of Groovy and get me excited about learning more.

Overall, The Definitive Guide to Grails was a well-written, informative treatment of an exciting new web development framework. The code examples were woven in very well and really helped to understand the topics. If you’re looking to get up to speed on Grails in short order, I think you’ll be pleased with The Definitive Guide to Grails.

The following paragraphs provide a quick summary of each chapter.

Chapter 1 - The Search for the Holy Grail(s)

The first chapter provides some insight into the how and why of Grails. Graeme hits on the relative difficulty of developing applications on the JEE platform. He goes on to discuss how the prominence of Ajax and Web 2.0 have focused a lot of attention on web application development, and more specifically efficient web app development.

He then moves onto an introduction of Grails, paying homage to its Ruby on Rails inspiration. There’s a short discussion of how Grails leverages the power of the Java platform and specifically the Spring Framework, Hibernate, and Sitemesh.

The remainder of the chapter gets you up and running with Groovy and Grails. Graeme guides you though creating the first pieces of the sample application used throughout the book. Very few concepts are explained at this point, but it does whet the pallet.

Chapter 2 - The Groovy Language

Here’s your introduction to the Groovy language from the perspective of a Java developer. The basic topics introduced include classes, assertions, Groovy Strings (GStrings), closures, lists, maps, and Expando objects. Graeme follows up with some “power” features such as Groovy’s object-oriented design, Groovy’s notion of equals, metaprogramming, and builders.

You shouldn’t expect to become an expert on Groovy from this one chapter. For that, consider reading Groovy in Action or Groovy Programming: An Introduction for Java Developers. Luckily, I found most of the topics to be explained in enough detail for me to follow along. A Java or Ruby background is a big help here. Without it, I think you may have a difficult time understanding some of the code samples.

Chapter 3 - The Grails Project Infrastructure

This chapter dives into how a Grails project is organized and configured. If you’ve ever used Ruby on Rails, you’ll notice the project directory structure is similar. Either way, the big benefit here is that there’s a common structure for all Grails projects.

Graeme follows up the directory structure discussion with a brief description of Grails and the MVC architecture. At first I groaned about having to read yet another description of MVC, but it turns out that I didn’t have to. The whole discussion is only two pages covering where the different Grails components like controllers, views, and the domain model fit into the MVC picture.

The next few pages focus on configuring your data source and logging configuration for different environments. While I welcome the configuration simplicity Grails provides for these resources, I found myself wondering how I would specify other things on an environment by environment level.

The Grails command line utilities, console, and shell are also introduced in chapter three. The command line utilities are very Rails-like, providing you with quick scripts to create things such as applications, controllers, domain objects, tests and tag libraries. The command line can also be used to launch the Grails shell and console. Graeme doesn’t spend much time explaining these commands, nor do I think he needs to. Just being aware of them is probably good enough since they’re mostly self-explanatory.

The chapter finishes up with a discussion on Eclipse IDE integration. Graeme spends a good six pages describing the integration with plenty of screen shots to guide the reader along. I can’t comment on how good the instructions actually are since I didn’t try them.

Chapter 4 - The Application Domain

This is the chapter where you really see Grails shine. It’s a long chapter mainly covering Grails ORM (GORM) and domain model validation. I felt that Graeme spent a lot of time explaining these two concepts and it really paid off for me.

Grails ORM (GORM)

On the GORM side, he covers the basics of creating Grails domain objects and setting up relationships between them. He then goes on to talk about the various ways to query the database, including dynamic finders and a lengthy discussion on how to leverage the Hibernate Criteria API. The text on using the Hibernate Criteria made it seem relatively trivial to take advantage of the powerful library.

One thing I found strangely missing was a description of how to create the database schema. There were plenty of examples describing how to create the domain model, establish associations, and perform queries, but no description of how to create the necessary tables in the first place. I assume Grails is relying on Hibernate to automatically create the schema, but this is purely a guess since it’s not touched upon.

Data Validation

The discussion on domain model validation focuses on how to add simple constraints to individual fields of your domain model. Graeme also describes how to create custom constraints through the use of closures.

Chapter 5 - Scaffolding

Chapter five included a discussion of both dynamic and static scaffolding. Unfortunately (in my opinion), Graeme devotes three-quarters of the chapter to dynamic scaffolding, which I’ve found to be of little benefit in my brief time playing with the Ruby on Rails equivalent.

Dynamic Scaffolding

He uses dynamic scaffolding to create the first few pages of the sample application, showing the reader screen shots of the UI along the way. There are descriptions of how to modify some of the scaffolding by overriding default CRUD operations and customizing fields with constraints.

Static Scaffolding

I found the text on static scaffolding to be more beneficial. The discussion mainly focuses on using the command line tools to generate default implementations of controllers, views, tests, etc. There’s also some brief but clear discussion on the location of generated artifacts and the code that is created behind the scenes.

Chapter 6 - Testing, Testing, Testing

The chapter on testing was split up into two sections, unit testing and functional testing.

Unit Testing

The unit testing part of the chapter covered Groovy’s assert methods beyond those provided by JUnit and its mocking capabilities through the use of closures. The generous code examples really helped me understand how powerful Groovy’s mocking capabilities are. My collegue Scott Leberknight has a nice post that explains some of the finer points of mocking with Groovy if you’re interested in some more detail.

Functional Testing

In my opinion, you can probably skip the second half of the chapter devoted to functional testing with Canoo WebTest. Although Graeme does a nice job explaining how to use WebTest and its integration with Grails is commendable, I think it will largely be an exercise in frustration for any modern web application using Ajax. As far as I know, WebTest is not able to exercise any Ajax functionality.

Chapter 7 - Grails Controllers

The chapter on Grails controllers covers a lot of ground in a short thirty-one pages, so make sure you’re paying close attention when you read it. There’s a lot of great information that you won’t want to miss. Below are some of the highlights.

Actions

Graeme starts off by describing actions, the workhorses of controllers. He does a nice job of describing how Grails use of closures for action definitions is so beneficial. He quickly follows this up by describing how the developer can access various request attributes with little effort. For those of you who’ve written a lot of Java web applications in the past, you’ll be pleased to find that things like request.getSession().getAttribute(“attrName”) are reduced to session.attrName

Flash

The explanation of flash scope will be particularly helpful to anyone who hasn’t used Ruby on Rails before. Graeme does a nice job of illustrating how this scope differs from the familiar page, request, session, and servlet context scopes we’re all used to and why it’s so helpful to have it in your bag of tricks.

Data Binding

Three full pages are devoted to Grails data binding, which builds upon Spring’s binding code. Binding is one of the more tedious aspects of web development, but Graeme does a nice job at putting your worries at ease. He also takes the time to describe how binding can be used outside of the context of Grails domain objects.

Control Flow

Graeme follows up data binding with some text on controlling flow with redirects. There’s nothing exciting here, although the tactics are well explained.

Response Rendering

Grails has a very flexible response rendering framework wrapped up in a simple API. The text covers a wide range of rendering options with short code samples. The discussion of rendering HTML or XML using builders is especially cool.

Action Interception

Think of action interception as AOP for your controller methods, which is exactly how it’s described by the author. He gives a quick example of before and after advice followed by a discussion of how action interceptors can be used to implement authentication and authorization. The apparent simplicity of this approach makes me wonder if using Acegi (as briefly described in chapter eleven) is worth the effort.

File Uploads

The last topic in this busy chapter deals with file uploads, which again builds upon Spring’s binding technology. Graeme provides two examples of handling file uploads. The first involves pulling the file directly from the request from within a controller. The second example demonstrates binding a file directly to a domain model object.

Chapter 8 - Groovy Server Pages

The chapter on Groovy Server Pages (GSP) is quite long and covers a lot of material. The chapter starts off by talking about some of the more mundane basics; page directives, scriptlets, and GStrings but quickly moves on to more interesting topics.

Tags

Graeme starts off the tag discussion by describing the built-in Grails tags. There’s at least one usage example for setting variables with tags, logic tags, and iterative tags. These tags probably don’t sound all that different than the JSTL ones you may have used, and they aren’t. What is different are the filtering and iteration tags, including collect, findAll, and grep. For these more unfamiliar tags, Graeme provides several examples each that demonstrate their usage. He finishes off by talking about Grails dynamic tags, explaining both how to use the built-in Grails ones and also how to create your own.

Validation and Error Handling

Validation and error handling are next on tap. The discussion here is short and to the point. If you’ve had any experience with Spring MVC before, this text will be quite familiar.

Internationalization Support

The discussion of internationalization support is very brief, but I didn’t find it lacking. You’re mileage may vary. It basically boils down to describing where different language bundles are placed in the Grails directory structure and how those messages can be displayed using Grails tags.

Layouts and Templates

Graeme spends a full ten pages describing layouts and templates, more than I would have expected. He provides sample layouts and describes how layouts are selected by convention or through the use of meta tags. This is all the same stuff you’d expect if you’ve used SiteMesh before.

A discussion of templates follows the text on layouts. Templates are simply reusable snippets of markup. Graeme provides a few examples demonstrating how the g:render tag makes working with templates dead simple. If it weren’t for the g:render tag integration, templates would be little more than JSP includes.

Pagination

Pagination is one of those things that has to be dealt with in every web application, and it’s never fun. Here, Graeme explains how the g:paginate tag in Grails makes rendering paging links and managing the display of multiple pages a bit easier. As usual, there are plenty of code examples to help you understand how to use the tag.

Custom Tags

Graeme finishes up the chapter with a discussion on how to create your own custom tags and yes, this is different than creating your own dynamic tags. Graeme describes the process through an example of in-place editing that’s folded into the example played out throughout the book. I found the example easy enough to understand but the resulting code ugly. It reminded me of the long forgotten days of outputting HTML from servlets.

Chapter 9 - Ajax

The chapter on Ajax is focused on describing the tight integration of Grails custom tags with your favorite JavaScript library, as long as it’s Prototype/Scriptaculous, Yahoo UI, or the Dojo Toolkit. Most of the explanation is described by refactoring the book example to add in some Ajax goodness. Included are descriptions of the g:remoteField, g:remoteLink, and g:formRemote tag, the process of specify JavaScript to run before or after a remote call, and custom event handling. Lastly, there’s a quick example of adding some JavaScript UI effects using Scriptaculous.

Chapter 10 - Services and Jobs

Chapter ten starts with a discussion of the traditional service tier of a Java application. This chapter is also home to the first mention of transactional support from Grails, and it is certainly brief. I have to think there’s a lot more to Grails transaction support than Graeme is divulging.

The discussion of services finishes up with a demonstration on the use of the service layer by creating one that calls a del.icio.us web service. The example covers everything from writing the Jakarta Commons HTTP Client to calling the service from a controller.

From services we move to jobs, which Graeme has spent a whopping twenty-six pages describing. Jobs are built on top of the Quartz scheduling engine, and a good portion of the twenty-six pages is devoted to explaining it. He covers all angles associated with jobs, including creating, scheduling, testing, pausing, resuming, and removing jobs. All of this is done through a non-trivial example of a daily scheduled job that queries the database and then formats the results as an email delivered via JavaMail.

Chapter 11 - Java Integration

The last chapter covers Grails integration with Java. The discussion is most heavily weighted towards integration options with Hibernate and Spring. However, Graeme also covers using Acegi for Grails security and exposing a SOAP service using the XFire library. The following paragraphs describe each topic.

ORM Integration with Hibernate

Anyone using Hibernate on an existing project will likely be quite happy after reading this part of chapter eleven. Graeme describes how you can use Grails with an existing domain model and either Hibernate XML mapping files or EJB3 annotations. I have to admit that I had a bit of a smile on my face after reading this section and realizing that I didn’t have to wait for an entirely new project to try out Grails.

I was equally surprised to find that I can use Grails constraints on my non-Grails domain objects. Graeme provides an example of how to do this in short order.

Dependency Injection with Spring

The section on dependency injection with Spring shows you how to leverage the Spring Framework underlying Grails. A basic understanding of the Spring Framework will certainly help understand the text, although I don’t think it’s absolutely necessary.

In the chapter, Graeme talks about how to override Grails beans and how to use Spring controllers with Grails. The explanation of using Spring controllers is much more thorough than I would have expected, with plenty of sample code to help guide the reader.

Acegi

The section on using Acegi is jam packed with the XML code snippets you need for a basic configuration of the security framework. If you seriously plan to use Acegi, you’ll need to look elsewhere for more information. The eight pages of XML is hardly enough to understand what’s going on.

Exposing a SOAP Service with XFire

I have a feeling that Apress pressured Graeme into including the chapter on web services with XFire. After all, any respectable book on web development needs to talk about web services. Right? The content was nothing more than a brush pass and had nothing to do with Grails. The text, although well-explained, would have fit just as nicely in any book on JEE web development.

Posted by jkunkle Aug 15 2007, 09:11:01 AM EDT
20070415 Sunday April 15, 2007
Solid State Encrypted Drives - The next big thing?

I’ve noticed two topics generating a lot of buzz in the storage world lately.

  1. Hardware-Encrypted Disk Drives
  2. Solid State Disk Drives

I believe the first topic is a direct result of the disclosure of scores of high-profile data breaches resulting from stolen computers. The highest profile instance occurred in May of 2006 when a U.S. Department of Veteran’s Affairs laptop containing the names, social security numbers, dates of birth, phone numbers, and addresses of 26.5 million American veterans was stolen. Unauthorized information disclosure has unfortunately become an all too common occurrence in today’s world.

In response, vendors such as Seagate have introduced hardware-encrypted notebook hard drives to counter the unintended loss of sensitive information when a computer is stolen. The idea is that data stored on the hard drive is encrypted at all times, rendering the information practically useless to thieves. The encryption is done in specialized hardware to reduce the performance impact associated with the extra computation.

The second topic is the result of a continued increase in flash-based memory capacity to the point where it can now be considered as an alternative to traditional hard drives. Both Samsung and Sandisk have recently announced 64GB (Samsung) and 32GB (Sandisk) products targeted for laptop usage. Since there are no moving parts, flash-based memory consumes much less power than the spinning platters of a traditional hard disk, which is obviously a big benefit for laptop users. As a side benefit, these flash-based memory “drives” are rumored to be anywhere from 4-10x faster than a traditional hard drive, which brings me to the main point of this post.

How long will it be until we see solid-state “drives” such as the ones from Samsung and Sandisk coupled with dedicated hardware-based encryption as demonstrated on the new Seagate drive? A considerable downside to full-disk encryption of traditional drives is the performance impact. Since the new flash-based drives are several times faster, why not bake in full-drive encryption now when nobody will notice it. What you’d end up with are flash-based drives that provide full-disk encryption and still outperform traditional drives. Waiting to add full-disk encryption to later versions of flash-based drives will only introduce the performance debate that faces today’s traditional drives, making the purchasing decision all that much more difficult. Why not avoid the confusion and help customers better secure their data in the process?

Posted by jkunkle Apr 15 2007, 09:10:11 PM EDT
20070330 Friday March 30, 2007
Update Mac OSX split for Pieces Larger than 2GB and Greater

Split is a very useful command-line utility for breaking large files into smaller pieces. Unfortunately, the version Apple ships with OSX 10.4 cannot split files into pieces 2GB or larger. Luckily, there is a newer version of split that you can compile and use instead of the Apple-supplied one.

There is a nice article/post over at macosxhints.com describing how to upgrade split. It's really not very hard but I thought I'd write a script so people could upgrade with a minimum of effort.

The short script is shown below. Please note that it is currently hard-coded for version 1.21 of split. You may want to check and see if there is a newer version before running the script.

#!/bin/bash
curl -o split.c "http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/usr.bin/split/split.c?rev=1.21&content-type=text/plain"
perl -p -i -e 's/#include <sys\/cdefs.h>/#include <sys\/stat.h>\n#include <sys\/cdefs.h>/' split.c
cc -Os -o split split.c
sudo mv /usr/bin/split /usr/bin/split.apple
sudo cp split /usr/bin/split
sudo chmod ugo-w /usr/bin/split
sudo chmod ugo+rx /usr/bin/split
sudo chown root:wheel /usr/bin/split
echo "Upgrade Complete."
Posted by jkunkle Mar 30 2007, 10:26:23 AM EST
20070324 Saturday March 24, 2007
Logging into Mac OS X Hidden Administrator Accounts

Every once in a while I need to login to a hidden administrator account on my Mac. It's a simple process after you invest lots of time trying to remember the key combination needed to expose the User Name and Password prompt instead of the usual graphical user account login prompt (which doesn't show the hidden admin accounts of course). Many times I've searched all over the Internet to uncover the secret and never seem to find anything quickly, so I thought I'd document it here for future reference.

Let's assume that you're staring at the usual graphical login prompt. There's a nice little picture to the left of each of your user accounts, but no way to enter a username. If you only have one user account on your Mac, you're already being prompted for the password to that account. If this is the case, hit Esc.

Now you should only see a list of all the user accounts on your Mac, and should not see a password field. Press the down arrow key until you see a gray background behind one of your user accounts. It doesn't matter which one.

Next, press Option-Enter. Your normal graphical login screen should now be replaced with two text entry fields, one for your User Name and one for your Password. Now you can enter the username and password of your hidden administrator account (or any account for that matter). That's it.

Please note that I don't know if the Option-Enter key combination does anything if you don't have any hidden accounts. You'll have to try it for yourself and see.

Posted by jkunkle Mar 24 2007, 12:20:12 PM EST
20070314 Wednesday March 14, 2007
Performance of Guarding Debug Log Statements

A few days ago, some people in the office were debating the value of our time honored tradition of guarding debug log statements. If you're not sure what I'm talking about, a short code sample should clear things up quickly.

if (log.isDebugEnabled()) {
  log.debug("Log message number " + 1);
}

It's generally accepted that guarding your log statements with an if block will improve performance if your log statements involve some kind of string concatenation, such as the example above. But what kind of performance improvement are we really talking about here?

To determine the impact of this log guarding, I wrote a simple program that repeatedly calls log statements with three different logging implementations. See attachment for the actual code.

  1. UnguardedLogger.java has no if block guarding the log statement at all.
  2. IfGuardedLogger.java has the traditional if block surrounding the log statement, just like the example above.
  3. AspectGuardedLogger.java acts just like the UnguardedLogger except that it has an AspectJ aspect guarding it's log statement. The idea here was to allow you to abandoned typing the if block guard while still enjoying its benefits.

All three implementations were asked to log one million statements in three successive batches. Each log statement included a string concatenation of six components. Each batch ran the three implementations in a different order. The results of the test run are shown below.

ImplementationTest 1Test 2Test 3
UnguardedLogger1341ms1783ms1345ms
IfGuardedLogger35ms32ms30ms
AspectGuardedLogger1343ms1612ms1364ms

Broken down by average time per log statement, that's

  • UnguardedLogger - 1.49µs/statement
  • IfGuardedLogger - 0.03µs/statement
  • AspectGuardedLogger - 1.44µs/statement

From these numbers, I've drawn two conclusions

  1. Guarding your log statements is a lot faster (in this case, 50x faster) than not guarding them at all or guarding them using an aspect. Even so, we're still down in the microsecond range here. If you're doing a lot of logging, you may notice a small improvement from guarding your log statements. Otherwise, you may not want to bother.
  2. Guarding your log statements with an around aspect is really no better than not guarding them at all. I'm not familiar with the internals of AspectJ, but my hunch is that even an around aspect will have to do the log statement string concatenation so that it could potentially be exposed as context for an advice. Hence, it ends up being about the same as not guarding the log statements at all.
Posted by jkunkle Mar 14 2007, 08:37:14 PM EST
20061129 Wednesday November 29, 2006
Start with Something New

To one extent or another, I‘ve been involved with many projects whose goal was to replace an existing system while adding some new features. On the surface, these sound like rather straightforward efforts. After all, the existing system is the source for all your legacy system replacement requirements, right? Unfortunately, these projects often struggle and many are never deployed. Why? Because they don‘t start with something new.

In my experience, legacy replacement projects first focus on supplanting the features of the old system rather than building new capabilities. In many cases, the legacy system was built over a period of years where new features were continually added and refined. However, new development efforts are rarely given years to write replacement software for the legacy system. The result is usually an initial version that doesn‘t even provide the same capabilities as the old application and adds little or nothing new. Why would a busy user spend their valuable time to learn a new system that provides less functionality than what they have today? In many cases they don‘t and the system is labeled a failure before it even gets rolling.

Why not start by building the new features first? Hook your users with new capabilities they don‘t have today and slowly replace the legacy features until the existing system is no longer needed or used. As a side benefit, your users may decide they don‘t need certain features of the legacy system anymore or that they should work differently based on their experiences with the new capabilities you‘ve given them. At the end of the day, I think you‘ll end up with a more successful application that better addresses users‘ current needs.

Posted by jkunkle Nov 29 2006, 09:25:36 PM EST
20060711 Tuesday July 11, 2006
NotNull Hibernate Annotation Validation Problems

I recently decided to try out Hibernate's annotation-based validation framework. It seems like a great solution for ensuring consistent validation of the domain model regardless of the presentation tier (web interface, web service, etc.). It very much reminds me of the declarative validation available within Rails model objects.

To make a long story short, things did not go as well as I had hoped using a Hibernate Core 3.2.0 CR2 and Hibernate Annotations 3.2.0 CR1 combination. I struggled for hours trying to figure out why I was getting a "not-null property references a null or transient value" error rather than a validation error when attempting to use the NotNull validation annotation. Eventually I discovered the problem was not that the NotNull validation wasn't working properly, but that it wasn't running at all.

In order for the annotation-based validation framework to execute, Hibernate Annotations provides a ValidatePreInsertEventListener and ValidatePreUpdateEventListener to fire the annotation validations prior to persisting any changes to the domain model. "Pre-insert" and "pre-update" events are fired after other events, in this case SaveOrUpdateEvent(s). By default, Hibernate uses the DefaultSaveOrUpdateEventListener, which is an extension of AbstractSaveEventListener. The AbstractSaveEventListener checks for null values corresponding to non-nullable database columns ( AbstractSaveEventListener:284 ) before adding the insert or update events to the execution queue( AbstractSaveEventListener:290 ) responsible for triggering pre-insert or pre-update event listeners. In case that didn't make complete sense, the bottom line is the Hibernate Core checks entities against the null constraints of the database before the annotation-based validation framework has a chance to run.

Luckily, there is a workaround, although it feels like a bit of a hack. As I mentioned previously, the DefaultSaveOrUpdateEventListener gets a chance to run before any "pre-insert" or "pre-update" events so we can use that to our advantage. The following SaveOrUpdateEventListener simply extends the Hibernate Annotations-provided ValidateEventListener and calls the validation method on "save-update" events rather than "pre-insert" and "pre-update" events.


public class ValidationEventListener 
    extends ValidateEventListener 
    implements SaveOrUpdateEventListener {

  public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
    final SessionImplementor source = event.getSession();
    final Object object = event.getObject();
    if (!source.getPersistenceContext().reassociateIfUninitializedProxy(object)) {
      // only validate the entity if it has been changed
      final Object entity = 
        source.getPersistenceContext().unproxyAndReassociate(object);
      super.validate(entity, event.getSession().getEntityMode());
    }
  }

}

One extemely important thing to remember when using this workaround is that you must configure the DefaultSaveOrUpdateEventListener as the second "save-update" listener (following the ValidationEventListener) or your objects will never be persisted.

Posted by jkunkle Jul 11 2006, 08:59:58 AM EDT
20060625 Sunday June 25, 2006
XSS Vulnerabilities of JSP 2.0 Expressions

&JSP 2.0 introduced a handy new capability allowing you to use JSP Expressions directly within the template text (i.e. outside of tag libraries or tag files) of a web page. This allows developers to easily expose data and objects stored in application, session, request, or page scope using a simple Ant-style syntax. It allows you to replace this


<table>
<c:forEach var="book" items="${books}">
<tr>
<td><c:out value="${book.title}"/></td>
<td><c:out value="${book.author}"/></td>
<td><c:out value="${book.isbn}"/></td>
</tr>
</c:forEach>
</table>

with this

;code>
<table>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.isbn}</td>
</tr>
</c:forEach>
</table>

As you can see, the syntax in the second example is much cleaner. But, “with great power comes great responsibility.” The chink in the armor that every tutorial I‘ve read (including Sun's Java EE 5 Tutorial) fails to mention is that the expression syntax does not escape HTML characters. Therefore, any web application using JSP Expressions to output unsanitized, user-entered data will be vulnerable to Cross Site Scripting (XSS) attacks.

Unfortunately, the cure for this XSS vulnerability leads us right back to our first example. As section 2.2.2 of the JSP 2.0 Specification reads, “In cases where escaping is desired (for example, to help prevent cross-site scripting attacks), the JSTL core tag c:out can be used.”

My advice is to use JSP Expressions only as tag library attribute values and stick to using JSTL‘s c:out tag for writing text to a page. Deciding which instances of template text expression usage are safe and which are not is simply too error prone and the consequences of a mistake too dangerous.

Posted by jkunkle Jun 25 2006, 03:46:48 PM EDT