Archive for the 'Programming' Category

New Kid on the Block

On this cloudy Dallas Saturday morning, the ExtJS team announced the availability of Ext Core (beta). Ext Core is the core DOM selection, manipulation and events library of ExtJS which has been extracted out into a separate library released under a more liberal license. They smartly released this under the very permissive MIT license, in contrast to the cancerous GPL used for the full ExtJS.

What makes this interesting is it positions Ext Core as a direct competitor to the popular JQuery library. I really like both ExtJS and JQuery, so I decided to run a quick comparison of the two libraries to see if Ext Core is up to the task of replacing JQuery in my developer toolbox. Since there is so much overlap between the two, it makes no sense to use both.

Round 1 – Size

Library size of the two is pretty close. The minified version of JQuery runs about 56K, while the minified version of Ext Core weighs in at 75K. The 19K difference might matter for an iPhone application, but even then, I would consider it negligible. Both are pretty small libraries, so we’ll call Round 1 a tie and move on to feature comparison.

Round 2 – Load Event

How each of these libraries works the document ready event is more a matter of style. The JQuery convention is to use the dollar sign ($) for for operations, although you can fall back to using the full name (jQuery). Setting up a ready event in JQuery looks like this:

$(document).ready(function() {
    // do cool stuff
});

Ext Core uses the static Ext class for the same functionality. Like the jQuery object, the Ext object is the heart of Ext Core. Setting up the ready listener in Ext Core looks like this:

Ext.onReady(function() {
    // do cool stuff
});

One big difference is the onReady method can take an additional parameter specifying the scope in which the onReady method should execute. This is not a big deal in most cases, but shows Ext Core’s attention to support object oriented JavaScript. Since I’ve never actually needed to specify the scope, I’ll call this round a tie too.

Round 3 – Selectors

This is the heart of both libraries, and a full comparison could fill a dozen pages. The short story is they both support basically the same set of CSS3 selectors along with some custom enhancements. From looking at the documentation, I couldn’t find any typical use cases that either couldn’t handle. Like the document ready example above, it just comes down to a matter of convention. For example, here is the code from each to add a class to a set of nodes:

// JQuery
$('td.age').addClass('someclass');
 
// Ext Core
Ext.select('td.age').addClass('someclass');

One major style difference between the two is that Ext Core has a tighter focus in handing elements with ids, since that is critical to the full ExtJS library. For example, Ext Core has the get() method to directly grab an element by ID, along with a memory-friendly fly() method. The fly() method does not create a new element wrapper in memory, and instead reuses a single global element object. This can save a lot of memory when you just need to do quick manipulations of single objects.

// Add a class to the element with ID of 'header'
Ext.fly('header').addClass('someclass');

For the memory saving fly operation, I’ll give the advantage to Ext Core, although they are essentially equal in their DOM selection abilities.

Round 4 – Events

Like the selectors above, there are basically style differences between the two libraries in how they handle basic event use cases. JQuery adds some methods to the jQuery object for registering common events. For example, here is the code to add a click event to a button for each, including the JQuery shortcut:

// JQuery with bind()
$('#myButton').bind('click', function() { alert('Clicked');});
// JQuery with shortcut
$('#myButton').click(function() { alert('Clicked');});
// Ext Core
Ext.fly('myButton').on('click', function() { alert('Clicked');};

JQuery brings some some additional enhancements to the game in the form of “live” events. This provides a way of attaching an event to all current, and future, instances of the selector. JQuery also supports event namespaces, where events can be fired in a hierarchy. Both are powerful concepts, but I’ve never had to use either.

The secret sauce for Ext Core is in extended configuration. With Ext Core events, you can also configure the scope (a common Ext Core theme), along with configuring the event propagation, extra parameters, and a delay. Here is a sample of a click event configured with ‘this’ scoped to the onClick event itself, to only fire once (single), with a delay of 100ms and an additional parameter (forumId) to be passed to the event handler:

el.on('click', this.onClick, this, {
    single: true,
    delay: 100,
    forumId: 4
});

So again, I’m going to call this round a tie. Both libraries handle simple event binding very easily. If you need the live events, the nod goes to JQuery. If you need the extra configuration options, Ext Core is your best bet.

Round 5 – DOM Manipulation

Once again, the two libraries provide a near complete overlap of basic DOM manipulation functionality. Each can easily create, move, add and insert DOM elements.

JQuery aims for convenience. For example, one feature of JQuery I really appreciate are simple methods to clear the content of a DOM element and set the text. For example, given:

<div id='message'>First Message</div>

With JQuery, it is simple to update the text:

$('#message').text('New Message');

The text() method removes all the child nodes of the matching elements and appends a text node containing the specified text. The text() method without a parameter will retrieve the text for a matching element. For Ext Core, you have to drop down to the DOM to set the new text value:

Ext.fly('secret').dom.innerHTML = 'New Message';

The Ext.Element class does not provide simple methods for setting the text or removing all the children of an element, which I find to be an annoying inconsistency.

On the plus side, Ext Core provides a lot more methods for manipulating the DOM. One of the cool ones is the radioClass() method. This method will add a class or classes to an element and remove that same class (or classes) from all the siblings. For example, here is a simple table with a row having the ’selected’ class:

<table class="data">
    <thead>
        <tr><th>Name</th><th>Age</th></tr>
    </thead>
    <tr>
        <td>Bill</td><td class="age">20</td>
    </tr>
    <tr class="selected">
        <td>Alice</td><td class="age">21</td>
    </tr>
    <tr>
        <td>Jeff</td><td class="age">22</td>
    </tr>
    <tr>
        <td>Susan</td><td class="age">23</td>
    </tr>
</table>

This one line of Ext Core code will remove the ’selected’ class from the current TR element and add it to the first row in the table:

Ext.select('table tr:first').radioClass('selected');

So for this round, I’ll give the advantage to JQuery for the more consistent API, especially around manipulating the text nodes of an element. This is something pretty simple for Ext Core to address, which they really should. Ext Core does, however, offer more powerful DOM manipulation options.

Round 6 – Effects

I’m not a big effects junkie, so I won’t have a lot to say about this. Both Ext Core and JQuery provide a very similar set of effects for elements (hide/show, fade, slideIn/Out, etc…). Ext Core provide a more powerful API for creating custom effects, while JQuery addresses this with its rather extensive set of plug-ins. I’m calling this one a tie.

Round 7 – AJAX

Ext Core and JQuery both make AJAX simple, but again, we’ll see that JQuery adds more simplified methods while Ext Core offers more powerful configuration. Here is a sample of an AJAX call that returns JSON data:

// URL returns a JSON object like this: {name: 'Tim'}
 
// JQuery 
$.getJSON('http://myurl', function(data) {alert(data.name);});
// Ext Core
Ext.AJAX.request({
    url: 'http://myurl', 
    success: function(response) {
        var data = Ext.decode(response.responseText);
        alert(data.name);
    }
});

JQuery provides the simplified getJSON() method where the parameter to the callback has already been decoded into a JSON object. For Ext Core, the callback receives the XHR response object and you have to decode the text to JSON.

The Ext Core request() method demonstrates a typical ExtJS convention of using a JavaScript configuration object as a parameter instead of using multiple parameters.

Both libraries provide strong AJAX support, so we’ll go with a tie for this round too.

Round 8 – Documentation

There is no contest in the documentation department. While the JQuery documentation has improved, the Ext Core documentation blows it away. From the excellent manual to the high-quality API documentation, Ext Core sets the standard for what all documentation should look like.

Round 9 – Intangibles

For JQuery, the biggest intangibles are its plugins and support from Microsoft. JQuery is intentionally designed to provide a simple core set of functionality and to be easy to extend. There are hundreds of plugins people have written for JQuery in the Plugin Repository. As with all things open source, some are very good and some are kinda crappy, but you can be pretty certain to find a plugin that covers about anything you might be trying to do that is not covered by the core JQuery API.

Microsoft support is also a biggie. They have decided to include JQuery as a base JavaScript library in their web tools going forward. This means you won’t need to get special blessings to use JQuery in large corporate environments — it will be part of the core Microsoft bundle, with support and all.

Ext Core, being brand new, is lacking in both community and support. Ext LLC, the company behind ExtJS and Ext Core is a small software shop trying to get by in a tough economy. While their products are cutting edge, I’m expecting them to be bought out by a larger company before too long. I keep trying to talk my Spring Source contacts into buying them, but I have a feeling they’ll be bought by Adobe.

So from an intangibles perspective, JQuery is the winner. It is guaranteed to have longer legs under it, at least until we see where Ext LLC ends up.

Conclusion

Both Ext Core and JQuery are solid, complete base JavaScript libraries. JQuery leans towards simplicity while Ext Core offers enhanced configuration. The choice of which to use will come down to where you are now.

  • If you use JQuery, and don’t anticipate using ExtJS, stay where you are. You’ve got a winner.
  • If you use ExtJS and have used JQuery as a light weight option for when you didn’t need the widget library, Ext Core is now your library of choice.
  • If you are in search of a JavaScript library, the choice is tougher. Unless there is a particular JQuery plugin you want to use, I recommend going with Ext Core. It starts laying the groundwork for using ExtJS, which you’ll want to do as you get in to building RIAs.
  • If you’re a corporate Microsoft shop, you probably don’t have a choice. JQuery is now something you can slip by the infosec police without making waves.

Ext Core is definitely a winner. In the past, I have used JQuery for projects that need simple DOM manipulation and ExtJS for when I need the widgets, layouts, etc… Now that I have Ext Core, I don’t see using JQuery anymore for the simple cases. I can standardize on using the same API paradigm between Ext Core and ExtJS.

Follow-up #1: Beyond the Core
Follow-up #2: Slick Speed

ASP.NET MVC 1.0

I’m not sure why Microsoft is being so quiet about it, but they have apparently released the ASP.NET MVC 1.0 final. Kudos to Caleb for tipping me off via a random tweet.

I went fishing all over yesterday and didn’t find any big release announcements. I expected Scott Guthrie to have something on his blog, but nothing yet. The MSDN site finally had a release announcement this morning.

This is fantastic news for .NET web developers. This finally gives ASP.NET a production-ready web MVC framework distributed by Microsoft. This framework is the future of ASP.NET.

Getting Groovy

As we get more into our project at Orange Leap, we’re starting to see a lot of instances where a dynamic language would make our life easier. On all of our entity classes, we associate a map of custom fields. The custom fields are so that clients can customize the entities without us having to change the code each time. The custom field definitions go beyond basic key-value pairs and can include references to other custom fields. For example, spouse is a custom field that relates two entities and is bidirectional. If you open either entity, you’ll see the other in the spouse custom field.

A dynamic language would come into play in that we could access all the attributes of an entity in a consistent way, preferably through dot notation. Since we’re already running on top of Java 6, Groovy came to mind as the best candidate for a dynamic language.

I’ve never really played with Groovy before. I mostly played with Ruby and Rails, which really opened my eyes to the power of a good dynamic language. Some of the developers on my team wanted to get into Groovy while I was at Countrywide, but I kept us out of it for fear of ending up with an unmaintainable monster if one of the experts left. (this is actually the primary motivator in 99% of all enterprise technology decisions — the bus factor)

So this week I finally jumped in with both feet and I have to say I like what I found. Everything cool I liked about Ruby and .NET 3.5 was in Groovy. Metaprogramming, check. Mixins and Closures, check. Full access to all the JVM goodness, check. The recently released Groovy 1.6 even goes beyond Ruby and .NET 3.5.  For example, if you tag a class with the annotation @Singleton, it turns it automagically into a singleton.

@Singleton
class Friend {
    def name
}
f = Friend.instance
f.name = "Tim"
print "Hello, $f.name"

If you try and call new on the Friend class, you get an error that you can’t instantiate a Singleton. All this handled with a simple annotation. For an excellent overview of all the coolness in Groovy 1.6, check out this article on InfoQ.

So I’m going to keep working my way through Programming Groovy and am eager to start applying what I learn. And best of all, my favorite IDE has the industry’s best support for both Groovy and Grails.

Compiler Wierdness

I was playing around with the Spring/ExtJS Template on my Ubuntu box and ran into a strange problem. On the Vista laptop, if I compile with IntelliJ or from the command line with Ant, the application works perfectly fine when I deploy it to Tomcat. On the Ubuntu box, the WAR file generated by IntelliJ worked fine, but the WAR file output of the Ant script puked and died.

It took about an hour of hair pulling to figure out what the problem is. In the original build.xml file, the compile task looked like this:

Notice I didn’t specify and of the compiler, source or debug options. On Sun’s JDK 1.6.0_12 for Windows, debug appears to be the default. The Spring annotation needs the debug information for mapping parameter names in views.

On Linux, the same JDK (Sun 1.6.0_12) behaves differently. It does not include the debug information by default. In order to make my Ant build file work, I changed the compile attributes to this:

Explicitly defining debug=”true” resolved the issue. This is the first time I’ve bumped in to a basic behavioral difference for Java across operating systems. The lesson learned is play it safe and always specify compiler values.

Springing Around with ExtJS

While playing around more with ExtJS and Spring, I ran in to one of my favorite annoyances — setting up a new project. I can create a new webapp in IDEA (or Eclipse) and add some dependencies, but it is still pretty empty. Maven can go a bit farther, but I don’t like how it handles transitive dependencies. None of these will really give me a good starting point out of the box without either copying a bunch of stuff over from other projects or writing a lot from scratch.

To finally scratch that itch, and move further along the Spring & ExtJS path, I turned my demo project into a basic template. The zip archive that you can grab at the bottom is a fully-configured Spring web application, including Tiles, Spring Security, Spring MVC, custom JSON view, Transactions and a Datasource.

To get started, grab the file, extract it to some directory. Open a shell, navigate to the Template directory and run the ant command ant dist. This will compile the whole project and create a Template.war file in the dist directory. Note, I use Java 6 for all development, so if you’re not at least at Java 5, you won’t be able to use this.

Before you drop the war file into Tomcat’s webapp directory, you’ll need to setup the database. First, copy the jar files in lib/tomcat into Tomcat’s lib directory. This is the MySQL JDBC driver and the JTA files for transactions. You’ll then need to create a new database on your local MySQL instance called tomcat. For simplicity in development, create a user with all rights to the tomcat database. Here’s the code to run from a MySQL shell:

create database tomcat;
use tomcat;
grant all on tomcat.* to tomcat@localhost identified by 'apache';

Your other option is to just put in your MySQL root username and password. To do that, or change the connection string completely, edit context.xml under web/META-INF. If you don’t use MySQL, you will have to edit this file and also put the correct driver in Tomcat’s lib directory.

Once you have the database setup, drop the Template.war file into your Tomcat webapps directory and startup Tomcat. Assuming Tomcat is configured to listen on port 8080, you can open the sample by browsing to http://localhost:8080/Template

The application only has a couple pages. First, the login page:

Login Page

Spring Security is configured to route unauthenticated requests through this page for login. You can take a look at the applicationContext-security.xml file in WEB-INF to see how this was done. There are two users configured for now. User scott with a password of tiger and user bob with a password of password. Yes, not very clever, but it works. Scott is in both the ROLE_ADMIN and ROLE_USER roles, while Bob is only in ROLE_USER.

If you login with scott, you’ll be taken to the index page, which looks like this:

Home Page

The index page simply contains a text box with a button. Entering a message and pressing the button results in an Ajax call to the server which echos the message back to the page. An HTML element in the middle of the page is updated with the result via JavaScript.

You’ll notice in the footer of the page you can see the currently logged in user on the left, and a link to log out on the right. Clicking the log out link takes you to the logout page, which looks like this:

Logout Page

Again, nothing fancy. Just a message saying you have logged out and a link to login again. Use the login link to login as bob and try the echo functionality again. This time you get a different result:

Not an Admin

This demonstrates what happens with Spring Security via annotations. Here’s the echo method in the service layer:

As you can see, the method is secured with an annotation indicating the user must be in the ROLE_ADMIN role to use the method. Bob is only in the ROLE_USER role, so the call to this service fails.

The application makes use of a ResourceBundleMessageSource for the pages mapped through the htmlDispatch servlet. The login.jsp and logout.jsp don’t go through the dispatch servlet, so they can’t use the message bundle for the window and page title.

There is way too much to this simple application to cover completely now, but I’ll give the highlights of what to go look at in the major configuration files. Paths are relative to the project root:

  1. web/WEB-INF/web.xml - notice that I configure two dispatch servlets. One catching *.htm and one *.json. This sets things up to treat Ajax requests differently. Spring Security is also configured here.
  2. web/WEB-INF/applicationContext.xml – typical application context for a Spring application. I turn on annotation handling with package scanning under the sample.core package. Apache Tiles is configured in this file, and I have also configured a Transaction Manager around the JDBC DataSource. You should tweak this based on your underlying persistence preferences. I’m a RowMapper fan, but you can plug in Hibernate or JPA.
  3. web/WEB-INF/htmlDispatch-servlet.xml - the context for web (*.htm) requests. This sets up the ResourceBundle for messages and a typical ViewResolver mapping the *.htm requests to jsp files under web/WEB-INF/jsp. Also configures component scanning for the sample.web package.
  4. web/WEB-INF/jsonDispatch-servlet.xml – the context for Ajax (*.json) requests. Configures component scanning for the sample.json package and specifies a custom Ajax ViewResolver. This will automagically serialize all ModelMaps returned out of the Controller responded to *.json requests to JSON.
  5. web/WEB-INF/applicationContext-security.xml – so simple to look at, yet so painful to figure out. This is the Spring Security configuration file. Although it looks deceptively simple, it was a beating to figure it all out. It enables annotation-driven security, which you saw on the EchoService above. It also sets up the form login and locks down all the pages. Note I leave the /resource directory open. This is where I put all my javascript, stylesheets and images. If you want to secure those resources, you’ll need to get more specific on the intercept-urls.
    Users are declared at the bottom. Passwords are clear text, which is fine for a trivial demo, but you would want to replace this with something more industrial-strength in a real application.
  6. web/WEB-INF/tiles-config.xml – the Apache Tiles configuration. I only setup one definition here to keep it simple.
  7. web/WEB-INF/jsp/layouts/baseLayout.jsp – the base layout used for tiles. I’m only inserting content at two locations in the template. In the HTML head section, I allow for an optional insert of headerContent. I use this to include JavaScripts specific to a page. The other content is within the center div called mainContent.
    Note that the body is pretty empty and that the divs all have the x-hidden class. This means they are not normally visible. I use an ExtJS Viewport for layout, which uses the contents of these divs.
  8. web/resources/javascripts/layout.js – this JavaScript file was included in the baseLayout.jsp above. It creates the Viewport using a border layout.
  9. web/resources/javascripts/index.js – the JavaScript file included for the index.jsp page. It decorates the plain HTML inputs on the page to do the cool Ajax stuff. Note towards the bottom how I use ExtJS to set focus on a form field and to bind the ENTER key to the submit button.
  10. web/resources/javascripts/login.js – the JavaScript file use for the login.jsp page. If you look at login.jsp, you’ll notice there is no form. Everything is created by ExtJS from the login.js file, including the cool box effect. One trick is that Spring Security wants a normal form POST for the login form. I override the form to do a standard submit instead of an Ajax submit and set the form action explicitly.

This covers the major features. I’ll be using this as a base for other projects and will be expanding out my ExtJS demo. Since there are pretty much zero examples out there of tying together this stack, I hope this can be of use to some folks.

Project Template

  • 2/28/2009 – upgrade to ExtJS 2.2.1, fixed compile issue on Linux, added in iBatis for ORM
  • 3/26/2009 – I’ve setup a dev server with the latest version of the template at CodeZombie.com so you can check it out without having to install. User scott/tiger for credentials. I’ll be updating this install with a more feature-rich demo application shortly
  • 3/28/2009 – changed around the project structure and build.xml to use Ivy for dependency management. Check the README.txt file in the root directory for the details.
  • 4/28/2009 – updated the included JSON encoder to be able to return JSON arrays by using the key _root in the model map. If this key is found, its content will be used as the root element of the return JSON instead of encoding the whole map. Also removed the unicode characters from StringScrubber to make the compiler on Linux happy.

p.s. this pulls together a lot of jars and pieces from different folks to build the demo. If you use this for more than playing around, you need to make sure you respect whatever licenses the authors have in place.

New Laptop

I finally got my new work laptop yesterday. For the past month and a half I had been using my personal Dell Latitude D620 for daily development. It is a good little workhorse but is getting a bit dated in the CPU department and I’ve never been particularly fond of the screen, which I always found a bit too dim.

Now say hello to my little friend (and the D620’s big brother), the Latitude E6500. I got it with the 15″ LED-back lit screen, which I can’t recommend highly enough. This screen blows away anything else I’ve seen and is on par with the new screens on the macbook pros. Toss in a dual-core 2.8ghz CPU and 4GB of RAM, and you’ve got the perfect software development laptop.

I got my E6500 with Windows Vista. I know there are plenty of Luddites who still stick with XP because they think it is “faster”, but Vista just rocks. I’m using it for Java development and have installed IntelliJ, MySQL 5.1, Apache HTTPD. All work flawlessly and IntelliJ is beautiful in Aero.

Speaking of a developer laptop, since I just had to do this, I’ll share my “Java on Windows” essential tools list:

  1. Java 6 JDK
  2. IntelliJ IDEA 8
  3. MySQL 5.1
  4. Subversion 1.5
  5. Tortoise SVN
  6. WinSCP
  7. Putty
  8. UltraEdit
  9. SnagIt
  10. WinZip Pro
  11. DbVisualizer
  12. Firefox 3 with Web Developer, Firebug, ColorZilla and Tamper Data add-ons
  13. Chrome
  14. Tomcat 6

This is my must-have kit for Java development tools. Yes, some are not free, but they are well worth it. Note that I don’t get into all the libraries. Of course I’m using Spring, JUnit, MySQL Connector/J, etc… This just covers core tools.

Core Tools + E6500 = Happy Java Coder

Java, Anyone?

I was at a Christmas party this past weekend and was talking with a friend I hadn’t seen in a while. I was telling him about my new job and mentioned that it was Java, but I was hoping to get a chance to do some .NET too. He said his recruiter friend told him she can’t find Java people anymore.

I was slightly surprised at this. The DFW area has a lot of Java talent, so the only reasons I can think of are:

  1. Pay sucks: you won’t attract A-list Java talent with a VB-coders salary
  2. WebSphere Application Server: every good Java coder I know would gladly chew off their own arm to escape having to work with this piece of shit.
  3. .NET: 80% or more of the top Java guys I have known throughout the years have moved to C#

It is this combination of things that will limit the Java talent pool. The last one, .NET, cannot be understated. .NET 3.5 is a lightyear ahead of Java 6 from a programming language standpoint, and .NET 4.0 doubles that lead. The saving grace for Java right now is the Spring Framework, which is simply phenomenal.

So here are the things needed to attract top Java talent in DFW.

  1. Minimally Java 5, and preferably Java 6
  2. Spring Framework
  3. Deploy to Tomcat
  4. Agile methodology
  5. Embracing of the open source toolset
  6. Salary in the 110-120K range

This probably applies nationally, but adjust the salary to market conditions. A true senior Java developer with the kind of experience people want should easily be in that pay range. Hiring managers are deluding themselves if they think they can get top talent for 90K. I don’t know a senior Java guy worth his salt who would get out of bed for 90K.

IntelliJent Spring

One of the most impressive features of IntelliJ IDEA has been its support for the Spring Framework. IDEA 7 had great Spring support, and IDEA 8 expanded it to include Spring 2.5. What makes Spring a dream with IDEA is how well it understands the Spring grammer and configuration files. I’ll give some basic samples so you can see what I’m talking about.

Let’s start with some very basic beans implemented as interfaces and implementation classes. They are:

This gives us a very basic interface for a Car and simple implementation. Not quite HelloWorld, but close. The Driver interface and implementation look like this:

Again, a very simple implementation. As you have probably guessed, we’re going to define two beans and inject the Car implementation into Driver. Just to make things interesting, we’ll also use a properties file so we can do some token substitution. Our file, called driver.properties, looks like this:

Now lets get to work and implement the Spring XML configuration file. With the above classes implemented, one of the great features of IntelliJ is great support for the p: namespace. IntelliJ has auto-completion for the beans properies, as you can see in this image:

As you can see, since we gave the name of the implementation class, the parser picked up the names of the setters and made them available via the p: namespace. Of course, there is also full auto-completion of the class name, so no copy-paste is needed.

The same auto-completion is available for properties in the imported properties file. Here is the import statement and the auto-complete pop-up as we’re filling in the property for the Driver’s name:

As you can see it enumerated both the property names and their values from the properties file configured in the property-placeholder.

The Spring support also extends from the back source to the configuration. With the Spring XML configuration file in the project, IntelliJ will detect it and provide hints in the code for Spring beans, including quick navigation between the code and the configuration. Here is what the Car interface now looks like with the Spring configuration:

As you can see, IntelliJ puts a “bean” marker in the left margin next to classes or interfaces declared in the Spring configuration file. Clicking the marker will open the Spring configuration file, highlighting the configuration line for the bean. You’ll also notice the little “I” in a circle. This is a basic IntelliJ feature which means a class has implemented the method and can navigate directly to the implementation. If multiple classes implement the interface, you can choose which one to navigate to, like this:

Clicking the little “I” next to the line declaring the Car interface brings up a dropdown allowing you to pick which implementing class you want to navigate to. The same applies for the method declarations.

Spring also has quick navigation of bean properties. For example, in my Spring configuration file, I have declared my car bean like this:

If we take a look at the class file for CarImpl, you’ll see that IntelliJ has placed a marker next to the setter methods to indicate they are Spring properties being set in the configuration file:

Clicking the property marker takes you directly to the definition of the property in the configuration file. The reverse is also true. Using CTRL + click on a property in the configuration file takes you to the implementation in the class file.

It is all this goodness that makes working with Spring such a pleasure in IntelliJ IDEA 8, and this only scratches the surface of how powerful a code editor it really is. Give it a try and enjoy!

Catching the 8

The latest version of my favorite Java IDE, IntelliJ IDEA 8, was released today. I’ve been using IDEA since version 2.0 and have consistenly upgraded my personal license every new release. This time is no different. IDEA has been my favorite IDE for the simple fact it is the ultimate coders tool. No other IDE I have ever used has been so good at helping me with the things I need while staying out the of way the rest of the time. There is not a better Java development environment on the planet.

Yes, I’m sure I’ve offended the Eclipse mafia. I have used Eclipse, on serveral occassions. But I go back to IDEA every time. It is hard to describe the difference in feel between the two. Eclipse is like a swiss army knife — it does a little bit of everything, but none of it particularly well. IntelliJ IDEA is like a Spyderco knife, the perfect cutting instrument. Eclipse is the Visual Basic to IntelliJ IDEA’s emacs.

So what’s new with IntelliJ IDEA 8? The coolest thing I’ve used so far is the built-in JavaScript debugger. You no longer have to depend on Firebug to debug JavaScript files in a project, you can simply set breakpoints in the JavaScript and run the page. For the full list of the new features, check out this page. I’ll be doing a more in-depth review of IDEA 8, using it with a Spring MVC web project.

If you haven’t tried IntelliJ IDEA, and you’re a Java developer, I strongly encourage you to check it out. Personal licenses are only $249 and they are well worth it. Eclipse may be free, but you get what you pay for.

The Missing Linq

I’ve almost wrapped up porting my ExtJS demo application to ASP.NET. It has been pretty simple so far once I realized I was trying to make it too complex. After getting a handle on ASP.NET MVC, I realized I didn’t need to use WCF for the JSON calls. ASP.NET MVC is pretty slick and has excellent built-in support for returning JSON data via the JsonResult class and Json method.

For the data, I’m using a very simple database I called Demo which contains two tables, City and Country. They look like this:

I’m using Linq to SQL for data access, and everything was moving along quite nicely until I ran into a small problem. In the Java version of my demo application, I used server-side sorting for the grid. How this works is that when you click a column header on the ExtJS Grid, the data store makes an AJAX call to the server controller with the POST data containing two parameters. The sort parameter contains the name of the column in the data store that the sort should be based on. The dir parameter has either the world ASC or DESC, indicating the direction of the sort.

The method signature in my controller which catches this request looks like this:

ASP.NET MVC will automatically map the two POST parameters to the two parameters in the method, since they have the same names. Where I hit a wall though was with Linq.

One of the big design features of Linq is to provide a strongly typed interface for the query language. Since I wanted the orderby statement to be based on the POST parameter, I thought I could do something like this:

Noticing no red squiggles, I assumed this would work. But it doesn’t. The problem is Linq is strongly typed, so it won’t accept a string after orderby. Linq wants something like this:

This would be cool in normal circumstances, but since I need to vary the orderby based on the sort parameter, I would have to do a large if-then block with multiple Linq queries, executing the required one based on the incoming parameter. Since that sounded like a pretty stupid idea, I dug a big deeper.

After much searching, I determined that Linq, as implemented, can’t handle the dynamic queries. But fortunately some other very smart people created a work around in the form of an extension to Linq called the Dynamic Query Library. Scott’s article provides a pretty good introduction. All you need to do is include the Dynamic.cs file in the solution and add the namespace to the imports.

Using the Dynamic Query extension methods, I can now do something like this:

The Dynamic.cs adds a new version of the OrderBy method which takes a string parameter containing the name of the field to sort on and an optional sort parameter. No if-then loops from hell and no more hair pulling trying to find the simplest solution that works.

I would bet the Dynamic.cs stuff ends up in core Linq, as it is simply too valuable for situations requiring dynamic data access, like my ExtJS demo. It also provides similar support for strings to the other Linq commands.

Now that I’ve gotten past the ugliness, I’ll be able to wrap up my ExtJS demo application. I’m adding some additional features to it which demonstrate some of the coolness of ASP.NET MVC, so stay tuned.