Rich Web Experience

JSFOne

Private Events

Blogs

View all Blogs >>
  • Andrew Glover

    Co-author of "Continuous Integration"

    Enjoy the reading, baby: Continuous Integr more»

  • Michael Nygard

    Agile technology leader and dynamicist

    If large amounts of dirty data are actually valuable, how do you go about collecting it? Who's in the best position to amass huge piles? more»

  • Keith Donald

    Lead of Spring Web and Creator of Spring Web Flow

    I am pleased to announce that Developing Rich Web Applications with Spring, a three-day bootcamp lead by SpringSource engineers on web... more»

  • Mike Levin

    Software Developer specializing in Web2.0 websites

    “ align=“left” Del.icio.us is one more»

  • Matt Raible

    Creator of AppFuse and author of Spring Live

    Last Thursday, Kevin Brown visited LinkedIn's Mountain View office to do a presentation on Shindig, more»

  • Ted Neward

    Enterprise, Virtual Machine and Language Wonk

    If you've peeked at my blog site in the last twenty minutes or so, you've probably noticed some churn in the template in the upper-left... more»

  • Neal Ford

    Application Architect at ThoughtWorks, Inc.

    OK, it's finally here. I g more»

  • Richard Monson-Haefel

    VP of Developer Relations, Curl Inc.

    more»

  • Nathaniel Schutta

    Author, speaker, software engineer focused on user interface design.

    I don’t get to go to quite as many conferences as I’d like but luckily more and more organizers are putting talks on-line or... more»

  • Alex Miller

    Sr. Engineer with Terracotta Inc.

    I’m just starting to build out an app that uses Hibernate. I started with Hibernate mapping files but switched over to using JPA... more»

  • Pramod Sadalage

    Co-author of "Refactoring Databases:Evolutionary Database Development"

    When creating a Foreign Key constraint on the database as shown below ALTER TABLE BOOK ADD (CONSTRAINT FK_BOOK_ more»

  • Guillaume LaForge

    Groovy Spec Lead & Project Manager

    more»

  • Pratik Patel

    Software Architect

    I've been (very) slowly hacking away at new-and-improved Dojo plugin for Grails. I've found that Dojo, not Grails, has been my bottleneck -... more»

  • Graeme Rocher

    Project Lead of the Grails Project & CTO of G2One

    Apologies for not posting as frequently recently, I've been hard at work on the second edition of "The Definitive Guide to Grails" and also... more»

  • Jeff Brown

    G2One Director Of North American Operations - Groovy and Grails Developer

    G2One have announced our G roovy/Grails No more»

  • Jared Richardson

    Agile coach and co-author of Ship It

    Ouch. I feel guilty. The Joy of Tech on 3G iPhones more»

  • Ryan Shriver

    Business and Technology Consulting

    more»

  • Venkat Subramaniam

    Founder of Agile Developer, Inc.

    I have been waiting for this book since I saw my friend Neal more»

  • Jason Rudolph

    Author of Getting Started with Grails

    As of 8:55 EDT, there’s no direct link to the store just yet, but you can “hack” your way in. Just search the iTunes st more»

  • Howard Lewis Ship

    Creator of Tapestry and HiveMind

    I'll be flying into Cambridge, UK for a week of Tapestry training. I'll be there from Sunday through Thursday night before returning to... more»

  • Erik Doernenburg

    Principal Consultant @ Thoughtworks

    For a few releases the Apple development tools have included OCUnit and many developers have now started to write unit tests. There are lots... more»

  • Brian Pontarelli

    Brian Pontarelli - founder of Inversoft

    Found a good shortcut for getting access to hidden folders in OS X file dialogs and the Finder. It requires some typing and it doesn’t... more»

  • Vladimir Vivien

    Software Engineer / Consultant

    Judging from the list of features that will be included in NetBeans 6.5, more»

  • David Bock

    Principal Consultant, CodeSherpas Inc.

    I just spent this weekend speaking at the Ag ile IT Exchange conference i more»

  • Scott Leberknight

    Chief Architect at Near Infinity

    I ran into a situation the other day with Groovy that baffled me at first. Let's create a range from 0.0 to 10.0 and then use it to check if... more»

  • Kirk Knoernschild

    Software Developer & Mentor

    I’ve published a summary of the OSGi survey results on the APS blog more»

  • Stuart Halloway

    CEO of Relevance

    I was talking to Tim the other day about auditing Rails projects, a more»

  • Brian Goetz

    Author of Java Concurrency in Practice

    This surprised the heck out of me.�� We recently finished a new TV room down in the basement.�� We have a 50″ plasma TV, mounted on the... more»

  • Jason Harwig

    Senior Software Engineer at Near Infinity

    I was reading a blog entry at more»

  • Craig Walls

    Author of Spring in Action

    For quite some time I've been pondering OSGi and how it fits into enterprise Java. And that interest has been magnified over the past month... more»

  • Pete Behrens

    Organizational Agility Coach

    Marti nig & Associates Methods & Tools group recentl more»

  • Joseph Nusairat

    Author of Beginning JBoss Seam & Co-Author of Beginning Groovy & Grails

    Today is the first day of JBoss World, I survived the first three presentations and waiting for the keynote to be  complete to d more»

  • John Heintz

    Principal Consultant with New Aspects of Software

    This post is to mostly keep track of the numerous blog threads going on about IDLs and schemas for REST. I find myself with more to say that... more»

  • Brian Sam-Bodden

    Java author, Ruby geek and Open Source Advocate

    In this installment we are going to build the Dashboard page of the Tempo application. T more»

  • Mark Fisher

    Spring Integration Lead

    In my recent post, I had mentio more»

  • Ron Bodkin

    Chief Software Architect, Quantcast

    I'm looking forward to speaking at The Rich Web Experience conference in San Jose next month. The event runs from September 7th through 9th.... more»

  • Mark Goodwin

    Web Application Security Specialist

    We've already looked at one of the two big problems posed by anti DNS pinning on Java applets; because there's rebinding on the applet and... more»

  • Scott Davis

    Author of "Groovy Recipes" & TDD Expert

    Every time I see a live show at the Denver Botanic more»

  • Romain Guy

    Java User Interface expert.

    more»

  • Ramnivas Laddad

    Author of AspectJ in Action, Principal at SpringSource

    InfoQ.com has published my AOP myths and realities talk recorded at a No Fluff Just Stuff conference. InfoQ.com founded by Floyd Marine more»

  • David Geary

    Author of Graphic Java and co-author of Core JSF

    The 2006 NFJS tour kicked off t more»

  • Jason Hunter

    Author of Java Servlet Programming

    I just posted the JDOM 1.1 release for download. This release includes about 20 improvements and bug fixes. more»

  • Kito Mann

    Editor-in-chief of JSF Central and the author of JSF in Action

    In this three-part series, author and Java™ developer Andrei Cioroianu shows you how to automatically save form data in a Java Web... more»


In the Spotlight - Scott Leberknight

Chief Architect at Near Infinity

Scott is Chief Architect at Near Infinity Corporation, an enterprise software development, training, and consulting services company based in Reston, Virginia. He has been developing enterprise and web applications for 13 years professionally, and has developed web applications using Java, Ruby/Rails, Groovy/Grails and a smidgeon of Python. His main areas of interest include object-oriented design, system architecture, testing, and frameworks of all types including Spring, Hibernate, Ruby on Rails, Grails, and Django. In addition, Scott enjoys learning new languages to make himself a better and more well-rounded developer a la The Pragmatic Programmers' advice to "learn one language per year."

Scott holds a B.S. in Engineering Science and Mechanics from Virginia Tech, and an M. Eng. in Systems Engineering from the University of Maryland. Scott speaks at the No Fluff Just Stuff Symposiums and various other conferences. In his (sparse) spare time, Scott enjoys spending time with his wife, two daughters, and two cats. He also tries to find time to play soccer, go snowboarding, and mountain bike whenever he can.















Presentations by Scott Leberknight

Google Your Domain Objects With Hibernate Search

Hibernate is one of the pre-eminent object/relational mapping technologies, but the Hibernate Search project adds full-text search capabilities to an already extremely capable tool to allow you to Google your domain objects.

Introduction to Hibernate

This session introduces the Hibernate Object/Relational Mapping (ORM) framework, showing the basics of persisting Java objects to relational databases. No prior knowledge of Hibernate or ORM is assumed.

Streamlined Web Apps With Spring

With the release of Spring 2.5 comes a host of new features that make Java web application development faster, cleaner, and more streamlined. We'll use Spring 2.5 to implement a simple web application from the ground up in this session.

Real World Hibernate Tips

Hibernate is a very powerful object/relational mapping framework. With the vast amount of power also comes the responsibility to choose which features of Hibernate to use and how to use them, as well as things to avoid. We'll look at some real world Hibernate tips and tricks in this session.

Groovier Spring (More Flexible Applications With Spring and Groovy)

Spring provides a solid foundation for web and enterprise applications. Its support for dynamic languages like Groovy adds interesting capabilities that can make your application architecture more flexible and dynamic.






Books by Scott Leberknight

by Glenn Vanderburg, Rebecca Parsons,Ted Neward, Scott Davis, Brian Sletten, Howard Lewis Ship, David Geary, Neal Ford, Paul Duvall, David Bock, Venkat Subramaniam, Nate Schutta, Jared Richardson, David Hussman, Mark Richards, and Scott Leberknight.





Scott Leberknight's Weblog
Some Day I'll Have More Time...


Scott Leberknight's complete blog can be found at: http://www.sleberknight.com/blog/sleberkn

Wednesday, June 25, 2008

I ran into a situation the other day with Groovy that baffled me at first. Let's create a range from 0.0 to 10.0 and then use it to check if a certain number is contained within that range, like this:

groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.contains(5.6)
===> false

WTF? The number 5.6 is not contained in the range 0.0 to 10.0? I beg to differ. So what's actually going on here? Using the shell we can do some more digging, interrogating the range object to see what its bounds are, what values it contains if you iterate it, and so on:

groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.class
===> class groovy.lang.ObjectRange
groovy:000> r.from.class
===> class java.math.BigDecimal
groovy:000> r.to.class
===> class java.math.BigDecimal
groovy:000> r.each { print " $it " }  
 0.0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0  10.0 ===> 0.0..10.0
groovy:000> r.contains 5 
===> true
groovy:000> r.contains 5.0
===> true
groovy:000> r.contains 5.6
===> false

So what did we learn? First, the range is an ObjectRange whose bounds are BigDecimals. Second, that iterating by default iterates in increments of one. And third that the contains method does not quite do what I would expect by default. Looking at Groovy's ObjectRange class makes it clear exactly what's going on, so let's look:

public boolean contains(Object value) {
  Iterator it = iterator();
  if (value == null) return false;
  while (it.hasNext()) {
    try {
      if (DefaultTypeTransformation.compareEqual(value, it.next())) return true;
    } catch (ClassCastException e) {
      return false;
    }
  }
  return false;
}

The Groovy ObjectRange's contains method defines containment as whether a value is contained within the values generated by its iterator. By now many of my many millions of readers are about to post a comment telling me the problem, so I'll preempt that temptation by adding a few more lines of interaction with the Groovy shell:

groovy:000> r.containsWithinBounds 5.0
===> true
groovy:000> r.containsWithinBounds 5.6
===> true

Aha! So contains doesn't do what you might think it should, but containsWithinBounds does. Its JavaDoc says "Checks whether a value is between the from and to values of a Range." Conspicuously there is no JavaDoc on the contains method to tell me that what it actually does is check whether a value is contained within the discrete values generated by the iterator. Let's try more more thing:

groovy:000> r.containsWithinBounds 5
ERROR java.lang.ClassCastException: java.lang.Integer
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...

Oops! Not only do you need to call containsWithinBounds rather than contains, you also need to call it with the correct type, as there is no coercion going on since it uses Comparable.compareTo() under the covers.

Notwithstanding all the recent activity regarding all the Ruby security flaws recently discovered, how does Ruby handle inclusion of a number within a range? Here's some irb output:

>> r = 0.0..10.0
=> 0.0..10.0
>> r.class
=> Range
>> r.begin.class
=> Float
>> r.end.class
=> Float
>> r.each { |item| print " #{item} " }
TypeError: can't iterate from Float
        from (irb):53:in `each'
        from (irb):53
>> r.include? 5
=> true
>> r.include? 5.0
=> true
>> r.include? 5.6
=> true

To me this is more semantically and intuitively correct behavior. First, while I can create a range with float bounds, I cannot iterate that range - for non-integral numbers, how exactly can you define the next item after 0.0 for example? 0.1, 0.01, 0.001, and so on till infinity. Second, the include? method behaves as I would expect no matter what type of argument I pass. I am able to iterate ranges of integral numbers, however, which could arguably also be confusing since the behavior of the method depends on the type. Then again, that's pretty much what polymorphic method behavior is about I suppose.

>> r = 0..10
=> 0..10
>> r.each { |item| print " #{item} " }
 0  1  2  3  4  5  6  7  8  9  10 => 0..10

In the case of integers Ruby uses an increment of one by default. You could use the step method to get a different increment, e.g.:

>> r.step(2) { |item| print " #{item} " }
 0  2  4  6  8  10 => 0..10

So what's the point of all this? That Ruby is better than Groovy? Nope. I really like both languages. I think there are a couple of points that were reinforced to me:

First, RTFM (or source code --> RTFC). Even though Groovy's contains method doesn't behave how I think it should, there is the method I was looking for with containsWithinBounds.

Second, having a shell to play around with short snippets of code is really, really useful, without needing to create a class with a main method just to play around with code.

Third, documentation and semantics matter. If something doesn't feel intuitively correct based on how similar things act, it is more likely to cause confusion and errors. In this case, since my unit test immediately caught the error, I was able to figure the problem out in a few minutes.

Finally, following on from the last point, unit tests continue to remain valuable. Of course anyone who knows me would roll their eyes over my anal-ness (which Mac's dictionary is telling me is not really a word but I don't care at the moment) expecting me to get something about unit testing in somehow.


Monday, June 23, 2008

One really cool feature in Spring 2.5+ is classpath component scanning. For example, instead of manually defining and wiring up all the beans comprising your Spring-based application, you simply add a few "driver" snippets of XML to your application context configuration, and then annotate your component classes with @Component (or any specialization such as @Controller and @Service). I am calling the XML snippets a "driver" because all they do is enable a specific feature, such as classpath scanning or component autowiring:

<-- Enable autowiring via @Autowire annotations -->
<context:annotation-config/>

<-- Scan for components in a package (and its subpackages)  -->
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

After seeing this was pretty cool, I wanted to know how exactly they did the classpath scanning. It boils down to doing some gymnastics with class loaders and resource path matching and using the ClassLoader.getResources(String name) method which returns an Enumeration containing URLs representing classpath resources. Those resources (Java classes) are then checked to see if they contain the @Component annotation (or a specialization of it) and if so, are considered a "candidate" component. Other filtering can take place but by default those components are then defined programmatically as Spring beans. When annotation configuration is enabled, autowiring of components also takes place, so I can have Spring scan the classpath for all my web controllers, and then automatically inject dependencies such as services or data access objects. Cool!

The actual classes that perform this magic are the ClassPathScanningCandidateComponentProvider which, by default, uses a PathMatchingResourcePatternResolver to find matching classpath resources using ClassLoader.getResources(). As a quick example, you can see this in action by writing a simple script, like so:

ClassPathScanningCandidateComponentProvider provider =
    new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
    System.out.printf("Component: %s\n", component.getBeanClassName());
}

Running this code (using the PetClinic sample application shipped with Spring), you get the following output:

Component: org.springframework.samples.petclinic.hibernate.HibernateClinic
Component: org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic
Component: org.springframework.samples.petclinic.jpa.EntityManagerClinic
Component: org.springframework.samples.petclinic.web.AddOwnerForm
Component: org.springframework.samples.petclinic.web.AddPetForm
Component: org.springframework.samples.petclinic.web.AddVisitForm
Component: org.springframework.samples.petclinic.web.ClinicController
Component: org.springframework.samples.petclinic.web.EditOwnerForm
Component: org.springframework.samples.petclinic.web.EditPetForm
Component: org.springframework.samples.petclinic.web.FindOwnersForm

For a more fun experiment, I tried to scan using "org" as the base package...

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at org.springframework.asm.ClassReader.a(Unknown Source)
	at org.springframework.asm.ClassReader.(Unknown Source)
	at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
	at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:68)
	at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:181)
	at org.springframework.samples.petclinic.ClassPathScannerTester.main(ClassPathScannerTester.java:17)

Ok, so you need to restrict the scan space that Spring will use or else you could run out of memory scanning every possible class in your system! Regardless, with classpath scanning of components and autowiring of dependencies, you can cut down the amount of XML in Spring-based apps a lot.


Wednesday, June 18, 2008

On a current project I needed to create an executable JAR that does a bunch of processing on collections of files. As with most projects, I rely on a bunch of open source tools as dependencies. Since, to my current knowledge anyway, there is no way to have JARs within JARs I needed a quick way to create an executable JAR containing all the required dependencies. I did a bunch of searching and asking around and eventually found the Maven Assembly Plugin. This plugin generates "assemblies" which could be just the executable JAR or could be an entire source distribution in multiple formats (e.g. zip, tar.gz, etc.).

The basics of the plugin are simple. Add the <plugin> to your Maven POM file, define the assembly, and for executable JARs specify the main class. Here's how I configured the plugin:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>com.nearinfinity.arc2text.ARC2TextConverter</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

In the above, I used one of the conveniently predefined descriptor references, in this case "jar-with-dependencies" which does pretty much exactly as you would expect. You could also define your own assembly but that looked quite a bit more complicated and all I needed was to simply produce an executable JAR. When the assembly plugin executes the above example configuration, it creates a single executable JAR with all my classes and all the classes from all the dependencies. It also sets up the JAR manifest with the Main-Class that you specify. The dependencies, which in my case were all other JAR files, are extracted from their JARs and placed directly into the JAR file, i.e. the classes in the dependent JARs are extracted and then put into the new custom JAR. The plugin even copies over license files, e.g. LICENSE, ASM-LICENSE.txt, etc. into the META-INF directory in the JAR.

The only things left to do is use the plugin. To do that you can simply run the command:

mvn assembly:assembly

There are other goals in the assembly plugin but this is the main one you need. So if you need to create an executable JAR containing dependencies, this is a nice quick way to do it, especially if you were already using Maven.


Tuesday, May 13, 2008

Often when writing unit tests I use EasyMock to mock dependencies of the class under test. And many times I need to test that a certain type of exception is thrown during a test. Sometimes I need both, for example I am using a mock to simulate a dependency that throws an exception and I want my test to verify the appropriate exception was indeed thrown and that the mock was called properly. In those cases, I use a simple little trick: use a try/finally block along with a JUnit "@Test(expected = FooException.class" annotation on my test method. Voila! Now you can verify mock behavior and verify the exception was thrown at the same time. This is cleaner than using a catch block and asserting the correct exception was thrown, since you rely on JUnit to verify the exception using the "expected" attribute of the @Test annotation. For example:

@Test(expected = ThrottleException.class)
public void testSomethingWithDependencies() {
    // Create mock
    Rocket mainBooster = createMock(Rocket.class);
	
    // Record behavior
    mainBooster.ignite();
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class);
    
    // Replay mock
    replay(rocket);
    
    // Create object with dependency on mainBooster
    SpaceShuttle shuttle = new SpaceShuttle(rocket);    
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff();
    }
    finally {
        verify(rocket);
    }
}

If instead of writing tests in Java you write them in Groovy, the above code could be a little bit Groovier, though not much. (In an earlier post I showed how you can write unit tests in Groovy and still use JUnit instead of GroovyTestCase if you like.)

@Test(expected = ThrottleException)
void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
    
    // Record behavior
    mainBooster.ignite()
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff()
    }
    finally {
        verify rocket
    }
}

Even more Groovy in this case would be to extend GroovyTestCase and use its shouldFail method, like so:

void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
	
    // Record behavior
    mainBooster.ignite()
	
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    shouldFail(ThrottleException) {
        shuttle.blastOff()
    }
    verify rocket
}

The GroovyTestCase version is probably the cleanest of the above three options. If you're not into Groovy, you can still use the JUnit "@Test(expected = BarException.class)" together with a try/finally/verify in plain Java unit tests for a cleaner test experience.


Monday, April 14, 2008

Have you ever wondered, what is the best way to implement SOA in your organization? How can it help you? What benefits await and what are the possible gotchas? Well, here's my take on it:

Proper Role of SOA

Used this way, the benefits include ensuring my monitor is at eye level for proper posture when writing code. In addition, any time I read in some article how SOA is going to solve the world's problems at some undetermined point in the future, I can always look down from the monitor and see the real role of SOA. Among the possible gotchas? For one, I have to actually look at the words "Service-Oriented Architecture" all day I suppose. Perhaps turning the book around might help on that issue. Another, possibly offending those who would prefer to use SOAP for all message passing (in lieu of methods which of course tightly couple the message sender and receiver, right?) in their application to ensure loose coupling between their components. Last, if and when the SOA hype cycle gives way to the next hype cycle, I'll need to actually spend more money to get another book to remind me to disregard the hype.