Dienstag, 18. November 2008

Fun with annotations in Groovy/Griffon

The 1.6 version of Groovy seems to have full-fledged annotation support.

I took the occasion to finally learn to create some annotations on my own, and wrote an annotation which can be used in a Griffon model to give the controller some hints about how to best display its data.

I might have taken this a little bit too far, but it is also possible to declare strings in annotations which can later be evaluated.

Take this annotation as an example:


package annotations

import java.lang.annotation.*

@Retention(RetentionPolicy.RUNTIME)
public @interface TableModelInformation {
boolean displayed() default true
String displayName() default ""
String displayValue() default ""
}


This can be used in the model like this:


...
@TableModelInformation(displayValue='"Total Subprocesses: ${object.subprocesses.size()}"')
List subprocesses = []
...

(Note the weird string syntax: only double quotes (i.e. GString) are rightfully not interpreted as Strings. Furthermore it expects to receive an instance of the object in a variable named (tadaaa) "object".

This can be evaluated later in the controller:

return new GroovyShell(new Binding([object:object])).evaluate(object.class.getDeclaredField(field).getAnnotation(annotations.TableModelInformation).displayValue())

("object" and "field" are available in the context of the controller)

I am not sure how to optimize this code, especially the verbosity of annotation retrieval. It nevertheless is kind of funny to see groovy behavior in an (at least from me) unexpected way...

Freitag, 14. November 2008

Using ocmgroovy as Persistance Layer for Griffon

Griffon is a very interessting approach to create an agile and fun framework for building Swing applications. Currently a very shy version numeration is used (0.0.1 is current), but the whole package is built using large know-how.

One thing missing is the persistance layer. It is planned to use GORM, the hibernate-based layer of Grails.

This situation is an opportunity for ocmgroovy, my "framework"(*) for persisting Groovy objects into a JCR. While beeing a little ugly hack atm, the basic things like save() and get() seem to work, at least for my basic test cases.

Using ocmgroovy in grails is one annoying and 2 easy steps
  1. download ocmgroovy (either create the project via pom.xml or download all dependencies manually, which basically means to download all jackrabbit dependencies and xstream with its dependencies) and install it into {griffon_project}/lib directory
  2. declare the class to be persisted in {griffon_project/lifecycle}/Startup.groovy
  3. use it in your Griffon mvc


Step 2 looks like this

TransientRepository repository = new TransientRepository()
def session = repository.login(
new SimpleCredentials("threatmanagment", "password".toCharArray()))
JcrPersister strategy = new JcrPersister()
strategy.session = session
strategy.instanceRoot ="threatmanagment"

strategy.instrumentate(ThreatModel, "name")
strategy.instrumentate(Dataflow,"id")

This makes model classes ThreatModel and Dataflow persistable, i.e. currently mostly adds save() and get() methods to instance and class, respectively

And Step 3: about as easy

ThreatModel model = new ThreatModel("name": "TestModel")
model.save()
...
ThreatModel model2 = ThreatModel.get("TestModel")

Please note that this is all very shaky at the moment (and therefore will create a black hole if you try it at home ;)), but might prove usable in the future.

I probably will release a PoC-project in the near future.

===
(*): ocmgroovy is very alpha and only used by myself. Therefore I do not consider this to be a framework

Mittwoch, 17. September 2008

Ditching Flex ... for now

Well, killing another fairie: I am dissing Flex for my pet project. There are several reasons:
  1. not too good Flex-Support in IDEA
  2. roundtrips are slow (create compile load)
  3. open source built on closed source doesn't work
  4. mxml: simply don't like those
  5. actionscript will not be the next ecmascript
  6. verbosity: too much to write while using MVC frameworks. Convention over Configuration is not there yet (?)
  7. HTTP support is kind of crippled
There are very good reasons to love Flex:
  1. the looks: I am no expert, but I got the feeling Flex just looks great out of the box
  2. components: component based UIs are great.
  3. event models
  4. ubiquity
I am sure that some of the points are due to the fact that I am a novice. I might come back to it, but now it is time to move on...

Donnerstag, 11. September 2008

An "in between" review of Sling

Now that I have been using Apache Sling for a pet project for some weeks now, I thought I could share some insights on it. The spaghetti western way, of course :). And all utterly subjective.

The Good

  • java -jar sling.jar -> http://localhost:8080 and dav://localhost:8080. This is fantastic.
  • Scripting support
  • REST: learn it the Sling way
  • webdav-support
  • A good community
  • best-of-breed technologies: OSGI (with Felix), JCR (with Jackrabbit)
  • JCR muscle flexing included: query, hierarchies, versioning
  • semi-structured data approach
  • it's fun

The Bad

Nothing bad, just great stuff with some edges:

The Ugly

  • Docu. Yeah I know. Is getting better, but should be more (please kill those "out of sync" pages)
  • After a fast start, there still is a learning curve (OSGI, REST, JCR, Maven, ...). Since these are hot topics anyway, this is no big deal, expect when you want something fast and nownownow :)
  • bootstrapping problem: despite the available help, I still did struggle with the question whether controls (scripts) or data should be created first. But this is just me, I guess :)
  • JCR Editor support: Days eclipse plugin is great, but unfortunately doesn't work on my Ubuntu-system
  • No out-of-the-box solution for rich applications (Except dojo, which is a beast on its own...)
All in all, Sling holds its head up high in a tight, competitive market. I am looking forward to do more stuff with it. The rough spots are being addressed, therefore I am positive and quite impressed. Most important thing now would be to flesh out the documentation....

update 13th Sept: The JCR Plugin for eclipse works after a fresh install, using Eclipse Ganymede and JCR Plugin version 3.6.6. Nice thing is, that Eclipse editors seem to work, e.g. when editing a HTML file. Have to check if this works with the groovy editor too ...

Sonntag, 7. September 2008

Flex/Flash wasn't made for REST

Well, it did take longer than others, but I finally got the message: Flash was not built with HTTP in mind. There are other issues flying around, but I think it all boils down to HTTP not being treated as first-class-citizen in the Flex/Flash environment.

I guess that the reason is a historical one: all remote connection protocols where proprietary, only in the last years Adobe opened itself a little bit (by releasing BlazeDS and open sourcing Flex). Now I think Adobe should go 2 steps further:
  1. implement standards (e.g. using HTTP how it was meant to be used)
  2. open source the whole stack
This is highly speculative, but perhaps the "Nay" to EcmaScript4 was due to the apparent closeness of the Flash ecosystem.

The saddest thing is that Flex is great! Real good default (looks nice out of the box), a real component model, just plain fun! Next stop: Dojo, I think ...

Donnerstag, 4. September 2008

Using Groovy Builders in Sling

Sling is a new approach in web development. It is, amongst other, a thin REST layer onto a JCR repository.

Sling also makes use of the language neutral scripting features of the java platform. Out of the box, several scripting languages are supported, like javascript and jruby. Since Groovy does have JSR 223 support, it is rather easy to create a groovy module to be used inside Sling. The only pity is that the Groovy Scripting Engine is not available via maven. See this Jira issue for some hints on creating a Groovy OSGI-module for Sling.

The thing I like most about Groovy is the real cool builder support. Using the MarkupBuilder, it is a snap to generate HTML or XML documents. I personally started to like MarkupBuilder syntax more than the templating approach.

The first time I saw something similar was at a demonstration of the excellent Seaside framework, where everything, including layout, is done in smalltalk. I am not sure wether the Groovy builders have been inspired by smalltalk or even Seaside, but both are sexy (I cannot speak for Seaside, haven't had the chance to play with it).

Anyways, on to some comparisons:

First a piece of jsp:


<%@page import="javax.jcr.query.Query"%>
<%@page import="javax.jcr.NodeIterator"%>
<%@page import="javax.jcr.Node"%>

<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%>
<sling:defineobjects/>
<div class="blueprint detail">
<a href="">.details.html"><%= currentNode.getName() %></a>
<h2>Properties</h2>
<h2>Controls</h2>
<div id="List">
<%
String q = "/jcr:root"+currentNode.getPath()+ "//*[@sling:resourceType='secmanagment/control']";
Query query = currentNode.getSession().getWorkspace().getQueryManager().createQuery(q, "xpath");
NodeIterator result = query.execute().getNodes();
%>Total <%=result.getSize()%>
<ul><%
while(result.hasNext()) {
Node n = result.nextNode();
%><li><%
out.flush();
sling.include(n.getPath() + ".overview.html");
%> </li><%
}
%>
</ul>
</div>
<div class="new">
<form action="">/controls/" method="POST">
<input type="text" name="name" value="Name">
<input type="hidden" name="sling:resourceType" value="secmanagment/control">
<input type="hidden" name="jcr:primaryType" value="nt:unstructured">
<input type="submit" value="create">
</form>
</div>


The same using Groovy with MarkupBuilder:

import groovy.xml.MarkupBuilder
import javax.jcr.query.Query
import javax.jcr.NodeIterator
import javax.jcr.Node


def q = "/jcr:root${currentNode.path}//*[@sling:resourceType='secmanagment/controls']";
def query = currentNode.session.workspace.queryManager.createQuery(q, "xpath");
def result = query.execute().nodes;

def builder = new MarkupBuilder(out)
builder.div(class:"blueprint detail") {
a(class:"blueprint details", href:"${currentNode.path}.details.html", currentNode.name)
h2("Properties")
h2("Controls") {
ul(class:"List") {
result.each { node ->
//this is necessary: need to put the outer tags explicitely
mkp.yieldUnescaped "<li>"
sling.include(node.path)
mkp.yieldUnescaped "</li>"
}
}
h3("Create new")
div(class:"new") {
form(action:"${currentNode.path}/controls/", method:"POST") {
input(type:"text", name:"name", value:"Name")
input(type:"hidden", name:"sling:resourceType", value:"secmanagment/controls")
input(type:"hidden", name:"jcr:primaryType", value:"nt:unstructured")
input(type:"submit", value:"create")
}
}
}
}



While not being too different, those 2 samples (hopefully) show the usage of MarkupBuilders as valid alternative to a templating engine like jsp or gsp.

Dienstag, 19. August 2008

Oh what irony

So, after some years of java-programming I am getting used to dynamic, loosely typed languages, walk like a duck, y'know the drill.

Then enters Flex, enters AS3 and you know what? Explicit type declarations all the way (Not mandatory at all, but, you know, the compiler complains and stuff, so you better behave...)

This is not a problem and all, but something about the whole thing just made me smile :).