JSF Charting Monster is back to the city

Finally eagerly waited 1.2.0 RC1 is ready. This version fixes the reported bugs and adds new features which are demanded for some time. I’ve also change the documentation at jsf-comp and updated the example web application.

ChangeLog of 1.2.0 RC1
- Instead of a servlet, charts are created by a JSF phaselistener, this gets rid of the servlet configuration and adds plug ang play behavior with zero configuration.
- Added portlet support.
- Support for DHTML events like onmouseover, onclick and etc.
- The output format is customizible now, it can be jpeg or png.(SVG and PDF later)
- Html image map support for creating image maps.
- Fixed the value binding problems.(Like the one for the type attribute or the bundle reading).
- Enhancements for preventing the browsers from caching the charts.
- Fixed “same chart for all rows” bug when used in a datatable.
- Added a foreground color attribute to change the color of the chart plot.
- Added support to change the colors of the plot sections for all kinds of charts.
- Fixed the state saving bug.
- Added accessors enabling to create the component programmatically.
- Added html img tag attributes support like alt, title and more;
- Border attribute is removed.

Checkout the online demo showing the creator in action;

http://www.cagataycivici.com/chartcreator

There may be two issues considering the backward compatibility, one is that since the servlet is not used not Chartlet class configured for previous versions could cause errors. Removing the config elements from web.xml should solve possible problems. Also border attribute is removed from tld and the component. You can use styleClass attribute instead.

I guess authors of the commercal JSF Charting solutions won’t like this but I’d say it’s getting more stable and mature with each release. The download number is over thousands in total and the popularity is still growing, this realy gives enthusiasm to work more. I hope with this new version, more and more requirements of the users will be satisfied. Anyway, along with the previous releases, version 1.2.0-RC1, example webapp, source, the documentation and more can be found at sourceforge JSF-COMP project land.

Posted in Java. 1 Comment »

JSF State Saving: Best of Both Worlds

When the state saving method of a JSF application is set to server by the javax.faces.STATE_SAVING_METHOD context parameter, state of the each page is saved in session map. The viewid of each page which corresponds to the pagename is used as the key in session. Although this method has performance advantages compared to the client state saving, nobody is perfect. The thing is that, if you have memory issues saving each page’s state in session does not seem to be a good choice.

Following is the output of FacesTrace tool visualizing the situation, there are 3 pages visited, each view of the page is hold in session by the page name and there is also a list in session holding the list of the view ids.

When the state saving is set to client, the state is sent to the browser as a hidden variable and then restored when a post occurs. This means there is only one view each request is aware of, this is also possible with the server side state saving,(with a little manual tuning of course). The best place to intersect the navigation and clean the view which is navigated from is a navigation handler. Here is one for this job;

  
    
    

    public class MyNavigationHandler extends NavigationHandler{
  
  protected NavigationHandler baseNavigationHandler;
  
  public NavigationHandler getBaseNavigationHandler() {
    return baseNavigationHandler;
  }

  public void setBaseNavigationHandler(NavigationHandler baseNavigationHandler) {
    this.baseNavigationHandler = baseNavigationHandler;
  }

  public void handleNavigation(FacesContext facesContext, String actionMethod, String actionName) {
    removeViewFromSession(facesContext);
    baseNavigationHandler.handleNavigation(facesContext, actionMethod, actionName);
    
  }
  
  protected void removeViewFromSession(FacesContext facesContext) {
    Map sessionMap = facesContext.getExternalContext().getSessionMap();
    String viewId = facesContext.getViewRoot().getViewId();
    sessionMap.remove(viewId);
      List viewsInSession = ((List)sessionMap.get("com.sun.faces.VIEW_LIST"));
      if(viewsInSession != null)
        viewsInSession.remove(viewId);
  }
}
      

This example works for the Sun’s RI implementation, I remember once there is a context parameter to tune the number of views in session in MyFaces but I cannot see it in the latest builds. Anyway this method takes the both side’s advantages in the state saving business. There is only one view the session allowed and the overhead caused by restoring the encoded state in client mode is escaped.

Posted in Java. 2 Comments »

FacesTrace Strikes Back

After being reported the bugs and recieved new demands for FacesTrace, me and Yigit started working on the new version (0.8.1). One of the most interesting features is that the FacesMessages in the request is displayed with it’s severity and the text. Also “http header” information for the request joined the scope variables.

Personally I was not surprised to hear that FacesTrace is being used in JSF training courses, because I’ve also used it in my last JSF presentation in a seminar. Other than the debugging capabilities, it can be used as a tool when learning JSF. I was working on limiting the size of the views in session when the state is hold at the server. By the help of FacesTrace, I’ve realized that, each view is saved in session with it’s view id and there is another list holding these view ids. Using this information I’ve written a navigation handler to do the cleaning. This was just an example of a usage.

Posted in Java. 1 Comment »

Diaries of a JSF Client Side Validation Lunatic

Day by day I’m getting closer to be a JSF Client Side Validation Lunatic. I’ve finished my beta work on the myfaces client side validation features and I’m glad everyone liked the results. I’ve brainstormed a lot on this client validation stuff in JSF and I believe I came up with the optimal solution which is as a result of a lot of experience on the topic.

JSF Client Side Validators
My initial work was a seperate validator library that enables javascript to be rendered to the client. There is a scriptgenerator component that traverses the component tree, finds the validators and encodes them. Although the results are very promising, there are some downsides. First of all, it is not in JSF nature and not compatible with the server side validations. Errors are displayed where the validator components are places not in message components. Also since the component tree is created during rendering, the approach won’t work for datatables and in case scriptgenerator component is above the validator components. I’ve donated this library to myfaces but we’ve decided to cancel the donation because of these downsides and I’ve believed there is a better approach out there(Yes, there is). So JSF Client Validators library is released in jsf-comp for now, I’m planning to get rid of the disadvantages in the next release.(0.9.2).

Shale Commons Validators
At work, the developers in my team seem to struggle with the validation stuff and we spend lots of times for input validation. My team leader Kenan Sevindik came up with the idea of integration client side validation to our project and assigned me to do the job. The library we’ve decided to use was Shale’s support for commons validator. Although I’m not a fan of using one tag to do lots of work, it seemed the best way for that time. However the thing is library itself is not usable in a real world application, I mean who fancies popups for validation, we’ve already extended message components to give them the look the customer demanded. So I’ve changed the scripts of commons-validator and the renderers of message components, also I’ve hacked shale’s validatorscript component which generates scripts by traversing the tree. It works for our project now but I’d prefer a library that works out of box. Paired with Yigit, we’ve rewritten shale validation to make it usable in an application. Also Oracle ADF which will be known as “Trinidad” from now on has client side validation, unfortunately it also uses popup but contains nice features like enabling client validation with a context-param.

MyFaces Client Side Validation
Finally, when brainstorming on figuring out a way for Apache MyFaces Client Side Validation I was looking for an idea which will be 100% compatible with the server side validation infrastructure and minimize the effort of the myfaces user to enable validation at client side. Also it should not break anything in the pages built with myfaces. So here is the big deal, each input text renderer looks for the validators of the component it renders. If there is a validator that implements IClientValidator, the renderer creates a ClientSideValidationCall object and queues it. The queue is saved temporarily at a request scope object called ClientSideValidationCallsHolder. When the form renderer takes the scene, it accesses the holder object, gets all the queued ClientSideValidationCall objects and renders them. A ClientSideValidationCall object simply has a function name and String array params which corresponds to a js validator function with parameters. Also a context param called org.apache.myfaces.ENABLE_CLIENT_SIDE_VALIDATION is used for controlling the client side validation. You can see the results of this approach at a special myfaces sandbox example project I’ve created, it’s under “Input Handling -> Validation topic” as “Client Side Validation“. Thanks to Martin Marinschek and Ernst Fastl, it is deployed at IRIAN.at.

http://www.irian.at/cagatay-validation-sandbox/home.jsf

Main Advantages;
* The key advantage of this approach is that since the renderers are extended, “there is no need to add anything” to the JSF pages, not even a single tag.
* After adding the context param, the application starts validation at client side. For security reasons, server side validation cannot be disabled and this switch only turns on/off the client side validation.
* Almost %100 compatibility with the server side, uses message components to display the errors.
* There is no tree traversal, this allows to escape performance issues and possible bugs since component tree is created during rendering(not in JSF 1.2 and Facelets).

UPDATE : 07.02.2007
This myfaces client validation project has changed a lot and it’s successor written from the beginning has joined myfaces sandbox now.

Posted in Java. 3 Comments »

Making Managed Beans Aware of the JSF Lifecycle

An event that runs when a JSF page is being loaded should be useful for initialization stuff. In my project team several developers use bean constructors to do such things which I think is a bad practice. Although I prefer the getters to do initializations, I’ve added a onPageLoad event to our application for people who prefer the constructors. It is similiar to Shale view mapper, the managed bean and the page name must be mapped in order to run the event. There are two things needed to do the job, a phaselistener and an interface to mark the managed beans. PhaseListener runs maps the viewId to the managed bean and executes the onPageLoad event.

public class PageLoadListener implements PhaseListener {

  protected final static Log logger = LogFactory.getLog(PageLoadListener.class);

  public void afterPhase(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    String viewId = phaseEvent.getFacesContext().getViewRoot().getViewId();
    System.out.println(viewId);

    if (viewId.endsWith(".jsf")) {
      String managedBeanName = getManagedBeanNameFromView(viewId);
      Object object = facesContext.getApplication().createValueBinding("#{" + managedBeanName + "}").getValue(facesContext);
      if (object == null)
        logger.error("OnPageLoad cannot be executed, no such managed bean:"+ managedBeanName);
      else {
        ILifeCycleAware lifeCycleAwareBean = (ILifeCycleAwareobject;
        lifeCycleAwareBean.onPageLoad();
      }
    }
  }

  public void beforePhase(PhaseEvent phaseEvent) {
    
  }

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

  public String getManagedBeanNameFromView(String viewId) {
    String pageName = viewId.substring(1, viewId.length() 4);
    return "pc_" + StringUtils.capitalize(pageName);
  }

}
      

And the interface that makes the managed bean aware of the lifecycle.

public interface ILifeCycleAware {
  public void onPageLoad();
}
      

For example there is a page called index.jsp, and it is referred as the virtual mapping /index.jsf. Phaselistener extracts the index token and gives the mapping pc_Index. Also the managed bean class Index.java implements ILifeCycleAware interface and overrides the onPageLoad event. Then phaselistener executes this event. Finally the backing bean of index.jsp is declared in faces-config.xml as;

  <managed-bean>
  <managed-bean-name>pc_Index</managed-bean-name>
  <managed-bean-class>barca.Index</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
 </managed-bean>

 The good thing is more events can be added like the ones in Shale, eg prerender, preprocess and etc. So you can execute similiar events and make the managed beans aware of the lifecycle.

Posted in Java. 12 Comments »

ISPOSTBACK in JSF

Although this kind of mechanism is not necessary as it’s in other frameworks like asp.net, I’ve observed in many places where people are demanding such a feature to understand a postback in JSF. I still don’t belive this need is a good practice since developers should not need to care about http cycles and consider them in the development process, but in the end it seemed challenging to figure out a way. I thought the best place to check for the postback is a view handler. In JSF using the decorator design pattern you can change the default behavior of the view handler.

A view handler has several methods like creating, rendering and restoring the view. This reveals the answer actually, when create view is called than it is simply not a postback. Here is the custom view handler.

package extensions;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

public class CustomViewHandler extends ViewHandler {

  protected ViewHandler baseViewHandler;

  public CustomViewHandler(ViewHandler viewHandler) {
    super();
    this.baseViewHandler = viewHandler;
  }

  public Locale calculateLocale(FacesContext facesContext) {
    return baseViewHandler.calculateLocale(facesContext);
  }

  public String calculateRenderKitId(FacesContext facesContext) {
    return baseViewHandler.calculateRenderKitId(facesContext);
  }

  public UIViewRoot createView(FacesContext facesContext, String arg1) {
    setPostback(facesContext, false);
    return baseViewHandler.createView(facesContext, arg1);
  }

  public String getActionURL(FacesContext facesContext, String arg1) {
    return baseViewHandler.getActionURL(facesContext, arg1);
  }

  public String getResourceURL(FacesContext facesContext, String arg1) {
    return baseViewHandler.getResourceURL(facesContext, arg1);
  }

  public void renderView(FacesContext facesContext, UIViewRoot arg1throws IOException, FacesException {
    baseViewHandler.renderView(facesContext, arg1);
    
  }

  public UIViewRoot restoreView(FacesContext facesContext, String arg1) {
    setPostback(facesContext, true);
    return baseViewHandler.restoreView(facesContext, arg1);
  }

  public void writeState(FacesContext facesContextthrows IOException&nbs
p;
{
    baseViewHandler.writeState(facesContext);
  }
  
  public Map getRequestScope(FacesContext facesContext) {
    return (Map)facesContext.getApplication().createValueBinding("#{requestScope}").getValue(facesContext);
  }
  
  public void setPostback(FacesContext facesContext, boolean value) {
    getRequestScope(facesContext).put("ispostback"new Boolean(value));
  }

}
      

To plug-in this view handler to the application following decleration goes into the faces-config.

 <application>
   <view-handler>extensions.CustomViewHandler</view-handler>
</application>

In order to get the info set by the view handler, the following method can be used;

    public boolean isPostback() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    Map requestScope = (Map)facesContext.getApplication().createValueBinding("#{requestScope}").getValue(facesContext);
    boolean ispostback = ((Boolean)requestScope.get("ispostback")).booleanValue();
    return ispostback;
  }
      

Important: The view handler approach won’t work when the state saving is set to server because the views are cached in session and create view is not called. I guess a better alternative to the viewhandler is hacking the navigation handler. I don’t think same issue will occur when a navigation handler is used to check for a postback.

Posted in Java. 11 Comments »

JSF Client Side Validators v0.9.1 and Facelets

This version is focused entirely on bug fixes. Unfortunately I could not get the enough free time to add new features and tried to fix the reported bugs instead. Here is the changelog of version 0.9.1.

  • An empty popup was displayed even the input was valid. Fixed.
  • Multi access to global javascript variables was subject to fail. These are converted to local ones.
  • A state saving bug regarding the display mode is fixed.
  • Resource loading is done via the *.jsf mapping instead of /faces/*.
  • Regular expression validator now considers empty input as valid.
  • Instead of document.all, w3c standart document.getElementById is used.
  • Improved example web application demonstrating both validation summary both with and without a popup.

Also if you are a Facelets user, I’ve provided the facelets taglib file as the following;

<?xml version=”1.0″?>
<!DOCTYPE facelet-taglib PUBLIC “-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN” “facelet-taglib_1_0.dtd”>
<facelet-taglib>
<namespace>http://sourceforge.net/projects/jsf-comp/clientvalidators</namespace>
<tag>
    <tag-name>requiredFieldValidator</tag-name>
    <component>
       
<component-type>net.sf.jsfcomp.clientvalidators.requiredfieldvalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>rangeValidator</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.rangevalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>compareValidator</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.comparevalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>regularExpressionValidator</tag-name>
    <component>
       
<component-type>net.sf.jsfcomp.clientvalidators.regularexpressionvalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>lengthValidator</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.lengthvalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>customValidator</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.customvalidator</component-type>
    </component>
</tag>

<tag>
    <tag-name>validationSummary</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.validationsummary</component-type>
    </component>
</tag>

<tag>
    <tag-name>scriptGenerator</tag-name>
    <component>
        <component-type>net.sf.jsfcomp.clientvalidators.scriptgenerator</component-type>
    </component>
</tag>
</facelet-taglib>

More information on JSF Client Side Validation Library is here. So what is next, I have many other new features in my mind like running the validations onblur-onkeypress other than onsubmit, improving the compare validator(add more operators) and etc. I am currently working on MyFaces Client Side Validation support for tomahawk validators and dont know when I will implement the features I’ve mentioned. Also Acegi’s 1.0.0 version is released and I feel like the time to improve the Acegi-JSF components is near. Moreover someone asked me when the new version of JSF Chart Creator is coming, I had also many ideas on the new version just have not enough time. All of these mean to me just one thing; More nights without sleep, in the end that is the discipline of a “NIGHT DEVELOPER“.

Posted in Java. 20 Comments »