28 October 2008

Random Thought On The Internet

This is one of the random thoughts that usually pop right into my head when I least expect it.

I was on a work trip. One of those where you get to travel to exotic destinations but all you get to see is the office, the company cafeteria and the hotel. I was having dinner at the hotel and I started thinking of how come people have this strange need to aggregate in some area. How did people start living with other people, and how did they manage to eventually take this concept to such gigantic proportions as to create today's biggest cities, with millions and millions of individuals living close to each other.

The first reason I thought of was procreation and the continuation of the species: a certain gene pool needs a minimum degree of diversity in order to avoid extinction. Did humans in the upper palaeolithic or in the mesolithic really think along those lines? Probably not. So here I am, I'm not very good at running, hiding, or throwing spears. I can't hunt for food, but I'm good at growing legumes. If I find someone who's good at hunting, maybe we can trade food. Now, wouldn't it be easier if the two of us lived relatively close to each other instead of a half-day walking distance? I haven't studied anthropology, archaeology or any related branches, but that kind of makes sense to me.

Without going that far back in time, just think that a hundred years ago a grain of black pepper needed to travel for months to reach Europe, from south west India to Italy, but people could still find black papper in grocery shops, because they lived in human settlements where specialisation of roles could support a complex social infrastructure: different people can do different things and provide different needs, but they need to be in relatively close proximity in order to maximise their reciprocal advantage.

In physics, this is equivalent to a system trying to find its equilibrium by minimising its energy. An electron in an excited atom "prefers" to drop to a lower energy level if that level is not already full. This is what the electron thinks: what's the point in doing so much work just to keep running like mad in a "higher orbit", when I could just cruise casually around a "lower orbit"? So the electron "drops down" an energy level and sheds the excess energy in a flash of light. And no, I haven't studied much physics either, but that kind of makes sense to me.

Extrapolating the principle of minimising a system's energy, here's what a human might think instead: what's the point in spending half a day travelling to buy some food, load up enough food to last me a while (because it's not like I'll do this again tomorrow, or the day after), then carry all that food back home and manage its storage, when I could just move downtown and simply pop down to the corner shop whenever I need to?
The real achievement in moving downtown, in really fancy terms, is not that I have found a low-energy equilibrium. My half-day walk has become a two-minute stroll. The 20 kilometers between the shop and my house have become less than 100 metres. By moving downtown I have effectively compressed space and time.

Today, as a human living in the remote countryside, I don't actually need to move at all, but I can still compress space and time. How? With Internet, of course. I don't need to live in relatively close proximity to other humans and human structures: I need to move to wherever there is an Internet connection and a postal service, and these might well exist in the remote countryside as well as downtown. So will internet reverse the process of urbanisation, or at least will it make such reversal possible? I think so. Virtual offices, internet videoconferencing, voice-over-IP, news streaming, bla bla bla... it's all there already. The recent hype of "going green" even encourages to great extents to stay where you are, avoid travelling, avoid lighting up an entire office or unnecessarily loading the public transport system if you can work from home. The fascination for "going downtown", perhaps, will eventually be confined only to touristic attractions. I'm not saying people will have no more reasons for sticking together in organised physical conglomerates: I'm just saying, IMHO, that there will be a lot less of a motivation to do so in the future.

M.

23 October 2008

Expressions in IceFaces Navigation Targets

I must write this lest I forget.

I've been working on an exception handling mechanism for a JSF-based application using IceFaces, and I was thinking... "why oh why can't we dynamically navigate to error pages using a navigation rule?"
Navigation rules in the faces-config.xml look like this:
<navigation-rule>
    <from-view-id>/somePage.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>error</from-outcome>
        <to-view-id>/errorPage.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>
That is fine but very limiting for my navigation purposes. What if I want to navigate to a different page according to the actual error code? In other words, I want to be able to do this:
<navigation-rule>
    <from-view-id>/somePage.xhtml</from-view-id>
    <navigation-case>
        <from-outcome>error</from-outcome>
        <to-view-id>/#{errorBean.errorCode}.xhtml</to-view-id>
    </navigation-case> </navigation-rule>
Well, it seems that I can't do that with the Sun JSF RI or IceFaces, so I decided to make it happen. I figured that if I wanted to add expression evaluation in a navigation target URL I needed to write a view handler. With IceFaces, the application view handler is com.icesoft.faces.facelets.D2DFaceletViewHandler, which is reponsible for setting up the direct-to-DOM rendering etc, so I needed to extend that class and find what methods I needed to override in order to get me to where I wanted to be. After a bit of experimentation I found there are two scenarios:
Scenario #1: Navigation Rule With Redirection
This is where the navigation rule has a <redirect/> tag. The method in D2DFaceletViewHandler that handles this is
public String getActionURL(FacesContext context, String viewId)
Scenario #2: Navigation Rule Without Redirection
This is where the navigation rule does not have a <redirect/> tag. The method in D2DFaceletViewHandler that handles this is
public void renderView(FacesContext context, UIViewRoot viewToRender)
The way I decided to process the expression is very simple, almost elementary:

  1. Parse the URL/ViewId looking for a sub-string that begins with '#{' or '${' and ends with '}' 
  2. capture the sub-string and create a value binding to evaluate the expression 
  3. Replace the expression in the URL/ViewId with the actual value 
  4. Process the newly evaluated URL/ViewId

Before I get any comments on step 1... no, I don't like regex because my brain just doesn't get it, and it takes me considerably longer to figure out a regex pattern to capture such a simple substring than to actually write a few lines of code to do the parsing.

So here's my (edited) code.
/**
* Constructor
*/
public MyViewHandler(ViewHandler delegate) {
    super(delegate);
}

/**
* Processes a view id that may contain an expression, by evaluating the
* expression and replacing the expression tag in the original view id with
* the expression result.
*
* @param context The faces context.
* @param viewId The view id to process.
* @return The processed view id.
*/
private String processViewId(FacesContext context, String viewId) {
    String processedViewId = viewId;

    int startExpression = processedViewId.indexOf("{") - 1;
    if (startExpression > 0) {
        char expChar = processedViewId.charAt(startExpression);

        // expressions start with # or $
        if ((expChar == '#') || (expChar == '$')) {
            int endExpression = processedViewId.indexOf("}", startExpression);

            if (endExpression > startExpression) {
                // viewId contains an expression
                String expression = processedViewId.substring(startExpression, endExpression + 1);

                try {
                    ValueBinding vb = context.getApplication().createValueBinding(expression);

                    if (vb != null) {
                        String evaluatedExpression = vb.getValue(context).toString();

                        // replace the expression tag in the view id
                        // with the expression's actual value
                        processedViewId = processedViewId.replace(expression, evaluatedExpression);
                    }
                }
catch (ReferenceSyntaxException ex) {
                    // do nothing: processedViewId = viewId;
                }
            }
        }
    }

    return processedViewId;
}

/**
* Used to process a URL that may contain an expression. If a navigation
* rule in the faces configuration file has a <redirect> tag, this
* method will be used to process the URL specified in the
* <to-view-id> tag
*
* @see javax.faces.application.ViewHandler#getActionURL(FacesContext, String)
*/
@Override
public String getActionURL(FacesContext context, String viewId) {

    String processedViewId = super.getActionURL(context, viewId);
    processedViewId = this.processViewId(context, processedViewId);

    return processedViewId;
}

/**
* If a navigation rule in the faces configuration file does not have a
* <redirect> tag, this method will be used to process the URL
* specified in the <to-view-id> tag
*
* @see com.icesoft.faces.application.D2DViewHandler#renderView(FacesContext,
* UIViewRoot)
*/
@Override
public void renderView(FacesContext context, UIViewRoot viewToRender)
throws IOException, NullPointerException {

    String viewId = this.processViewId(context, viewToRender.getViewId());
    viewToRender.setViewId(viewId);

    super.renderView(context, viewToRender);
}
To use my spanking new view handler I just have to change the application section in the faces-config.xml file:
<faces-config>
    <application>
        ...
        ...
        <view-handler>
            <!--
            com.icesoft.faces.facelets.D2DFaceletViewHandler
            -->

            myViewHandler
        </view-handler>
    </application>
</faces-config>
M.

21 October 2008

Finding Kokkyu

This is about one of those amazing discoveries in my world of Aikido.

I'm walking fairly fast to reach home before the Simpsons start on TV. I get to an underpass to get to the other side of a large busy road. I have a 5-year-old sitting on my shoulders, let's say about 20 kilograms. I have my techno-backpack on my back, let's say another 10 kg, for a total of 30 kg concentrated on my neck and shoulders. I am also pushing a buggy with a 1-year-old, for a total of, say, another 10 kg. The underpass, by definition, routes me downhill at first, then across, then uphill, and it's during the uphill phase that I start struggling.

Instinctively, I simply stretch out my arms to push the buggy, and compensate the additional weight on my neck and shoulders by tensing the muscles in my upper body.

WRONG! That's hard work!

Then it just dawned on me: I relaxed my shoulders, dropped my weight towards my hips, energised my forearms, putting just a tiny bit of zanshin on each step... and there I was, cruising uphill without noticeable effort!

Aikido will never cease to amaze me.

M.

16 October 2008

2309

sorridi
come una volta
al chiaro del mare
ai sogni di luna
su un volto solare

      

smile
like you used to
in the brightness of the sea
to your moondreams
on your sun-kissed face

canta
ai colori del mondo
alle amate colline
alle palme incantate
con la tua voce eterna
di brezza d'estate

sing
to the colors of the world
to your loved highland
to the enchanted palms
with the eternal voice
of a summer breeze

vola
sereno
oltre le mura
di tutti i colori
senza paura
senza dolori

fly
unworried
over these walls
of all colors
without fear
without pain

ecco un artista!
un autore
un sole
un padre

here is an artist!
an author
a sun
a father

adesso
solo un pianto
e un sussurro
un ultimo ciao

and now
only a cry
and a whisper
one last hello

luceran
ancora
le stelle

the stars
will shine
again

M.