Life Codecs Ruminations. Reflections. Refractions. Code.

February 24, 2009

Theme Redesign!

Filed under: general — Tags: , , — Kamal Advani @ 10:33

I got sick of the fixed-width default theme, so I took the WordPress classic theme (which was variable width, what an improvement!), and replaced it with my colors! Whew! Thank God for CSS. I then proceeded to apply the same colors (not yet uploaded) to the main site! Enjoy, funnily enough, the dark colors are a lot easier on the eyes when writing code.

– Kamal

Delegates in Java – Introducing delegates4j

Filed under: software dev — Tags: , , , — Kamal Advani @ 10:29

Background:

For a while now I’ve wanted a delegate-like (C# delegates – think of them as basically type-safe function pointers) feature to use in Java (and don’t mention closures or dynamic languages please, I know it will make my whole post obsolete :P), and I tried several attempts to simulate them, but didn’t quite get it right. I learnt about funky uses of the proxy pattern from my ex-team lead (very neat person, hey Steve!) in various projects. Then Java 5 came along…

No wait, before that, one day as I was messing around with cglib (I call it an AOP enabling tech through proxies – go proxy!), I noticed that they provided a dynamic delegate creator, in the cglib sources, see: net.sf.cglib.reflect.MethodDelegate – quoting from Apache Avalon‘s Delegate class, a delegate is defined as an interface with a single method. Note that Avalon has been marked as a closed project – but I don’t think it had anything to do with the delegate definition, phew.

delegates4j is Born:

Anyway, while that was neat (and backward compatible with pre-Java 5 stuff, hmph), it required a method name as a string, not a very big deal, but not quite what I wanted either, I wanted something a little more declarative, and something perhaps simpler, and a little more typesafe; and not requiring an external class enhancer (yes, maybe I just wanted to reinvent the wheel and not use cglib to do it). Annotations to the rescue! So! Keeping in mind that a delegate is an interface with a single method, let’s look at what I have (might want to paste this into an editor if it’s too annoying to read):

1
2
3
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package net.namingcrisis.delegates4j.core;

import static net.namingcrisis.delegates4j.core.DelegateFactory.cdg;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class DelegateFactoryBasicTest {
    // Basic case, also a sampling of how the API is used.

    @Before
    public void setUp() throws Exception {
    }

    // Delegate type interface, only a single method.
    // Think of it as a function pointer in disguise
    // (C# of course supports delegates natively)
    private static interface IStringProcessor {
        String process(String s);
    }

    // A strategy class with different string processing routines
    // Does NOT extend StringProcessor, nor do the method names have to match,
    // this is the point.
    private static class GString { /*
                                     * It's a joke here, but GTK actually has a
                                     * gstring type
                                     */

        private static final String UPPER_CASE = "upper case";
        private static final String PRAYER = "prayers";
        private static final String EMPTY = "nada";

        @Implements(clazz = IStringProcessor.class, mode = UPPER_CASE)
        public String toUpperCase(String s) {
            return s.toUpperCase();
        }

        @Implements(clazz = IStringProcessor.class, mode = PRAYER)
        public String toPrayer(String s) {
            return "Hallelujah! " + s;
        }

        @Implements(clazz = IStringProcessor.class, mode = EMPTY)
        public String toEmptyString(String s) {
            return ""; // :P
        }
    }

    // A test client of StringProcessor, assume it to be a simple visitor
    // Returns a new array of processed strings
    public String[] printStrings(final String[] strings, IStringProcessor proc) {
        final String[] res = new String[strings.length];
        for (int i = 0; i < strings.length; i++)
            res[i] = proc.process(strings[i]);
        return res;
    }

    @Test
    public void testCreateDelegate() {
        final String[] strings = new String[] { "you", "and", "i" };
        final GString gs = new GString();

        // Dynamically create delegate instance, cdg is a static import
        // meaning "create delegate", deliberately keeping the name
        // short and unintrusive.
        // cdg(interfacetype, mode, implementationInstance)
        final IStringProcessor upperCaseProcessor = cdg(IStringProcessor.class,
                GString.UPPER_CASE, gs);
        String[] res = printStrings(strings, upperCaseProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = 0; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toUpperCase(strings[i]));

        final IStringProcessor prayerProcessor = cdg(IStringProcessor.class,
                GString.PRAYER, gs);
        res = printStrings(strings, prayerProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = 0; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toPrayer(strings[i]));

        final IStringProcessor emptyProcessor = cdg(IStringProcessor.class,
                GString.EMPTY, gs);
        res = printStrings(strings, emptyProcessor);
        Assert.assertTrue(res.length == strings.length);
        for (int i = 0; i < strings.length; i++)
            Assert.assertEquals(res[i], gs.toEmptyString(strings[i]));
    }
}

A couple of things (noted in comments):

  • The implementation class did NOT implement the delegate’s interface (or the delegate rather, “delegate interface” is redundant going by the above definition!), it merely provided compatible methods, whose names did not have to match.
  • The use of mode, is of course a string, and perhaps not very typesafe either, but it is exclusively there to support the scenario where multiple similar methods implement different behaviour, allowing you to have several strategies in a class, very handy for quick things. Probably not a good idea for larger reusable strategies. If you didn’t have it, just set it as an empty string (at the moment it’ll NPE-out otherwise :P)
  • This test doesn’t illustrate it, but to keep things single and fast (method resolution is done at runtime after all), it matches declared methods only, nothing inherited is usable – an interface that extends another but has no method will error out as a delegate type, a class with a superclass annotated method overridden but not annotated, also errors out. (The class bit is redundant, annotations are not inherited anyway, so).
  • Finally – also not illustrated by this test, delegates4j supports Java 5 covariance, where the return type of the implementor can be narrower than that of the delegate type.

Hopefully, it is simple enough to use – my initial attempts had multiple steps, but they tried to do more too. An improvement to this is possibly somehow caching resolved methods for reuse keyed by the annotation detail for example, in practice I don’t know if this is worth it yet.

The project is available as Maven downloadable jar (licensed under Apache License v2.0) in my repository, including sources, and tests to better illustrate usage/limitations (and of course, test that it works!). Set the dependency as follows: groupId = net.namingcrisis, artifactId = delegates4j, version = 0.5.

For the curious, under the hood, the only real magic is the use of the JDK Dynamic Proxy to implement the delegate and pass on the request to the supplied instance, and reflection for method resolution – the source is there anyway :-). If you do use it, hate it, try it out, etc. drop me a line anyway :-).

– Kamal

Bloggy: Wicket Demo Blog App!

Filed under: software dev — Tags: , , , — Kamal Advani @ 02:54

I pointed out in a previous post that I was learning Wicket. I decided to write something a bit more realistic in it, and since blog applications are all the rage these days (oh wait, are we past Web 2.0 yet? :P) – I figure it was as good an app to write as any, fairly simply domain model if you don’t go crazy, you can find it – Bloggy – in the code section. Due to the huge number of dependencies (uses Spring, Hibernate, and the Hibernate JPA implementation, and of course the Wicket jars as well), I have simply provided the sources – it is a Maven-based project however, so it should be fairly easy to get up and running. I have tested it on Jetty, and you will require Java 6 for 2 reasons:

  1. I marked the source and target to be 1.6 in the POM, hah!
  2. I have used @Override annotations on interface implementations, which is a Java 6 only thing (as I found out from a friend just a few days ago)

As far as Wicket itself goes – I am impressed, thoroughly enjoyed using it. Some points worth noting:

  • The thing I tripped on most often was ensuring that my object and markup hierarchies were in synch – a little annoying (though I’d rather have it disciplined this way than overly forgiving models) – but the error messages turned on in development mode/configuration were awesome[1]
  • As pointed out in Wicket in Action, you do tend to think a fair bit more about reusing components, so you initially start slow because Wicket encourages you to write your own components (panels being the most reusable components)
  • I found it was necessary to have the sources (recommended just for the heck of it) open in order to see how certain things could be extended, not necessarily a good thing, but the sources are well-written and useful to write your own stuff, or just understand how things are handled underneath, especially dealing with models. Speaking of sources, it is very OO that I learnt a few new ways to use patterns myself. (Sigh, been dealing with crappy UIs far too long)
  • I think with Wicket 1.4+ where Java 5 is the minimum requirement, using models will be much clearer, I admit to having been spoilt by Java 5+ generics thoroughly, and I created a couple of base parameterised models
  • Serialization – wasn’t as big a deal as I thought it would be – in fact in a 3-tier app where we generally use DTOs, this won’t even be an issue, granted however, it’s still something to look out for, you don’t wish to be serialising huge stuff into the session, and it is easier to do that than in something like struts because of the very stateful nature of Wicket
  • Wicket’s spring integration layer is quite nice, it allows you to inject stuff, but since it does not have explicit bean definitions of your components, I don’t think (and I may be wrong) it allows you to do funkier things like AOP, in UI code, I generally don’t find this to be a problem, the injection is far more crucial for me. I think the point as justified by the authors is that Wicket is by default an unmanaged framework
  • Ooh the Ajaxy stuff – I am no front-end Javascript guy – this made it a breeze to use, you obviously must understand basic Ajax concepts, but you don’t actually need to write Javascript, fascinating, I used editable labels, and link-submittable forms mostly (which were POST-ed, no nasty GETs for side-effect producing actions). I did not venture far enough as to write my own Javascript components however :-).
  • The default URL generation scheme’s not pretty – but Wicket provides additional schemes (packaged as URL codec classes) which are much prettier, and you can write your own – I found the provided ones to be quite sufficient though. I love the way they’ve designed the hook into the URL generation.
  • Well, I hope someone finds this useful, if google ever gets you here!

    [1] If you’ve worked with the Struts tag lib (Struts 1 anyway), you will see what I mean – Wicket’s UI handling is certainly no hack of a solution tacked on with inconsistent conventions and uber-crappy error messages (anyone like “bean ” not found in scope” or something to that effect – gee thanks, or that there’s no select-EL version or one of those damned controls). I dread going back to the work force having to use that piece of unholiness again. Note that my harsh criticism is directed at solely the taglib, the rest of Struts is something to be respected for having achieved what it did way back!

February 23, 2009

Blog Name Change

Filed under: general,personal,philosophy — Tags: , , , — Kamal Advani @ 23:09

So I googled “lifeflow”, my God I am embarrassed – that turned up a heap of hits – could I be part of the hive mind that is the world. No, that can’t be, I attribute it to a quirk of fate :P. So here’s the new name, the tagline has “Code” added to it. In a sense the original intent of this web log has not changed, and I think figuring life out takes some encoding and decoding, and I do enjoy writing code, and and ‘codex’ is a book or manuscript – very log-y – so ‘Life Codecs’ sounds rather apropos. And googling this, as expected a lot of results turned up on audio/video codecs, but that’s okay – at least I am not some quick fix to gain enlightenment. I mean, I wish I was – like for real – but I’m not :P.

Let’s hope I don’t have to change it again.

Code and Maven Repository

Filed under: software dev — Tags: , , , — Kamal Advani @ 22:16

I have added a code section, quite thrilled about that – even though there isn’t much in there :-). I’ve also set-up a Maven repository, which is very handy for people wanting to try out stuff easily. Ah the joys of being a bum (speaking of which, got a job? :P).

February 22, 2009

Website!!

Filed under: general,personal,software dev — Tags: , , — Kamal Advani @ 16:26

I have some semblance of a website! And I finally put some code on, yeah baby! This being a bum business is kinda fun, hmm now if only I could bring in money while staying at home without methods mentioned in scammy ads. Anyway, check it out :D.

– Kamal

February 17, 2009

WordPress’ Tag Cloud Limit

Filed under: how to,software dev — Tags: , , , — Kamal Advani @ 04:34

So I got sick of wordpress seemingly not updating my tag cloud – after googling – turns out the tag cloud is limited to 45 items, and the admin interface (using WordPress 2.7.1 at time of writing) has no way of updating it. If you wish to up this limit, you:

  • Navigate to /path/to/wordpress/install/wp_includes
  • Backup the file widgets.php as widgets.php.orig in case you mess up (and no I did not).
  • Edit widgets.php, around line 1867 you’ll find a function wp_widget_tag_cloud($args) which looks like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Display tag cloud widget.
 *
 * @since 2.3.0
 *
 * @param array $args Widget arguments.
 */

function wp_widget_tag_cloud($args) {
        extract($args);
        // [... snip ...]
        echo $before_widget;
        echo $before_title . $title . $after_title;
        wp_tag_cloud(); // REPLACE ME!! ME!!! (and no this comment did not exist in the source)
        echo $after_widget;
}
  • Replace the commented call (can you guess which one?) with:
    wp_tag_cloud(array(‘number’ => 78))
    replacing 78 with the no. of tags you want to display.

If you’re so inclined and have shell access to your install, you can instead apply this patch which sets the number to 101, my setting, and if your file is different (say due to a different version of wordpress), it probably will fail :P.

Enjoy. I’m going to tag this post, among others, with ‘tag’, bet you didn’t see that coming ;).

– Kamal

February 6, 2009

Wickedt!

Filed under: software dev — Tags: , , , , , , , — Kamal Advani @ 16:48

The title means “Wicket is Wicked!” in German (I know, lame, still kinda funny though :P). More seriously I just finished Parts 1 and 2 of Wicket in Action. I found the book to be very well-written with one exception: the analogies to the lasagna preparation made me very hungry – I am currently fasting, ahem. Apart from that, it certainly explained the framework well enough to enable to me to write this post, so kudos to the authors and Manning. Here’s my ‘review’ (if I may be so bold) of the book/framework (note that this is based on fairly limited usage writing toy apps, so caveat emptor):

I fully read and tried out examples in parts 1 and 2. I love the framework, it truly brings an OO component-driven model to web programming. As the authors aptly pointed out, Wicket solves the impedance mismatch problem between the stateless nature of HTTP and stateful object model, and Wicket solves it well! The impedance mismatch issue is analogous to the one we have between OOP and RDBMSes which of course ORM solutions like Hibernate solve. Some pros and cons:

Pros:

  • Familiar OO UI programming model, especially for people who’ve written thick client apps in toolkits like Java Swing.
  • Encourages typesafe – almost transparent – state maintenance using objects rather than direct manipulation of the Servlet HttpSession.
  • Excellent abstractions make learning logical and intuitive, for example a Page represents a top-level container, similar to a Frame object, to which you can add child components.
  • Minimal configuration gets you started. Pretty much just web.xml to configure your wicket app, the other plumbing can be done using Maven 2, definitely check out the bonus chapter 15 online very early on to configure your IDE so you can play with the examples.
  • Makes wizard creation – a fairly common and very tedious task in web programming, God the pain… – a breeze, not because it has specialised classes or declarative ways of doing it, but because state maintenance is easy, passing one page instance to the next page instance is straightforward (Page1.java: page1 = this; … setResponsePage(new Page2(page1, …)).
  • Previewability – allows HTML pages to be viewed with dummy data that will be removed at runtime. The authors admit however, if a page has a lot of components, it makes it more tedious to preview.
  • A lot of thought has gone into packaging new components, complete with their own resources such as CSS files, images, and Javascript. This extensibility does allow a lot of reuse of components easily, very much in line with OO principles.
  • I did not mess with this a lot – but Wicket seems to have decent Ajax support, including transparent fallback to non-Ajax behaviour if it is disabled on the browser. The authors point out that Wicket takes the view that Ajax is optional, and assuming you use the correct Ajax+Fallback component, no code changes are needed to accomodate both Ajax and non-Ajax behaviour. Chapter 10 of the book which I hardly read (part 3) goes in more depth about using Ajax.
  • Due to the stateful nature – makes checkbox and multi-selection handling a breeze, woohoo!!
  • A lot of built-in validators for common validations – having said that, these days I tend to prefer having validations (== business rules) done via my models, so this doesn’t buy me a lot – in fact it would make me put business rules in the web tier. Ideally we could annotate models and use some form of code generation (I hear screeches of pain…) for both the models and the client side for better responsiveness, of course some validations just can’t be done on the client side, so still thinking on this.

Cons/Gotchas:

  • There’s a lot of reliance on Java object serialization – to achieve transparent state maintenance, Wicket serializes the manipulated markup and code at the end of each request. This means any models you have used in the session must also be serializable. The good news is the authors spend time talking about this, and ways to get around it, using detachable models (I’d rather call them model wrappers for they wrap your actual model object) for example. This is also something to take note of when considering performance issues.
  • For people used to request-response based frameworks like Struts, the programming model will take a little bit of getting around – although I got around it pretty quickly, it seriously is way easier and more logical, especially to back-end programmers. As with any framework, there are new concepts to pick up here and there.
  • To bind models to web forms, strings are used in the form of property expressions (e.g. foo.getAddress().getStreet() -> “foo.address.street”), this obviously will not be picked up when your models get refactored. Hopefully smarter or Wicket-aware IDE plugins will help in this area. This plague is common to many frameworks… (e.g. in Hibernate: HQL and even when using the Criteria API).
  • In spite of adherence to the DRY principle, it does not generate HTML for you, and markup (which are tagged with “wicket:id” attributes referenced in the code) and code must remain in synch or Wicket will throw an error when accessing that page. This is good and bad, the nice bit is it does allow web designers to maintain the look and feel for you. Wicket IDs, Code Hierarchy, and Markup Hierarchy synchronisation is another place where Wicket-aware IDE plugins would be useful.

I only skimmed through Part 4, but it definitely has a lot of useful advice on integrating Wicket with with other toolkits and middleware such as Spring and Hibernate, and on internationalization (i18n) and localization (l10n) (still trying to figure what the latter’s scope is exactly…), something that’s missing in many books – while it’s not strictly necessary thoeretically, practically no framework works in isolation these days except perhaps if you get full-stack frameworks like Grails or JBoss Seam that Ruby on Rails popularised; dunno, I still kinda like cherry picking my parts, but I haven’t explored these so I may change my mind.

Hmm, I wonder how it compares to GWT – something else to try out when I have time, for now, time to check out EJB 3.

– Kamal

February 2, 2009

Bad Hairday!

Filed under: general,gripe,personal — Tags: , , , , , — Kamal Advani @ 21:02

Ya know, like many geek-types, I am not one who is too concerned with how I look, at times I look a little messy, but clean, not dirty or icky – to me that is sufficient. Fortunately (for it is overall fortunate), hair grows and there are times when I need to cut it. I kept long hair for a couple of years – looked very hacker-ish, but alas, it was a maintenance nightmare. So anyway – I do not have a regular salon that I go to, and am not one to spend any more than 30 dollars per haircut, even that is excessive! Unfortunately, it seems that in Melbourne, there’s no such thing as a “decent” haircut unless (I assume here, for I have not done it) you shell out some absurd amount. So today, despite my inner voice telling me to do it tomorrow (no kidding!), I decided I needed to get a haircut. I went into the city, looked at a few places on Elizabeth St., went to Melbourne Central basement – there was a place I had intended to try out but they were closing already. Went into China town, entered a place… and for a simple male cut in this standard-ish looking place in an arcade, they were charging 63 dollars! Can you believe that?! Like, what magical I-Ching hexagram was consulted to get that number?! So I stood there, raised an eyebrow, then declined and left. I ventured back to Elizabeth Street to this decent looking salon (by no means a 2-seater barber shop, though I reckon I’ll try that next time… couldn’t be worse). I was asked to wait 15-20 minutes, and then it was my turn…

The lady (in her early 20s) asks what kind of cut I’d like, I said I wanted it short, and “square at the back” – the latter phrase is something I picked up way back when I moved here, to say I want a clean angular lining at the back, as opposed to curvy one I suppose. Firstly, I asked for a haircut and I came to a salon, so what’s with these people asking me what number I am!? Like how the heck am I supposed to know what clipper I want to use, isn’t that why I’m there!? Okay, so maybe there are people who know their hair and the tooling for it well, I am not one of those lucky folk. So anyway, I tell the lady I have no clue, she says she’ll try a number 4 (she was Chinese, I am told the character for “4″ in Chinese is similar/the same to the character for death!). I’m like yeah whatever. And BANG, she runs the thing like a bloody lawnmower on grass. I mean I asked for “short“… not “let the outline of my head be visible to all who will see“! She moved it so fast that by the time I told her that I didn’t want it that short, she replies in her accent, “this is no. 4 – must be same len’ everywhere, if start, cannot stop”… what the bleep!? I realised then there was nothing I could do about it, it was way too late.

Now if it was just that, perhaps I could let go and move on (actually I have done that already, I’ll just feel better once I have this all in writing!), she also had no sense of symmetry… when she was placing the mirror at the back of my hair, I had to point out a couple of things – it wasn’t “square at the back” damn it!, and in one case, she just could not see what was wrong… so I literally just went “nevermind”, because I was afraid she’d ruin it further :(. Folks, if you have no sense of symmetry – please, don’t consider hairdressing, or software engineering, become an abstract artist or something, you know. So yeah, I have had a bad hairday – this must be the worst to date, once it grows I shall be able to get it cut again (I don’t where, but I do know where NOT!). Oh and worst of all… she did not use scissors… the biggest no-no in my book[1]. I asked for a haircut, not a clipper cut (a concept I have only heard of here…)!

Now some upsides – yes there are upsides, hard to believe: despite the cost advertised – 30 dollars – I was charged 15 – I so would have left some diplomatically caustic (is that even possible, or is it an oxymoron?) words for her to ponder otherwise. It appears she thought I wanted a clipper cut (but I said I wanted a HAIRCUT, H-A-I-R-C-U-T!!) – boy I must look like a starving student (that’s another upside, I must look young and fresh)… I suppose I hadn’t had any food yet at the time. The final upside I guess the lack of hair will keep my head cool during the summer. Meh.

References:
[1] Kamal’s Book of Life Skills, by yours truly, Chapter 33, p22, verse 11: “Profess’d as a hairdresser, ask’d for a haircut, clippers come and clippers go, but thou shalt use scissors without fail, else, a pox o’ thee, curses, boils, and sores spattereth across thy body, Heretic O’ A Hairdresser, Liar, Cheat, Heathen and Most Unholy Scum.”

February 1, 2009

Hoosain Narker’s “My Karate Odyssey” Travelogue

Filed under: martial arts,philosophy — Tags: , , , , — Kamal Advani @ 02:22

Back when I was a toddler (well not quite that young), a few influential people influenced me (coz that’s what influential people do…) and made me stick to practicing Karate. Hoosain Narker, a master of the Ashihara style was one of these people. He has written a wonderful travelogue, full of fascinating tales, and more importantly life tenets that he’s learnt and lived through his several decades of of training. I highly recommend his book, for martial artists and non-martial artists alike.

– Kamal

Powered by WordPress