[Presentation] Tomorrow’s Tech Today: HTML5

Groovy / Grails ‘personality’  (and I mean that in the most fondest use of the term) Scott Davis presents a great round up of some cool HTML features.

InfoQ: Tomorrow’s Tech Today: HTML5.

He introduces some good tools and utils that help the forward compatible specification be read by HTML4 browsers none the wiser.

Firstly the HTML5 CSS trick to treat all the new HTML5 elements (header, nav, footer, video) to be treated as block elements in all browsers (except IE) and the html5shiv that does the same thing for IE.

Trivia: <input type=”someType”> gets rendered as a textbox if yourbrowser doesnt knowhow to show it.

There are some references to these sites which talk more about HTML

DiveIntoHtml5.org – an upcoming o’reilly book you can read for free here

HTML 5 Rocks

He talks about some stuff I wasnt too aware of such as HTML5 caching support (5mb) and SQL (25mb but no FF or IE, but useful for iPhone and Android browsers)

html5demos.com

Modernizr (detect support for HTML5 & CSS3) – see findmebyip.com for an example.

“The goal is to program for HTML 5 and backfill for the rest of the browsers”

mod_pagespeed

There is a new mod from Google for Apache servers called mod_pagespeed that removes redundant HTML before sending it to the client.  Very neat idea.  Makes me shed a tear I am wanting to move our legacy php into a Glassfish appserver so I cant take advantage of this, but still would be useful in future.

Optimization Made Easy with mod_pagespeed.

A Grails rant.

I agree with most of the points on this blog: Why Grails Sucks Less Than Your Framework.

Except #1. “It works on your current environment.” based on what I’ve been trying to during the last couple of weeks.

Firstly, the point isnt wrong for the conventional cases (which is what Grails is great for looking out for).  I’ve worked with Grails apps in the past that integrate with existing apps. I’ve always been able to deploy them as wars to Glassfish using a shared Jndi datasource. However for integration we have generally kept a thin layer (one or two database tables) kept between each app for them to share data.

This week I’m taking that integration further. I’ve been trying to get an integration happening between Grails and our legacy app which has recently been given some JEE love (session beans for services and JPA annotations over the legacy domain classes, deployed in a Glassfish container).  I want my Grails app to be a consumer of those EJB services, which return these legacy domain classes.

You’d think this would be easy, these problems have been addressed and covered in tutorials, blogs and presentations on the web:

  • Having a container managed datasource with your Grails app having access to that is aok.
  • Having existing hibernate mappings and legacy Java domain objects, also solved.
  • I was also able to talk to local, remote and no-interface session beans deployed in the same Glassfish domain just using the initial context that is supplied by using an empty JndiTemplate and Springs JndiObjectFactoryBean.  Works a charm.

You’d think with all these things I’d be set.  I thought I was too.  But like any app using a new platform/framework, the developers go off and develop and the deployers (or the developers later wearing the deployer hats) have to deal with the implementation issues when it comes to deploy the production release many months later.  Thankfully as I was trying to build a proof of concept I came across these issues early, but I can imagine it would be a hard task for any deployer to try and get this to work.  I suppose thats why many large shops with separate systems teams ask for their Grails apps to be packaged as EARs instead of WARS to avoid any other surprises.  Insurance via forced isolation perhaps.

Whilst I can get the war to generate and deploy successfully, once deployed, I’m still having issues finding the legacy domain classes in the classpath.  One problem is that the domain objects have different versions of the libraries (hibernate, logging, spring etc) that are also used in Grails.  And so you end up with NoSuchMethod or ClassNotFound exceptions.  Jar hell clashes between the large Grails jars library base.  I know that with a bit more time and knowledge I could change our legacy domain class dependencies and our grails libs so that they match and then unit test everything so that it still works, but I just dont have the time.  Whilst this is not a problem with Grails per se, the amount of time spent resolving this erodes the promised productivity gains gotten from using Grails in the first place.

Also to keep things flowing, what I’d really like to do is put the war within an EAR file so that I can access the EJBs in the container and share the same classpath so I can get to all those legacy domain objects and their dependent classes that they require.  Again I run into the above Jar hell.    Additionally getting the web app to work has led to some interesting errors with Spring Web Application Context which look like Jar hell style error messages, but dont appear to have duplicate jars in the CP.

The other issue about trying to deploy a Grails war into an EAR is tooling support.  As an Eclipse shop, the tooling for our EAR with the Glassfish/JWT plugins only supports generating an EAR project that is assembled from other Eclipse projects with JEE facets attached to them.  Of course, the Grails project itself isn’t in the form that a Dynamic Web Facet requires.  To get around this, I built the war using grails war, then extracted the war into a new project called webapp_exploded that I setup as a standard Eclipse Dynamic Web Project, which I can then tell Eclipse to bake into the Ear project.  Its a lot of hoops but gives my the META-INF/applications.xml that I want and appears to have the correct classpaths generated.  (Side note: I think IntelliJ has better support for building such artifacts and it can fire off maven/ant scripts pre-and-post execution in order to get this to work in a nicer fashion but as 2/3 of our dev team prefer Eclipse over Idea, I have to get this working for them).  (And I’m still a Maven n00b).

Once I tried to deploy this though, I got exceptions about the Spring Web App context.  I’m not sure if this is because of my Eclipse hack above or some unfortunate Grails bug because not many people are trying to deploy Grails apps in this way.

I also found that the Grails plugin for Glassfish is old.  It only supported Grail 1.0 initially with embedded GF and shared-war command to reduce the size of wars.  But the grails 1.1 release of the plugin advises in its readme that those features aren’t currently working.  To add insult to injury, WinMerge tells me the glassfish/grails(1.1.2) is exactly the same as the Grails 1.1.2 you’d get from Codehaus.  This defeats the whole purpose of having a plugin in the first place.

That said, I’m still in love with Grails, but think I have to take some smaller bites before I tackle this one again (though just typing out this blog has given me a few more ideas of how to address the problem).  Also to be fair, I haven’t sought help through any of the Grails community lists due to time pressures.

If you are starting from scratch, or even if you have a domain object layer that you can bring in without worrying to much about the dependency tree and you are happy to deploy as a separate war, then of course, Grails is great.  I am sure if I had more time I would get it to work – try maven or IntelliJ to build the WAR – figure out why the Spring container’s ConfigurableWebApplicationContext.setId(String) cant be found when trying to deploy the app.

Rick Wagner’s Blog: How to find which .jar a class is in (easily)

Holy heck, I needed this earlier today

Rick Wagner’s Blog: How to find which .jar a class is in (easily).

Makes mention of JBoss’ tattletale utility.

The comments also mention the Java Class Finder plugin for Eclipse (I used the CTRL+SHIFT+T today personally which did the same job)

There is also LibraryFinder plugin for IntelliJ and classjarsearch command line tool to search a directory of Jars for a class.

Glassfish V3.0.1 and Update Tool

When installing plugins for glassfish at work I would receive a Premature EOF just after accepting the license terms for the plugin. This would occur regardless of method used, updatetool cli, gui or web.
Strangely it worked at home, but for me and my colleagues at work, we couldnt get through. I suspect some network issue on our end but didnt need to delve too deep as I found a workaround.

The simple thing to do is to install the latest version of the pkg command. I used pkg-2.3.2 from updatecenter (http://wikis.sun.com/display/IpsBestPractices/Downloads) site.

After extracting the archive, I ran this at a command prompt (in its bin directory)
C:DevEnvpkg-2.3.2bin>pkg install updatetool

The download is strangely very slow and it timed out about three times before I could install update tool. Thankfully running the same command again resumes from where it left off.

C:DevEnvpkg-2.3.2bin>pkg install updatetool
DOWNLOAD PKGS FILES XFER (MB)
wxpython2.8-minimal 1/2 915/929 7.5/7.9

Errors were encountered while attempting to retrieve package or file data for
the requested operation.
Details follow:

1: Framework error: code: 18 reason: transfer closed with 2028 bytes remaining t
o read
URL: ‘http://pkg.sun.com/layered/collection/dev’. (happened 4 times)
2: Framework error: code: 18 reason: transfer closed with 1901 bytes remaining t
o read
URL: ‘http://pkg.sun.com/layered/collection/dev’. (happened 4 times)

C:DevEnvpkg-2.3.2bin>pkg install updatetool
DOWNLOAD PKGS FILES XFER (MB)
Completed 2/2 929/929 7.9/7.9

PHASE ACTIONS
Install Phase 1092/1092
PHASE ITEMS
Reading Existing Index 8/8
Indexing Packages 2/2

You then can simply run updatetool from the command prompt to kick off the GUI app. Downloading plugins via here was slow and timed out also, but it found my local Glassfish install and worked to install plugins to it as I needed.

Java EE, Spring, and why I care

Finally a post that seems to be sticking up for the Spring framework. (nice change)

Java EE, Spring, and why I care « techscouting through the news.

Sure EJB 3.1 does make things easier, but it has taken a lot of time to catchup to where Spring was.  And as the blogger points out, as new versions of the technologies that JEE use like JPA come out, how long will it take for JEE to implement these.

Also, one thing that does bother me with all the ‘my JEE is better than your Spring’ articles is, and the blogger alludes to here, is that they compare annotations in EJB to Springs old XML config which just like EJB is seldom needed these days.  This is a little unfair.

As for myself, I’m technology agnositic, but easily develop biases based on the path of least resistance factoring in long sightedness too.  Like many, if a tool does what I want and is scalable, I’m going to use it.  I think both approaches are fine but they aren’t necessarily compatible.  Unfortunately we aren’t unified yet although the standards are in place to get it to work (eg Spring components <-> JEE components).  Getting a Grails app to talk locally to EJB components hasn’t been easy as I learnt last week primarily due to having the app log to the right place in a container its not used to, and thats just at the container level, but thats another post.

Deploying grails 1.3.x war to glassfish

This was a recent bug bear which may be a regression from 1.2.x line

When you deploy to Glassfish you get an error message

An error has occurred
There is no installed container capable of handling this application com.sun.enterprise.deploy.shared.FileArchive@1e46947

The fix is to include in BuildConfig.groovy

grails.project.war.osgi.headers=false

Maven users can also set the property when running the grails war artificat.

mvn clean grails:war -Dgrails.project.war.osgi.headers=false

via Grails – grails 1.2.2 and glassfish.

Junit Kungfu

A great presentation with audio that talks about Junit 4, test naming and other things.  I liked this presentation because it starts expression Behaviour Driven Development concepts without actually using a Behaviour Driven Development Framework.  Additionally its one of the more in-depth presentations covering the new features of JUnit like Rules.

The presenter is John Ferguson Smart who runs testing and agile tools bootcamps around Australia and NZ (as well as elsewhere) so if you are in the vacinity you should consider looking into em.

My notes from the presentation:

Naming tests

Dont use the name testXXX – you aren’t testing methods of your code

You are testing use cases – what should your class be doing

Take out private methods, maybe extract to a separate class and test those separately if they are getting too big.

Use the word should.  Express an outcome

Class Name: When is a behaviour applicable
Method Name: When at is the behaviour testing

Tests become more readable.

Arrange-Act-Assert

Create the test collaborators – Inputs and Expected Outputs (Arrange)

Test the behaviour (Act)

Verify behaviour is correct (Assert)

Extending Hamcrest Matchers

Combine matchers together – hasItem(someOtherHasPropertyMatcherYouPreviouslyDefined)

Create a new matcher –

  1. Extend TypeSafeMatcher<type of thing you are checking against)
  2. Implement Constructor take in  a matcher of expected value
  3. Implement matchesSafely(type of thing you are checking against)
  4. Implement describeTo – decorate the existing test result/matcher description…  description.appendText(“WuzUp!”); matcher.describeTo(Description);
  5. Create a Factory Class for your matchers with static factory methods to return a new matcher
  6. Use It

Multiple asserts per test are bad (see also Integration Tests are a Scam)

You can combine hamcrest matchers into one test

assertThat(itesm, allOf(hasSize(1), hasItem(“java”)));

assertThat(itesm, hasSize(greaterThan(1)));

The error messages will be cleaner too – expect list size of one, and has item java but received <blah>

Parameterized Tests

Usually just one test per Parameterized test class – they get run once

Ways to get test data

Use an xls spreadsheet source

Use Selenium 2’s WebElement to get a webpage

@FindBy(name="HD_EN") WebElement importerName;
@FindBy(name="HD_EA") WebElement importerAddress;
@FindBy(name="HD_ER") WebElement importerRepresentative;

// getters and setters
 // getter return importerName.getValue();

// setter
public void setImporterName(String value) {
     enter(value, into(importerName));
}

Smoke test to make sure getters and setters are correct

image

Make sure the annotations aren’t wrong

JUnit Rules

Delete folders after test run

@Rule public TemporaryFolder folder = new TemporaryFolder()
folder.newFile(“a file name”);

ErrorCollection,

accumulate errors rather than fail on first.  This saves having to write 20 different tests with large setup that check 20 things on the same page (eg login and load webpage table then verify each cell)

@Rule public ErrorCollector collector = new ErrorCollector();
// in your test
 collector.addError(new Throwable(“blah”));
collector.addError(new Throwable(“something else”));
collector.checkThat(result, yourMatcher);

The result will show “blah”, “something else” and the result of your failed matcher, as well as fail the test.

TimeoutRules

When you know something should have a short response time, a DAO for example should be shorter than 1 second

@Rule public MethodRule globalTimeout = new Timeout(1000);
@Test public void catchInfiniteLoopInTest() { for(;;); }

Catch any major issues before they get into production and become embarassing

Verifier Rule

Something that happens after a test is completed, like an assert

Inject behaviour to make JUnit add checks after each test…. kind of like a test post-condition or invariant from Betrand Meyers OO Software construction, but just for the tests themselves.

private List<String> systemErrorMessages = new ArrayList<String>();
@Rule
public MethodRule verifier = new Verifier() {
    @Override
    public void verify() {
        assertThat(systemErrorMessages.size(), is(0));
    }};

A good example I see would be using it to tie up mock verification calls in EasyMock

Watchman Rule

Called when a test fails or succeeds.  Additional logging perhaps?  How about restarting a GUI, or take a screenshot when a test fails.

Categories

Group tests in your own hierarchy based on your classification of the test rather than writing test suites.  Performance tests  that integration tests.  Slow running or fast running tests?

You can setup plain old normal interfaces for your categories, and have them extend each other via subclassing.  There is no Junit annotation here to indicate its an interface for testing, so you can potentially use any interface in your source.  I’m not sure if this is good practice or not, but say you wanted all your DAO tests that implemented a GenericDAO to be tested, you could do this…. or how about test all classes that implements Serializable?

You can annotate a test class, or tests methods with @Category(InterfaceName.class)

When running a category suite however you still need to include the classes to inspect as well as the category name.

@RunWith(Categories.class)
@IncludeCategory(PerformanceTests.class)
@SuiteClasses( { CellTest.class, WhenYouCreateANewUniverse.class })
public class PerformanceTestSuite {}
You can also exclude from a Run and run a
@RunWith(Categories.class)
@ExcludeCategory(PerformanceTests.class)
@SuiteClasses( { CellTest.class, WhenYouCreateANewUniverse.class })
public class PerformanceTestSuite {}

But how about scanning your whole test bed?  Can we programmatically inject suite classes and use them with Categories?  At this point it is a limitation unless you want to use a classpath hack.

Parallel Tests

If you have fast IO and multicore (like my new work PC Smile) and well written tests that don’t trodd on each others data.

U use Maven’s surefire 2.5 plugin to achieve this, and say methods, classes or both in parallel.  Classes is probably safer since most people write the test slipping thru later tests in the same class depend on earlier test methods accidentally.

Infinitest

This is a tool for IntelliJ and Eclipse that runs tests when you save your source and tells you if you have failed runs.  I remember twittering about how cool this would be if it existed a while back, and I’m glad I wasnt the only one with this idea and that someone actually implemented it Open-mouthed smile.

Also there was a plugin for IntelliJ called Fireworks but I could never get it to run tests properly on my Windows PC; always complaining about not being able to find a JDK home Sad smile.

This tool seems pretty cheap at $29 for an individual license, I’ll check it out and give it a shot.

http://improvingworks.com/products/infinitest/

What would be super cool is if it worked with Categories mentioned above, to be able to exclude GUI tests from being executed.  There may be a feature in Infinitest that handles it but I’d be keen to see.

Mockito

I’m traditionally an EasyMock guy but Mockito has always had good buzz.  At my new job we dont actually have a mocking framework yet so I’m keen to give it a look.

Mockito seems to have less verbose setup of tests, something that when learning EasyMock bashed me around a bit – ever forget to get out of record mode and get a green test accidentally.

As per Integration Tests are a scam ypresso recommends, you can verify interactions, verify a method is being called with certain params.

Other Stuff (comments from the Q&A of the presso)

Hibernate mappings – use an in-memory database

FEST asserts – an alternate to Hamcrest that avoids the Generic issues that plague Hamcrest!!! (boy this frustrates me a lot as a Hamcrest user)

Cobertura – a code coverage tool, alternate to Emma

Private methods shouldn’t be tested explicitly – you should be able to sufficiently test a class by its public facing API.