Ph: 10203040

[image] About me

Java.net profile

View Andres Almiray's profile on LinkedIn

ohloh profile

View aalmiray's profile on slideshare

Twitter Feed FriendFeed

Currently reading:

Programming Groovy - V.Subramaniam Beginning Java SE 6 Platform - J.Friesen The Story of the Irish Race - S.MacManus NFJS Anthology 2007 - N.Ford et al Groovy Recipes - S.Davis

[image] Recent Entries

[image] Tags

[image] Subscribe

Subscribe in Rojo

Add to Netvibes
Add to Google

[image] Projects

[image] I Recommend

GetJava Download Button

No Fluff Just Stuff

[image] Blogs I read

[image] Search

[image] Categories

[image] Monthly

« September 2008
Sun Mon Tue Wed Thu Fri Sat
 
1
2
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
       
             

[image] Badges

[image]
[image]
[image]
[image]
[image]
Add to Technorati Favorites

 

Locations of visitors to this page
On July 18th Eitan released a new version of JMatter, which includes many improvements and support for forms created with Abeille Form Designer (more on that later), but there is also another feature currently in svn that will give you more freedom in the regard of what a command may return. JMatter commands may return 3 values, handled by the framework as
String - will display a short message (like Growl in MacOS X) DomainClass - will display the view that belongs to that class View - will display the view as is
But now we have a fourth option: JComponent, when one is returned the framework will automatically wrap it in a generic View, relieving the developer of creating such a view. There is already demo-app bundled with JMatter (Self) which has a command that will display a JPanel with animations, so I thought that it may be great to test the fourth option and what better way to do it by embedding Google Maps support into the app, don't you think?

JMatter comes with another demo-app called Sympster, which is a Symposium Manager, modeled after the format of the NoFluffJustStuff Symposiums; each Symposium has a Venue, a venue may be a Hotel, a Conference Center or a Campus. As it currently stands a Venue only has a name and a list of rooms, we're going to add an address so that we can map it. We're going to use Groovy for the view because it is so simple to create custom UIs by hand with it (see previous post) and also because configuring JXMapViewer with it is pretty straightforward, as Guillaume Alleon and Guillaume Laforge show here and here.
Download a copy of JMatter from svn (http://svn.jmatter.org) Copy the Address class from demo-app/CustomUI to demo-app/Symspter
We could have used a built-in type (USAddress) but we'll stick with this one for the time being
Modify Venue, adding an Address field, some metadata and the command that will launch the Map

You'll find more info on the framework's metadata here.
Modify Address, adding a custom toString method which will be very helpful when translating the address into geo coordinates
Let's create the view, because any JComponent will be wrapped into a generic view we can extend from JPanel or JXMapViewer directly. Looking for more information on how JXMapViewer could be customized I found JXMapKit which will also display Waypoints (this little red & blue markers you can see on Google Maps when searching for an address), so I went with it
Before compiling the app, we have to do a little hack. JMatter bundles two different versions of swingx (2007_02_15 & 2007_06_17), unfortunately for us, the SwingX team has made some changes in the api that make those versions binary incompatible. Exchange swingx_2007_02_15 with swingx_2007_06_17.jar on modules/ds-swing/lib, compile it and make adjustments. It turns out that com.u2d.ui.desktop.MsgPnl$MsgPanelPainter should now implement doPaint instead of paintBackground, so its just a matter of wrapping one over the another, recompile and copy the new ds-swing.jar into jmatter/lib/runtime Don't forget to add the required libraries into Symspter/lib/runtime, download the 2007_06_07 version of swing-ws (includes JXMapViewer), put the swingx-ws.jar, and all co-bundled jars (except json.jar, it's already included by JMatter) Because we're using a custom view with Groovy, and the domain class references it but its coded in Java we'll need to enabled the joint compilation, which is explained here, substitute the javac call on the compile target with
We're ready to compile and test the app, type 'ant schema-export run' and if everything is ok and after a bit of JMatter magic... you should see a login screen, type in admin/admin as user/password and we're in!
Create a new Venue, right-click on the Venue icon and select 'New' on the menu Select a venue type, I went with 'Hotel' Fill up the venue data, notice that there are two tabs, the second one being the address of the venue. I configured the Hotel with the addres from the G2One meeting that took place this year. Save it and notice that a new command 'Show in Map' has appeared, click it and you should be able to see the address mapped into Google Maps
JMatter+GoogleMaps

Because it is a generic view, it doesn't have a title nor a custom icon. There may be an option in the future to do just that, perhaps with clientProperties or with a properties file. The point is that we concentrated our efforts on modifying the Model and provided a custom view without having to merge the view with the framework itself. These type of views may come in handy when doing quick app prototyping and then when the design has been approved you can get fancy with icons, colors and custom names & labels.

Keep on Grooving! and don't forget to stop by JMatter if you're into form-based business applications on the desktop :-)

groovy howto jmatter swing
Another announcement of the week is the release of FEST 0.3 (here and here), a great milestone for Yvonne & Alex. I've exchanged information with them about adding Groovy support to FEST, so I decided to believe in my own words first and take FEST for a spin with Groovy UIs.

There are a couple of articles out there that show how to use FEST (previously know as TestNG-Abbot), I picked the examples shown at Andy's In pursuit of code quality: Automate GUI testing with TestNG-Abbot, following the spirit of TDD, I started with the test and later moved to the real code.

Here is the test code:

Notice something strange? anything missing? no? well the code is Groovy code (you can tell by the missing semicolons and public modifiers) but other than that is equal to a 100% Java TestNG testcase, and that makes FEST amazing, it's fluent-interface design makes coding tests a breeze, and it behaves like a DSL, you don't need to use Groovy to get to this level of abstraction (but it doesn't hurt either, right?).

To run the test you'll need TestN'Groove (or groovyng), you can grab a bin distribution from the project site and follow the README for installation instructions. As I prefer to manage my dependencies with maven, a copy of the groovyng-1.0.jar gets installed on my local repo. After that its just a matter of configuring a basic Ant build with the following targets:

Its time to code the UI that will make the tests green:

Notice that each widget has an id and name properties, the first one assigns an internal variable with that name into the SwingBuilder and serves as a reference to the component, the second one will let Abbot find the component during tests. The findWord closure uses the fact that SwingBuilder has a reference of the components to locate the TextField and retrieve its text, the query on the dictionary uses a clever trick available to Maps, it calls get() with a default value, which will be stored and returned if no value is assigned to the key, the next time the same key is requested, the default value will be retrieved directly from the Map.

I hope this little demonstration has made you excited about trying FEST (an Groovy!), I know I am. I really wish FEST was available a year ago, when I was in the middle of a project (desktop app) which required a lot of user interaction, had a lot of paths and many options that had to be proven before letting it into the wild. We looked at Abbot at that time but deemed the learning curve too steep for our time constraints and decided to go with a home-brew solution (highly tied to our architecture, making it neigh reusable). Now I look at FEST and see what I was expecting 12 months ago, and it is on version 0.3, imagine what's coming next!

Congratulations to Yvonne and Alex for a fine work, truly remarkable.

Keep on Groovying! and don't forget to test ;-)

fest groovy howto testing
If you're into Groovy you've probably know that there is built-in annotation support since release 1.1-beta-1 but "unfortunately" it will only work for the following
types fields methods constructors
parameters and local variables are still allowed by the parser but they are pretty much left aside (for now?). But did you know that there is a way to annotate closure parameters and have access to those annotations? by using a custom GroovyClassLoader. Jochen blogged about it a while back (ChitChat with the Groovy Compiler) and in case you're wondering this is one of the tricks Grails uses to inject properties to your domain classes; essentially by subclassing the GroovyClassLoader you can provide your on CompilationUnit "handler", and we need to do it this way because the annotations we're targeting can't be accessed at runtime. Now that we have covered a bit of theory, let's get this party started!
...
This step intentionally left blank, to find out why go to Scott Davis's blog, I don't have a Mac (yet!).
Create a new Java class with yout favorite IDE or editor, where we're going to setup our GroovyClassLoader, following Jochen's example, we'll define and implement a subclass right away (hence the use of Java instead of Groovy, remember that Groovy doesn't support annonymous classes), which may look like the following code:

The interesting code will be in AnnotationParser. To make this class reusable you may define it as a property and set it at the appropriate time, in fact, this is what Grails does, it inserts a GrailsInjector through Spring into its GroovyClassLoader.
Remember we're targeting something like this

and the annotation has been defined as

so we'll iterate through all fields and inspect only those which initial value is a closure, let's create some skeleton code for AnnotationParser:

Yup that's right, we'll need to work with ClassNode, FieldNode and Expressions, all part of the org.codehaus.groovy.ast package which will grant you acces to all source artifacts in a Groovy AST. By checking if the initial value is instance of ClosureExpression we can continue inspecting the field, if not the we discard it and continue with the next field.
Now that we have a hold to the "closure" in question we'll inspect its parameters looking for the desired annotations. This is the step where an hypothetical framework may cache and wire any metadata based on those annotations, because this is just an example we'll simply output the values of the annotations 'properties'.

Notice that in order the access the annotation's 'properties' we'll have to use getMembers() and that the value of each 'property' is assumed to a be a ConstantExpression (meaning a string or number), which in this case it is.

Running AnnotationTester will yield the following output:
salute::name
[value=Name]


You'll find more info about annotations and Groovy at Annotations with Groovy, there's even an example of annotations on method parameters, Using Popper with Groovy.

Keep on Groovying!

annotations closure groovy howto
Lately I've been messing around with SwingBuilder, and as you probably know, when building Swing apps you usually have the impulse (need?) to code quick event adapters as anonymous classes, but Groovy does not support anonymous classes.. or does it? SwingBuilder already supports a shortcut for components that can register an ActionListener, as that interface has only one method, you define a closure and the builder takes care of the wiring with actionPerformed. But what if your listener has more than one method? no problem, Groovy Maps and the as keyword come to the rescue. If you didn't know, you can cast any Map (or any object for that matter with proper type support) to any other object, but what makes Maps special is that when used with conjunction with the as keyword it behaves like an anonymous class definition!

Take for example the following code, which is part of the test suit of the upcoming JideBuilder (I'll post about it later):
By specifying a map key of type Closure and then "casting" the Map to the proper type you obtain an instance of the specified type, just as if you were defining and instantiating an anonymous class, how cool is that? Just be sure to provide the complete list of parameters of each "implemented" method, otherwise you'll get an exception.

Keep on Groovying!

groovy howto
Parts I & II. Going further with the experiment of using Fuse with Groovy I had the goal of having a 100% Groovy app running, as I previously mentioned, I only accomplished that by compiling Groovy to byte code and running the app with Java.

The good news is that its possible! I was having classpath problems, which prevented the Fuse injectors to locate the theme files, you may run your own example with a similar configuration as the one being shown next:
Notice that I'm not using the Groovy Ant task, but instead running the main Groovy interpreter, that is because it seems there may be an issue with that task and its classloaders, so then again, this solution works for the time being when testing your app with Ant tasks.

Keep on Groovying!

fuse groovy howto swing
This is a follow up of Fusing with Groovy. After a couple of tries to get a custom UI component annotated with Fuse coded in Groovy to work, I decided to talk to the pillow and let the issue aside. The next morning I noticed I was always running the tests with the Groovy interpreter (from 1.1-BETA-1 of course) and decided to try again, but with the Java interpreter instead. Lo and behold , it worked!

So it's possible to create an UI component in Groovy, annotate with Fuse and inject resources, provided that you compile the code into byte code and run it with Java (for the time being). I'm sure it will be possible to do the same with the Groovy interpreter in the very near future.

The code I tested was a slight modification of ContentPanel (provided by the demo), which is the same code but with a little syntactic sugar on it.

Note that there is no need to cast Graphics to Graphics2D and some methods as setPaint() and setComposite() are treated as properties, oh, and no semicolons as well ;-)

Keep on Groovying!

fuse groovy howto
Recently Daniel Spiewak announced the availability of Fuse 0.4, having worked on a custom solution for resource injection I decided to give Fuse a look, as I remembered that it was used in a little app that astonished everyone at last year's JavaOne, I'm talking of course about Aerith.

I usually configure my projects with maven + eclipse, after adding the Fuse jars to my local repo and setting the Eclipse classpath, everything is ready to start hacking. The first thing to do is get a sample app with Fused resources, so I grabbed a copy of SwingHive demo and everything works as expected, you get a nice looking black gradient frame and two buttons, labeled "Black Theme" and "Red Theme", when you click on the red one, the gradient changes to a red hue, when you click the black one, the gradient returns to its original state.

So far so good, now its time to make the demo Groovier using the SwingBuilder, the resulting code follows:

Notice that because the main frame is composed of custom UI elements, it is required that widget() be used to append the elements to the frame (If you can't wait for James to finish SwingXBuilder, you may insert Swinglabs components in this way), resource injection is done iterating on properties set at the SwingBuilder instance (use the 'id' property for that) and that button interaction is pretty easy with closures. Executing this class with the Groovy Eclipse plugin yields the same result as before, but we chopped 70 lines from the original Java source =)

The next logical step would be to create a custom UI component in Groovy with resource injection ... and this is where I got stuck, neither the Eclipse plugin, maven mojo nor Ant task will let me inject a resource into my Groovy component, perhaps I'm missing something.

For the time being, here is a list of resources I found useful to get this little example to work:
the SwingBuilder test case. Groovy UI samples at the PLEAC project. Danno's Verbosity in Swing post. and of course GINA.

Keep on Groovying!

fuse groovy howto swing
I've been reading again The PickAxe for a while and one thing that keeps "haunting" me is how easy (and weird) is to create overloaded operators, the weird part being the name of the method call, which in Ruby is the operator itself. There is an example on the book on how to overload the index ([]) operator, so that it may receive two args; I tried to visualize how to do the same on Groovy and came with the following solution, I'll not reproduce Dave's full example [get the book to see the rest! =)], instead I'll post something similar, but you'll get the idea.
Ruby Version:

Groovy Version:

The trick in Groovy is to override the default getAt() that all beans inherit from the default Groovy MetaMethods, query the type of the arg, if it is a List, and in this case of size == 2, we call the subSong() method and return that Song, null otherwise. If the arg is not a list, we let the super class handle the call. The Groovy code to handle the overridden index operator may not look as fancy as the Ruby one, but it is very easy to mimic the same functionality and get the same results.

Keep on Groovying!

UPDATE: Following Dierk's suggestions, here is the updated Groovy version:


groovy howto ruby
Continuing the saga of Groovy applets, Grapplet is now groovier (I'm not kidding) the source is 100% Groovy now. I noticed that while JSObjectGroovyInterceptable was a plain Java class, the title on the sample JFrame was not correctly presented, instead of displaying 'Groovy', the default Object.toString() was displayed. I suspected the cause was in the signature of invokeMethod( String name, Object value ), changing to Groovy and leaving the value type undefined did the trick. I also added an each() method that will work on JS arrays, so it's possible to invoke a Groovy closure on each element of a JS array :)

Grapplet is temporary hosted at Json-lib's site, you may find it at http://json-lib.sourceforge.net/grapplet/grapplet.html and the 'binary' distribution at http://json-lib.sourceforge.net/grapplet/grapplet.zip. You'll need to configure your security settings to accept the certificate and grant permissions. I recommend that you download the binary distribution and try it locally, as the invoking mechanism will make several roundtrips to gather all the classes it needs. In my previous post I showed the security settings I followed, here I present the steps you'll need to test the applet from Json-lib's site:
Create a file named '.java.policy' at $USER_HOME with the following contents:
keystore "file:${user.home}/groovy";

grant codeBase "http://json-lib.sourceforge.net" {
   permission java.security.AllPermission;
};
. Copy the keystore 'groovy' from the binary dist to $USER_HOME. Point your browser to http://json-lib.sourceforge.net/grapplet/grapplet.html (tested with FireFox only) . Enjoy!

Here is another sample Groovy sample script that you may want to try, but first you must create a JavaScript array, filled with integers, on the window (easy if you use the JavaScript Shell for FireFox)



Keep on Groovying!

applet grapplet groovy howto
Let's say that your JavaScript array is [1,2,3,4], the Groovy script should output '1234'. If the type coercion to int was not made the output would be '1.02.03.04.0' instead. Feedback is always appreciated.
It took me a while (because work has been so intense lately) but I have a working version of Groovy in the browser as Dion did with Ruby. The good news besides running Groovy with <script type="text/groovy"> is that its also possible to call JavaScript code between your Groovy code without triggering a SecurityException (but I think its related to my security settings somehow, more on that). Dion's version included a tricky but clever way to read all <script> tags from the document with JavaScript and later feed them to a dynamically created JRuby applet. This version does the same but adds support for JSObject (as it was in the last post). For now you may run a script an use the 'window' reference to get a hold on the JS world; but if you try to use that variable inside a class, you'll have to declare it as an explicit field or property, obviously this feature should be handled in a groovier way and inject it to any class that is declared in the script.

I'm making the source available from this site (download here) but remember that this is still a work in progress, it shouldn't be used in any production environment!

In order to run the applet you'll need to sign it (or accept my certificate). The first time I did this experiment, the signing process was smooth but with this version I ran into some trouble, knowing that others may want to try it too, I present the steps I followed to get it running, perhaps you'll notice that a step is superfluous or unnecessary, please let me know.
Create a keystore which will hold the certificate.
I created an external keystore so I wouldn't mess up my personal security settings while finding out the correct way to do it. All you have to do is issue the following command:
keytool -genkey -keystore groovy -storepass groovy\
        -keypass groovy -alias groovy
Trust your own certificate.
Unless you want to spend some bucks on this experiment I recommend you selfcert your certificate. To selfcert your newly created certificate, issue the following command:
keytool -selfcert -keystore groovy -storepass groovy\
         -keypass groovy -alias groovy
Export your certificate.Export your certificate to an external file with the following command:
keytool -export -keystore groovy -storepass groovy\
        -keypass groovy -alias groovy -file groovy.cer
Sign the jar. This will attach the certificate to the jar and add entries to the jar's manifest.
jarsigner -keystore groovy -storepass groovy\
        -keypass groovy grapplet-0.1.jar groovy
Verify your jar (just in case). You may verify that your jar has indeed been signed and includes the certificate, for more information on jarsigner's output refer to the command's help (jarsigner -help):
jarsigner -verify -verbose -certs -keystore groovy grapplet-0.1.jar
Configure your local security settings. For this step you must touch $JRE_HOME/lib/security/java.policy and $JRE_HOME/lib/security/java.security, in windows $JRE_HOME usally points to "c:/Program Files/Java/jdk1.x.x/".
Add the following lines at the end of java.policy:
grant {
   java.lang.RuntimePermission "usePolicy";
};
Create a file named '.java.policy' at $USER_HOME with the following contents:
keystore "file:${user.home}/groovy";

grant signedBy "groovy" {
   permission java.security.AllPermission;
};
grant codeBase "http://localhost" {
   permission java.security.AllPermission;
};
Copy the keystore 'groovy' and 'groovy.cer' (just in case) to $USER_HOME.
Copy the binary dist to your webserver. I'm using Apache 2.2 in my laptop, so I copied grapplet.html, groovy.js, grapplet-0.1.jar, groovy-all-1.0.jar, groovy and groovy.cer to $APACHE_HOME/htdocs/grapplet
You've surely noticed that although the applet's full URl would be 'http://localhost/grapplet/' the policy file refers to 'http://localhost', I don't now why (yet) but the applet said several times that its codebase was the later URL instead of the former, perhaps I should have specified a codebase directly.

Uff, that was a little long but those are the steps I followed to get my Groovy FireFox going on, yep, I haven't tried it with IE or Safari yet, on Dion's page someone said that the dynamically applet tag should be created in a literal way in order to get it working on Safari.

Scott, if you're reading this, please notice that I know I should have started this work by buying a mac :)

Keep on Groovying!

applet grapplet howto roovy
Jochen has recently posted an article on the Visitor Pattern, but design pattern aside, the article shows how easy is to migrate from a 100% Java code to Groovy code, demonstrating again why Groovy is a great glue language for the JVM.

groovy howto
Romain Guy has posted an update on Groovy and JPA. He had to use the latest snapshot (1.1-SNAPSHOT) to access annotation support. Now that we now a way how this can be accomplished we'll see how the Grails team assimilate the info (JPA basic support is scheduled for 0.7 [Grails Roadmap]).

annotations groovy howto
Previously I demonstrated how to work with in-memory databases with DbUnit and enabling one-time setup & teardown on a JUnit 3 TestCase. Now I'll show how to apply the TestDecorator to a DBTestCase to accomplish the same feat but allowing for code reuse.

The TestDecorator works with a TestSuite, which in turn handles an instance of your TestCase for every test that is run; the TestSuite does not provide and easy way to invoke arbitrary methods on the instances, so the TestDecorator appears to work in a static way from the TestCase point of view; so how do we pass the database configuration to the decorator?
We could try with a ThreadLocal but that will entangle and complicate our setup, besides tying our tests to a only one scenario (no ThreadLocal from the decorator, no working test), another solution must be found. Tipically when testing with an in-memory database you'll probably use a subclass of DBTestCase or JdbcBaseDBTestCase, but because DBTestCase uses an internal PropertiesBasedDatabaseTester that pulls its configuration from System.properties, there is no need for an extra artifact to do the configuration, the tester (any PropertyBasedDatabaseTester) will use the same configuration (this may pose a problem when in a multithreaded, multitest environment, but that may not be your case).

The code to read and process our DDL is very simple and should be in its own utility class. Putting all pieces together yields the following:
A TestDecorator that uses a PropertiesBasedDatabaseTester to obtain a java.sql.Connection. An utility class that hanldes the DDL loading and execution, used by the decorator. A subclass of DBTestCase that holds the database configuration.

Without further ado here is the sample code from the TestDecorator:

And the code for the testcase:

The code for the DDLUtils helper class is the same as in the previous posts so I'll not show it again. You'll notice that it is the TestCase that defines the database properties to establish a connection, but because the properties are defined in System.properties it is possible to define those properties at runtime. With little extra code it is also possible to refactor the suite() method, querying System.properties to find out if we return a decorated suite or just a simple suite, in this way the code may work for in-memory database test that need to create its own schema, or a normal test that access a database that has an already defined schema.

Keep on testing!

dbunit howto testing


You are viewing a mobilized version of this site...
View original page here

Mobilized by Mowser Mowser