Sunday, 6 July 2008

Groovy for XML transformation

I have been playing with groovy recently, specifically with the MarkupBuilder, the groovy native support for markup languages. It basically means writing XML using native groovy syntax. Pretty neat.

In my job I have more often than not, have to write software to integrate two or more systems. This, often, means writing code that reads an XML stream onto a Java object for manipulation and eventually writes the result into another XML stream.

This typically involves creating binding objects for the input XML and the output XML and then a sequence of calls to getters on the input object and setters on output object to implement the mapping.

This task is very error prone and tedious. A good solution is using the MarkupBuilder (and, yes, I know about XSLT, but this is not the point here!)

So, suppose that you have the following POJO

public class Contact {
private String id;
private String name;
private String surname;
// ...
}
and you want to serialize the instance

Contact c = new Contact();
c.setId("123");
c.setName("John");
c.setSurname("Bloggs");
into the following XML

<contact>
<key>123</key>
<firstname>John</firstname>
<secondname>Bloggs</secondname>
</contact>


Note the difference between the POJO attribute names and the XML tag names

Using groovy and its MarkupBuilder, the first thing to do is to create a groovy converter, a class with a method that reads the data from the bean and produces the XML. Create a file src/groovy/ContactConverter.groovy with the following code:
class ContactConverter{
def convert(bean){
def writer = new StringWriter();
def xml = new MarkupBuilder();
xml.contact {
firstname(bean.name)
secondname(bean.surname)
}
writer.toString()
}
}

If you execute the code
println new COntactConverter().convert(c)

in a groovy shell, you get the XML shown above.

The next step is then to make this code executable from your Java service.
You can use this class (an adaptation of the code available in the groovy documentation):
public class GroovyConverterInvoker {
public String invoke(String fileName, Object bean){
GroovyObject groovyObject = createObjectFromStreamName(strName);
String result = (String)groovyObject.invokeMethod("convert", new Object[]{bean});
return result;
}

public GroovyObject createObjectFromStreamName(String fileName) {
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass;
File f = new File(fileName);
try {
groovyClass = loader.parseClass(f);
return (GroovyObject)groovyClass.newInstance();
} catch (CompilationFailedException e) {
throw new IllegalStateException("Unable to compile " + fileName, e);
} catch (IOException e) {
throw new IllegalStateException("Unable to open file " + fileName, e);
} catch (InstantiationException e) {
throw new IllegalStateException("Unable instantiate object for class in " + fileName, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unable access object of class in " + fileName, e);
}
}
}

You can then invoke the conversion:
public String invokeContactConverter(Object bean){
String fName = "src/groovy/ContactConverter.groovy";
return new GroovyConverterInvoker().invoke(fName, bean);
}

You can now use JAXB/XStream or XmlBeans to parse the result of invokeContactConverter and initialize a new POJO for further use, or send the XML on the wire.

The solution can be generalised and optimised to a point where you only need to write groovy converters and load/modify them dynamically when necessary.

Saturday, 5 July 2008

Sicilian as a language

I am randomly browsing the web today. I just finished to read a Wikipedia entry on the Sicilian language. I always thought that Sicilian was an Italian dialect, although I was aware on several influences from French, Spanish, Latin and Greek, but I realised that scholars do consider it as a language in its own merit. That makes Sicilians bilingual at least.

Tuesday, 1 July 2008

UMLGaph for auto generating class diagrams from your source code

As part of improving the documentation of our software - a REST API - for the benefit of our customer (mainly an architect) and (future) users, we have investigated UMLGraph, a free application that is able to parse source code and (with the help of graphviz) generate class diagrams that can be embedded in the javadoc documentation.

The tool is very good and we're trying now to integrate it in our continuous integration build via ant.

Monday, 9 June 2008

BT Web21C SDK wins eWEEK Excellence Award

The BT Web21C SDK has been awarded with the eWEEK Excellence Award under the category "Application Development" as reported here. I am part of the team who built it and I feel proud that 2 years of hard work have been recognized.

Sunday, 8 June 2008

Smartrics tag cloud

Go figure why the guys at blogspot have not provided a tag cloud widget. So, kudos to phydeaux3 for supplying the code for my tag cloud. Except for changing the font colors and types to make it look better it was a matter of copy and paste in my blog template. Nice and easy...

Saturday, 7 June 2008

The (hyper)reality of social networking

I was reading about hyperreality when I started thinking of how it relates to the social networking phenomenon and communities built around it. Is there a connection between the two? Maybe. In fact someone else has already discussed this topic in this rather interesting post.

My favourite definition of hyperreality is Umberto Eco's one: "the authentic fake". As you would expect the web is full of information about hyperreality, for example this is fairly complete article with examples.

I'll try to write down my thoughts on how social networking community members do live in a hyperreal world. I should warn you though: I may sound cynical and destructive. Far from me: I think there's a place for social networking web sites and services (after all I am blogger too) and there's nothing wrong with being a consumer of these services. As far as I am concerned now I am just trying to understand the mechanics, why they work and why they exist the way they are now, and how they will transform in the future to come. So bear with me on this aspect.

At the core of the meaning of hyperreality is the ambiguity between "real" and "fake" reality that arises when facts and events or objects are filtered by a multitude of media.

Members of communities built around any of the latest and cutest Web2.0 website interact by the means and rules offered by the portal they use (Facebook, MySpace and the like). This medium filters the behaviour adopted by people. Actually, members of any community, in a way, always interact within an accepted framework: think of the rules, implicit (values, culture) or explicit (laws), that manage our relationship in a social environment and how they drive our behaviour.
The main difference, though, is that people meeting face to face have other means (environment, body language, time...) that contribute to maximise the possibility that facts and events are perceived and understood correctly and close to the reality.

Now back to the social networking. As said the web shapes the behaviour; there's also in the mix the fact that content and messages are exchanged using a different time pattern compared to normal face to face relationships. A message, a profile, a blog post, a twit is sent to the server and then delivered to the intender recipient(s). The recipient(s) reads it, digests it, formulates a response and eventually sends it back. This, to me, contributes to the creation of a world and of a reality that is transformed: what the recipient perceives is the autentically "fake" reality that the sender wants to transmit having lost its immediacy and being tailored to the media chosen to operate upon. Besides the fact that sender and recipient know that the content being generated is public.
I like to think that communities in Facebook (I am not picking on Facebook, it's just an example) are equivalent to the community of house mates in the BigBrother house (or, for argument's sake, to any other reality). The media, the place and being observed changes the behaviour allowing the community (participants and viewers) to create a fake real world.

So, it seems that social networking is son of its time: it has been made possible by new technologies - higher network speed, new web site capabilities, etc - and it's expression of our current time where appearance rules.

I have a memory from my infancy: if you're Italian or you watch Italian TV you know about the Mulino Bianco commercial (this is one of the many) which epitomises the (hyper)real world. We (the community of consumers) are let to believe that that is a beautiful real place with a real family where - obviously - plumcakes and brioches are soft and tasty.

Is there any difference between the Mulino Bianco ad and any of the profiles in Facebook? Let alone the style and the manufacture - Facebook users may not be professional advertisers - the communality is that both are hyperworld where the authors want the recipients to walk in and live the life they want them to live.

In this context let me fool around. If hyperreality is made of hyperreal facts and hyperreal events that exist in a hyperreal world, then Twitter allows users to exchange hyperreal facts; MySpace and Facebook as hyperreal multi-worlds; SecondLife as real hyperreal world.

The astute reader may now say that hyperreality is just a play on words, people make real money with this sites, businesses and enterprises back them up. It depends, it's a matter of prospective. Vegas and its casinos is extreme hyperreality made true. Punters entering a casino get in a manufactured hyperreal place where everything is obviously fake to let you believe that our money is fake too. Incidentally, those who think that your money isn't fake are casino owners who live in the real reality of gambling business.

So, who's making real money in this hyperreal world? I guess those who are able to spoil the user data by aggregating it and extract useful market information, for example. I suspect that biases will eliminate each other when aggregated, providing the clever data manager with information to use at his like (hopefully within the boundaries of the data protection acts).

A real example is available here: it describes how Amazon makes money using information extracted by user generated data.

Yes, clearly this is a win-win situation. Community members get value by being able to cultivate their social aspirations, voyeurism, need to be heard, trend and fashion, benefiting of other members' experience. Providers - on the other side - are able to target established communities by processing generating data, aggregating it with the purpose of extracting financially useful information (read the Facebook case study).

I am sure there's more to say. I stop now but I am interested to hear from you, dear reader, your view on this.

Covering the obvious

I was listening to Led Zeppelin whilst doing the restyling job at home and acknowledging how popular some of their songs are. Obviously Stairway to Heaven is amongst those... so I started wondering how many covers have been published in almost 40 years. I started digging the YouTube website, but, funny enough, at the same time I found that Ernesto Assante - a famous italian music critic - did it all for me by listing on his blog the most unusual covers of that masterpiece. The one I like amongst those he's listing is the version of Robyne Dunne, very 80s' and colorful. Here it is:


Saturday, 31 May 2008

Agile restyling

Whilst my wife and son are away I took few days off at work and started to mess with the floor and the walls in the corridor of my house.
I am a brave man... with the help of a DIY book, some imagination and memories of a decorator who worked in my parents' house 20 odd years ago, I started taking off the horrible green carpet I found when I moved in. Surprise! Under the carpet there was an even more horrible black and red vinyl tiles floor stuck on the floor boards. Three days of hammering off the tiles inch by inch with a chisel didn't do the job: I had to hire a floor sander and use 7 P24 - amongst the coarsest - sand paper disks to get rid of the mixture of plastic and glue stuck in the 6 square mt area I am working on.
I took off the skirting boards and a portion of the wall plaster and redid all the necessary fixes to modernise the look and feel. I started four days ago and am now at the stage of painting all the surfaces i can pass a brush on.
Plenty to do and little time! No new news then.

I am learning though... a lot of things! I am practicing day by day (and mistake by mistake) new manual skills: lying undercoat and plaster, sanding, varnishing, painting and I haven't even started with the wood. But I am (re)discovering how to relax by doing manual activities: I am on my own, I am not under pressure to finish (yet!) and I can take my time whilst listening to my music. I am also fooling around by trying to apply agile techniques to my day to day activities. Ok, there's a conflict of interest (I am the customer and the development team) but I avoided a big upfront design and I am organising my activities to best respond to changing circumstances - this in fact has helped: I found on Friday that I have a meeting in London on Monday that I don't want to miss and this has forced a re-org of my activities.
In practice, I have a list of things I need to do and it's comprehensive to the best of my knowledge to date. I keep adding (or removing) to-do items as and when they come and re-prioritise the list every day: I pick the next to-do item from the list and do it, depending on what makes sense doing (I am the customer after all), what I fancy doing (as I am the developer too). I tend also to organise the list to minimise waste (of time mainly) taking into account task dependencies (take off the carpet before lying the new floor) and minimise the risks (paint the wall before lying the floor, because the paint may drip on it!)
The only visible side effect is that I need to go frequently to the nearby DIY shop to buy stuff. Not a big deal though, it's only 2 miles away, and it's also an excuse to see the cloudy sky.

PS: amazingly, when I took one of the skirting board off the wall, I found a little book published by Lloyds Bank with the list of cash points in the whole UK - all in 6 pages, mind you - and a 2p coin. Respectively dated 1973 and 1974.

Uncle Pino

Sadly today my uncle Pino passed away. He was a fine musician who played guitar and bass and toured the world with many famous Italian artists including Domenico Modugno and Nini Rosso. He also published records: the one I can very well remember is titled Marmalade, back in the late 70's (copies are on sale on eBay.it at the time of writing).
I still remember the story that granma Teresa used to tell me, when I was a little boy, of him leaving Sicily when he turned 18 to fulfill his dream of being a musician.
And I'll be always grateful to him for having bought in Rome in March 1985, on behalf of my parents, a - very much desired - Commodore 64: my parents' present for my birthday. (That machine started my passion for computers and programming).

The Boss is in town!

Great show! Probably the best I have seen in years. Bruce Springsteen and the E Street Band have played at the - almost full - Emirate Stadium in London a 3 hours gig with a mixture of old and new stuff. You won't believe how that 62 years old man was able to excite the crowd running up and down the stage shouting and playing Badlands, Born To Run, Thunder road (my favourite), Rosalita, Lonesome Day and so on.
He also had time to pass on to us a couple of (silly) jokes about English stereotypes: the weather - today was a sunny day after a miserable week of clouds and rain - and T time. Anyway... I took two pictures with my mobile, one before the start of the concert when the stadium was filling up, the other when it was dark already so the quality is pitiful, so you'll have to guess.