Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, July 14, 2011

Java 7 Small Language Changes Screencast

This screencast demonstrates the small language changes that are part of Open JDK 7, which is available from the Open JDK website. It demonstrates multi-catch, try with resources, strings in switch statements, underscores in literals, and the diamond operator.

If you have any issues watching the video below, then you may have better luck viewing it on the JetBrains.tv site.

I've made a lot of screencasts and blog posts over the years. If you like this, then there are many ways to see the other stuff I've done: 

The screencast was created with Ubuntu 10.04, PiTiVi, Audicity, gtk-RecordMyDesktop, IntelliJ IDEA, and LibreOffice. OS from top to bottom.

Thanks for watching, leave a comment, or upvote it at your favorite link site!

Thursday, March 31, 2011

Interview with Antonio Goncalves about the past, present, and future of Java EE

I got a chance to sit down and talk to Java Champion Antonio Goncalves about the past, present, and future of Java EE. I've been working for the last six months in a heavy EE/SOA stack, and it's been interesting to see the advantages and disadvantages. I definitely come from the other side of the world where specifications aren't seen as an inherent sign of quality, and frameworks not sanctioned by Sun/Oracle are not to be feared. It was fun to get his opinions about this stuff.

The full interview is on the JetBrains Zone at DZone. We're both JetBrains Academy Members and we're slowly interviewing each other.

P.S. This is the first post I've ever made that mentioned Java Enterprise Edition. I suspect the next time EE is mentioned will be in another few years :)

Tuesday, March 29, 2011

IntelliJ IDEA Static Analysis: Custom Rules with Structural Search & Replace

Well, well, I made another screencast. This time I'm taking on IntelliJ IDEA code inspections, and writing your own static code analysis rule (and quick fix!) using Structural Search & Replace. Not bad for under 5 minutes.

If you have any trouble viewing the video then perhaps you should watch it directly on the JetBrains site. And if you're feeling generous, then clicky clicky to upvote at DZone.



Check out these pages for more information on IDEA inspections:

Read these pages to learn more about Structural Search and Replace:

I've made a lot of screencasts and blog posts over the years. If you like this, then there are many ways to see the other stuff I've done:

Phew, that's a lot of self-promotion :)

Thanks for watching, and leave a comment!

Wednesday, March 2, 2011

CDI Event Bus Basics Screencast

Another day another screencast. This one's about the Event Bus that is part of CDI. Contexts and Dependency Injection is part of Java EE but available in SE using the Weld framework. This screencast shows you how to use CDI events and the event system, which is just one part of the larger CDI feature set. The screencast briefly explains the benefits of an event system and then shows how easy it is to use it from CDI.

If it doesn't play correctly, you may want to launch it from the JetBrains.tv site.



You could do worse with 5 minutes of your time.


If you like this, you can check out my other screencasts on YouTube (http://www.youtube.com/user/HamletDRC) or JetBrains.tv (http://tv.jetbrains.net/tags/hamlet)

Friday, February 25, 2011

Screencast: GWT Event Bus Basics

Wheee! I made a screencast. Happy Friday to you too.


This screencast is about the GWT Event Bus. It explains how an Event Bus can be used to loosely couple controllers or views in MVC applications, and includes live coding of a GWT using the SimpleEventBus client. The source is all available on GitHub. And as always, up votes are appreciated.

If it doesn't play correctly, you may want to launch it from the JetBrains.tv site.



"This screencast explains why MVC applications benefit from an event bus, and it demonstrates how to create, wire, and respond to events in Google Web Toolkit (GWT). Not bad for just six and a half minutes." Too much fun.

Tuesday, December 14, 2010

Mockito – Screencasts for Stubbing, Verifying, and Argument Matching

We're rolling out Mockito and trying to raise our testability at work and I'm set to give a presentation/training session tomorrow to a few new teams. In case you don't know, Mockito is a mock object framework for Java. It's competitors are EasyMock, JMock, and others if you're more familiar with those. If you haven't seen it then you may want to check out my old post "Mockito - Pros, Cons, and Best Practices". To prepare for my presentation I decided to record myself practicing my material and post it on youtube. Enjoy!

The first screencast is about creating mock objects and stubbing behavior. These are the absolute basics of mocking.


The second screencast is about verifying behavior, or verifying side effects, using Mockito. This is a little more advanced but still an essential API in working with Mockito. YouTube reports this video as 13 minutes long, but don't worry it is only 4:45. Some quirk of YouTube.


The final screencast is about argument matchers, which add flexibility to your stub and verify phases.


I hope you enjoyed these. They could be a little more practiced, but I'm happy enough with the quality. I recorded these on Ubuntu 10.4 using recordMyDesktop and mencode to convert from .ogv to .avi.

Friday, November 5, 2010

Advanced Mockito: Capturing State with Answer and Captors

Hmmm… I really need to mock out java.sql.ResultSet, I know I’ll just subclass it with a hand-rolled mock. Oh-no, the default implementation without method bodies is 650 lines of code long. WTF? Did you know there are 197 public methods on the java.sql.ResultSet interface? This is an absurdly large interface, possibly the largest in the JDK (if not drop a comment, I’d love to know what the largest is). The workaround is to throw one together in Mockito (or your mock framework of choice). My implementation turned out to be 21 lines of code long. Not bad at all. To do it I creatively used ArgumentCaptors, Answer objects, and anonymous inner classes to capture state... (read on for the full article).

The full article is posted over on the Canoo Blog. And don't forget to vote at dzone.

Wednesday, September 29, 2010

Mockito - Pros, Cons, and Best Practices

Mockito - Pros, Cons, and Best Practices

It's been almost 4 years since I wrote a blog post called "EasyMock - Pros, Cons, and Best Practices, and a lot has happened since. You don't hear about EasyMock much any more, and Mockito seems to have replaced it in mindshare. And for good reason: it is better.

A Good Humane Interface for Stubbing
Just like EasyMock, Mockito allows you to chain method calls together to produce less imperative looking code. Here's how you can make a Stub for the canonical Warehouse object:


Warehouse mock = Mockito.mock(Warehouse.class);
Mockito.when(mock.hasInventory(TALISKER, 50)).
thenReturn(true);

I know, I like a crazy formatting. Regardless, giving your System Under Test (SUT) indirect input couldn't be easier. There is no big advantage over EasyMock for stubbing behavior and passing a stub off to the SUT. Giving indirect input with mocks and then using standard JUnit asserts afterwards is simple with both tools, and both support the standard Hamcrest matchers.

Class (not just Interface) Mocks
Mockito allows you to mock out classes as well as interfaces. I know the EasyMock ClassExtensions allowed you to do this as well, but it is a little nicer to have it all in one package with Mockito.

Supports Test Spies, not just Mocks
There is a difference between spies and mocks. Stubs allow you to give indirect input to a test (the values are read but never written), Spies allow you to gather indirect output from a test (the mock is written to and verified, but does not give the test input), and Mocks are both (your object gives indirect input to your test through Stubbing and gathers indirect output through spying). The difference is illustrated between two code examples. In EasyMock, you only have mocks. You must set all input and output expectations before running the test, then verify afterwards.

// arrange
Warehouse mock = EasyMock.createMock(Warehouse.class);
EasyMock.expect(
mock.hasInventory(TALISKER, 50)).
andReturn(true).once();
EasyMock.expect(
mock.remove(TALISKER, 50)).
andReturn(true).once();
EasyMock.replay(mock);

//act
Order order = new Order(TALISKER, 50);
order.fill(warehouse);

// assert
EasyMock.verify(mock);

That's a lot of code, and not all of it is needed. The arrange section is setting up a stub (the warehouse has inventory) and setting up a mock expectation (the remove method will be called later). The assertion in all this is actually the little verify() method at the end. The main point of this test is that remove() was called, but that information is buried in a nest of expectations. Mockito improves on this by throwing out both the record/playback mode and a generic verify() method. It is shorter and clearer this way:

// arrange
Warehouse mock = Mockito.mock(Warehouse.class);
Mockito.when(mock.hasInventory(TALISKER, 50)).
thenReturn(true);

//act
Order order = new Order(TALISKER, 50);
order.fill(warehouse);

// assert
Mockito.verify(warehouse).remove(TALISKER, 50);

The verify step with Mockito is spying on the results of the test, not recording and verifying. Less code and a clearer picture of what really is expected.
Update: There is a separate Spy API you can use in Mockito as well: http://mockito.googlecode.com/svn/branches/1.8.3/javadoc/org/mockito/Mockito.html#13

Better Void Method Handling
Mockito handles void methods better than EasyMock. The fluent API works fine with a void method, but in EasyMock there were some special methods you had to write. First, the Mockito code is fairly simple to read:

// arrange
Warehouse mock = Mockito.mock(Warehouse.class);

//act
Order order = new Order(TALISKER, 50);
order.fill(warehouse);

// assert
Mockito.verify(warehouse).remove(TALISKER, 50);

Here is the same in EasyMock. Not as good:

// arrange
Warehouse mock = EasyMock.createMock(Warehouse.class);
mock.remove(TALISKER, 50);
EasyMock.expectLastMethodCall().once();
EasyMock.replay(mock);

//act
Order order = new Order(TALISKER, 50);
order.fill(warehouse);

// assert
EasyMock.verify(mock);


Mock Object Organization Patterns
Both Mockito and EasyMock suffer from difficult maintenance. What I said in my original EasyMock post holds true for Mockito:
The method chaining style interface is easy to write, but I find it difficult to read. When a test other than the one I'm working on fails, it's often very difficult to determine what exactly is going on. I end up having to examine the production code and the test expectation code to diagnose the issue. Hand-rolled mock objects are much easier to diagnose when something breaks... This problem is especially nasty after refactoring expectation code to reduce duplication. For the life of me, I cannot follow expectation code that has been refactored into shared methods.
Now, four years later, I have a solution that works well for me. With a little care you can make your mocks reusable, maintainable, and readable. This approach was battle tested over many months in an Enterprise Environment(tm). Create a private static method the first time you need a mock. Any important data needs to be passed in as a parameter. Using constants or "magic" fields hides important information and obfuscates tests. For example:

User user = createMockUser("userID", "name");
...
assertEquals("userID", result.id());
assertEquals("name", result.name();

Everything important is visible and in the test, nothing important is hidden. You need to completely hide the replay state behind this factory method if you're still on EasyMock. The Mock framework in use is an implementation detail and try not to let it leak.
Next, as your dependencies grow, be sure to always pass them in as factory method parameters. If you need a User and a Role object, then don't create one method that creates both mocks. One method instantiates one object, otherwise it is a parameter and compose your mock objects in the test method:

User user = createMockUser(
"userID",
"name",
createMockRole("role1"),
createMockRole("role2")
);

When each object type has a factory method, then it makes it much easier to compose the different types of objects together. Reuse. But you can only reuse the methods when they are simple and with few dependencies, otherwise they become too specific and difficult to understand.
The first time you need to reuse one of these methods, then move the method to a utility class called "*Mocker", like UserMocker or RoleMocker. Follow a naming convention so that they are always easy to find. If you remembered to make the private factory methods static then moving them should be very simple. Your client code ends up looking like this, but you can use static imports to fix that:

User user = UserMocker.createMockUser(
"userID",
"name",
RoleMocker.createMockRole("role1"),
RoleMocker.createMockRole("role2")
);

User overloaded methods liberally. Don't create one giant method with every possible parameter in the parameter list. There are good reasons to avoid overloading in production, but this is test. Use overloading so that the test methods only display data relevant to that test and nothing more. Using Varargs can also help keep a clean test.
Lastly, don't use constants. Constants hide the important information out of sight, at the top of the file where you can't see it or in a Mocker class. It's OK to use constants within the test case, but don't define constants in the Mockers, it just hides relevant information and makes the test harder to read later.

Avoid Abstract Test Cases
Managing mock objects within abstract test cases has been very difficult for me, especially when managing replay and record states. I've given up mixing mock objects and abstract TestCase objects. When something breaks it simply takes too long to diagnose. An alternative is to create custom assertion methods that can be reused. Beyond that, I've given up on Abstract TestCase objects anyway, on the grounds of preferring composition of inheritance.

Don't Replace Asserts with Verify
My original comments about EasyMock are still relevant for Mockito: The easiest methods to understand and test are methods that perform some sort of work. You run the method and then use asserts to make sure everything worked. In contrast, mock objects make it easy to test delegation, which is when some object other than the SUT is doing work. Delegation means the method's purpose is to produce a side-effect, not actually perform work. Side-effect code is sometimes needed, but often more difficult to understand and debug. In fact, some languages don't even allow it! If you're test code contains assert methods then you have a good test. If you're code doesn't contain asserts, and instead contains a long list of verify() calls, then you're relying on side effects. This is a unit-test bad smell, especially if there are several objects than need to be verified. Verifying several objects at the end of a unit test is like saying, "My test method needs to do several things: x, y, and z." The charter and responsibility of the method is no longer clear. This is a candidate for refactoring.

No More All or Nothing Testing
Mockito's verify() methods are much more flexible than EasyMock's. You can verify that only one or two methods on the mock were called, while EasyMock had just one coarse verify() method. With EasyMock I ended up littering the code with meaningless expectations, but not so in Mockito. This alone is reason enough to switch.

Failure: Expected X received X
For the most part, Mockito error messages are better than EasyMock's. However, you still sometimes see a failure that reads "Failure. Got X Expected X." Basically, this means that your toString() methods produce the same results but equals() does not. Every user who starts out gets confused by this message at some point. Be Warned.

Don't Stop Handrolling Mocks
Don't throw out hand-rolled mock objects. They have their place. Subclass and Override is a very useful technique for creating a testing seam, use it.

Learn to Write an ArgumentMatcher
Learn to write an ArgumentMatcher. There is a learning curve but it's over quickly. This post is long enough, so I won't give an example.

That's it. See you again in 4 years when the next framework comes out!

Monday, September 27, 2010

Clearer Unit Tests: Assert, Guard, and Throw

I hate the book “xUnit Test Patterns” for being over 800 pages long. I am convinced a good editor can turn any 800 page book into a 700 pager with the exact same content… that includes you Leo Tolstoy! The problem is that xUnit Patterns is still the definitive reference to test concepts and implementation. There is no better book on testing available, but the sheer weight and size the book means few have actually read it. Well I have, and I highlighted the damn thing just to prove it. In this post you’ll find 3 techniques to improve test clarity that, in my opinion, are underutilized in the development world today.


Surf over to http://canoo.com/blog to read the rest of the article, or go straight to the Dzone link if you're inclined to vote it up. Thanks!

Friday, September 24, 2010

Beautiful Java Enums

File under “It’s never too late to blog about Java 5 features” and “you wrote 1000 words on what?”.

Way back before Java 5 I fell in love with the Type Safe Enum pattern described in Martin Fowler’s Refactoring. You know the one, where an instance of a class has members of itself as public static fields. It was so clever (not always a compliment) and I applied it everywhere I could. Fowler’s example dealt with blood types... to read the full article surf over to http://canoo.com/blog/2010/09/24/beautiful-java-enums/


And don't forget to spread a little DZone love...

Tuesday, July 27, 2010

Project Lombok - Java Without the Boilerplate

I've been playing around with Project Lombok and Canoo's RIA Suite (nee ULC) recently, getting ready for my next project. Lombok is a pure Java library that does compile time byte code generation to remove/generate a whole bunch of Java boilerplate for for you... getters, setters, toStrings, etc.

You can read about Lombok, and how to use it within RIA Suite, on the Canoo Blog. And, of course, you may vote for it on DZone.

Enjoy!

Friday, May 7, 2010

Gilad Bracha and the Java Post Mortem

At Jax.de this week I got to see two sessions with Gilad Bracha and sit on a panel with him (never would have imagined that).

I wrote my thoughts about the day up on the Canoo blog in a piece called "Gilad Bracha and the Java Post Mortem"

Upvotes always appreciated!

Tuesday, February 9, 2010

Asynchronous Unit Test Coordination with JConch 1.2

Slowly but surely, JConch Java Concurrency Library is becoming a depot for multithreaded and asynchronous testing on the Java platform. First there was SerialExectorService, allowing you to test with a Java ExecutorService that never started threads (example, javadoc). Then there was assertSynchronized, allowing you to make easy unit test assertions about your object's synchronization policy (javadoc, example).

And now JConch 1.2 offers TestCoordinator: a tool for testing asynchronous code and multi-threaded callbacks. The TestCoordinator solves the problem of how to properly wait for asynchronous method calls without littering your unit tests with wait/join calls or CyclicBarrier/CountDownLatch API calls. In this regard, it provides a useful unit testing abstraction over the great Java 5 concurrency primitives.

Note: If you'd like to skip all the prose then go straight to the example and unit tests that are part of JConch 1.2.

Writing good unit tests requires the same input as writing good production code: practice, dedication, and about 10,000 hours hours experience. Almost any component framework that requires some sort of event listener invariably has a unit test that looks like this:

MyComponent component = new MyComponent()

ActionEvent event
component.addActionListener({ ActionEvent e ->
event = e
} as ActionListener)

component.click()
Thread.sleep(1000)

assert event.source != null
assert "click" == event.actionCommand
OK, usually it's in Java and not Groovy, but you get the point. Life's too short to write Java at home. The simple format is 1) create a component with a listener that captures the input, 2) activate the component, and 3) put the thread to sleep for a while and hope that the event fires before your assertions get run. The obvious problem is that you end up with either slow or intermittently failing unit tests depending on how long you sleep (no, there really isn't a perfect sleep number that avoids both).

In the Java 4 days this was "solved" by monkeying with Object#wait and Object#notify method calls. Ewww. Java 5 introduced CyclicBarrier and CountDownLatch which solved the problem nicely albeit in a primitive way. It is an improvement, but we can do better than this:
@Test(timeout=5000)
public void testClick() {
CyclicBarrier gate = new CyclicBarrier(2)

MyComponent component = new MyComponent()

component.addActionListener({ ActionEvent e ->
assert "click" == e.actionCommand
gate.await()
} as ActionListener)

component.click()
gate.await()
}
This approach allows us to move the assertion methods inside the callback, because we're insured that either the callback will be called or the test will fail with a timeout (the @Test(timeout=5000) bit). It is simpler and hides some complexity, but there is still a bunch of primitives distracting the reader from the core content of the test... what is that (2) parameter on the barrier constructor? Is the timeout value clear or is it hidden within a method annotation? And just what does await() mean? There is a lot of primitiveness involved here, which is what TestCoordinator abstracts over:
import jconch.testing.TestCoordinator

TestCoordinator coord = new TestCoordinator()

MyComponent component = new MyComponent()
component.addActionListener({ ActionEvent e ->
assert "click" == e.actionCommand
coord.finishTest()
} as ActionListener)

component.click()
coord.delayTestFinish(1, TimeUnit.SECONDS)
As you can see, TestCoordinator acts alot like a barrier or latch, but without all the low level API. When you've activated your class under test then you call delayTestFinish(...); the unit test will wait unit the listener calls finishTest(). And if finishTest() has already been called (a frequent possibility with multithreaded systems), then delayTestFinish just proceeds. If the timeout value expires then the test fails. No funny timeout annotation. No funny API. Just a simple coordinator. You want to delay a test until a callback is finished, and the API is designed around this nomenclature.

There are two other options to delay as well:
coord.delayTestFinish(1000) // milliseconds
coord.delayTestFinish() // requires @Timeout value!
For those of you coming from GWT... yes, this is almost exactly the API of GWTTestCase. Use what works, I say.

For more info on TestCoordinator, check out the UnitTest and the example. Happy Testing!

Monday, January 11, 2010

Accelerated GWT Report Card

Student Name:Accelerated GWT
School:Apress
School Year:2008
Teacher:Hamlet D'Arcy
Overall Grade:A-Strong on client side, i18n, and advanced topics.
Grading Scale: A=Outstanding, B=Good, C=Average, D=Poor, F=Fail
 
Teacher Comments
This was a good book and a worthwhile read. It was very strong on the client side and documented many edge cases of the GWT framework without reducing itself to an overly specific "recipe" book.
 
Client Side ProgrammingA-
Knowledge of Standard GWT Widget SetA-
Great coverage of basic widget set. Contains examples and advice about how to layout widgets in various containers, including composing widgets in the Composite class. Sometimes the widget API was explained too completely and it felt like reading Javadoc, but these sections can easily be skimmed. Also, this book was written for GWT 1.4, so UiBuilder is not covered at all.
Knowledge of CSS StylingA
Great coverage of how to work with the CSS of widgets including several good examples. Best coverage of the topic I could find.
General Client ConcernsA
Overall, the client sections are excellent. Serializing your own classes is covered, the output of the GWT compiler is given fair due, and generators for creating custom JavaScript code at compile time are covered. So far, this is the best book on client side GWT that I've found, even though it doesn't cover the 2.0 features.
Knowledge of JSNI (JavaScript Native Interface)D
JavaScript Native Interface is barely covered. In comparison, GWT in Practice covers it maybe too much. Embedding JavaScript in multiline Java comments is the most controversial part of GWT, but it's not the most important. Still, a little more info would be helpful.
 
Server Side ProgrammingB
Knowledge of GWT RPC (Remote Procedure Calls)B
GWT RPC is covered in 14 pages. Do you need more than that? Maybe not, it's pretty straight forward. The appendix does cover some of the newer 2.0/1.5 features, like generics.
Knowledge of InternationalizationA+
Over 30 pages on i18n, including an example using localization at either compile time or run time. Very good chapter.
Knowledge of Security ConcernsB+
Same origin policy and cross site scripting: check. Not as lengthy coverage as in other books, but adequate.
Knowledge of GWT TestingB
GWT Testing is surely the easiest chapter of the book to write. GWT ships with GWTTestCase for testing asynchronous calls and a benchmarking tool for measuring performance, and they are clearly explained all over the Internet. Speed Tracer, the 2.0 profiler that runs in Chrome, is of course not covered.
Creative Code SamplesB
Decent enough code samples (with an occasional error) covering browser history and server sessions, as well as the other topics mentioned. Some of the code samples were a little long and ImageBundle was given too much space given that it is deprecated in 2.0.
Knowledge of Alternative Server StacksD
Nothing on the server side beyond GWT RPC is covered.
 
GWT Best PracticesB+
Tools to Write GWT ClientsA
The Enterprise means constraints: existing domain objects, maybe a crummy DAO, etc. Enterprise GWT apps will need things like custom serializers and custom generators to work around their legacy constraints, and Accelerated GWT covers these topics well.
How to Design GWT ServicesB
General advice about domain objects and writing RPC services is given and a DTO approach is avoided, which pleases me. Overall, however, not a lot of information is given on building "Enterprise" backends, which is part of the book's title.

Saturday, January 9, 2010

"GWT In Practice" Report Card


Student Name:GWT In Practice
School:Manning
School Year:2008
Teacher:Hamlet D'Arcy
Overall Grade:B (solid effort; time well spent; not enough on client side)

Grading Scale: A=Outstanding, B=Good, C=Average, D=Poor, F=Fail











Server Side ProgrammingA
Knowledge of GWT RPC (Remote Procedure Calls)A+
How Ajax calls are made from the client to the server using GWT RPC is clearly explained in a variety of use cases (almost too many!). The difficult to understand relationship between service interfaces, server/servlet implementations, and the client asynchronous interface is explained in words, with diagrams, and within the IDE. Explaining GWT RPC is where GWT in Practice really shines... and this topic is still relevant today in GWT 2.0.
Knowledge of Alternative Server StacksA
GWT in Practice demonstrates how to consume REST and POX services with GWT, how to integrate Flash for SOAP services (not a good idea IMO), how to use Java Applets(!) for a SOAP client, and how to use Comet for streaming data to clients. The book focuses so much on server side technologies that perhaps it should have been called "GWT Server Stack Recipes".
Knowledge of Security ConcernsA
The Manning "In Practice" imprint means the author is targeting real world developer concerns rather than giving a generic overview, and security is one of these real world concerns. GWT in Practice does a great job explaining all the cross site scripting concerns (and how to work around them), security certificate issues (and how to work with them), and how to configure Tomcat security (which isn't even unique to GWT). It's clear the authors have real experience with securing a GWT app in a variety of contexts.
Knowledge of GWT TestingB
GWT ships with both GWTTestCase (for easing the testing of asynchronous and multithreaded components) and a performance benchmarking tool. The tools are straightforward and covered in every other GWT text as well. While a testing section is essential to any GWT book, this one didn't stand out against the other material. I'd have liked to see more testing best practices. Plus, GWT ships with a new performance testing tool, so this section is starting to age.
Creative Code SamplesB
The book deomonstrates how to turn on history to support the browser back button and how to record and playback certain Comet messages. The former is useful (and part of the GWT project) while the latter seems unlikely to be needed by almost any other GWT developer (and is custom implemented for the book).










Client Side ProgrammingC+
Knowledge of Standard GWT Widget SetC
Granted, the "in Practice" title is not meant to be a basic introduction, but there is almost no material on the standard GWT widget set. If you want to know all the user interface widgets supported by GWT then look elsewhere. However, some widget layout and CompositeWidget material was covered, the GWT in Practice salvages a C grade.
Knowledge of JSNI (JavaScript Native Interface)B
Surely the most controversial part of GWT is the ability to embed JavaScript within multiline comments of Java files. Sounds nasty even if IDEA does support refactoring and highlighting, right? (And as of 2.0, Eclipse does as well). This books contains a ton of JSNI. Pages of it, actually; which isn't always a good thing for the book or for GWT. GWT in Practice will definitely show you how to wrap JavaScript libraries, even if it makes for poor reading. The best part of the JSNI examples was the recipe for adding drag and drop, which appeared twice in the book for some reason. If you need drag and drop or to wrap a JavaScript library then this is the book for you!
Knowledge of CSS StylingB
CSS styling gets a whole 2 pages. Which means there isn't much to say beyond what the browser offers already.
General Client ConcernsC
There simply wasn't enough information about client side programming in GWT in Practice. The example that were shown left me wondering, "Is that something I'll really need to do?"








GWT Best PracticesB+
How to Design GWT ServicesA
This is the only book I found that included best practices about how to design services, which the author recommended using DTOs and keeping interfaces seperate from implementations to decouple physical services. However, some of the diagrams seemed forced and pointless (and they were, did you know Manning requires a visual aid on every spread?)
How to Design GWT ClientsF
What should client side design be in an Ajax application that consists of pretty much just one web page? This wasn't covered at all. Note to authors: please include this in your GWT 2.0 update! Also, there was no coverage of how to deal with degenerate browsers like IE6. This is the bane of my current project and any hints would be appreciated.
Knowledge of the Best Tools for the JobB+
GWT in Practice shows NetBeans, Eclipse, and IDEA in action. The most helpful diagram of how a GWT project is structured was actually an IDE screenshot. For builds, the Maven plugin is covered ad naseum, which is understandable considering the authors wrote it. But still, Maven is dead to me so it was time wasted (now where is that Gradle GWT plugin)?



Teacher Comments
Even in light of the GWT 2.0 release, GWT in Practice holds up as a solid GWT book for newcomers. It definitely favors the server side and gives the client side short shrift. My biggest complaint was that it seemed to be a lot of recipes bundled into an "in Practice" format, and many of the recipes I didn't need (Flex? Applets?). Given the book is from 2008 when GWT had just been released, I wanted to dislike it. But it's held up quite well. It should not be the only GWT book you read, but probably it should be one of them.

Saturday, December 12, 2009

Java 5 + GPars: Throttling Action Processing

An interesting question came up on the GPars mailing list today: In a system that generates events, what is the best way to throttle back event processing to one event per second? I thought about an answer... then thought some more... and finally decided to write it all up in this blog post. The example uses Groovy and GPars, but it is easily adapted to a generic Java solution. Don't let the actors scare you! (or the lack of semi-colons, for that matter).

The example is the classic "Sleeping Barber" problem (I hadn't heard of it either). Basically, there is a barbershop. The barber is asleep. Customers walk into the waiting room periodically, and the barber wakes up to give each of them a haircut. When he's done he returns to his slumber. It's a lesson in reaction: something is asleep, then awakens to do some work, then returns to sleep.

The GPars docs provide a decent Actor based solution to this problem: there is a waiting room and a barber, and both are actors. When the barber is free, a customer from the waiting room is moved into the barber's chair. The barber and waiting room communicate via actor messages. But what if our barber is a bit of a diva, and no matter how busy the shop gets, he wants to give one haircut every 15 minutes and never any more (otherwise, he might get burnt out you see). That is the throttling problem: how do you make sure events are processed (a haircut is given) no more than x number of times in a given time period?

My solution: keep a work queue, and have a scheduled executor pull work off the queue at a specified interval. Java 5 gives you all the tools to do this without resorting to busy waiting, polling, or writing scheduling code. The classes you need to know about are ArrayBlockingQueue and ScheduledThreadPoolExecutor.

ArrayBlockingQueue is a FIFO (First-In-First-Out) queue that supports blocking instead of busy waiting. When you take() an item from an ABQ, the call blocks until an item is available... no polling or sleeping to see if an item is ready to available. Just call take() and your code won't proceed until there is an element found.

The ScheduledThreadPoolExecutor supports executing both Runnable and Callable objects at a fixed interval. If you're looking to execute the same task every 1 second then STPE is what you need... Timer, for all intents and purposes, has been deprecated.

So here's the barber that just won't stand to be over-worked... setting it all up we need customers, a barber, and a waiting room:

class Customer {
String name
}

// waiting room can't hold more than 12!
def waitingRoom = new ArrayBlockingQueue(12)

def barber = Executors.newScheduledThreadPool(1)
barber.scheduleAtFixedRate({
println 'Barber: Next customer please!'
Customer customer = waitingRoom.take()
println "${customer.name} gets a haircut at ${new Date().format('H:m:s')}"
} as Runnable, 0, 15, TimeUnit.MINUTES)


Customer is a simple bean; nothing interesting here. The waiting room is an ArrayBlockingQueue filled with customers that need a haircut. And the barber is an executor service with a scheduled task to give haircuts. The number of threads in the scheduled thread pool is 1 because there's only one barber. The barber takes customers from the waiting room and cuts their hair once every 15 minutes. The call to waitingRoom.take() is blocking... if there is a customer ready then he is serviced immediately, and if one is not, then the call blocks until someone is available. Once thing to note... the waitingRoom has a size of 12... if a 13th customer is added then the calling code will either block until there is enough room or throw an exception. There is an API to do either case.

So how do customers get into the waiting room? That's where GPars actors come in. The barber shop is a "reactor" in GPars terminology. Messages can be sent to the barbershop ("Enter" the waiting room), and the reactor adds the customer to the waiting room. A maƮtre d' of sorts. Here it is in action:
def barberShop = new PooledActorGroup().reactor {message ->
switch (message) {
case Enter:
println "${message.customer.name} waits for a haircut..."
waitingRoom.add(message.customer)
break
}
}

class Enter {
Customer customer
}

barberShop << new Enter(customer: new Customer(name: 'Jerry'))
barberShop << new Enter(customer: new Customer(name: 'Phil'))
barberShop << new Enter(customer: new Customer(name: 'Bob'))
barberShop << new Enter(customer: new Customer(name: 'Ron'))

The barberShop is a PooledActorGroup, a GPars object, and the "actor framework" just means adding a closure to the reactor() method of that group. The closure, or actor, and responds to Enter messages by adding the customer to the waitingRoom. At the bottom you see the nice << syntax for posting events to the ActorGroup.

So there you have it. There are many ways to do this, but I think the Java 5 Concurrency libraries are some of the best options. I'd be interested to hear other ideas too. Now go give those hippies some haircuts!

Thursday, December 10, 2009

Groovy 2009 Year in Review and 2010 Predictions

Groovy in 2009

Groovy 1.6 Released
Groovy 1.6 was released at the beginning of the year, and the most exciting new features have turned out to be Grape and AST Transformations.

Grape allows a developer to declare dependencies within their Groovy source code and then, at runtime, Groovy will download and install the dependencies using Ivy repositories. Want to ship scripts to your operations team? You no longer need to email or build JARs! It's no Jigsaw, but maybe that's a good thing.

AST Transformations allow developers to hook into the Groovy compiler and alter the way the code is compiled. This has enabled great work like the @Bindable and @Delegate annotations, as well as many forward thinking (read: visionary) libraries like the Spock testing framework and the CodeNarc static code analysis tools. Watch for more cool libraries and frameworks to use these features in 2010.

Griffon Released
While Flex and JavaFX duked it out for developer mindshare in the coveted (and hyped) RIA space, a groovier team quietly forked the Grails codebase and adapted it for Swing desktop applications. Griffon is way more than a dynamically typed builder pattern on top of Swing components. Griffon gives you property binding to widgets (you're not the only one Flex), a standard and simple MVC architecture without a spaghetti monster diagram (that's you PureMVC), more components than just a TextBox (the complete JavaFX widget set last Winter), a plugin system that allows you to decompose problems into reusable addons, and an easy way to deploy your app via webstart. If the Griffon team can keep the energy they had in 2009 then 2010 should be the year of the lion. Or eagle... or dog. What the hell is a griffon anyway?

Groovy Tooling Explosion
Looks like IntelliJ IDEA has some competition for best Groovy IDE. The Groovy Eclipse plugin got new life as Andrew Eisenberg revived the project, and SpringSource released better Grails support in SpringSource Tool Suite. Was the open sourcing of IDEA a response to the new competition? Who cares, it's free now! While IDEA is still the best IDE for Groovy, Groovy users will surely benefit from each IDE maker trying to outdo the other.

VMWare Buys SpringSource
Seriously, who saw this coming? This week at Groovy/Grails Exchange, Graeme Rocher demoed deploying to the cloud from his IDE (according to Twitter). Easy cloud deployment is good news... it will end the monthly "who do you use for Java hosting?" questions on user groups. Now if only the price would come down.

GR8 Conference
A Groovy conference created by the community, for the community, and priced for the community. It's great to see not for profit additions to the Groovy conference scene, and next year sees two GR8 events: one in Europe and one in North America (Minneapolis!). In other community news, Chicago Groovy Users Group started posting video sessions to blip.tv. Can we get some other GUGs to do the same?

A Groovy 2010

Don't think of these as predictions... think of them more as premature facts.

Gradle

To be clear: Gradle is not a Groovy technology. It is an enterprise build system written in Java with Groovy used as a build script. Anyway, the 0.9 release will include "Smart Execution/Incremental Compile" and 1.0 will support multi-threaded builds. These are enterprise level features that would be totally unique to Gradle... and they're sure to intice a lot of unhappy Maven developers. If the Gradle team can hit 1.0 and publish a book(!), then a lot of people will migrate.

GPars
I can't find anyone with anything bad to say about either the Fork/Join Framework or BMW Motorcycles... and I just sold my bike to spend more time coding. GParallelizer hasn't been widely adopted to date, in my opinion because it chased the Actor-Model hype a little too strongly. But now it's been rebranded GPars and an all-star team has been assembled to work on it. This isn't a good project to just follow, it's a good project to download and play with. Get the bits and join the mailing list. Your opinion counts! It's too bad that they hate cool the logo I made for them.

Griffon
The decision by the Grails team to make almost everything a plugin was genius. It provides a standard mechanism for everyone to modularize their own applications, and provides an easy path for users to push their non-business-critical plugins back into the community. If Griffon users embrace the plugin system, and then push their plugins back to the community, then Griffon could be a real alternative to JavaFX/Flex by the end of the year.

Java Closures
I wish the JDK team the best of luck meeting their September 2010 release deadline. While I have doubts that JDK 7 will ship in 2010, I do believe the closure syntax will be decided upon. And Groovy will be the first Java language to support that syntax. Whether a version of Groovy containing Java closures actually ships before JDK 7 is probably dependent on how the Groovy team wants to address the modularization issues of Jigsaw, which sounds like a much harder problem to solve.

Groovy IDE Support Improves... a little
IntelliJ IDEA still leads in features by a wide margin, but Eclipse and STS aren't stealing IDEA users, they're stealing TextMate users. People just want to debug without parsing all the files in the world. IDEA will remain the sole provider of Groovy refactorings, intentions, and auto-completions. But Eclipse will finally become a better alternative than a text editor. However, the open sourceing of IDEA should make it easier (and faster) to get IDEA support for newer frameworks, which is a good thing.

Groovy-User Mailing List Shuts Down
For the entire month of June, all posts to groovy-user will be answered with the same response: "This is covered in Groovy in Action 2nd Edition". By the end of the month admins will simply replace the mailing list home page with an advertisement for the book.

What Won't Happen

InvokeDynamic
InvokeDynamic is set to greatly improve implementing and running dynamic languages on the JVM. Only it won't be released until September 2010 at the earliest. Sure you can get the OpenJDK now, but most users won't do that. I predict InvokeDynamic being the story of 2011, not 2010... and even then I bet the JRuby guys beat us to it.

The Java Store
Let me get this straight... you want me to pay US$50 yearly so that I can give my Griffon app away free on the Java Store? You gotta be kidding. Griffon + the Java Store could be a match made in heaven: Griffon makes JNLP Webstart simple to configure and the Java Store handles hosting the files. But Sun/Oracle is turning too many hobbiest and small time developers away with their entrance fee. Are you listening Mr Ellison? I said I want... oh wait, you're not listening. How hard would it be to make the Groovy Store?

This was fun. What are your Groovy 2009 highlights and 2010 predictions?

Thursday, December 3, 2009

Simple XML Testing from Java

2009 is coming to a close and I'm writing a blog post about Java and XML. The blog's called "behind the times" for a reason: no fancy dynamic languages, JSON, or REST. Straight up XML on Java action.

One of my favorite editions to our enterprise toolset this year was XMLUnit. We'd been using Groovy in testing, and multi-line strings led to a ton of expressiveness in test cases... but then we stopped using Groovy. I switched back to Java testing and was left with making String based assertions and doing String#contains() calls. Not ideal; enter XMLUnit.

XMLUnit supports XML based equality comparisons so that things like these two snippets are equal:

<root/>

<root></root>

As well as these:
<root>data</root>

<root>
data
</root>

In fact, there's a whole gaggle of options around what is a meaningful versus a meaningless difference. For instance, I often consider two dates equal as long as they are formatted correctly (ignoring those pesky timestamp issue is nice).

The problem with XMLUnit is that the API is not as nice for the simple case as it could be. What I want is a simple custom assertion that asserts two XML snippets as similar. Something like this:
XmlAssertions.assertXmlSimilar("<root/>", "<root></root>"); 
XmlAssertions.assertXmlSimilar("<root>data</root>", "<root>\ndata\n</root>\n");

This was as simple as creating a small utility class and hiding the XMLUnit API behind a nicer custom assertion:
import java.util.List;
import junit.framework.*;
import org.custommonkey.xmlunit.*;

public class XmlAssertions {

private static final String ERROR_MSG = "XML comparison failure. \nExpected: %s\nReceived: %s\n%s";

static {
XMLUnit.setIgnoreWhitespace(true);
}

public static void assertXmlSimilar(String expected, String actual) {
try {
Diff diff = new Diff(expected, actual);
List differences = new DetailedDiff(diff).getAllDifferences();
Assert.assertTrue(
String.format(ERROR_MSG, expected, actual, differences),
diff.similar());
} catch (Exception ex) {
Assert.fail(String.format(ERROR_MSG, expected, actual, ex.getMessage()));
}
}
}

The raw XMLUnit code is clearly not something you want to see within the body of a test method. The custom assertion seems simple, but it's made a real pleasure of writing XML based functional tests around all our web services. Feel free to steal my code here: http://svn.assembla.com/svn/SampleCode/xmlunit/XmlAssertions.java

Sunday, August 23, 2009

Exploring Immutability

When did immutable objects become idiomatic Java? I suppose it depends on your frame of reference and what your experience brings to coding. It may not be idiomatic Java to you. In fact, Java Beans and fluent interfaces seem to rely on in-place side effects and mutability to function properly. Exactly what place do immutable objects have in the Java world?

The immutability of String surprised me when I was learning Java. One of the first programs I wrote assumed String#replace did an in-place edit of the String, one of the first debugger sessions I conducted clearly showed me that String#replace was not editing the String, and one of the first Sun Forum questions I posted was about String#replace being broken in Java. BROKEN, I say! This represents the one time when an answer to a Sun Forum question clearly solved the poster's problem without a lengthy chain of "please post your code" responses. The point is that immutability has been with Java forever. And now that the days of Object Pools and persistent performance concerns are behind us, it's time to embrace immutability in our own code.

The benefits of immutability are many and well-documented. Effective Java (either edition) is a good start. I'll touch the highlights with the example of a Person object:

class Person {
def firstName
def lastName
}
HA! Tricked you, it's Groovy. In the Groovy compiler, the Person class gains two methods for each property defined:
public void setFirstName(Object)
public Object getFirstName()
...
The problem with the Class (as the JVM sees it), is that many threads may access Person and see the same instance in different states. It is difficult to share this object correctly across threads. The problem with the Java source is the cruft of writing getters and setters. The problem with the API of Person is that working effectively with the object requires many calls to setX and setY mutators just to get simple interactions working. The problem with maintaining this code is that the object is somewhat non-deterministic and difficult to reason about. Groovy uniquely solves only one of these issues: the source level cruft. Sure, you don't have to write out getters and setters, but that is the least important problem to solve.

Fluent APIs solve the issue of having to munge up the source code with repetitive calls to setX and setY. Instead of following the Bean pattern of setters being void methods, instead have all your setters return a 'this' reference:
class Person {

def firstName
def lastName

def setFirstName(firstName) {
this.firstName = firstName
this
}

def setLastName(lastName) {
this.lastName = lastName
this
}
}
Now you have a nicer API to work with at the expense of not having a standard Java bean. Remember the Java language change proposal to make void methods always implicitly return a 'this' reference? I feel like I'm the only guy wanting that in Project Coin. Oh well. Here is what consuming the API now looks like:
def person = new Person()
.setFirstName('hamlet')
.setLastName('darcy')
assert 'hamlet darcy' == "$person.firstName $person.lastName"
Groovy has a solution to this same problem: the with block. All object have a with method, and when inside the closure parameter, all method and field references are resolved back to the object having with invoked. Visual Basic had this feature and I always missed it in Java:
def person = new Person()
person.with {
firstName = 'hamlet'
lastName = 'darcy'
}
assert 'hamlet darcy' == "$person.firstName $person.lastName"
So both Groovy and Java have an answer for the boilerplate involved with writing and consuming APIs. But again, these aren't the big issue with mutable objects: non-determinism and thread safety are. To help solve that you can use immutable objects.

Can we get nice, fluent interfaces in Java without sacrificing mutability? The go-to solution in Java is the Builder idiom. Make your Person object immutable (all final fields), and the constructor private. Then define a mutable Builder class that wraps the constructor in a better API. In the end, creating Person instances looks like this:
def person = new PersonBuilder()
.setFirstName('hamlet')
.setLastName('darcy')
.build()
assert 'hamlet darcy' == "$person.firstName $person.lastName"
You instantiate the Builder and the builder instantiates the Person. This is nice... I guess maybe. Remember the idea of a "meaningless abstraction"? PersonBuilder is definitely a meaningless abstraction. It does not exist to solve any of the problems the system was designed to do. It exists solely to solve a problem in the implementation. Suspect. Very suspect.

The Builder has by far the longest implementation, and the DRY principle is glaringly violated in the duplicate fields:
class Person {
private final def firstName
private final def lastName

Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}

class PersonBuilder {
def firstName
def lastName

def build() {
new Person(firstName, lastName)
}

def setFirstName(firstName) {
this.firstName = firstName
this
}

def setLastName(lastName) {
this.lastName = lastName
this
}
}
It should be said, though, that this idiom does address the determinism and concurrency issues with mutability. Person can now be shared freely across threads, cached safely, and behaves in a more deterministic manner.

The best approach has not yet been mentioned. Simply create an immutable object without a builder, and also provide a nice fluent API around it. The calling code can look exactly the same as the previous fluent API example:
def person = new Person()
.setFirstName('hamlet')
.setLastName('darcy')
assert 'hamlet darcy' == "$person.firstName $person.lastName"
You can do this by slightly tweaking the fluent API example. Don't return a 'this' reference from setters, just return an entirely new object. And don't worry about all those little objects you're creating and tossing away.
class Person {

private final def firstName
private final def lastName

Person() { }

Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}

def setFirstName(firstName) {
new Person(firstName, lastName)
}

def setLastName(lastName) {
new Person(firstName, lastName)
}
}
Is a Person instance threadsafe? Yes. It is immutable.
Is a Person instance deterministic? Yes. No race conditions here.
Is a Person instance API easy to consume? Yup, it has a fluent API.
Does the Person class introduce a meaningless abstraction? Nope, and good thing!
Does the Person class require an exotic programming language to implement? No, this works fine in Java.
Does the Person implementation require tons of boilerplate? Maybe. The good part is that every implementation of a setter is exactly the same. The bad part is that every implementation of a setter is exactly the same. Not very DRY, but it could be automated in Groovy at runtime with a little metaprogramming.

That's it, immutable exploration over. And what place should immutability have in the Java world? It should be front and center. I hope I've shown that immutability and good APIs do not need to conflict with each other. You can get both with a tiny bit of extra work.

Saturday, August 22, 2009

How to Tell Your Co-Workers Have Discovered Functional Programming

Three ways to tell that your co-workers are learning a Functional Programming language at home:

1. You've found the number of .class file in your project quadrupled in the last month.

Here is an output directory with 17 .class files, only 2 of which are not inner classes, most of which are anonymous.



See all those dollar signs indicating inner/anonymous classes? Uh oh, looks like someone discovered shitty lambdas. Your chaos meter should be increasing... will your project be maintainable of it's not idiomatic Java?

2. You've found a class named Pair

public class Pair<T, U> {

private final T left;
private final U right;

public Pair(T left, U right) {
this.left = left;
this.right = right;
}

T getLeft() { return left; }
U getRight() { return right; }

static <T, U> Pair from(T left, U right) {
return new Pair<T, U>(left, right);
}
}
It's not a tuple, but it's about 2/3 of the way there! There's already jfun.util.Pair in JFun and gnu.lists.Pair in Gnu Lists, and now you've got your own too. Hooray. But wait, how will you maintain your code base if the declared name of your data structures don't tell you how it's meant to be used? Chaos... level... rising...

3. You've found a widely implemented one-method highly generic interface

An interface like this has over 100 implementations, many of which are anonymous:
public interface Transformer<T, U> {
U transform(T input);
}
This is equivalent to F in Functional Java and Transformer5 in JConch.

At this point your chaos meter should be off the chart. These functional programmers are surely ruining your system and livelihood. So, I'm hesitant to mention what happens when you combine all of them together:
Transformer identityfunction =
new Transformer<Pair<String, String>, Pair<String, String>>() {
public Pair<String, String> transform(Pair<String, String> input>) {
return input;
}
}
}

Voila, an anonymous function object that uses the Pair class to make a 1-arity method into a 2-arity method, returning multiple values.

These are the trials and tribulations of finding the appropriate use of new programming paradigms in old languages. Looking at version control history, the person that committed all these sins was... me. Will this be the Java code I write in two years time? Certainly not. But which of these example is the growing pains of learning FP and which of these will still be with me in the future?

Comments are open!