Ajax is everywhere with AjaxAnywhere

It’s been quite some time since I’ve started playing with AjaxAnywhere which I think one of the most interesting Ajax Frameworks out there drawing attention. Nowadays I’ve paired with Kenan Sevindik and began to explore the possibility of using AjaxAnywhere in our project. The idea behind is quite interesting actually, you specify zones in your page and these zones in dom are reloaded using javascript library of ajaxanywhere. The best thing is you do not need to change your current structure, just specify zones, add the zones to be refreshed and tada: the zones are reloaded with no postback.

The framework uses it’s own filter to manipulate the flow and currently it both supports jsp and jsf. The main idea is the following; The form is submitted as a whole actually not just the zones,  the JSF components(zones) output spans with the components’ ids, when the response reaches, the inner html of the span is set by the mechanisms in aa.js of ajaxanywhere.

The Good
I’ve managed to apply some cool ajax features in few minutes using the framework. For example, I’ve created two dependent comboboxes, and a datatable presenting the search results with no postback. I think these are nice examples that AjaxAnywhere can do to satisfy the impatient client. AA is very useful in these cases and considering the workload to create the same thing with phaselisteners, xml parsing, etc, it just rocks.

The Bad
The framework is useless in some cases. Since it is likely to have scripts and hidden fields in a page which cannot be located in an aa zone, problems begin to occur. Unfortunately we are using ibm jsf, where there is a script collector component on top of the h:form collecting scripts form components and outputs them in encodeEnd. In order to overcome the reloading problems of hidden fiels(e.g. state) and scripts, we have written a PreSendHandler class that takes the response and reloads the scripts-hidden fiels using javascript. We used nekohtml the parse the response buffer and dom inspector(for testing) to traverse the dom tree. However the idea failed because of the problems occured in programmatically manipulating scripts-hidden fields of the dom tree at runtime and ibm’s bad designed scripts. In addition one more disadvantage is, since the whole page is submitted, you should not get the performance you expect and the validation conversion errors are another question.

The Ugly
IBM’s approach to JSF, not related with AjaxAnywhere actually:)

What I can tell briefly about aa is; it rocks on simple cases I’ve mentioned but do not expect much on complex ones.

Posted in Java. 2 Comments »

Night Programmer vs Day Programmer

I’ve came across an entry by Mitch Denny about Night and Day developers. I totally agree with him and want to add a couple of things from my point of view.

The night developers like to explore, compare and analyze the new tech stuff and always aware of what is going on outside. They have this criticizing point of view and like questioning the current environments.  Day programmers see this as a waste of time which I think causes them to be out of date sooner or later. Considering my project team, the number of day developers are much more than the night side, and I just do not have respect to a day developer and does not consider what he or she says as important. On the other hand, one can learn lots of things from a night developer and everyone in the team shows respect. Always the day people ask questions to the night people, the opposite is not likely.

Well I am definitely in the the night side of the force, last night after getting back home, because of wondering what AjaxAnywhere is capable of I played with it until 02.30 a.m. which makes me an early morning rather than a nightly developer I guess:) So which type of developer are you? Maybe the answer is obvious, I do not think a day developer will ever visit this blog or jroller.

Ruby on Rails; The First Encounter

Last week I’ve attented a Ruby on Rails presentation given by master. It was a nice experience for me to see the famous Ruby on Rails in action. Firstly I must say I am impressed, developing an application is so rapid and agile. You don’t even need to restart the server, it is a dream for a J2EE developer:) The crud interfaces, active record orm, the controller practice, no metadata and etc. Also the RadRails Tool seems to be making life easier.

And now the things I don’t like, Ruby just does not attract me, all the symbols, attempts to do lots of work in a few lines and etc. Also I guess the active record orm will be inadequate in cases when the complexity grows up. It should include more mapping strategies rather than table per hierarchy. Compared to hibernate it seems too simple.

After the presentation I don’t feel any enthusiasm to go home, download radrails and try some hands-on approach. I don’t know, maybe my expectation was too much after reading lots of news and entries on Rails. It is definitely great to create simple applications like e-commerce sites, management tools and etc, ruby on rails seems to the best at productivity, however thinking the great complexity of the project I am working in now, it is just not very applicable in complex cases. In order to deal with complexity, you need some complexity.

I have a list of stuff of waiting to be practiced, like maven2, advanced aspectj, shale, facelets and etc. Personally I feel enthusiastic about these but I just don’t have it for Ruby on Rails(for now), maybe in the future who knows? Nevertheless I will continue keeping an eye on rails world.

Posted in Java. 3 Comments »

Phaselistener renders an image,no more Servlet

In my previous entry, I mentioned about the underestimated powers of jsf phase listeners and presented some cases demonstrating some of these in theory. The first two was well known ajax cases and the third one was a secret power:rendering an image. I had not tried the third solution when writing the entry but using the chart component as a test case I’ve done some coding and now I am presenting the results.

Well, the theory in practice worked fine, using a phaselistener instead of a seperate servlet, I was able to present the images in a page with no problem. In order to do it, I’ve done small changes, first of all I’ve deleted the servlet definition. That shows how much I believe in phaselistener approach:) Then created a phase listener and register it in the faces-config.xml. The last thing was to change the img source rendered by the component. Instead of a servlet request, a faces request is used now;

<img src=”/servlet/Chartlet?id=chart1″ />

<img src=”faces/chartlistener?id=chart1″ />

The new img src is handled by the faces servlet which initiates the jsf lifecycle, after restore view phase when the view id is set, chartlistener takes the scene and by changing the response type to image/png or image/jpg or whatever, responses an image.

So why using a phaselistener instead of a servlet is necessary in this case and why do I do that?
# I wondered the possibility actually, it seemed to be a cool idea instead of an old-school servlet solution.
# Now no need to declare a servlet, instead a component user needs only the jar file.(Plug and Play)
# Servlet does not allow the portlet integration, now it is possible.

Here is a general example of this approach, the image is in hex format and phaselistener renders it to the client.

 
    
    

    public class ImagePhaseListener implements PhaseListener {

    public final static String IMAGE_VIEW_ID = "hex_image";
   
    private final static Log log = LogFactory.getLog(ImagePhaseListener.class);

    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        String viewId = context.getViewRoot().getViewId();
        if (viewId.indexOf(IMAGE_VIEW_ID!= -1) {
            log.info("Handling image request");
            handleImageRequest(context);
        }
    }

    public void beforePhase(PhaseEvent event) {
            //Do nothing here...
    }

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

    private void handleImageRequest(FacesContext context) {
        HttpServletResponse response = (HttpServletResponsecontext.getExternalContext().getResponse();
        response.setContentType("image/jpeg");
        response.setContentLength(17);
        try {
            String hex = "SOMEHEXCODEHERE";
            byte [] bts = convertHexToByteArray(hex);
            response.getOutputStream().write(bts);
        catch (Exception exception) {
            log.error(exception.getMessage());
        }
        context.responseComplete();
    }
   
    private byte [] convertHexToByteArray(String hex) {
        byte[] bts = new byte[hex.length() 2];
        for (int i = 0; i < bts.length; i++) {
            bts[i(byteInteger.parseInt(hex.substring(2*i, 2*i+2)16);
        }
        return bts;
    }
}
      

In order to let the phaselistener to do it’s job we have to refer the source of the image as;

 <h:graphicImage value=”/hex_image.jsf” /> or  <h:graphicImage value=”faces/hex_image />

Phaselisteners can respone anything actually, this was an example of an image rendering, you just need to change the response type and send the output to the client. Anyway I will use this approach when dealing with the next release of the JSF Chart Creator since  the component is more pluggable this way. As Matthias commented to my previous entry: “PhaseListeners are great for developers, YES!”.

Posted in Java. 6 Comments »

JSF PhaseListeners: Underestimated from day one

JSF’s lifecycle is well defined and the developer takes the stand usually at invoke application phase where the button actions are handled. However using the underestimated powers of phase listeners one can play with the strict lifecycle. A Phaselistener reminds me an around advice, because it has both an after and before phase method that is executed in order. You can do whatever you want to do before and after each phase, it depends on your imagination but my favorite place to use a phaselistener is after restore view. After restore view, here is the possible use cases that I can think of, feel free to add one if you have;

Handle ajax requests.
 In one of my entries I implemented a simple application using both a servlet and a phaselistener in order to compare them. Here is the example showing how to use a phaselistener to enable ajax.

Serve resources like javascript or style sheet files from a single jar file.
 From a component developer’s point of view, phaselisteners have a great value, first thing is that the resources like .js and .css can live in the distribution jar file, and a phaselistener can register itself to the context. That means an all in one jar file can be used. This reminds me the cool ExtensionsFilter of myFaces. A phaselistener could be used instead of a filter or a servlet without requiring user configuration since it is pluggable.

Use like a servlet.
 Here is an example from me, I am planning to use a phaselistener instead of a servlet in my chart component because people who use it must define the servlet class in their web.xml’s. Instead a phaselistener can register itself to the context and  after the restore view phase, by changing the response type, a response like an image or an xml file can be rendered.

All needed to be done is to take the attention of the faces servlet, this is needed to start the lifecycle and it is as simple as using a prefix(/faces/*) and a special view id name for you to realize whether the request is a regular faces request or one of what you are looking for. Here is a simple example;
   
public class UnderestimatedPhaseListener implements PhaseListener {

    private static final String AJAX_SCRIPT = “ajax-script”;
   
    private static final String AJAX_VIEW_ID = “ajax-view”;
   
    private static final String CREATE_CHART_IMAGE = “create-chart-image”;
   
    public void afterPhase(PhaseEvent event) {
        String rootId = event.getFacesContext().getViewRoot().getViewId();
        if (rootId.indexOf(AJAX_VIEW_ID) !=-1)
            // Handle Ajax Request
        else if(rootId.indexOf(AJAX_SCRIPT) !=-1)
            // Serve the script file from jar
        else if(rootId.indexOf(CREATE_CHART_IMAGE) !=-1)
            // Just create a chart image
    }

    public void beforePhase(PhaseEvent arg0) {
          // Do nothing
    }

    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}

In each of the three cases responseComplete() of facesContext must be called in order to cut the lifecycle and prevent it from going further. So the answer to the question: Is there life after a phaselistener is no in this case. For the first two, Bpcatalog provides an excellent example of using a phaselistener to enable ajax in jsf, here is a more detailed jsf-ajax explanation from bpcatalog if you want to go further. The third is my idea, never tested it for now but changing the response type and copying some code from the chart servlet will do the work. I still guess there is more that can be done with phaselisteners, as I mentioned before, it depends only on the developers imagination. For example, this just hit me now, by checking the request parameters, one can understand which component caused a postback and use this information before apply request values and etc.etc.etc.

Posted in Java. 3 Comments »