Dabble -> Scribble

Saturday, 12 December 2009

Griffon Bytes: Application Version at runtime

Griffon is a Grails like application framework for developing desktop applications in Groovy. See my earlier post for links.
'Griffon bytes' are/will be quick tips and notes about Griffon development. I'm just a dabbler, so these tips are definitely not authoritative ...

Application Version at runtime
It's useful to know an app's version number during runtime, for example, in an 'About' message box. The version number is stored in a file called application.properties, and sure enough all the entries in application.properties are available within every MVC component.

Here's the short version:
def versionString = 'version '+app.applicationProperties.'app.version'

Here's an example of using app.version in a View script.
See also app.name, using the same technique.

application(title: app.applicationProperties.'app.name',
size:[320,480],
pack:false,
//location:[50,50],
locationByPlatform:true,
) {
menuBar()
{
menu(text:'Help')
{
menuItem (text:'About '+app.applicationProperties.'app.name', actionPerformed: {
optionPane(message: app.applicationProperties.'app.name' + ', version '+app.applicationProperties.'app.version'+"\n\nCopywrong 2009.\n")
.createDialog('About '+app.applicationProperties.'app.name')
.show()
})
}

}
label('content ...')
}


Note: I found this out by looking at Griffon 0.2 source code (see griffon.application.SwingApplication.groovy).


Saturday, 7 November 2009

Starting out in Griffon: 3. Logging

I soon wanted to do 3 things with logging in my Griffon app:
  • Inject a logger (e.g. log4j) into all my MVC components.
  • Filter out the cruft from Groovy's massive stacktraces.
  • Log unhandled exceptions in the same way as everything else.
Here's how ...

* Injecting log4j loggers in MVC components
I want to be able to write a log entry from anywhere in my MVC code, without needing to explicitly define the logger in each component. Griffon makes this easy ...

1. Grab a copy of log4j-1.x.xx.jar (there's one in GRIFFON_HOME/lib), and copy it into [projectname]/lib

2. Initialise logging at application startup:
Edit the file [projectname]/griffon-app/lifecycle/Initialize.groovy
To simply send logs to the console, just use BasicConfigurator. Add this line:
org.apache.log4j.BasicConfigurator.configure()

... Normally, you would use a PropertyConfigurator, or maybe even call System.setProperty to tell log4j about your log4j configuration file.

3. Inject a logger into each MVC component.
* Create or edit the file [projectname]/griffon-app/conf/Events.groovy
* Add the following (I added 'mvc.' to the logger name because my MVC components are all in the 'default' package):
import org.apache.log4j.Logger
onNewInstance = { klass, type, instance ->
instance.metaClass.logger = Logger.getLogger("mvc.${klass.name}")
}
Now, you can call logger.debug("variable x is ${x}") from anywhere in your Model, View and Controller classes.
Sweet.

* Filtering Groovy Stacktraces
Groovy generates extremely long, unwieldy stacktraces.
Groovy itself provides support for filtering a lot of the 'noise', in org.codehaus.groovy.runtime.StackTraceUtils, so let's filter and forget.

Just wrap this call around any Throwable, whenever you log it:
StackTraceUtils.deepSanitize(t)
e.g.
logger.error("Uncaught exception: ${e.message}", StackTraceUtils.deepSanitize(e))

... You could take this further and override 'logger.warn()' and 'logger.error()'


* Logging unhandled exceptions
I want to log unhandled exceptions in the same way I log everything else.

Simply configure an UncaughtExceptionHandler.
Again, I configure this in Initialize.groovy
1. Create an exception handler, something like this (I've put in the deepSanitize)
import org.apache.log4j.Logger
import org.codehaus.groovy.runtime.StackTraceUtils
import java.lang.Thread.UncaughtExceptionHandler

class LoggingExceptionHandler implements UncaughtExceptionHandler {
private static Logger logger = Logger.getLogger(LoggingExceptionHandler.class)

public void uncaughtException(Thread t, Throwable e)
{
logger.error("Uncaught exception ${e.message}", StackTraceUtils.deepSanitize(e) )
}
}
2. Configure the app to use the ExceptionHandler
Edit the file [projectname]/griffon-app/lifecycle/Initialize.groovy
Add the following lines, *after* the log4j configuration lines:
Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
System.setProperty("sun.awt.exception.handler",LoggingExceptionHandler.class.getName())
Note that this replaces the functionality of griffon.util.GriffonExceptionHandler. If you prefer, you could extend this instead

HTH.

Amir

Starting out in Griffon: 2. Debugging

Having played a bit with some MVC code and got comfortable with 'griffon run-app', I wanted to take control of the development environment. Resorting to 'println' statements is just pants, so I got together some debugging and logging ..

I'll start with debugging. I'm assuming that you've done a command-line 'griffon create-app' by this point.

Debugging
Essentially, I'm running the app in debug mode and then attaching a 'remote debugger' from my IDE.

This is kind-of a 2-step approach. Let me know if you have a one-step approach.

Note: I had trouble getting NetBeans to debug groovy code properly. It just couldn't seem to find the Groovy line numbers. I'm normally an Eclipse user, so that might have something to do with it.

In this case, I'm using Eclipse. I have been using SSTS (SpringSource Tool Suite) distribution of Eclipse, (SSTS v2.1.0.SR01), and I downloaded the version with Groovy support included. I highly recommend this approach

Create an Eclipse project (File > New > Groovy Project; "Create from existing source", i.e. your [projectname] folder, as created by the command line 'griffon create-app')
You'll need to set the GRIFFON_HOME variable:
1. menu: Window > Preferences
2. drill into Java > Build Path > 'Classpath Variables', and add a GRIFFON_HOME

1. Start app in 'debug' mode
You can start the app from the command-line ('griffon debug-app'), but I'd rather not.
I'm running the debug-app task from the eclipse 'Ant' view.
1. If you cant see an Ant view, choose menu: Window > Show View > Ant
2. Drag [projectname]/build.xml from the Package Explorer view into the Ant view
3. Expand the project item and double-click debug-app.
(this has the same effect as running 'griffon debug-app')
Then, I'm noting the port number from the console output:
[exec] Listening for transport dt_socket at address: 18290

2. Start a Remote Debugger
Create and save a 'Debug Configuration':
1. menu: Run > Debug Configurations ...
2. Right-click "Remote Java Application" and select 'New'.
3. In Connection Properties, put Host: localhost, Port: 18290, then click 'Debug'.

...

Hey presto. Breakpoints work and stepping-through works great.

So, on subsequent starts, you can just double-click the 'debug-app' ant task and then pick the Debug Configuration from the toolbar (see the bug icon in your toolbar). I tend to start the remote debugger as soon as I see that port reference in the console.

Simple really. Next up, logging ...

Saturday, 31 October 2009

Starting out in Griffon: 1. Some links

Griffon
Griffon is a young Java desktop development framework, using Groovy as the main development language, and Model-View-Controller as the key development paradigm.
Griffon is a very young project, which has recently celebrated its first birthday. The documentation is still quite sparse.
I recently started using Griffon in earnest, and I'm really loving it. I'd like to share some experiences about this very young project.

Why me likey?
In the past, Swing development has made me want to pull my own teeth out and stab my eyes with them. Too much GUI code, ugly L&F, awkward APIs, etc etc.
Groovy itself helps matters in several ways, improving APIs and reducing boilerplate code.
Griffon builds on these features, and adds in MVC structure, sensible defaults (convention over configuration), a 'plugin' ecosystem, and command-line tooling for build, deployment, code generation, and plugin management.

FP, First Post
First up, I'm just going to list the main resources I've utilised to get going.
There's plenty of more experienced hands to offer introductions to the framework than me. They're just a bit spread out.
I'll describe my own experiences in later posts.

Griffon's own docs:
As I say, it's a bit sparse. I've been limited to the bundled sample apps, Griffon QuickStart, Griffon source code, and not least the user@ mailing list.

SwingBuilder documentation:
SwingBuilder is Groovy's main built-in helper for swing apps, and forms the basis for Griffon View objects.
View development in Griffon begins here, and returns here regularly:
(still a bit sparse)
This page is also worth some study:
(Remember, Swing doesn't manage threading for you, but SwingBuilder.doOutside and SwingBuilder.doLater make this task less of a chore)

The 'GriffonCast'
There's just one screencast so far, but well worth watching, particularly for the demonstration of how easy it is to enable/disable buttons by binding them to a model property. Downloadable source available.

Blogs
Andres Almiray is one of the Griffon developers and certainly its most vocal contributor:
Josh has written one great post in particular about Multiple Document Interfaces in Griffon:
http://josh-in-antarctica.blogspot.com/ (maybe check out his Griffon app PSICAT)
James has some handy tips:

Andres' E-Book (Early Access edition):
Andres Almiray is writing 'Griffon In Action'. There's only 4 chapters of 15 so far, one's free anyway and one needs updating, but he's a good writer so why not buy it now.
Edit: the multithreading chapter is really worth reading, especially for desktop noobs like me
Also the book's example code is here:

General Groovy resources:
Some Groovy docs I keep coming back to:
Mr Haki (very nice, concise & frequent posts for someone learning Groovy in their spare time)

General Swing resources (other than the Swing API Docs!!):
Java Desktop Links of the week (often contains Griffon snippets)

IDE stuff:
NetBeans Griffon plugin (worked ok for me but still very alpha)
Eclipse Groovy plugins work well for me (in conjunction with the ant plugin)
I am currently using SpringSource Tool Suite (a free but Spring-branded eclipse distribution):
JetBrains now have a free version of their IntelliJ IDEA, including Groovy support.
Apparently it's as good as sliced bread


Please throw back more Griffon links

Ta

Amir

Blogger Syntax Highliter

Followers