Grails 3 Released: Installing Gradle and Groovy 2.4 Support in Eclipse/GGTS

Grails 3 has been released with a ton of new features.

GGTS logoIf you’re used to adding a new Grails distribution in Eclipse or Groovy/Grails Tool Suite, you’ve might have experienced that your good old IDE might not support Grails 3 projects right out of the box.

You might be missing:

  • Grails 3 support at all :-)
  • Gradle support
  • Groovy 2.4 support

Here’s how I think you can fix some of these things.

Grails 3 support

As you regularly do with new Grails distributions is to add it in GGTS under Preferences > Groovy > Grails. But dang!…it doesn’t recognize the grails-3.0.x-directory you just unzipped a minute ago.

GGTS doesn't recognize Grails 3

No worries! We have Gradle now.

Gradle is the new Grails 3 build system, in favor of Gant. If you’ve created e.g. the helloworld-application as used in the Getting Started section of the manual, you see a few files like build.gradle and gradle.properties.

Because of this we don’t need a specialized IDE plugin perse, since existing Gradle tooling can do the trick! So we skip adding a Grails 3 distribution and we look for…

Gradle support

It is possible that GGTS doesn’t know to import a Grails 3 project into your workspace, because of missing Gradle support. You can:

Generate Eclipse/GGTS…

  1. … files with gradlew eclipse.
  2. This will generate .project and .classpath which will allow you to “import it as an existing project” into your workspace

or install Gradle support

  1. Open Eclipse Marketplace, search for “gradle”
  2. Choose e.g. the Gradle IDE pack or just the Gradle Integration plugin
  3. Now you can find and import your project too

In GGTS your Grails 3 project is just a “regular” Gradle project.

Hello world!

The above screenshot is possibly an idealized view – it might as well that you have some red markers! I did.

Grails 3 comes with Groovy 2.4, and if you don’t have the correct version set, you get:

Groovy: compiler mismatch Project level is: 2.4 Workspace level is 2.3
Groovy compiler level expected by the project does not match workspace compiler level.

It’s similar as when you had to install Groovy 2.3 into GGTS :-) You can fix the project level to 2.3 but then you get

Groovy:Unexpected problem with AST transform: The Spock compiler plugin cannot execute because Spock 1.0.0-groovy-2.4 is not compatible with Groovy 2.3.10. For more information, see http://versioninfo.spockframework.org

You’ll have to get…

Groovy support

Assuming you don’t already have it, we have to install the Groovy Compiler 2.4 Feature into GGTS.

1. Go to Help > Install New Software and use the update site http://dist.springsource.org/snapshot/GRECLIPSE/e4.4/

2. Select the Groovy 2.4 compiler and Next.

GRECLIPSE update site

3. If there’s a conflict, just press on – it’ll install Groovy 2.4 next to the other versions.

GRECLIPSE update site - just continue!

4. Continue all the way. Finish, restart.

5. Switch the compiler for the workspace. Go to Preferences > Groovy > Compiler and switch to 2.4.3.

Switch to Groovy 2.4.3 compiler

Done.

Happy programming!

Basic Groovy and Grails Code Review Guidelines

I’ve been – and still am – teaching Grails to non-Java programmers for a while now. This also meant to coach them into some ways of working I hold very dear, such as pair programming and doing code reviews.

Code Review

Of course, in the beginning with a new team I am doing the lot of the reviews, but as time passes I need everybody to do understand why they matter and what to look for in the code as a reviewer themselves. Every team should have a set code review guidelines they agree on – so we wrote down some conventions and rules and agreed to follow them.

Here I describe some guidelines and good practices to perform a peer code review of (the work of) a colleague. It’s not an exhaustive list and some are pretty straight-forward for seasoned developers, but it served me well to cover some basics for non-Java junior teams beginning with Java, Groovy and Grails.

General

  • Does the code fulfil the specifications or acceptance criteria written in the user story, or is there a gray area?
  • Do you understand what’s been programmed? Would you be able to make modifications to it later on?
  • Have the proper Grails and Groovy constructions been used to realize the proper things?
  • Is the code readable and does it adhere to our guidelines of code style and naming of things? See following sections.

Naming

Use the proper structures and names. Use the correct names of Grails artifacts, such as Domain Classes, Controllers, Services, TagLibs and methods and variables.

  • Packages should start with nl.<company> followed by application name, such as nl.first8.myapp
  • Classes start with CAPITALS, such as Animal, methods and variables are written in camelCase, such as displaySummary() or animalInstanceList
  • Try to avoid abbreviations. Prefer domainCode over dmnCd
  • Does the name actually cover the subject?

Readability

General readability- and formatting guidelines to read code easy and have it written in a consistent manner. A part can be done automatically with the built-in Formatter in the IDE, e.g. Ctrl-Shift-F in Eclipse or GGTS, but not everything.

Not all one-liners

In example below, split up e.g. the initialization of variables, in order for its usage to become more clear.

out << body() << ( (attrs.int('offset')) + "-" + ( Math.min(attrs.int('count'), attrs.int('offset') + attrs.int('max') ) ) + " " + title + " " + attrs.int('count') )

could become

int start = attrs.int('offset')
int total = attrs.int('count') )
int end = Math.min(total, start + attrs.int('max') )
 
out << body() << start + "-" + end + " " + title + " " + total

Spock tests and labels

There’s plenty to say about “proper” writing Spock tests, but that’s beyond the scope of this post.

Use the proper labels in Spock tests for readability. Use and:to separate multiple labels – with additional “textual description” after them – to make them stand out. Write

when: "searching for existing animal"
...
then: "we have results"
model.animalSearchResults.animalsCount == 1
flash.successMessage == "animal.all.found.message"
session.selected.size() == 1

as

when: "searching for existing animal"
...
 
then: "one found animal is returned"
model.animalSearchResults.animalsCount == 1
 
and: "all found message is displayed"
flash.successMessage == "animal.all.found.message"
 
and: "animal has been auto-selected"
session.selected.size() == 1

White-space

Use white-spaces to separate combined statements. Write

Integer.valueOf(params.offset?:attrs.offset)

as

Integer.valueOf(params.offset ?: attrs.offset)

White-space and brackets

Before and after brackets in general you do NOT have to use white spaces. Write

if ( params )
if ( total > 0 )
if ( end < begin )

as

if (params)
if (total > 0)
if (end < begin)

Curly brackets

Use curly brackets for one-liners. Write

if ( end < begin )
      end = begin

as

if (end < begin) {
  end = begin
}

Although you can write an if-statement on one line or just the line below without the curlies, especially when there are multiple statements after each other, it will improve readability and shows intent more clearly.

Compare

if (end < begin)
end = begin
end = end + 1

with

if (end < begin) {
  end = begin
}
end = end + 1

Comments

Use comments to state the purpose of classes and methods, clarify difficult pieces of code and document the decisions (“why?”) made. For Java en Groovy code we can use Javadoc to generate API documentation in HTML format in the source code.

Javadoc on classes

Use Javadoc comments at the top of a class to describe the general purpose, such as

/**
 * General convenience tags for layout - header, body and footer - purposes.
 */
class LayoutTagLib {

Javadoc on methods

Use Javadoc on public methods to describe the purpose and its parameters. You can use @param for parameters, @return for what it returns, when or if exceptions are thrown with @thrown etc.

/**
 * Gets the user for specified code and role.
 *
 * @param code The code, either username or email address
 * @param role The role identification e.g. A, B or C. Default is A.
 * @return the user or null if not found
 */
User findUser(String code, String role = "A")

Clean up

Remove obsolete comments, e.g. which got left behind, or which are plain wrong, or correct them!

Simplicitly

Is the code simple and does it do its work in the most simple way….but not simpler

Intuitive API

Use an intuitive API. Use similar structures or naming. Is only the actual required input needed and are for others sensible defaults being used? If you’re creating a betterPaginate tag, don’t burden the user too much with all kinds of input. Have him instead of

<g:betterPaginate offset="${params.offset?:0}“ count="${results.animalsCount?:0}" max="${params.max?:0}"/>

allow to use your tag as

<g:betterPaginate count="${results.animalsCount}" />

where you take care of the defaults, and the reading from paramsetc.

Simple writing

The more complicated lines used, the more difficult it is to understand what happens and where changes should go. It turns out that the following 10 lines created by a co-worker

int offset = 0
int total  = 0
int max    = 0
  
if (params) {
    offset = Integer.valueOf(params.offset ?: attrs.offset ?: 0)
    max    = Integer.valueOf(params.max ?: attrs.max ?: 0)
} else if (attrs) {
    offset = Integer.valueOf(attrs.offset ?: 0)
    max    = Integer.valueOf(attrs.max ?: 0)
}
total = Integer.valueOf(attrs.total ?: 0)

can be rewritten in just 3 lines with the same behavior:

int offset = Integer.valueOf(params.offset ?: attrs.offset ?: 0)
int max = Integer.valueOf(params.max ?: attrs.max ?: 0)
int total  = Integer.valueOf(attrs.total ?: 0)

If you have a good test, you can refactor somewhat more freely these kinds of constructions and still be fairly confident you didn’t change anything unexpectedly.

Oh and:

Rule 1: Try to find at least something positive
Image credits:

[1] What is Code Review? – http://smartbear.com/all-resources/articles/what-is-code-review/

[2] – How to Facilitate Friendlier Code Reviews – http://www.syncano.com/friendly-code-review/

GGTS: Clean up Grails 2.0 output

GGTS logoHave you ever had in Groovy/Grails Tool Suite (GGTS) that console output, by a running Grails application, which is exactly the same as the previous output, just isn’t displayed?

This can often be seen with println statements for debug-purposes e.g. in a Controller, which you think should output some line to the console every time, but simply doesn’t.

class TestController {
	def index() { 
		println "index called"
	}
}

When http://localhost:8080/test/test/index is invoked repeatedly in the browser, you just keep seeing only the first occurence.

....index called

When the same message repeatedly is sent to the console a certain convenience feature of GGTS swallows some output – if it looks the same. It has to do with the – since Grails 2.0 introduced – ANSI codes to make some output to the console coloured or re-appear on the same line.

Kris de Volder gives a nice example in JIRA issue STS-3499 about how multiple lines such as

Resolving Dependencies.
Resolving Dependencies..
Resolving Dependencies...
Resolving Dependencies....

are supposed to ‘rewrite over themselves’ on ANSI-supported consoles, so you’d only see

Resolving Dependencies...<increasing periods>

on the same line.

Output in the GGTS non-ANSI-enabled console is stripped from these codes – which would result in additional output which some people find unpleasant. So GGTS uses a workaround – which is enabled by default – and strips the beginning of the output which matches previous output and only print the remainder.

So if you were wondering why

class BootStrap {
	def init = { servletContext ->
		['A', 'B', 'B'].each { println it }
	}
}

would only print

|Running Grails application
A
B
|Server running. Browse to http://localhost:8080/test

instead of

|Running Grails application
A
B
B
|Server running. Browse to http://localhost:8080/test

you know now this is not a bug :-)

You have to disable the option ‘Clean Grails 2.0 output‘ in the GGTS preferences under Groovy > Grails > Grails Launch to prevent this swallowing-behaviour.

Now your output appears in GGTS when you want it to appear :-)

Starting a video blog: Grails in the First8Friday series

I recently recorded the first Grails video in my company’s newest video-blog: the First8Friday-series.

A videoblog?

We already wrote “regular” blog articles, but sometimes you’ve got to try different things as a company, so why not a video blog — for now in Dutch only. Since we know Java, the first few episodes are planned to be about Grails, one of the more powerful, full-stack web application frameworks I’d love to use.

This opening episode shows how easy it is to create a CRUD application for managing spaceships using the scaffolding ability of the framework. It’s pretty low-level to begin with, so Grails-beginners can see what Grails can do for them.

Creating a video blog

For the first time we didn’t want to set the bar too high too handle. Even though it’s only a few minutes long, it cost quite some time to produce! Getting the content as if one was writing a regular blog post with code snippets and images was the easy part :-)

The bulk of the time was taken by a few things.

The script!

It’s not just like a blog post, it’s like a movie. You have to have script or a story-board. Going from just “content” to a story to tell is quite different: figuring out how to start, what’s in the middle and how to end. When should I be talking to the viewer on screen and when would a voice-over suffice?

Some parts were still images or screen casts I had to record before or afterwards on my laptop, where I not only had to deal with recording the actual action (command-line operations, viewing/editing of some code in the editor), but also revising the story itself as I was making image snapshots and screen captures. Why doesn’t have GGTS (or Eclipse) a presentation-mode, is a regular text-editor with syntax-highlighting maybe better? Why introducing all kinds of fluff in examples when it’s not about thát fluff.

ScriptImage: indiegogo.com

The green screen

The hardware, such as lights, camera and microphone, was easily acquired, but then using it is another story.

The lighting was initially flawed, unwanted shadows, distance between myself and the camera vs the microphone, positioning of myself (somewhat right from centre, visible from the waist up) etc.

The Green Screen at First8Image: The Green Screen at First8

The spoken lines of text

Re-runs of the same introduction and paragraphs with different pronunciations, rhythm, etc. What seems like a well-crafted sentence on paper, is a real tongue twister on camera :-)

It also doesn’t look great if a sentence takes 1 minute to complete, because the version on paper reads nice and poetic like that, but you can’t memorise it completely without an auto-cue. So yes, long lines without an auto-cue is hard (for any non-actor, like me), and the video-editor-person can’t keep trying to fade me out and in real quickly whenever I had to look sideways to my speaker notes.

The first-time technicalities

Seems that my screencasts were recorded by default as .avi files encodes as H264 and MP3 audio. Reviewing my video snippets with the media player caused no worries, but somehow integrating these in Adobe Premiere in the real production – you know, in the green part of the green screen – caused either a black edge, or flickering pixels, or, or… Since we couldn’t figure out all the causes (or even more, solutions), even after playing with some interlace-settings, I re-recorded screencasts as MP4 which could be handled more easily.

Better figured this out before recording anything at all :-)

Suffice to say, producing the real thing and integrating a kinds of screenshots, screencasts and other Powerpoint-like slides I could think of, made my video-producer also need to Google for a quite a few quirks and “features” of the his video-editing software himself.

All kinds of videos

Even though it seems we’ve encountered nothing but hardship by the looks of it, it’s been quite a fun experience and a lot of these things can be categorised as first-time start-up issues. While we’re busy now with video’s 2 and beyond, we’ve already gathered some valuable insights of things to do differently.

If you’re Dutch you can actually understand what’s going on, so if you haven’t done so, head over to First8Friday edition 1 about Grails on the company blog.

I welcome any comments or feedback or just any thoughts on video blogs (or regular screencasts) you might have seen, create or use in your daily life.