Wednesday, April 4, 2012

Injection in JSF

Injection in JSF:

The dependent managed bean can be injected in to the managed bean using the @ManagedBean property annotation in JSF2

Say for example TestBean is holding a property of type DepartmentBean, the bean shall be injected to the TestBean as below.

@ManagedBean
@RequestScoped
public class TestBean {

   @ManagedProperty(value="5")
    private int id;

   @NotNull(message="Name cannot be blank")
    private String name;

   @ManagedProperty(value="#{departmentBean}")
   private DepartmentBean deptBean;

   public DepartmentBean getDepartmentBean() {

     return deptBean;
   }


   public void setDepartmentBean(DepartmentBean deptBean) {
     this.deptBean= deptBean;
  }

   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

 }


@ManagedBean
@RequestScoped
public class DepartmentBean {


   @ManagedProperty(value="admin")
   public String dept;

   public String getDept() {
     return dept;
   }

   public void setDept(String dept) {
     this.dept = dept;
 }
}

In the above example you could notice the managed bean injection performed using the @ManagedProperty annotation and also EL is been used to refer the dependent bean (#{departmentBean}. You could also notice there is no name attribute is been used in both the managed beans and hence the default value is been assigned with the naming conventions.
 
The same can be done in JSF1.2 using the faces Config xml configuration

<managed-bean>

    <managed-bean-name>testBean</managed-bean-name>
    <managed-bean-class>com.test.TestBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
         <property-name>deptBean</property-name>
         <value>#{departmentBean}</value>
     </managed-property>
</managed-bean>


<managed-bean>
    <managed-bean-name>departmentBean</managed-bean-name>
    <managed-bean-class>com.test.DepartmentBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
<managed-bean>



JSF Request Processing Lifecycle

JSF Request Processing Lifecycle:

JSF has six phases in its life cycle and below is the overview of each phase.


1. Restore View: Restores or creates a server-side component tree to represent the UI information from a client
2. Apply Request Value: Updates the server side components with request parameters from client
3. Process Validation: Performs validation and data type conversion
4. Update Model: Updates the model(bean) with the data
5. Invoke Application: Invokes application logic and performs navigation processing
6. Render response: Renders the response to the client.

Restore View


1. Restores the existing view from previous transaction or creates a new view.
2. Created view is placed in the container object known as FacesContext
3. FacesContext contains all the data pertaining to the current request that runs through the request processing life cycle.

Apply Request Value

1. Updates the server side components with request parameters from client
2. JSF runtime calls the processDecodes() on View
3. Subsequently all the processDecodes() on all components are called
4. This decodes the incoming name-value pairs and apply the value to the component.

Process Validation

1. Conversion and validation is performed on the components.
2. JSF Runtime calls processValidators() method on the View Root.
3. Propagation to processValidators() method is called on each components.
4. Data conversion happens before the validation in the same phase.
5. Any component failing conversion or validation

Update Model Values

1. Once the validation and conversion is performed with out any errors, values are now updated to the model bean.
2. JSF Runtime calls processUpdates() method on the View Root.
3. Propagation to processUpdates() method is called on each components.

Invoke Application

1. Invokes application logic and performs navigation processing
2. Any action method or action listener method is invoked.

Render Response

1. As in other phases, components encodeXX() methods are called on each component.
2. The rendered mark up language can be anything, such as HTML, WML, XML etc.,
-------------------------------------------------------------------------------------------------------------

Below are the example on request processing for few scenarios

Scenario -1: Initial Request to view register.jsf

1. User submits a request to the URL of the register page
2. The request is processes by the Faces Controller Servlet, which creates a FacesContext instance for this request and initiates a call to the lifecycle.
3. Since it’s a first request, the restore view phase will create an empty view and stores it to the FacesContext instance.
4. After view is created, since it is not a post back request , after the restore view phase, render response phase will be called for.
5. The state of the view will be stored for the future request.

Scenario-2: User Enters invalid data (Assume user does not enter data for the mandatory field)


1. User doesn’t enter the mandatory data and enters submit
2. The request is processes by the Faces Controller Servlet, which creates a FacesContext instance for this request and initiates a call to the lifecycle.
3. Since it’s a post back request, the restore view phase will retrieve the earlier created view and stores it to the FacesContext instance.
4. In the Apply Request value phase, the request parameters are processed and stored in the component tree
5. In the process Validation phase, a validation error occurs as the value was not entered for the mandatory field and the error message is added to the FacesContext.
6. Now other phase is skipped as the validation error occurred and directly goes to the last Render Response phase where the components are rendered as HTML.

Scenario-3: User Enters data valid data and submits again


1. The request is processes by the Faces Controller Servlet, which creates a FacesContext instance for this request and initiates a call to the lifecycle.
2. Since it’s a post back request, the restore view phase will retrieve the earlier created view and stores it to the FacesContext instance.
3. In the Apply Request value phase, the request parameters are processed and stored in the component tree
4. In the transition to Process Validation phase, conversion happens and since no validation occurs, the transition happens to the next phase
5. In the Update Model phase, now the values are updated to the model bean and then the action method is called in the Invoke Application phase.
6. The return string of the action method is being used by Navigation processor for deciding the next page to be rendered and the view root of the page is rendered in the Render Response phase.





Initializing Managed Bean Property

Initializing the MangedBean property:
Managed beans shall be initialized on the object creation and this shall be performed using configuration in Faces Config xml in JSF1.2 and using annotations in JSF2.0
Initializing a property in JSF1.2:

<managed-bean>

                      <managed-bean-name>testBean</managed-bean-name>
                      <managed-bean-class>com.test.TestBean</managed-bean-class>
                      <managed-bean-scope>session</managed-bean-scope>
                      <managed-property>
                                 <property-name>name</property-name>
                                <property-class>java.lang.String</property-class>
                                <value>Enter the Name</value>
                      </managed-property>

               </managed-bean>

Initializing the same in JSF2.0: Take a look at the annotation @ManagedProperty introduced in JSF2.0 and the value attribute holds the default value to be initialized.

@ManagedBean

@RequestScoped
public class TestBean {

  @ManagedProperty(value="Enter the Name")
   private String name;
   /**
     * @param name the name to set
     */
    public void setName(String name) {
          this.name = name;
     }
   
    /**
     * @return the name
     */
     public String getName() {
         return name;
    }

-----------------------------------------------



JSF Managed Bean

MangedBean in JSF:

Managed Beans are the mere POJO that represents model of the JSF application and are managed by the JSF container. Managed Beans are to be registered in the JSF container through Faces Config xml in JSF1.2 and via annotations in JSF2.0 onwards. By registering it in annotation entry in the faces Config can be avoided. But still one can register managed bean in Faces Config without using annotations in JSF2.0. The criteria for managed bean are same as java bean conventions.

Registering a managed bean in Faces Config (JSF 1.2) :

<managed-bean>
                           <managed-bean-name>testBean</managed-bean-name>
                           <managed-bean-class>com.test.TestBean</managed-bean-class>
                           <managed-bean-scope>session</managed-bean-scope>
              </managed-bean>

Sample Managed Bean:

               public class TestBean {

                       private int id;
                       Private String name;

                      /** Getters and setters for Properties **/
                     
                 }


Registering in JSF2.0 :

@ManagedBean

              @RequestScoped
              public class TestBean {
              -------------------
             ---------------------------

Binding Managed Bean in XHTML:
               <h:inputText value="#{testBean.name}"></h:inputText>


Tuesday, April 3, 2012

Features in JSF2.0

New Features in JSF2.0


JSF2.0 has introduced many new features in align with its design goals. Few of the major new features are listed below.

 1. Avoid entries to Faces-Config.xml with annotations. There are new annotations added in JSF2 for declaring managed beans, scopes for managed bean. Few annotations are listed below
    • @javax.faces.bean.ManagedBean
    • @javax.faces.bean.RequestScoped
    • @javax.faces.bean.SessionScoped
    • @javax.faces.bean.ApplicationScoped
    • @javax.faces.bean.ViewScoped
    • @javax.faces.bean.NoneScoped
    • @javax.faces.validator.FacesValidator
    • @javax.faces.convert.FacesConverter  
2. Bean names are assigned with default if not explicitly stated in the @ManagedBean annotation with name attribute. In the below code, the ManagedBean annotation is not explicitly named and hence the managedbean name shall be defaulted with testBean (javaBean naming convention) 
                         @ManagedBean
                         @RequestScoped
                         public class TestBean {--------
                          -------------------------------------- 
3. Facelets are the default view technology for the JSF from JSF2.0 and JSP view technology for JSF is deprecated from JSF2.0. Facelets provides a powerful Templating for the application
4. Creating a custom component is made much easier in JSF2.0 compared to its earlier version and JSF2 brings in an enhanced resource handling

5. JSF has support to Groovy and hence all the managed bean, validators, converters, renderers shall be a based on groovy

6. Default Navigation mappings using the result of the action method. The page navigation shall be defaulted using the result of the action method. In the below piece of action method, the next page is defaulted to welcome.xhtml. By this way the navigation configuration in the Faces xml shall be avoided 

 /* * on the call of this action method, the user name is placed in the flash scope
   * and redirected to the new page.
   * @return welcome page string
   */
    public String save() {
         Flash flash=FacesContext.getCurrentInstance().getExternalContext().getFlash();
         flash.put("name",this.name);
         return "welcome";
     }

7. Ajax is enabled in JSF2.0 architecture and thus it is not necessary to depend on third party API for ajax features. Ajax shall be used using the f:ajax tag.

       <h:commandButton action="#{testBean.save}" value="submit">
                  <f:ajax execute="@form" render="@displayPanel" event="click"/>
       </h:commandButton>

8. Creating a custom component is made much easier in JSF2.0 compared to its earlier version and JSF2 brings in an enhanced resource handling.

9. JSF has support to Groovy and hence all the managed bean, validators, converters, renderers shall be a based on groovy

            

Monday, April 2, 2012

New Scopes in JSF2.x


New Scopes in JSF2.x

In JSF2, beans can defined in two additional scopes apart from the existing scopes (request, session and application scope). Those are View Scope and Flash Scope

ViewScope:
  1. Defining a bean in view scope: Bean can be defined in view scope using the annotation @ViewScoped (javax.faces.bean.ViewScoped). Beans can be defined through annotations from JSF2 and is not required to define in the faces-config.xml file.

  2. Beans of viewscope shall be alive till the current view (page) is active. That is the bean shall be alive till the user interacts with the same page and doesn’t navigate to new view (page).

  3. The scope of viewscope is higher than the request and less to session scope.

  4. If the same page is returned in the action method, the bean shall be dead and shall not be retained in view scope, since the same view is recreated again.

FlashScope:
  1. The object placed in the flash scope shall be retained till the next request cycle. Thereafter it is destroyed. It is handy and most commonly used for post-redirect-get cycle where the messages need to be transferred to the request on a redirect

  2. Placing object in a FlashScope: (in the below example also note the redirection done using the the attribute “faces-redirect=true”
  3. public String save() {
    Flash flash=FacesContext.getCurrentInstance().getExternalContext().getFlash();
    flash.put("name",this.name);
    return "welcome?faces-redirect=true";
    }

  4. The flash scoped objects shall accessed using the EL object flash.
    <h:outputLabel value="Hi #{flash.name}"</h:outputLabel>


Sunday, February 27, 2011

Robin Sharma speech at chennai

Recently I had an opportunity to listen the Robin Sharma’s speech. I had read couple of his book and the way he portrays the leadership value through story has made me to get through his work. Below are few notes from his speech,

Leadership is all about

1. Impact, Influence and Inspiration
2. What do we do when no one is watching
3. Way I do one thing is way I do everything
4. Double the income, triple the learning
5. Behavior broadcast the values
6. Become a rock star at work
7. Lead yourself first
8. Take care of relationship and money takes care of itself

The points seem to be more of the one that we would have heard through all the time from different people. But when it was put through with strong examples, by a proven person it really gets into our mind. Is this what he was referring to creation of impact and influence? In that case he seems to be leader for himself for keeping his words through his work.

He then spoke about few key points which the successive people have been following

1. Get Up Early and do some workouts and readings
2. No excuses.
3. Don’t check email in the morning
4. Learn to say “No” with respect
5. No gossips, No critcs, No Negative
6. Understand clarity provides mastery
7. Eat less
8. Super hydrate
9. Take an hour nap
10. Aware of environments
11. Understand you become your association


I felt the above words were really useful as I failed in most of them. Atleast I knew these were important. There were few tactics that he put across which seems to be useful

1. Avoid radio star syndrome and be authentic
2. You are in show business, Practice before stage
3. Win is the motivation + momentum
4. Distraction is enemy of production
5. Technology free period and solitude work
6. Leave your ego at the door and give what you can
7. Develop leadership language
8. Launce a beta and then iterate daily
9. Be inspirational.

Hmmm above were few of what I took notes. It was like cyclone of thoughts and words that were put across the mind. Sure it will have impact only if those words were categorically put in to actions. Finally got an opportunity to take a snap and autograph with him. Seems to be little childish when self and friend were eager to get a snap and autograph. But everyone present there were professionals and everyone were crazy.