Friday, December 7, 2012

Cool Feature of Java 6- JSR 223 & JSR 199


JSR 223- Scripting for the Java Platform

   Java introduced the support for scripting languages for java platform from Java- 6.

  1.  JSR 223 - Scripting for the Java Platform helps developers integrate the standard java code with the scripting language by a standard framework and API. With this API we can
    1. Access and control Java objects from a scripting environment
    2. Create web content with scripting languages
    3. Embed scripting environments within Java based applications
  1. Java 6 by default ships Javascript Engine Implementation called Rhino provided by the Mozilla
  2. New scripting engines that compliance JSR 223 can be plugged in to avail the feature. So now the Python, Ruby scripting advantages can also be availed.
  3.  With this new API, now the power of scripting can be availed from the java.

Example: In the below piece of code, a javascript function called printName(name) is evaluated from java and the argument is passed is the java object.
public static void main(String[] args) {
            // create Script-Engine-Manager object
            ScriptEngineManager factory = new ScriptEngineManager();
            // Get Script Engine from factory
            ScriptEngine engine = factory.getEngineByName("js");

            // Create binding variable to pass value to script
            Bindings bindings = engine.createBindings();
            bindings.put("name", "JAS Technologies");

            // evaluate JavaScript code from String
            try {
                  engine.eval("printName(name);" +
                                    "function printName(name){" +
                                          "print(name+' company');" +
                                    "};",
                              bindings);

            } catch (ScriptException e) {
                  e.printStackTrace();
            }
      }



JSR 199 – java Compiler API

1.       One of the cool features introduced in java 6 is to compile the java source file dynamically.
2.       As a part of JSR 199-JavaTM Compiler API, there is a standard java Compiler API which defines the interfaces for java compiler functions and a standard service provider framework by which vendor can provide implementation for the interfaces.
3.       The API for compilation is now available part of javax.tool package and ships with Java 6
4.       So having said above what a developer can do with this is
a.       Dynamically compile java source file
b.      Can compile multiple files
c.       Can compile a java source from a string object
d.      Also several advanced options are also available. Check the API for complete details.
  Below is the small example for compiling the java source file dynamically

      public static void main(String[] args) {
            //File to be compiled
            String fileName = "D:/jas/workspace/com/test/compile/CompileMe.java";
            //Get the java compiler
            JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
            //Compile the java file. Look at the API to find more on options
            int returnVal = javaCompiler.run(null, null, null, fileName);
      }

   Content from CompileMe.java used in the above example

package com.test.compile;

public class CompileMe {
      public static void main(String[] args) {
            System.out.println("The JAS Technologies");
      }
}

Brief on JVM Heap Memory


let’s take a look at how the JVM organizes memory into different areas. This has been helping several garbage collection algorithms and memory management to work efficiently. These areas are called Generations which are categorized based on the life of the objects.

1.       There are separate pools that hold objects of different age. They are
a.       Young Generation
b.      Old Generation
c.       Permanent Generation

2.       Young Generation:
a.       Most of the objects are initially placed in the young generation space.
b.      Young Generation Garbage collection occurs frequently and operates at high speed since the young generation space contains lots of objects that are less referenced.
c.       In Java HotSpot VM, Young Generation again categorized into
                                                               i.      Eden Space : Most objects are initially allocated in the Eden space
                                                             ii.      Survivor Space: Objects that survive atleast one young garbage collection is moved to survivor space.

3.       Old Generation:
a.       Objects that survived Garbage Collection (From Survivor Space) are tenured or Promoted to the Old Generation
b.      Garbage Collection algorithm that works on this space is designed to be more space efficient since Old generation occupies most of the heap.

4.       Permanent Generation (PermGen) :
a.       Permanent Generation usually contains the objects that describe classes & methods and also classes & methods.




Handling the comment block in Facelets/JSF2



Even if the block of code is commented using the HTML comment (<!--     -->) the JSF lifecycle still process the part of code and it is rendered in the HTML source although the component is not rendered in the HTML page. This shall be viewed in the browser source view option. This reveals the sensitive information to the third party which is not intended to be known.

Example:

In the below piece of code, a part of the code is commented using HTML based comment (<!-- -->)




Even though the Browser doesn’t render the component in the browser, still the code in the HTML contains this piece of information. And also JSF processes this component.

HTML Source viewed from the Browser.












Possible solutions:
1.      
      Configure web.xml to inform Facelets to skip comment.
<context-param>
    <param-name>facelets.SKIP_COMMENTS</param-name>
    <param-value>true</param-value>
</context-param>

2.       Use Facelets ui:remove tag to comment the code block. 

Friday, April 13, 2012

My Quotes

Character:

It might take years to build a character; but requires lots of character to keep up for ever

Its Insane behavior of few people make me feel i am still sane

Fear tolls my head; but confidence pulls it out;
Anger thrashes my heart; but peace pushing it out;
Violence tries to take over; but character fighting it out.

Two things we can't teach people is Love and Friendship

Just learnt we cannot be perfect to all,,,But that does not mean we are not perfect

Why do my mirror always shows me slim. (always I justify what I feel even if its not)

Forgive people who hurts u; but forgive not who misleads u

Trust:

if u build trust, it is stronger than Tajmahal;if u break trust it is worse than tsunami

Hope:

Miles to go before i go to sleep
lost my smiles in travel to destiny
searching for a while to rest in peace
got hostile in this world of disharmony
waiting for a shoulder to pass through turnstile

At times words doesnot turn to action
At times action doesnot yield success
At times success doesnot bring happiness
At times happiness doesnot last long
But all times we shouldnot loose hope

Millions of heart starts playing the band
Thousands of prayers across the land
Eleven crusaders touches the sand
They Bat to win the battle
And bowl to win the hearts
----Hope India brings the cup

Its not the rising sun that made this day different;
Neither its not the beauty of moon that made difference;
But the hope of better tomorrow made it 
Wish u a very Happy New Year

The decisions in the life could be debated but not the life itself

Music

Music makes the mind listen to heart :)

Problems:

Few problems are like windows!!!!!the only solution is CTRL+ALT+DEL

Gift:

When we are kid, Parents are the best gift
When we are teen, friends are the best gift
When we grow up, partner is the best gift
When we bcm old, kids are the best gift
But do remember at any point,
 you are one of the best gift for someone and always spl!!!!

Loneliness:

Just realised loneliness is not caused by others but when my thoughts left wandering for others

When you feel missing yourself is because you miss someone

When you come to know the smile is not for you and tears are not on you,  it's not all of you

Time:

People say time is a healer but you know what -  time is in fact a hoax

It's not the memory it's indeed the moments define life

Even the unseen air can make you feel its presence and keeps you alive

One can't live in two places, we either live in the present or live in thoughts

When someone steals your time, it means someone has lost something

Meaning:

ஒவ்வொà®°ு கண்ணீà®°் துளிக்குà®®் à®…à®°்தமுண்டு ஆனால்
சில ஆழுந்த à®…à®°்ததுக்கோ எந்த
சுவடுà®®் இல்லை.

தனிà®®ையில், ஆழ் கடலிலுà®®் à®®ீன் பிடிக்கலாà®®்


Sunday, April 8, 2012

My First application of JSF2.0 with CDI



In this specific tutorial will list the steps of JSF2.0 that uses CDI. Used Jboss 6.1 application server which ships with the CDI implementation - Weld.

Step1:  We shall create a JSF page that shall  have 3 input text and bind to a managed bean.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">


<ui:composition>
  <h:body>
     <h:form>
<h:inputText value="#{employeeBean.name}"></h:inputText>
<h:inputTextarea value="#{employeeBean.id}"></h:inputTextarea>
<h:inputTextarea value="#{employeeBean.departmentBean.department}"></h:inputTextarea>
<h:commandButton value="submit" action="#{employeeBean.submit}"></h:commandButton>
     </h:form>
   </h:body>
</ui:composition>
</html>


Step2:  Now lets create a managed bean “EmployeeBean” and “DepartmentBean” which shall be a CDI managed java bean. You could notice there are new annotations @javax.enterprise.context.RequestScoped, @Dependent, @Named, @inject


package com.test;


import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;


@RequestScoped
@Named
public class EmployeeBean {
private String name;
private int id;

@Inject
private DepartmentBean departmentBean;


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String submit(){
System.out.println("submit action called");
return "welcome";
}
public DepartmentBean getDepartmentBean() {
return departmentBean;
}
public void setDepartmentBean(DepartmentBean departmentBean) {
this.departmentBean = departmentBean;
}
}

Now lets take a look at the use of these new annotations:

@ javax.enterprise.context.RequestScoped: A typical web request scope. There are new scopes added apart from the typical (request, session, application) such as @conversationScoped, @Dependent. Shall cover the new scopes in a separate post.

@Named: This annotation lets the managed beans to be accessed through EL.  If there is no value attribute been used then default value is been assigned according to the naming convention. In this case it is “employeeBean”

@Dependent: you could note yet another new scoped bean called @Dependent which is also a default scope if none specified and will serve exactly one client (bean) and has the same life cycle of the client (bean).

@inject:  This annotation is used to inject one bean in to the other. In this example you could see the dependent scope departmentBean is injected to the request scoped employeeBean.



package com.test;

import javax.enterprise.context.Dependent;

@Dependent
public class DepartmentBean {
private String department;

public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}


Step3:  Now lets create a simple new page where the values got from the user are being displayed.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html">

<h:body>
<h:form>
<h:outputText value="#{employeeBean.name}"/>
<h:outputText value="#{employeeBean.id}"/>
<h:outputText value="#{employeeBean.departmentBean.department}"/>
<h:commandButton value="back" action="Test?faces-redirect=true"></h:commandButton>
</h:form>
</h:body>
</html>

Step4: Apart from annotations you could have noticed there is nothing much difference in this application for CDI. The last small step is the addition of beans.xml. This xml is must required even if there is no configurations to be made. This shall allow the app server (jboss here) to use the CDI implementation (weld) to scan through for CDI beans and provide services.

This xml is to be placed in the web-inf folder.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:weld="http://jboss.org/schema/weld/beans" 
       xsi:schemaLocation="
          http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd
          http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd">
 </beans>

Now deploy the application in App server(jboss)







Troubleshoot – JSF 2 (Mojarro – JSF-2.0.3)

Troubleshoot – JSF 2 (Mojarro – JSF-2.0.3)


Next in the troubleshoot series is the dumb illegal argument exception on request of a jsf page. This specific problem seems to be a bug in the Mojarro implementation where it swallows the specific exception caused because of simple mistakes in the xhtml pages.


1:30:17,375 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/TestJSF2].[Faces Servlet]] Servlet.service() for servlet Faces Servlet threw exception: java.lang.IllegalArgumentException: null source
at java.util.EventObject.(Unknown Source) [:1.6.0_23]
at javax.faces.event.SystemEvent.(SystemEvent.java:67) [:2.0.3-]
at javax.faces.event.ComponentSystemEvent.(ComponentSystemEvent.java:69) [:2.0.3-]
at javax.faces.event.PostRestoreStateEvent.(PostRestoreStateEvent.java:69) [:2.0.3-]
at com.sun.faces.lifecycle.RestoreViewPhase.deliverPostRestoreStateEvent(RestoreViewPhase.java:256


The problem that might caused this exception would be because of a simple error in the xhtml page like missing tag or xml not well formed etc., Facelets is expected to throw exception with detailed message but the exception is swallowed. The issue seems to be still in open

http://java.net/jira/browse/JAVASERVERFACES-1758



Saturday, April 7, 2012

Troubleshoot-Jboss 6.1and Eclipse Indigo

Troubleshoot-Jboss 6.1and Eclipse Indigo


Jboss 6.1 doesnot start without any error or log in Eclipse Helios


Server: jboss 6.1-Final
Eclipse Version: Helios and Indigo

When jboss 6.1 was started from Eclipse Helios or Indigo without jboss tools plug-in, the server doesn’t start without any error or log. The problem seems to be jboss 6.1 expects a vm argument on logging.properties.

When the logging.properties is set in vm arguments, the server started without any problem.

In Eclipse, go to server tab, Click on server and then Arguments, in VM arguments section provide the below entry

-Dlogging.configuration=file:"\bin\logging.properties" 








Troubleshoot-Jboss 6.1and Eclipse Indigo

Troubleshoot-Jboss 6.1and Eclipse Indigo


Server: Jboss 6.1-Final
Eclipse Version: Helios and Indigo

When the jboss 6.1-Final is started in Eclipse Helios and above, the below error was thrown. There seems to be problem with plug-in.

Deployment "PostEjbJarMetadataDeployer" is in error due to the following reason(s): java.lang.NoSuchMethodError: javax.annotation.Resource.lookup()Ljava/lang/String;



By providing the below configuration in the vm argument, the problem is resolved.
In Eclipse, go to server tab, Click on server and then Arguments, in VM arguments section provide the below entry

-Djava.endorsed.dirs=\lib\endorsed


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