Tuesday, October 5, 2010

JSR 286 Portlet filter feature

JSR 286 introduces a new feature of portlet filter which is not included in earlier version of JSR specification. In this post, I am going to describe portlet filter feature briefly along with implementation code and example.

What is Portlet Filter?

Portlet filter is a piece of code that can transform content of portlet request and response. The concept is almost same as we already learnt from Servlet filter.
A filter by implementing one of the javax.portlet.filter.XYZFilter interfaces and providing a public constructor taking no arguments. A filter is declared using the <filter> element in the portlet deployment descriptor. A filter or collection of filters can be configured for invocation by defining <filter-mapping> elements in the portlet deployment descriptor.


Portlet Filter Lifecycle -

When request comes for portlet access, portlet container locate list of filters first and create instances of filters from the list and then calls init(FilterConfig config) method of filter.
When the container receives an incoming request, it takes the first filter instance in the list and calls its doFilter method, passing in the PortletRequest and PortletResponse, and a reference to the FilterChain object it will use.
Depending on target method of doFilter call, the PortletRequest and PortletResponse must be instances of the following interfaces:

1) ActionRequest and ActionResponse for processAction calls
2) EventRequest and EventResponse for processEvent calls
3) RenderRequest and RenderResponse for render calls
4) ResourceRequest and ResourceResponse for serveResource calls

Before a filter instance can be removed from service by the portlet container, the portlet container must first call the destroy method on the filter to enable the filter to release any resources and perform other cleanup operations.

Portlet Filter Configurations on application -

A filter is defined in the deployment descriptor using the <filter> element. In this element, the programmer declares the following:

1) filter-name: used to map the filter to a portlet
2) filter-class: used by the portlet container to identify the filter type
3) lifecycle: used to determine for which lifecycles the filter should be applied
4) init-params: initialization parameters for a filter

Here is an example of a filter declaration:

<filter>
 <filter-name>MyPortletFilter</filter-name>
 <filter-class>com.ibm.portletfiltersexample.MyPortletFilter</filter-class>
<lifecycle>RENDER_PHASE</lifecycle>
</filter>

Once a filter has been declared in the portlet deployment descriptor, the <filter-mapping> element is used to define portlets in the portlet application to which the filter is to be applied. Filters can be associated with a portlet using the <portlet-name> element.

PortletFiltersExample portlet:

<filter-mapping>
 <filter-name>MyPortletFilter</filter-name>
 <portlet-name>PortletFiltersExample</portlet-name>
</filter-mapping>

Filters can be associated with groups of portlets using the ‘*’ character as a wildcard.

<portlet-name>*</portlet-name>

A portlet filter can be applied to different lifecycle method calls: processAction, processEvent, render, serveResource. The following constants are valid values for the <lifecycle> element:

1) ACTION_PHASE requesting that the portlet container processes this filter for the processAction lifecycle method. The filter implementation must implement the ActionFilter interface.
2) EVENT_PHASE requesting that the portlet container processes this filter for the processEvent lifecycle method. The filter implementation must implement the EventFilter interface.
3) RENDER_PHASE requesting that the portlet container processes this filter for the render lifecycle method. The filter implementation must implement the RenderFilter interface.
4) RESOURCE_PHASE requesting that the portlet container processes this filter for the serveResource lifecycle method. The filter implementation must implement the ResourceFilter interface.

Example:

<filter>
<filter-name>MyPortletFilter</filter-name>
 <filter-class>com.ibm.portletfiltersexample.MyPortletFilter</filter-class>
 <lifecycle>ACTION_PHASE</lifecycle>
 <lifecycle>RENDER_PHASE</lifecycle>
</filter>

In this example the portlet filter is applied to the action and render phase.

And the code of filter class, which implements RenderFilter interface, is as:

public class MyPortletFilter implements RenderFilter {

 public void init(javax.portlet.filter.FilterConfig arg0) throws PortletException {
  // TODO Auto-generated method stub
  }

  public void doFilter(RenderRequest req, RenderResponse res, FilterChain chain) throws IOException,PortletException {
   System.out.println(" DEBUG: M Portlet Filter Pre-processing a render request");
   // Hand off control to the next filter in the chain, or the portlet itself if no more filters  
   chain.doFilter(req, res);
   System.out.println(" DEBUG: M Portlet Filter Post-processing a render request");
  }

  public void destroy()
  {
   System.out.println("DEBUG: Destroying My Portlet :-("); 
  }
}

If you need any sample application of portlet filter, you please click on followning link and download the attached applicaton 'PortletFiltersExample.war' in dilip's post.

http://www.ibm.com/developerworks/forums/thread.jspa?threadID=316941&tstart=0 

Monday, August 23, 2010

Serving resource using JSR 286

In JSR 286, one more method is getting introduced in portlet life cycle that is serveResource, the advantage of this method is, we can get resource in portlet response which is not possible in JSR 168.

Let's take an example for better understanding the use of serveResource method. Suppose, you have a collection of images and you need to display different images according to the selection. What you will do is?
First, you need to create a resource URL as mentioned below,

ResourceURL resourceURL = renderResponse.createResourceURL();

Now, you need to make a hiperlink through which you call the serveResource method. The code for reference is,
<a href="<%=resourceURL.toString() %>">Resource</a>

When you click on this link, it makes an Ajax call using resourceURL and call the serveResource method. Once it is called you can set the response for images (which is not effected in JSR 168) and write this byte format of image in XML format. Now response is ready which is called using Ajax callback methods. The reference code lines are,

public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {   
 response.setContentType("image/jpeg");
 // Image in byte stream
 byte[] b = getImage(); //Returns image bytes
 // writing image byte stream on portlet response
 response.getPortletOutputStream().write(b);
}

Also, you can use different types of resources. What you need to do is?
you have to add the following code with resourceURL,
resourceURL.setResourceID("image");

Through this ID you can perform your logic according to the image resource ID. You can get Id in serveResource method using code below,

request.getResourceID().

Sunday, August 22, 2010

JSF Page navigation using RAD 7 Add Rule feature

JSF provides page navigation using navigation-rule of faces-config.xml file. In this rule, you need to mention source JSP, destination JSP file and a token which returns from managed-bean method.
I will do the same thing using ‘Add Rule’ feature of RAD 7. Let’s see how we can do it?

First you need to open the JSP page in design view and single click on ‘SAVE’ button. Thereafter, you need to select ‘Properties’ tab (Lower middle portion of RAD) and then select ‘hx:commandExButton’ option. There you can see Add Rule button.

Please click on ‘Add Rule’ button (Right upper portion of properties tab). You will get ‘Add Navigational Rule’ window. Here you will mention final JSP page, the outcome name and action if required. Press OK button once you fill all the required information.






You can see the added code in faces-config.xml file as,

<navigation-rule>
 <from-view-id>/UserInformationView.jsp</from-view-id>
  <navigation-case>
   <from-outcome>success</from-outcome>
   <to-view-id>/UserInfoDetails.jsp</to-view-id>
  </navigation-case>
</navigation-rule>

JSF page design using drag and drop feature

JSF is a standard specification for building user interfaces. In this specification, drag and drop feature is also useful. In this feature, you can use existing beans for designing the web page. Through drag and drop feature, we can design our page very fast. For designing, we will use ‘page data’ option of RAD which will available in ‘web’ perspective.
First, you need to create a bean in which you can use two fields username and address. Codes for bean are,

public class UserInfo {
    private String userName;
    private String address;
    public String getAddress() { return address;     }
    public void setAddress(String address) { this.address = address; }
    public String getUserName() { return userName; }
    public void setUserName(String userName) { this.userName = userName;     }
}

Now, you will need to use Page Data (lower left portion of the RAD) option of RAD in ‘web’ perspective. You would need to create a new ‘Page Bean’ using existing bean named ‘UserInfo’. You can create new ‘Page Bean’ once you right click on ‘Page Bean’ option and come into New>Java Bean option and click on ‘Java Bean’ option. You can see the picture below,

You can see ‘Add JavaBean’ window where you can provide a new name (name starts with first lower case character) and add existing java-bean class. Also, if you want to make this bean class as managed bean, you can check the checkbox and select the scope of bean and press finish button.






Now, you need to drag the ‘userInfo’ Page Bean and drop it into cursor location of JSP page.













You will see ‘Insert JavaBean’ wizard in picture below. Here you will see java bean entries as input field of JSP page.









You can add submit button also using ‘options’ button. When you click on options button, you will get following window. Provide label name and press OK button.













You can see additional JSP code in picture below,













The preview of JSP page as,








In this way, we can implement drag and drop feature using java-bean classes. Apart from this, JSF provides lots of components in palette which you can drag and drop it in JSP file for designing your page vary efficiently. For each page, JSF automatically creates java-code which you can find in pagecode package.

JSF portlet application directory structure and required JAR files

You can see directory structure of basic JSF portlet application in picture below,
















In this diagram, you can see ‘src’ folder which contains all the source code and WebContent folder which contains the web pages and WEB-INF directory. In WEB-INF directory, we do have three required files these are,

1) faces-config.xml file
2) portlet.xml file
3) web.xml file

and we do have four required JAR files. These are,

1) icu4j_3_4_1.jar
2) jsf-ibm.jar
3) jsf-impl-messages.jar
4) jsf-portletbridge.jar

JSF portlet development using RAD 7.0

IBM RAD 7.0 provides integrated feature for developing JSF based portlets.
Through RAD, you can develop basic JSF portlet.
Let’s see, how can we develop JSF portlet using RAD 7.0? First you need to open the RAD 7.0 and come into File>New>Project option. You can see the picture below.

 While creating new project, please select portlet project option and press Next button.
 You will get ‘New Portlet Project’ wizard where you need to mention project name, portal server version, portlet API and portlet type. Press Next once you fill all the required information.

 Now you need to add portlet modes and press finish button and you will get a basic JSF portlet application with required JAR file and configuration files.


Wednesday, July 7, 2010

How portlet modes work in portal environment?

I have one JSR-168 based portlet in which I am using all kinds of modes. These are,

1) View Mode
2) Edit Mode
3) Help Mode
4) Edit-Default Mode
5) Config Mode

Now, I have one question in my mind. What is the use of these modes? If we take an example of any web-based application which is deployed on web container and this application does not have any kind of mode. Here I am going to describe a brief description of portlet modes which are helpful to understand the benefits of portlet application over web-based J2EE application.

View Mode -
This is the landing page of the portlet.

Edit Mode -
This is the different page of the portlet for storing personalized settings. These settings allowed for a particular instance of the portlet for particular portal user. If we make another instance of portlet in another page, personalized variable is not allowed to accessible.

Edit - Default Mode -
This is also different page of the portlet. We are using this mode for storing the configuration parameters of the portlet which are accessible for all portal users for the same portlet instances. For Example. An admin stores some parameters in edit-default mode of portlet and check the availability of these parameters in other portal users. These parameters are available for all portal users for a particular instance of the portlet suppose you add same portlet in different page, you will not allowed to see stored parameters for different instances of portlet.

Config Mode -
This is also different page of the portlet. We are using this mode for storing the configuration parameters of portlets which is accessible for all portal users for all portlet instances.

Now we have a big picture, how these modes are working in portal environment? We have tested this procedure for IBM Web Sphere portal server 6.0 using RAD 7.0 and JSR 168 specification.

Tuesday, June 29, 2010

JSF portlet example using datatable

This is also a good feature of JSF in which we are using datatable tag of JSF html tab library. You can find this tag on Palette portion. For implementing into webpage, you just need to drag this from palette and drop this in cursor position of webpage.

You will get the default code in webpage and there is no need to provide loop for table items. This tag manages all the list items according to the prototype provided by us.
Only one thing you need to keep in mind the value field in datatable tag which makes a call for perInfoAll method from syncExLoginManagedBean and the var field is the name of the table through which we can fetch the table items.
In datatable tag, facet tag provides the header of table and outputText provides the text value in data table.

<hx:dataTableEx border="0" cellpadding="2" cellspacing="0"
columnClasses="columnClass1" headerClass="headerClass"
footerClass="footerClass" rowClasses="rowClass1, rowClass2"
id="tableEx1" styleClass="dataTableEx" value="#{syncExLoginManagedBean.perInfoAll}" var="item">

<f:facet name="header">
<h:outputText value="This is 'SyncEx data Table' demo" />
</f:facet>
               
<hx:columnEx id="columnEx1">
<f:facet name="header">
<h:outputText id="text1" styleClass="outputText" value="ID"></h:outputText>
</f:facet>
<h:outputText value="#{item.id}"></h:outputText>
</hx:columnEx>
               
<hx:columnEx id="columnEx2">
<f:facet name="header">
<h:outputText id="text2" styleClass="outputText" value="Name"></h:outputText>
</f:facet>
<h:outputText value="#{item.name}"></h:outputText>
</hx:columnEx>
               
<hx:columnEx id="columnEx3">
<f:facet name="header">
<h:outputText id="text3" styleClass="outputText" value="Phone"></h:outputText>
</f:facet>
<h:outputText value="#{item.phone}"></h:outputText>
</hx:columnEx>
               
<hx:columnEx id="columnEx4">
<f:facet name="header">
<h:outputText id="text4" styleClass="outputText" value="City"></h:outputText>
</f:facet>
<h:outputText value="#{item.city}"></h:outputText>
</hx:columnEx>
               
<f:facet name="footer">
 <h:outputText value="The End" />
</f:facet>
</hx:dataTableEx>



JSF page script code using RAD quick edit feature

First you need to open the JSP page in design view and single click on ‘SAVE’ button. Thereafter, you need to select ‘Quick Edit’ tab (Lower middle portion of RAD) and then select required function which will execute when you click on SAVE button. Suppose you want to implement onclick function once you click on SAVE button so you need to select onclick once and then click on right portion where you can add the required code for onclick java script function.
















You can see the added code in JSP file

<script type="text/javascript">
function func_1(thisObj, thisEvent) {
//use 'thisObj' to refer directly to this component instead of keyword 'this'
//use 'thisEvent' to refer to the event generated instead of keyword 'event'
alert("hello");
}</script>

<hx:commandExButton id="button1" styleClass="commandExButton" type="submit" value="SAVE" action="#{pc_UserInformationView.doButton1Action}" onclick="return #{facesContext.externalContext.response.namespace}func_1(this, event);">
</hx:commandExButton>

Sunday, June 20, 2010

JSF tags reference

While developing JSF pages, we require a good understanding of JSF tags libraries. Mainly JSF provides two kind of tags library one is for core and second is for HTML.
Let's try to understand, how these two tags library has been used in JSF pages? You have to add the following lines in JSF pages,

JSF tag libraries-core
%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

JSF tag libraries-HTML
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

For understanding the core tags library in detail, you can go through the following link ,http://myfaces.apache.org/core20/myfaces-impl/tlddoc/f/tld-summary.html

For understanding the HTML tags library in detail, you can go through the following link
http://myfaces.apache.org/core20/myfaces-impl/tlddoc/h/tld-summary.html

In my searching I found some others links which are good to understand the basics of tags library. These are,

http://www.exadel.com/tutorial/jsf/jsftags-guide.html
http://www.roseindia.net/jsf/JSF_Core_Tag_Reference.shtml

Saturday, June 19, 2010

JSF inter portlet communication

Let me start with Inter portlet communication feature of portlets. Firstly, I will give you a brief idea about Inter portlet communication. This is not a new terminology. As web-developers who are using servlets, JSPs and portlets for development purpose. If they want to pass some parameters from one resource to another resource what they will do? In servlets, they can use RequestDispatcher to achieve this functionality and for portlets itself, they can use Inter portlet communication feature.

In portlets, Inter portlet communication can implement by following ways. 

1) Using portlet session in Application scope.
2) Using IBM's property broker services (portlet wiring).
3) Eventing using JSR -286 specifications.
4) Public render parameter using JSR-286 specification.

In this post, I will describe Inter portlet communication using portlet session (first point) and JSF eventing feature. You can see detail description of JSF portlet framework flow in one of our posts.
   I am taking an example of two portlets. First portlet is calculator portlet which contains two numbers and four submit buttons (for ADD, SUBTRACT, MULTIPLY and DIVIDE operations) and second portlet shows the result according to the operation performed by first portlet. You can see the whole picture of Inter portlet communication in the picture below,


















Now, you need to add portlet configuration for both portlets in portlet.xml file. You need to add init parameters which tell the JSF portlet about the render file (JSP file).

For SyncExCalculator portlet:
<init-param>
<name>com.ibm.faces.portlet.page.view</name>
<value>/SyncExCalculatorView.jsp</value>
</init-param>

For SyncExCalculatorResult portlet:
<init-param>
<name>com.ibm.faces.portlet.page.view</name>
<value>/SyncExCalculatorResultView.jsp</value>
</init-param>

 Now, both portlets are rendered successfully and call both JSPs which look as given picture below.
 

  We need to understand how the action is being created from SyncExCalculatorView.jsp (first portlet).

 <h:commandButton id="addsubmit" action="#{CalculatorController.add}" type="submit" value="ADD" />



Here, you can see the action which is for add() method of CalculatorController bean. Now we need to understand how JSF gets executed add method. When I click on ADD button of portlet, JSF portlet looks up the entry of the managed bean (CalculatorController) in faces-config.xml file.

<managed-bean>
<managed-bean-name>CalculatorController</managed-bean-name>
<managed-bean-class>com.yash.beans.CalculatorController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
Here, scope of bean is session which contains the bean in session scope.

In this way, JSF looks up the bean and calls add method of bean. In add method of bean we provide all business logics (perform logic for adding two numbers) and store the results in FacesContext using ApplicationMap. I am storing the result value in ApplicationMap since I need to use result value in other portlet. The code lines are,

FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getApplicationMap().put("result", new Integer(result));

The result has been saved in FacesContext. Now I have to retrieve the same result value in other portlet so what will I do? I will make another method which retrieves the result value from FacesContext. The code lines are,

FacesContext context = FacesContext.getCurrentInstance();
Map requestParams = context.getExternalContext().getApplicationMap();
result1 = ((Integer)requestParams.get("result")).intValue();

You can get the result value in JSP (SyncExCalculatorResultView.jsp) of another portlet as,

<h:outputText value="#{CalculatorController.result1}" />

This code of line does the same thing. This line makes a call for result1 method of CalculatorController bean and uses the same entry of managed bean which I have used earlier for first portlet.

This is the way, We can implement Inter portlet communication feature using Java Server Faces Specification. You can mail us on my mail id for source code.

Friday, June 18, 2010

Understanding Java Server Faces Portlet Workflow

For understanding the JSF portlet workflow, Let's start with portlet life cycle in which we are using two important methods. These are,
1) doView()
2) processAction()

When portlet renders first time, it calls doView() method of portlet life cycle. When we create any action (Click on link, submit button) processAction() method gets called, followed by doView() method. In doView() method, we usually include JSP which represents portlet's view. We perform these (portlet mode) operations on portlet class which includes in <portlet-class> tag under portlet.xml file. This class is modifiable.

In the same way, Java Server Faces specification also looks the portlet entry in <portlet-class> tag under portlet.xml file.

<portlet-class>com.ibm.faces.portlet.FacesPortlet</portlet-class>

Here, FacesPortlet is not allowed to modify the code. It contains all modes as I described in portlet life cycle and it understands all actions and JSP page includes in its own way. Here, I will describe you how JSF will do this.Firstly, I will let you know how JSF includes JSP on rendering phase of portlet. You have to include following lines in portlet.xml file.


<init-param>
<name>com.ibm.faces.portlet.page.view</name>
<value>/CalculatorPortletView.jsp</value>
</init-param>

JSF portlet class is much smarter which understands JSP file and includes in to render phase. We do not need to create an instance of RequestDispatcher and include the JSP file as we do in portlet life cycle.

Now, we need to understand, how action is handled by JSF? since we can not modify FacesPortlet class as we can do in portlet life cycle. This is also a very tricky approach which is done by JSF. When we click on any button or link in JSP page, JSF internally makes a call of processAction() method of portlet which finds managed bean class in faces-config.xml file and creates an instance of bean in different scope (request, session). You can understand this by following example,

Here, we are creating one action which executes when we click on submit button. It creates an action add which will get in CalculatorController managed bean .

<h:commandButton id="submit" action="#{CalculatorController.add}" value="ADD" />

The managed bean entry is present in faces-config.xml which creates a instance of CalculatorController bean and calls add() (event action called from JSP page) method in it.

<managed-bean>
<managed-bean-name>CalculatorController</managed-bean-name>
<managed-bean-class>com.yash.CalculatorController</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Now action created from JSP file executes completely. Thereafter, it looks up the navigation rule which provides the way for redirecting control to another JSP file or the same file. The codes for navigation rule are,

<navigation-rule>
<from-view-id>/CalculatorPortletView.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/result.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/CalculatorPortletView.jsp</to-view-id>
</navigation-case>
</navigation-rule>

This code represents source JSP file CalculatorPortletView.jsp (form-view-id) from where the action creates and according to the return statement of add method, it forwards the request to another JSP file.

Java Server Faces Page Lifecycle

This section discusses the various phases involved in a typical JSF page life cycle. JSF life cycle is expressed in the following phases:



Reconstruct Component Tree

This phase is initiated when a page request is submitted to the server (i.e a user clicks a submit button on a web page). During this phase the server creates a hierarchical tree of UI components which represent the elements constituting the page. The JSF engine parses this component tree and wires all the declared event handlers and validators to the specific components. All this information is finally persisted in a FacesContext. A faces context is nothing but a snapshot, an object tree representation of the incoming page. This information is utilized in the following phases until the response is rendered.

Apply Request Values

In this phase the JSF engine applies the values from the request object (parameters) to the respective components in the component tree (available from the current FacesContext) created in the previous phase. These values are stored locally in the UI components. In the event that conversion errors occur during storage of these values, they are queued up in the FacesContext, so they can be displayed when the content is finally rendered. If any event handlers were associated with specific components, they are notified of the relevant events.

Perform Validations

After the request values have been applied, the JSF page enters the validation phase, wherein all the registered validators are applied to relevant UI components. The locally stored values of these components are run through the associated validators and validation errors, if any, are queued in the FacesContext. If validation errors occur in this phase, the JSF engine skips the next two phases and the page enters the Render Response phase. The page is reconstructed from the component tree and displayed along with the validation errors and any errors or messages queued up in the FacesContext from the Apply Request Values phase. If no validation errors are detected, the page enters the Synchronize Model phase and any events generated at this point are broadcast to the interested event handlers.

Synchronize Model

In this phase any model objects associated with UI components are synchronized to the UI component's local value. If any conversion error occurs at this point, (e.g. a String value is mapped to an Integer property in a model object and cannot be parsed into an integer), the errors are queued in the FacesContext and the page enters the Render Response. The page is recreated from the component tree and rendered to the user displaying the conversion errors which occurred in this phase. Also any events generated at this point are broadcast to the interested event handlers.

Invoke Application Logic

After the model has been successfully synchronized, the page enters this phase. In this phase the JSF engine handles all application level events, such as linking to another page, performing updates to back end services, database updates, etc. When processing an application level event, a default ActionListener determines the outcome of the Action and passes the outcome to the NavigationHandler. The NavigationHandler then looks up the response to be generated from the navigation rule defined in the application configuration file, based on the outcome of the application logic, i.e. success or failure. The component tree for the next page to be generated is constructed and the page enters the final stage.

Render Response

In this phase the JSF engine renders the UI components in the component tree persisted in the FacesContext. If any errors or messages have been queued up from previous phases, they are rendered along with the page. This component tree is persisted so subsequent requests to this page can access it and it is readily available to the Reconstruct Component Tree phase.

Reference taken by: http://jnb.ociweb.com/jnb/jnbAug2003.html 

Thursday, June 17, 2010

Quick Understanding of Java Server Faces (JSF)

I would like to share my experience when I started work on JSF specification. I have development experience on portlets using JSR-168 and I tried to search technical notes which helps me to understand the JSF specification for portlet development. In my searching, I am not able to get any helpful technical note. Here, I am trying to describe all the things which I have learn t for JSF portlet development.

In this post, I will cover the basics of JSF and in other posts I will cover other features of JSF with examples.

Why we use JSF?

Before introducing Java Server Faces, developers who built web applications often relied on building HTML user interface components with portlets or servlets or Java Server Pages (JSP pages). This is mainly because HTML user interface components are the lowest common denominator that web browsers support. The implication, of course, is that such web applications do not have rich user interfaces, compared with standalone fat clients, and therefore less functionality and/or poor usability.

For years ago, Microsoft has evangelized the benefits of drag-and-drop support when advertising their Visual Basic product which provides quick and easy to build applications. JSF provides the same kind of development approach in multi-threaded environment.

What is JSF?

Java Server Faces (JSF) is a very powerful, component-based technology that is being led by Sun Microsystems as JSR 127 under the Java Community Process (JCP). JSF is a user interface (UI) framework for web-applications. JSF lets you build web applications that run on a Java server and render the user interface back to the client. This technology provides web application life cycle management through a controller, and a rich component model with event handling and component rendering. JSF provides standard specification for building User Interfaces for server side applications.

Java Server Faces technology is based on the Model View Controller (MVC) architecture for separating logic from presentation, so if you have been practicing this, you'll feel at home with JSF.

What are the benefits of JSF?

1) Benefits over Software vendors
Several software vendors have updated their toolkits to support JSF, promising rapid development and ease of use through drag-and-drop support when creating JSF-based web applications.

2) Benefits over rich user interface tools
There are a number of options out there today for building rich server-side user interfaces, such as Flash, Swinglets, and Jade. However, these solutions are proprietary; the tools and runtimes that support their development are usually only available through a single vendor. JSF is, above all, a standard, which means that the developer does not get locked into a single vendor.

3) Benefits over different components
Component Vendors provide reusable building blocks for application development and integration into JSF-based tools. Components cover a wide range of uses including reporting, charts and graphs, fields, and navigational components. Here are some of the vendors who offer components that support the Java Server Faces specification.

1) Otrix WebMenu
2) ILOG JViews
3) Quest Software JClass
4) Software FX Chart FX

4) Benefits at User level
Several types of users can benefit from this technology, including:
1) Page authors who use markup languages, such as HTML, will use the JSP tag library for expressing JavaServer Faces rich user interface components.
2) Application developers who write the model objects and event handlers.
3) Component developers who will create custom components based on the JSF components.
4) Tools vendors who will provide tools that incorporate JSF technology into a new generation of tools that simplify the development of multi tier web-based applications.
5) Application Server vendors who provide a runtime environment that incorporates JSF technology into a new generation of Application Servers that can deploy multi tier web-based applications that use JSF technology.

5) Integrated Ajax support
You can use jQuery, Dojo, or Ext-JS with servlets and JSP. However, JSF lets you use Ajax without explicit JavaScript programming and with very simple tags. Also, the Ajax calls know about the server-side business logic.

6) Form field conversion and validation
JSF has builtin capabilities for checking that form values are in the required format and for converting from strings to various other data types. If values are missing or in an improper format, the form can be automatically redisplayed with error messages and with the previously entered values maintained.

7) Centralized file-based configuration
Rather then hard-coding information into Java programs, many JSF values are represented in XML or property files. This loose coupling means that many changes can be made without modifying or recompiling Java code, and that wholesale changes can be made by editing a single file. This approach also lets Java and Web developers focus on their specific tasks without needing to know about the overall system layout.

This technology also opens up the market for reusable web user interface components. Developers and vendors can use JSF as the building blocks for developing custom faces.

Disadvantages of JSF

1) Bigger learning curve
To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet APIs. To use MVC with JSF, you have to be comfortable with the servlet API and a large and elaborate framework that is almost equal in size to the core system.

2) Similarly, if you have an existing app and want to add in some small amounts of Ajax functionality, it is moderately easy with jQuery (quite easy if you know JavaScript already). Switching your app to JSF 2.0 is a big investment.

3) Less transparent
With JSF applications, there is a lot more going on behind the scenes than with normal Java-based Web applications. As a result, JSF applications are:
1) Harder to understand
2) Harder to benchmark and optimize

4) Undeveloped tool support
There are many IDEs with strong support for standard servlet and JSP technology. JSF 2.0 is pretty new, and IDE support is weak as of 5/2010.

5) Much weaker automatic validation
Struts comes with validators for email address, credit card numbers, regular expressions, and more. JSF only comes with validators for missing values, length of input, and numbers in a given range.
You can use the Struts/Commons validation library with JSF, but still not as powerful as Struts.

6) Lack of client-side validation
Struts supports JavaScript-based form-field validation; JSF does not.

Monday, June 7, 2010

Event Handling in JSR - 286

As we all know about event handing. We perform some action on a source which is targeted to other source. When we talk about in an application, this task is very easy for us since we have certain methods through which we can pass data from one source to another source. In other way, you can pass your data from one source to another source of same application. Along with we talk about different applications (different WAR’s) which are running on same container. Can we pass data from one application to another application?

Yes, this is possible in JSR-286 where we can pass the data from one application to another application. In this process, we perform an action from one application which passes the data to another application.

There are some steps which describe how we can do it in Portlet applications. The steps are,

1) Let us take two portlet applications. Sender portlet application generates the event and receiver portlet application receives the event data from sender application.

2) Firstly, you need to add some configuration on portlet.xml file. What you need to do is you have to add event-definition information in sender application's portlet.xml file and receiver application's portlet.xml file. This is as,

<event-definition>
<qname xmlns:x="http://ndilip.com/events">x:ndilipevent</qname>
<value-type>java.lang.String</value-type>
</event-definition>

3) Now, you need to add 'supported-publishing-event' tag information under portlet tag of portlet.xml file for sender application. This is as,

<supported-publishing-event>
<qname xmlns:x="http://ndilip.com/events">x:ndilipevent</qname>
</supported-publishing-event>

These are the steps which are required in sender portlet application.

4) Now, you need to know, how to create event from sender application. The codes are,

QName qName = new QName("http://ndilip.com/events", "ndilipevent");
response.setEvent(qName, paramStr);

You have to add this code at processAction method.

5) Now you need to understand how you can handle this event on receiver portlet application.

6) You need to add 'supported-processing-event' tag information under portlet tag of portlet.xml file for receiver application. This is as,

<supported-processing-event>
<qname xmlns:x="http://ndilip.com/events">x:ndilipevent</qname>
</supported-processing-event>

7) Now, you need to know how you can utilize the event which is created by sender portlet application. You have to add processEvent method which handles the event created by sender. The codes are,

public void processEvent(EventRequest request, EventResponse response) {
Event event = request.getEvent();
String value = (String) event.getValue();
String valueString=value.toString();
}

valueString is the event string value comes from sender application.

Thursday, June 3, 2010

Inner classes in java

Inner classes are nested with in classes. Inner classes come in 4 flavors,

1) Static member classes
2) Member classes
3) Local classes
4) Anonymous classes

Let us take a quick look on these,

a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Like a static member class, a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

an anonymous class is a local class that has no name.

Synchronization in Java

Synchronization keyword is very useful while working with web-application on multithreaded environment.

Let us take an example of bank account where lots of transaction occurred simultaneously. Suppose you are having Rs.10000 in your bank account and you withdraw Rs.1000 and in the same time you are getting some interest of money Rs.600 and your cheque has debited of Rs.9100 from your account.

There are 3 transactions (threads),

1) T1 --> withdraw Rs.1000
2) T2 --> Interest Rs.600
2) T3 --> cheque debited Rs.9100


In these scenario, how do you know the latest value of bank account. If you want correct value of your bank account, you need to make the account value synchronized. In synchronization, each transaction makes a lock. When any transaction makes a lock, other transactions wait until the lock has been released.

Now we want to explore something more on synchronization keyword. What are the cases when one synchronization block will wait for other block and when one synchronization block will not wait for other synchronized block?

In this case you can go through the following link,
http://www.herongyang.com/java/Synchronization-Support-in-Java-synchronized.html