Life Codecs @ NamingCrisis.net

Ruminations. Reflections. Refractions. Code.

Feb 24, 2009 - software dev

Delegates in Java – Introducing delegates4j

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 = ; 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 = ; 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 = ; 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 = ; 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

Feb 23, 2009 - software dev

Bloggy: Wicket Demo Blog App!

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 awesome1
  • 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!

Feb 23, 2009 - general personal philosophy

Blog Name Change

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.

Feb 22, 2009 - general personal software dev

Website!!

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

Feb 16, 2009 - how to software dev

WordPress’ Tag Cloud Limit

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