Wednesday, May 1, 2013

A Lazy Coder != A Good Coder

Recently, a co-worker recently shared a quote with the group:
working as a programmer is the 1st time in history where lazy people (w.o. connections or personal wealth) get payed well to be even more lazy
I take issue with this on a number of levels, but mainly that this seems to be a common theme in the programming world, that a lazy programmer is akin to a good programmer. This can't be further from the truth.

A lazy programmer:

  • takes harmful shortcuts and hacks his features into production code
  • doesn't take the time to think about how his module will behave in the context of the larger system
  • writes poor (or no) unit tests
  • doesn't care to understand how the API he is using works
  • cuts and pastes code
  • uses global variables
I definitely would not want to have a lazy programmer on my team, or contributing in any way to my codebase.

What I think people must mean (hopefully!) is that a good programmer automates when he can. A good programmer is conscientious, meticulous, and thorough. 

Saturday, March 9, 2013

The case of the mysterious failing date test

I had such an aha! moment this afternoon that I thought I'd share it.

This test case was failing for me, and I was positive that I hadn't made any changes which would affect that part of the system:


The trick here is when I was running the test: March 9, 2013, at 1:55pm EST. Turns out that tonight is daylight savings, when we "spring ahead" and lose an hour, and of course 23 hours does not a standard day make!


Friday, March 1, 2013

Using StealJS in Jasmine Tests with Grunt

Grunt Jasmine Configuration

In this post, I'll detail how to use StealJS to author Javascript unit tests in Jasmine, and run them from the command line using the headless grunt-contrib-jasmine runner.

If you look in the documentation for grunt-contrib-jasmine, you'll see a section on using a custom template to run tests which use RequireJS as a dependency manager. You'll end up doing the same bit for StealJS, but will use a different template plugin: grunt-template-jasmine-steal.

First, install the necessary plugins into your local grunt project workspace:

npm install grunt-contrib-jasmine --save-dev
npm install grunt-template-jasmine-steal --save-dev

Next, import the tasks into your Gruntfile.js:

grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.registerTask('test', ['connect:test', 'jasmine']);

Finally, define the connect and jasmine plugin configs. Note that I'm setting up the connect plugin to start a local web server on port 8000, for phantomjs to connect to when running the jasmine suite:

var jsFiles = [
    'src/**/*.js',
    '!src/can/**/*.js',
    '!src/steal/**/*.js',
    '!src/thirdparty/**/*.js'
];

connect: {
    test : {
        port : 8000
    }
},

jasmine: {
    tests: {
        src: jsFiles,
        options: {
            specs: 'src/**/*_spec.js',
            host: 'http://127.0.0.1:8000/',
            template: require('grunt-template-jasmine-steal'),
            templateOptions: {
                stealOptions: {
                    stealUrl: '/src/steal/steal.js',
                    baseUrl: ''
                }
            }
        }
    }
}

Take note of the jsFiles variable I defined; that concisely lists all of my javascript source files, excluding libraries.

Cleaning and Linting your Sources

Another important build step is to clean and lint (error check and validate) your code, and thankfully grunt makes this easy on us. I use the jsbeautifier and grunt-contrib-jshint plugins for this:

grunt.loadNpmTasks('grunt-jsbeautifier');
grunt.loadNpmTasks('grunt-contrib-jshint');

        jsbeautifier : {
          files : jsFiles
        },

        jshint: {
            files: jsFiles,
            options: {
                jshintrc: '.jshintrc'
            },
        },

Note: look at the documentation for jsbeautifier to see the available configuration options (the defaults work fine for me out of the box).

Putting it All Together

Here is a complete Gruntfile.js and .jshintrc, detailing what I went through in detail above. I've set it so that the default grunt task performs the code formatting, checks using jshint, and then runs the full jasmine test suite.




A deferred loading cache in Javascript

I was playing around with jQuery deferreds the other day, and thought up a neat use for them, in a client-side ajax response cache. I created a simple expiring cache abstraction, and then wrote a 'loading' cache around it, which populates the cache with $.Deferred instances which are resolved with the result of a $.get.

Here's the simple expiring cache:




And here's the deferred loading cache:




Jasmine spec for the loading cache:




In my next post, I'll show how to use a jasmine spec runner for steal to run jasmine steal specs in grunt.

Thursday, February 28, 2013

StealJS Builds with Grunt

GRUNT!

I have seen the future of javascript builds, and it is Grunt.  Please, please, please disregard my earlier post on building with maven; it just doesn't make sense to use such a heavyweight Java-based tool for building javascript projects.

Grunt is rightfully taking the Javascript world by storm. It's got a great community around it, as shown by the wealth of plugins available. It runs on Node, allows for package management via npm, and lets you start working with Javascript in a way which makes us stodgy old enterprise Java guys breathe slightly easier ;-) (more posts on that soon!).

Steal Builds, with Grunt

So naturally I'd like to share how I've gotten steal builds to work with my gruntfile. There is a grunt-steal plugin, but it hasn't yet been updated for grunt 0.4, and steal builds don't run on node anyways. (but, excitingly enough, I've heard rumors that steal will run in node sooner rather than later!)

Here are the npm packages I'm using for my steal build:

    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-exists');

My approach is to copy all of the source files into a target/ folder (ala maven!) so I can apply the package version where appropriate, and build the production.{css | js} files outside of the src dir.

Here's where I copy the source files. Note that I'm only including HTML in the phase where I am replacing the project.version and steal environment variables. As with maven, if you filter binary files it will corrupt them.

        copy: {
            build: {
                files: {
                    'target/': ['src/**/*.html']
                },
                options: {
                    processContent: function (content) {
                        return content.replace(/env\s*: 'development', \/\/ live/g, "env: 'production',").replace(/\$\{project\.version\}/g, grunt.template.process('<%= pkg.version %>'));
                    }
                }
            },
            build_other: {
                files: {
                    'target/': ['src/**/*', 'src/**/.*', '!src/**/*.html']
                }
            }
        },

Here's my corresponding HTML snippets which get replaced:

<head>
  <link href="app/production-${project.version}.css" rel="stylesheet">
</head>
<body>
   <script>
      (function() { 
        steal = { 
          env: 'development', // live 
          startFile: 'app', 
          executed: ['app/production.css'], 
          production: 'app/production-${project.version}.js' 
        }; 
      }());
    </script>
    <script src="steal/steal.js"></script>
</body>

Note also in the build_other phase, that I'm explicitly including src/**/* and src/**/.*, so that my .htaccess file comes along for the ride.

Next, I'm using the shell plugin to run the steal build, the same way as you would manually from the command line. First, I need to make the js script executable, then I run it using the target dir as the base working dir.

        shell: {
          chmodjs: {
            command: 'chmod 755 target/src/js'
          },

          steal_app: {
            command: './js app/scripts/build.js',
            options: {
                stdout: true,
                stderr: true,
                failOnError: true,
                execOptions: {
                    cwd: 'target/src'
                }
            }
          }

And voila! You now have a target/src dir with a deployable web application. My last step is to verify that our production files were built successfully.


        exists: {
            prod_files: [ 
              'target/src/app/production.js', 
              'target/src/app/production.css', 
            ]
         }

Also note that I haven't physically changed the name of the production.js file to production-{project.version}.js. I'm using a neat .htaccess trick from html5boilerplate to do my filename fingerprinting in apache. This works because I've set no-cache for *.html.

<IfModule mod_rewrite.c>
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)\-\d+\.\d+\.\d+\.(js|css|png|jpg|gif)$ $1.$2 [L]
</IfModule>

I'm going to go into more detail on integrating steal with jasmine tests, and exploring other grunt goodies, in (near!) future posts.

Wednesday, September 26, 2012

My First Maven Release

As promised, I've gone and published my dropwizard-guice library jar to the central maven repository. This was a rewarding experience, being my first such release, and it feels good to be giving back to the community in such an "official" manner!

Here's the official maven dependency:


  com.fiestacabin.dropwizard.guice
  dropwizard-guice
  0.5.1



Many thanks to the official Sonatype docs, and Joel Orlina for helping me to get this set up properly. Also, this post helped as I needed to upload my PGP key to the mit keyserver, not the one listed on the sonatype docs.

Tuesday, September 4, 2012

Nostalgia

I've been coding for quite some time now. It just so happened that my freshman year of high school coincided with the release of an exciting new technology / language named Java. This was a language with its own runtime, which included the ability to run inside of a web browser (think Netscape). Seeing as how I already had some experience tinkering with C and C++, the prospect of creating visual applications made Java all that much more appealing to me. I borrowed my Dad's Teach Yourself Java in 21 Days book, read through a bunch of tutorials, and dove head first into the world of applets and AWT.

At this time, I was also very much into freestyle BMX, and with my best friend Eric Miller had created a moderately popular community site, JEBikes.com. In order to satisfy my urge to code, and also for us to put some interesting content on the site, we'd sit for hours in my room, Eric on Windows Paint, drawing the graphics and designing levels, and me in front of Notepad, typing away at my monolithic Java class file. We ended up creating a handful of these games, and it was a great experience.

A short while ago, an old friend of mine from high school contacted me about these games. Since the site had long since gone offline, and the domain had been surrendered, I got excited about the prospect of resurrecting them, just to see if and how they'd work today. It took some time, but I was able to locate the original source files on a portable hard drive tucked away in storage. The most annoying and difficult part about getting everything running was dealing with the old Windows 98 / DOS extended filenames; on the disk they were written out as eight characters with three character extensions, all in caps, and if there were any special characters or the length exceeded, then you'd have something like SCREE_~1.GIF, so I had to go through and carefully rename each file, even if it was simply to lowercase it.

For posterity and safe-keeping, I've decided to put these up on github. They are definitely not examples of my finest coding work, and might actually make interesting case studies in TDD refactoring in the future (if they weren't applet-based... ick!). It's always interesting to revisit code you've written 15 years ago, especially since most of the time I question what I was thinking with code I've written 6 months ago. Enjoy!

Sunday, July 22, 2012

Simple Guice integration for Dropwizard

If you haven't come across it yet, Dropwizard is a nifty new framework designed to streamline and simplify development of lean web services which are inherently "ops-friendly". By "ops-friendly", I mean that it provides out of the box support for and gentle encouragement to use things like health checks and metrics monitoring. By "lean", I mean that these services are run from within their own JVM processes, with embedded Jetty as a server. This idea of multiple, self-contained, fail-fast processes is best described by the Twelve Factor App.

So with Dropwizard, you extend from the base Service class, and add things to the Environment on startup (e.g. Jersey Resources, Providers, etc). I've created a simple extension to the Service class which does some classpath scanning to automatically install your resources, providers, health checks and tasks for you, via Guice, allowing you to use Dependency Injection throughout your application for object dependencies. Check it out on github! (IMHO) It's quite simple to integrate into your project, and I've found it to be very useful so far, in that I can simply create a new resource class with a @Path annotation, create a constructor marked with @javax.inject.Inject, and it will automatically be wired up and installed into the REST container.

Let me know what you think! If I get enough interest (read: any) then I'll throw up the binaries on an accessible maven repo.

Update (26 Sep): I did end up getting interest, and have since made this available on the central maven repo.

Friday, July 20, 2012

ProTip: Debugging Minified JavaScript using Chrome DevTools

Here's yet another reason why I develop exclusively in Chrome: they've got a killer feature in the JavaScript DevTools which will format any script file, even if it's been minified, and allow you to place breakpoints on that formatted output!

If you're working on troubleshooting an issue in a production app, for example, you'll have something like this:


If you notice, there's a button on the bottom toolbar that looks like a pair of curly braces { }. If you click that:


Then voila! Pretty-printed!


And I can set breakpoints and troubleshoot!


Saturday, July 14, 2012

Building CanJS with Maven (or Ant)

CanJS and other similar JavaScript frameworks are great for creating modular applications and keeping source files small and cohesive, but we all (should) know that when it comes to web site performance, it's important to keep the total number of downloads to a minimum. This becomes especially important when you start to factor in mobile devices, where the cost per connection is much higher than on desktop browsers.

Luckily, CanJS (and most of the others, I might add) includes the ability through StealJS of compressing and concatenating all of the source files for your application into a single production.js, as well as doing the same for your CSS files, into a single minified production.css.  When you use the generators which come with DoneJS / JavascriptMVC to create a new app, you'll notice in the folder structure a scripts folder, which contains a build.js and build.html. Steal uses Rhino to load the build HTML file, which includes a single call to load the main steal.js core and bootstrap your app (e.g. ../steal/steal.js?yourapp). It then tracks all of the imports, JS, CSS, and EJS, and bundles them into either the production.js or the production.css. Note: the folks over at Bitovi been busily cooking up a new "packages" feature which I haven't yet had the chance to play around with, which promises to shrink the size of the monolithic production.js into more on-demand modules.



The generated scripts folder of a DoneJS app. Also note that there are a few other fun features in that folder besides building, which I can go over in greater detail in a future post.

Building with Maven (err, Ant)

So now back to the subject of this article: how does one integrate this cool build feature into their existing build system? I've got it working in a Maven build (albeit via an Ant task), since the server-side component of my application is Java.
   
    org.apache.maven.plugins
    maven-antrun-plugin
    1.7
    
     
      org.apache.ant
      ant-nodeps
      1.8.1
     
       
    
     
      build-donejs
      prepare-package
      
       
        
        
        
         
         
        
        
         
         
        
        
         
         
        
        
        
                  
              
              
        
         
          
          
          
         
         
          
         
        
        
        
        
            
                
            
        
       
       UTF-8
      
      
       run
      
     
    
   

Things to note in this setup:

  • I've split my web application into multiple distinct DoneJS apps; the line is drawn at the point where there's a distinct HTML page (in this case, login, app, and admin are separate pages).
  • I'm hosting my static content out of /src/main/resources/assets, which is sort of a convention when writing DropWizard applications (more on that awesome framework in a future post!)
  • I'm attaching this execution to the prepare-package build phase, since it takes a while (on the order of 5 minutes or more) and it's important to fail fast on the unit test phase. I've already moved all of the relevant resources into target during process-resources.
  • The production build can fail for a number of reasons, including syntax errors in your JS files, so it's important to look for the production.js files in your output directory and fail the build when they are missing. If you don't, there's a chance you will deploy a broken build to production and your users will not be terribly thrilled!

Not quite done yet!

There are two more steps to do in order to fully take advantage of this awesome build stuff.

First, you need to reference the production.css stylesheet in your html files. Do so like this (in your document's head, of course):

This will give you 404's while in development mode, and your app will flicker a bit in that mode since you're using StealJS to import your CSS files, but in production mode the production.css file will be present and everything will be blazingly fast.

Next, you need to tell StealJS to load your production.js file. I've done so in my Ant task by using regexreplace to replace the references to steal.js with steal.production.js.


  


So there you have it. Add this plugin definition to the build / plugins section of your pom, and run mvn clean package to generate the production files!

Wednesday, July 11, 2012

Who's var is it, anyway?


Consider the following snippet of JavaScript code:
var cells = document.getElementsByTagName('td');

for(var i=0; i<cells.length; i++){
  var cell = cells[i];
  cell.addEventListener('click', function(){
    cell.style.backgroundColor = '#00F'; // which 'cell' ?
  }, false);
}
Does the click listener function do what it’s supposed to? Why or why not?

Closures and Scoping and Vars – Oh, my!

If you’ve gotten this far, it’s probably safe to say you’re aware of the fundamentals of the var keyword. It’s also likely that its use has been hammered into your consciousness as a “best practice” coding habit, and that’s a Good Thing™ (polluting the globe and the global namespace are equally heinous).

So, you follow this advice faithfully, and always declare your variables before you use them:
function foo(arg) {
  var a = 0;

  if( arg ) {
    var b = ‘arg: ‘ + arg;
    console.log( b );
  }
}

Here’s the caveat: unlike other C-style languages, JavaScript variables are NOT block-scoped; they are only global- or function-scoped. Those curly braces provide no protection for your poor vars.

What does this mean? I can update the previous code like this:
function foo(arg) {
  var a = 0;

  if( arg ) {
    var b = ‘arg: ‘ + arg;
    console.log( b );
  }

  console.log( ‘still b: ‘ + b );
}

One more thing…

In JavaScript, variables can be declared after they are first used. How is this possible, you (hopefully) ask? Because of a funny thing that the language parser does, called var hoisting.
foo = ‘bar’;
var foo;

// is implicitly understood as:

var foo;
foo = ‘bar’;
Because of this, it’s a good idea to declare variables at the top of functions. In our original example, the language understands it like this:
var i, cell;
var cells = document.getElementsByTagName('td');

for(i=0; i<cells.length; i++){
  cell = cells[i];
  cell.addEventListener('click', function(){
    cell.style.backgroundColor = '#00F';
  }, false);
}
Note that because the compiler moved the var to the top of the scope (and we don’t have block-scoping in JavaScript), our click handlers are all closing on the same cell instance, which will have the value of the last table cell element at the end of the for loop, so our click handlers will all only effect the last table cell in the document!


Reference: https://developer.mozilla.org/en/JavaScript/Reference/Statements/var

Monday, July 9, 2012

Simple(r) String Templates with Commons Lang

Whenever I have a need to use string templating in a project, I reflexively turn to Velocity, which works great, but it:
  • is "heavy": can be difficult to get into a project and functional, has some quirks with classloaders and logger systems, etc
  • is old: last updates were back in 2010
Velocity is also loaded with features like control constructs, loops, branches, etc, which seem like overkill when all I really need to do is format email notifications with some variables (I've already gone the route of client-side view templates for my UI stuff these days).

I know there are a million ways to solve this using homegrown regex's and other such things, but I found a convenient helper in Commons Lang3: StrSubstitutor. It allows you to replace variables in a string, denoted by:
${varName}
I've written a simple wrapper around it, which can pull a template string from a file on the classpath, caching it using a simple WeakHashMap.  This could be extended to use the nicer caching framework found in the fantastic Google Guava project, perhaps.

An example use of this class might be to stick a template text file into src/main/resources/templates/foo.template (for all of you fellow Maven'rs out there!), and invoke it like:
String output = Templates.template("templates/foo.template")
                         .value("foo", "bar")
                         .value("other", "val")
                         .render();

Friday, June 22, 2012

CanJS (or: How I Learned to Stop Worrying and Love the DOM)

Javascript?!? Ewww....

Let's face it: Javascript has gotten a bad rap over the years, and with good reason (mostly). Anyone with a less than favorable view of the language has likely formed that opinion after an encounter with some ugly messy spaghetti code, perhaps in a legacy enterprise web app, sprinkled throughout the HTML to add some basic form validation, or toggle visibility of a page section, or provide a rudimentary tabs control. When code grows organically, without an over-arching framework to guide its evolution, it tends to grow like a weed: out of control and in all the wrong places.

So we recognize that we need a framework, if we've got any shot of building a significant maintainable application. The problem then becomes, which one? There are a multitude of frameworks to choose from. The sheer volume of projects can make it quite intimidating to start on a greenfield javascript application.

This article will not be delving into the specifics of why to choose one framework over another; I don't have enough experience in all of them to make that an educated statement. It will, however, detail my experiences with CanJS, (and its sibling projects, StealJS, JQuery++, and FuncUnit, all of which now exist under the umbrella project DoneJS) and go into some depth on how I was able to utilize it successfully in a recent project. (also, I'm realizing that this will most likely end up a series of articles, as I'm finding that I've got a surprising amount to say on the topic)


CanJS: tl;dr

So what is CanJS, exactly? The website has a great explanation and description which I won't parrot here, but essentially it gives you some useful tools for building an application in Javascript conceptually as an aggregation of models, views, and controls (MVC, anyone?). There are a number of whiz-bang features they sprinkle in as well, like the concept of an 'observable' object, live binding with views, and URL hash 'routes'. It sits on top of a number of the "big" foundation javascript framework / libraries (e.g. mootools, dojo), but JQuery is the one I chose to base my app on (since, like, everyone is using it and stuff). You then use StealJS to "import" all of the dependency scripts for your app's components, with the added benefit of being able to compile complete, minified production js (and css) artifacts in a build process.

A big aspect of the DoneJS project is that it emphasizes and facilitates the creation of functional and unit tests for your code. Management-types will be giddy over the FuncUnit feature which can show you a line- and branch-coverage report for your test suite.

Why I think Can/DoneJS is cool

I like the way I'm able to logically structure my application into reusable components. I really like the EJS template library, which allows me to write my HTML in reusable fragments, "hookup" javascript objects and events to those fragments, and even "live-bind" to observable objects (where the view actually changes when you update an attribute on an observable). Can.Construct (and can.construct.super) give me class inheritance in Javascript with a nice syntax. Can.proxy allows me to write event handling and asynchronous code without devolving into nested nested callback functions. The Control concept is simple yet powerful.

Why I think Can/DoneJS is hard

My background is predominantly Java, with a heavy emphasis on server-side "enterprise" applications. It's possible that the doc sites are more grokkable by those native Javascripters, but I find them hard to decipher at times, and also often out of date or incomplete. That requires you to get familiar with the internals of the framework in order to troubleshoot when things don't work as advertised. That said, the guys at Bitovi do a good job of patrolling the forums and respond quickly to pull requests on github.

More to Come...

Now that I've (perhaps) whetted your appetite a bit, I will next go into deeper dives on some cool / interesting things I've done with CanJS, as well as illustrate some gotchas that I encountered which will hopefully help you in your coding. 


Tuesday, May 17, 2011

Hey 2011: Where is my easy pagination and sort?

Update (6/22/12): Even better; I've found a great new ORM library called ebean. Article forthcoming!


Update (5/23/11): I found some exciting stuff around JPA and pagination in the new Spring Data project: http://www.springsource.org/spring-data/jpa

No matter which framework I use, it always seems like I need to re-invent the wheel when it comes to supporting pagination and sort in my web applications. Now, I'll admit that my experience is still mostly limited to Java and Spring (and JPA/Hibernate, for that matter), but c'mon, at least give me something basic, like what I've written below. When you want to display a pagable, sortable table in a UI, you are going to want to do common things like determine total rows, total filtered rows, current count, as well as sort on one or more fields.



This snippet did require me to come up with a cool bit of code to statically determine the type of a nested property specified using bean notation:



*note that this uses org.springframework.beans.BeanUtils, and not org.apache.commons.beanutils.BeanUtils; this is mainly because Spring's version allows for static type resolution already.

Wednesday, August 25, 2010

System.currentTimeMillis();

I ran across an interesting issue today involving JVM internals, and how they behave differently based on the host OS.

The issue was with the following code snippet:

MyEntity a = new MyEntity();
a.setUid("foo" + System.currentTimeMillis());
a.setName("my entity");
entityService.save(a);

This was part of some object creation code I was using in a unit test, which ran successfully every time on my macbook but was failing on other's windows machines. When I found out the reason behind this, I was definitely surprised.

Believe it or not, it is more or less a known issue that the resolution of currentTimeMillis() on windows machines hovers around 10-15ms (linux and mac have a resolution of around 1ms). This was causing duplicate foreign key violations to occur.

So, as a general rule of thumb, it is a bad idea to rely on currentTimeMillis() to have a millisecond-resolution on windows, especially if you are using it to generate unique things like file names or db IDs. Looks like System.nanoTime() might tick faster.

Here are some links I found on StackOverflow about this:

On Windows, you'll more or less be limited to 10 ms resolution at best. Here's a bit from the Inside Windows NT High Resolution Timers article from TechNet:

Windows NT bases all of its timer support off of one system clock interrupt, which by default runs at a 10 millisecond granularity. This is therefore the resolution of standard Windows timers.

In my experience, using System.currentTimeMillis method gives about 15-16 ms resolution on Windows. Getting better time than the operating system timer will probably require more exotic methods.

Here's the StackOverflow question which helped me solve this issue:
http://stackoverflow.com/questions/351565/system-currenttimemillis-vs-system-nanotime

At the end of the day, I decided it was simpler for my test to use a static synchronized counter variable rather than depending upon currentTimeMillis() for generating my UIDs. Another possible solution could be to use UUID.randomUUID().toString().

Wednesday, August 11, 2010

Fixing ClassNotFoundExceptions when working with Eclipse WTP, Maven, Tomcat

Lately, I've been struggling off and on with ClassNotFoundExceptions when starting tomcat from within Eclipse (Springsource Tool Suite, to be exact). My projects are all dependency-managed by the Maven m2eclipse plugin (side note: its really important to install the m2eclipse WTP add-on, found here: http://m2eclipse.sonatype.org/sites/m2e-extras so that the web dependencies are all configured correctly).

Anyways, I would tend to encounter this error after restarting Eclipse. When I would investigate, by looking into the [tomcat_home]/wtpwebapps/[app]/WEB-INF/lib folder, it would of course be empty (hence, class not found). I would always flail about aimlessly for hours until it would magically start working again.

I have in the past week discovered a new trick, which has worked *both* times I've tried it: when I got the class not found error, I stopped tomcat, right clicked on my project in the Package Explorer, and clicked Maven -> Update Dependencies. For whatever reason, this caused WTP to publish the dependent jars into WEB-INF/lib, and everything worked again. :-)

Hope that helps save some debugging hours for some!

Thursday, June 3, 2010

DOM Events for HTML Radio Buttons

An interesting bug came up today, and it had to do with the way IE 8 processes DOM events differently than the other browsers.

Here's the scenario:

We were attaching to a radio button's onchange event to do some processing. When you click on an option, we show you a particular div relevant to your selected option. This worked just fine on Firefox and Chrome, but was wacky on IE8. It turns out that IE8 doesn't seem to fire the onchange DOM event until after the element *loses focus*, meaning that our divs didn't show up until we clicked somewhere else on the screen.

We fixed the issue by switching to the onclick event, which fires nicely, on the click, as you would expect, on all three browsers.

In summary: when you want to trigger something when a user selects one of your radio buttons, attach to the onclick event, and not the onchange event, which has variable behavior across browsers.

Friday, February 19, 2010

Unsigned Java Primitives

This one's just a quick note about unsigned primitives and how to work with them in Java, which technically has no notion of 'unsigned'.

If you need to find the unsigned value of a primitive (e.g. you are porting code in another language, or dealing with byte-level networking), you basically need to promote it to the next higher data type, and mask out the bits you don't need (anything above the size of your unsigned data type).

Examples...

To find the unsigned value of a byte (8 bits):


byte b = ...;
short unsignedB = (0x00FF & ((short)b));


And for a short (16 bits):


short s = ...;
int unsignedShort = (0x0000FFFF & ((int)s));


And so on.

You can read more on this and other exciting topics such as *-endian byte ordering, and why Java doesn't have unsigned in the first place here: http://www.darksleep.com/player/JavaAndUnsignedTypes.html

(hint: Gosling didn't think Java developers could understand them!)

Monday, November 16, 2009

ISO Language Codes

Every so often, I need to obtain a full list of ISO language codes for use in an application. I thought I'd write a reference post for future reference, and whomever else might find this kind of thing useful.

Languages are given a two-character code in ISO-639-2, which the Library of Congress is nice enough to host for us here.

I wrote a simple bit of code to generate a 'Language' table for MySQL, and posted it here:
http://www.fiestacabin.com/files/iso-lang-codes.sql.txt

Feel free to use this snippet; the table I created looks like:

CREATE TABLE IF NOT EXISTS Language (
id unsigned int not null auto_increment,
code char(2) not null,
description varchar(64),
primary key (id),
unique index iLanguage_code (code)
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;


Just for fun, I am including my Java snippet which generated the SQL; critique at will!

package sandbox;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrTokenizer;

public class ISOLangCodes {
public static void main(String[] args) throws Exception {
List<String> lines = (List<String>) FileUtils.readLines(new File("c:/temp/iso-lang-codes.txt"), "UTF-8");

for( String line : lines ){
StrTokenizer s = StrTokenizer.getCSVInstance(line).setDelimiterChar('|');
String langCode = s.getTokenArray()[2];
String langDesc = s.getTokenArray()[3];

if( StringUtils.isNotBlank(langCode) )
System.out.println(
"INSERT INTO Languages (code, description) VALUES ('" + langCode +
"', '" + StringEscapeUtils.escapeSql(langDesc) + "');");
}
}
}

Wednesday, October 14, 2009

Recursively Scanning Packages for Marked Classes with Spring

I thought I'd share a neat snippet of code which allows you to recursively scan all of the classes in a given package for those which have been marked with a particular annotation. This could be useful, for example, if you have a static factory class that wanted to know all of the classes which could be instantiated for a particular purpose, without having to add them in some sort of static block at the top of the factory.

String pkg = MyBaseClass.class.getPackage().getName();
String pkgPath = pkg.replace('.', '/');

List<Class<?>> classes = new ArrayList<Class<?>>();

PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
Resource[] packageClasses = resourceResolver.getResources("classpath*:" + pkgPath + "/**/*.class");

for( Resource res : packageClasses ){
classes.add(Class.forName(pkg + '.' + FilenameUtils.getBaseName(res.getFilename())));
}

for( Class<?> c : classes ){
MyAnnotation myAnnotation = c.getAnnotation(MyAnnotation.class);

if( myAnnotation != null ){
// this class was marked with @MyAnnotation; handle accordingly
}
}



I could devote a whole post to Spring's resource loading capabilities; they are the nicest I've used. The above snippet utilizes Spring's PathMatchingResourcePatternResolver, which is able to list resources which match a given ant-style path description. The secret is "classpath*:some/path"; note the asterisk before the colon. This searches *all* accessible jars on the classpath, instead of stopping in the first one in which we find a match. One gotcha here is that you can't do something like "classpath*:*/service/*Service.class"; it will choke if you attempt a leading wildcard search.