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"