JVM Language Storm

January 24, 2008

I’ve been following a bit the JVM languages that are struggling for pole position in the blogosphere of late. And the more time passes the more I’m convinced that the JVM is here to stay, even if folks might not be too happy about the Java language itself.

The stability of the JVM as well as the number of different technologies and APIs that it has evolved has made it a good breeding ground for languages that haven’t had the wide level of adoption as Java. Now with a greater push to support languages like Ruby (JRuby), Python (Jython) and totally new ones like Groovy and Scala, developers can still eat their cake and have it. There are even comments that JRuby is even faster than native Ruby, taking away the JVM startup time. And NetBeans is fast becoming the IDE for Ruby development. Support for other languages is being worked on aggressively in the IDE.

The focus on stability and platform independence is now reaping off for Sun Microsystems, and I’m happily exploring my options of getting on the bandwagon of new static and non-statically typed languages. The ability to still use all these language features as well as plugin to the technologies that Java and JVM already provide is very enticing.

Scala I must say looks very advanced and promising. A friend of mine said that sometimes exploring the language frightens him a bit because of the level of new, advanced and easy to use language features which are far from being just syntactic sugar. Scala is a statically typed language like Java, but it’s feature set is amazingly richer than Java’s. It is 100% compatible with Java. There’s a lot of noise on the blogosphere if Scala might not become the next flagship language for the JVM if Sun decides to move on from Java. Whichever they finally decide to choose, it will only be further to the advantage of the Java ecosystem.

The Scala support in IDEs is not as advanced as other languages like JRuby and Groovy. Here you’ll find a plugin for Groovy development in NetBeans. I’ve tried writing a few scripts with Groovy to get my feet wet and I’m beginning to enjoy it. This is basically because Groovy is so much like Java and the learning curve is not as steep. That is good for me, who hasn’t tried Ruby or Python before. My only issue is that IDE the support has not yet gotten to the point where I can productively use it in a project. However, I’m yet to explore the Eclipse support for it. Might be more advanced.

Proposals for JDK 7 include easy integration between Java and other JVM languages at JVM level. All the better I’d say. Fingers crossed, the JVM isn’t dieing anytime soon. It’s only getting better because unlike companies like Microsoft who just focus on doing things to please developers and gain market shares, Sun Microsystems takes it time to think throught the implications of it’s technology decisions, knowing that the future is what will vindicate it.


Update on JDK 6 update 4 and NetBeans 6.0 on Fedora 8

January 24, 2008

It turns out the problem with NetbBeans 6.0 not rendering well when desktop effects are enabled in Fedora 8 has been solved at the JDK level. Just upgrade to JDK 6 update 4 from Sun. Now my NetBeans will enjoy being wobbled about.

Oh and i just discovered JavaDB (or more popularly Derby) is bundled with JDK 6. Didn’t quite notice its existence. And with the latest JDK it comes with documentation on how to use it in your apps. This is good for simple applications that need to bundle some small database to work with. Congrats to Sun.


Using @RequestParameter and @Observer events model in Seam

January 24, 2008

<Simple DataTable Example | Seam on Tomcat >

One good thing that Seam adds to JSF is the ability to use GET requests to retrieve data. The JSF spec decided to make every request a post, and this makes it difficult to bookmark pages or fetch pages directly from entering a url along with some parameters.

Well see how this problem is solved in Seam using a simple annotation: @RequestParameter. This annotation allows us to pass a request parameter to our Seam component. Its value is injected before any method is called, guaranteeing us that the request paremeter will be available to us to make use of in our code. A look at our previous example shows us that departmens belong to specific faculties. This means we will need to pass the particular faculty whose departments we want to see on our departmentList.xhtml page displaying departments. Here’s the code that does it in our departmentListing Seam component:

@Stateful

@Name(“departmentListing”)

@Scope(ScopeType.SESSION)

public class DepartmentListBean implements DepartmentList {

@PersistenceContext(type=PersistenceContextType.EXTENDED)

EntityManager em;

@DataModel

List<Department> departments;

@DataModelSelection

private Department department;

@In FacesMessages facesMessages;

@RequestParameter

Integer facId;

@Out(required=false,scope=ScopeType.SESSION)

Faculty faculty;

@Factory(“departments”)

@Observer(“univseam.event.DepartmentChanged”)

public void departmentList() {

//select if a faculty id has been passed to us

if(facId != null){

try {

faculty = (Faculty) em.createQuery(“Select f from Faculty f where f.id=:id”).

setParameter(“id”, facId).getSingleResult();

} catch (NoResultException exception) {

facesMessages.add(“Non-existent faculty passed!”);

return;

}

}

//if the faculty is not null then select its departments

if (faculty != null) {

departments = em.createQuery(“Select d from Department d where d.faculty=:faculty”).

setParameter(“faculty”, faculty).getResultList();

return;

}

facesMessages.add(“No departments under this faculty yet”);

}

Our list of departments is as shown below.

old dept list

The “facId” is a request parameter passed from the page displaying the list of faculties. The method departmentList() is annotated with @Factory(“departments”), which forces Seam to load up the list of departments into the “departments” ArrayList. Seam guarantees that the faculty id will be properly converted to an Integer and placed in the facId variable before we initialize our list of departments, enabling us to first select the particular faculty and pass it to the query to load the departments. Outjecting the faculty object to the Session context is necessary to this discuss and we’ll see why soon.

But how was the request parameter passed? Well, the simple <f:param> tag in JSF allows use to do that. Take a look at this portion of the facultyList.xhtml facelet.

<h:column>

<f:facet name=”header”>Action</f:facet>

<s:link value=”Departments” view=”/departmentList.xhtml”>

<f:param name=”facId” value=”#{faculty.id}”/>

</s:link>

</h:column>

With the use of an <s:link> we are able to append the faculty id to our URL under the name facId and seam binds to that name using the RequestParameter.

Not only is RequestParemeter useful in searching, but can also be very helpful in determining if an entity is being edited or a new one being created. Here we are with a list of departments. We want to use the same page to edit as we do for new department creation. RequestParameter to the rescue.

@Stateful

@Name(“departmentManager”)

public class DepartmentManagerBean implements DepartmentManager {

@In

EntityManager entityManager;

@In

FacesMessages facesMessages;

@In

Faculty faculty;

@Out(required=false)

private Department department;

@RequestParameter(“depId”)

Integer depId;

public void createDepartment() {

//if the department already exists, then allow an edit

if(depId != null){

try {

this.department = (Department) entityManager.createQuery(“Select d from Department d where d.id=:id”).setParameter(“id”, depId).getSingleResult();

} catch (NoResultException noResultException) {

facesMessages.add(“Invalid department”);

}

facesMessages.add(“Editing a department”);

return ;

}

//else instantiate a new department entity

this.department = new Department();

this.department.setFaculty(faculty);

facesMessages.add(“Creating a new department”);

return;

}

Passing the department id enables us to find out if a department like this exists already, in which case we load up that department for editing. If not we create a new department instance, passing it the faculty to which it belongs (which we injected from the previously outjected instance).

Look at how this is done in the departmentList.xhtml facelet.


<h:column>

<f:facet name=”header”>Action</f:facet>

<s:link id=”edit” value=”Edit”

view=”/department.xhtml” action=”#{departmentManager.createDepartment}” propagation=”begin”>

<f:param name=”depId” value=”#{department.id}”/>

</s:link>

</h:column>

The page for modifying/creating a new department is below

new department creation

Again this appends the department id as depId to the URL, and Seam makes it available to our departmentManager to use before the createDepartment method is called. Through this the department.xhtml facelet can be used both for creation and editing of department entities.

I’ve also been looking at alternative ways of automatically refreshing a list when a new element has been added to it in the database. Since @Factory is called only if the referred to object is null, we need another way to reload the list of departments and add the new department as well. Seam has an event mechanism based on the Observer pattern. This allows me to raise events, and all observers of that event immediately get notified of it. After populating the fields of a department I call saveDepartment, which saves my entity to the database. I then raise my own pretentious event: “univseam.event.DepartmentChanged”.

@End

public String saveDepartment() {

if(department.getId()!= null){

entityManager.merge(department);

facesMessages.add(“Department updated!”);

}else{

entityManager.persist(department);

facesMessages.add(“New department added!”);

}

Events.instance().raiseEvent(“univseam.event.DepartmentChanged”);

return “success”;

}

Notice that the factory method that initializes the list of departments (displayed previously) is also annotated with @Observer(“univseam.event.DepartmentChanged”). This time the facId will be null, but faculty is still in session scope, so we are able to reload the list of departments as if it’s nobody’s business.

Updated list of depts

Seam events enable applications to be very stateful, updating themselves when changes happen on the fly. Combining it with request parameters even makes it more fun to do.


Added on 8th April 2008:
Here is the updated link to the source for this tutorial


Annoying NetBeans 6.0 Facelets Support Issue on Tomcat

January 19, 2008

Yesterday i got a call from a good friend of mine who has been dipping his fingers into JSF a bit. He’d decided to jump ship to using JSF on XHTML files, a technology known as Facelets. So he goes to download NetBeans 6.0 Facelets support plugin and installs it.

After developing a simple facelets page, he decides to deploy it to Tomcat 6.0.14 only to get BIG FAT class loader exceptions. What better way to treat a sceptic who is just getting into the game of web development in Java. These are the kind of things that can be so annoying about doing something in Java. Being a Seam advocate and user, I didn’t immediately realise what could have been the problem, since my Seam applications run fine using the jars from Seam.

After doodling around and making some changes to jars that came with the Facelets support, i just decided to ditch the jars from Facelets support and use my own. I picked the jars that come with Seam and VOILA! Problem solved. Makes me wonder if the guys who developed the plugin didn’t try to deploy it themselves AT LEAST to Tomcat before putting it out there. Anyways i just felt like putting up the solution to this simple but very annoying problem here for the sake of those who might try an introduction to Facelets.

Note that i got these jars from the JBoss Seam 2.0.GA’s lib folder. I can’t tell you where u can get them individually but downloading seam altogether will give you a change to start playing around with it if you haven’t started already.

Simply create a new Library in NetBeans by going to Tools->Libraries. I gave mine the name Facelets4Tomcat. Here are the jar files you need.

  • commons-beanutils.jar
  • commons-collections.jar
  • commons-digester.jar
  • commons-logging.jar
  • jboss-el.jar
  • jsf-api.jar
  • jsf-facelets.jar
  • jsf-impl.jar

This goes into your web.xml file.

<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
<param-value>.xhtml</param-value>
</context-param>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>facelets.SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>forward.jsp</welcome-file>
</welcome-file-list>

If you want to add the Ajaxified RichFaces components then add the following from the same Seam lib folder.

  • richfaces-api.jar
  • richfaces-ui.jar
  • richfaces-impl.jar

And add these to the top of your web.xml file

<filter>
<display-name>RichFaces Filter</display-name>
<filter-name>richfaces</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>richfaces</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
<context-param>
<param-name>org.ajax4jsf.SKIN</param-name>
<param-value>classic</param-value>
</context-param>

You may use a different skin if you want. Check out the documentation for details

You may then add the library you created to your project by right clicking your web project and selecting “Properties”. At Libraries, click “Add Library” and selected the library you just created. Make sure that the check box is enabled or else it will not put the jar files in the right location i.e. WEB-INF/lib.

Oh, and MAKE SURE that the Facelets support libraries are unchecked, or else you’ll be back to square 1.

Happy Faceleting.


Fedora 8 and NetBeans Problems

January 15, 2008

Last month i got a hold of Fedora 8 and upgraded my 7 installation. I’d heard about the IcedTea version of the JDK already installed in Fedora, so I decided to go ahead and install without updating to JDK 6. Much to my surprise, NetBeans won’t install with the following error

‘Assertion ‘c->xlib.lock’ failed.’ error.

and a lot more.

Changing to JDK 6 didn’t help either. NetBeans is the IDE, and not being able to use it outta the box just drove me nuts. In a hurry to use my system, i just re-installed Fedora 7 and went back to life as usual.

However, to all the folks who had also tried to install NetBeans 6 on Fedora, here is the solution to a problem that turns out to be from the JDK itself.

For sun-java5-bin:
sed -i ’s/XINERAMA/FAKEEXTN/g’ /usr/lib/jvm/java-1.5.0-sun-1.5.0.11/jre/lib/i386/xawt/libmawt.so

For sun-java6-bin:
sed -i ’s/XINERAMA/FAKEEXTN/g’ /usr/lib/jvm/java-6-sun-1.6.0.00/jre/lib/i386/xawt/libmawt.so

Got it from here

Also for those of us who want NetBeans to work alongside the XGL destop effects, here’s the workaround

put into the script file of NetBeans this line: export AWT_TOOLKIT=MToolkit

Here’s the source

Now let the Fedora 8 games begin


Seam: Simple Data Table & Conversation Example

January 10, 2008

<Getting NetBeans 6 … | Using @RequestParameter and @Observer …>

We’ll start off the new year running our series on Seam. In this post, we’ll deal with data in a table and with conversations. We’ll first try to model a university environment, something I know will come handy on this or some campus sometime.

 

Let’s assume that we had to capture Faculties, Departments and Courses in our system. Here, of course a course is run by a department, which in turn belongs to a faculty. This is our department entity

 

@Entity

@Table(name=”faculty”)

@Name(“faculty”)

public class Faculty extends Model implements Serializable {

 

private Integer id;

private String name;

private String dean;

private String office;

private List<Department> departments = new ArrayList<Department>();

 

public String getDean() {

return dean;

}

 

public void setDean(String dean) {

this.dean = dean;

}

@OneToMany(mappedBy=”faculty”,cascade=CascadeType.ALL)

public List<Department> getDepartments() {

return departments;

}

 

public void setDepartments(List<Department> departments) {

this.departments = departments;

}

 

public String getOffice() {

return office;

}

 

public void setOffice(String office) {

this.office = office;

}

 

@Id

@GeneratedValue

public Integer getId() {

return id;

}

 

public void setId(Integer id) {

this.id = id;

}

 

@Length(max = 20)

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

Don’t forget to override equals() and hashCode() as well. NetBeans can easily generate these for you using Alt + Insert.

 

Our list of faculties will be displayed on a facultyList.xhtml using the following facelet section, displaying only the id and names of each faculty.

 

 

<rich:dataTable id=”facultyList” var=”faculty” value=”#{faculties}”

rendered=”#{not empty faculties}”>

 

<h:column>

<f:facet name=”header”>Id</f:facet>

#{faculty.id}

</h:column>

<h:column>

<f:facet name=”header”>Name</f:facet>

<s:link id=”faculty”

value=”#{faculty.name}”

action=”#{facultyListing.showDetails}”/>

</h:column>

</rich:dataTable>

 

</div>

List page

 

The “faculties” is a List of Facultys with a @DataModel annotation. However the list can be initialized (for the first time only) by using a @Factory annotation on any method as follows.

 

@Stateful

@Name(“facultyListing”)

@Scope(ScopeType.SESSION)

public class FacultyListBean implements FacultyList {

 

@PersistenceContext(type=PersistenceContextType.EXTENDED)

EntityManager em;

 

@DataModel

List<Faculty> faculties;

 

@DataModelSelection

private Faculty faculty;

 

@Factory(“faculties”)

public void facultyList(){

faculties = em.createQuery(“Select f from Faculty f”).getResultList();

}

 

public void showDetails(){

faculty.setSelected(true);

}

 

 

I hope I don’t have to remind you that a Stateful EJB must have a method annotated with @Remove as well as Seam’s @Destroy annotation. Our Seam component “facultyListing” is also a session scope component, which preserves the DataModel “faculties” at session scope and makes it available to the page all through the user’s interaction with it.

 

The Faculty object annotated with @DataModelSelection enables us to select a faculty and inject it into this object, passing it to our “facultyListing” Seam component. This is possible with the <s:link on the facelet. The faculty’s “selected” property is set to true, which enables us to redisplay the details of the selected faculty on a different panel as ff:

 

<rich:panel rendered=”#{faculty.selected}”>

<f:facet name=”header”><h:outputText value=”#{faculty.name}”/></f:facet>

<h:panelGrid columns=”2″>

<h:outputLabel for=”office” value=”Office” style=”font-weight:bold”/><h:outputText id=”office” value=”#{faculty.office}”/>

<h:outputLabel for=”dean” value=”Dean” style=”font-weight:bold”/><h:outputText id=”dean” value=”#{faculty.dean}”/>

<h:outputLabel for=”departments” value=”No. of depts” style=”font-weight:bold”/><h:outputText id=”departments” value=”#{faculty.departments.size()}”/>

</h:panelGrid>

</rich:panel>

 

list_page_details.jpg

OK, enough with the gimmicks on data in a table. What about if you want to create a new “Faculty”? Well, there the power of conversations in Seam comes in.

 

Clicking the “Create faculty” button begins a conversation, which can be considered a series of steps needed to be taken before a process is complete.

 

@Stateful

@Name(“facultyManager”)

public class FacultyManagerBean implements FacultyManager {

 

@In

EntityManager entityManager;

 

@Out

private Faculty faculty;

 

@Begin

public String createFaculty() {

faculty = new Faculty();

return “success”;

}

 

 

@End

public String saveFaculty() {

entityManager.persist(faculty);

Contexts.getSessionContext().set(“faculties”, null);

return “success”;

}

 

The “facultyManager.createFaculty()” (annotated with @Begin) begins a seam conversation and the navigation rule defined takes us to the faculty.xhtml facelet if “succes” is returned. This method initializes the “faculty” object whose fields will be populated on the faculty.xhtml facelet and outjects it to the scope of the “facultyManager”, in this case conversation scope.

 

<page view-id=”/facultyList.xhtml”>

<navigation from-action=”#{facultyManager.createFaculty}”>

<rule if-outcome=”success”>

<redirect view-id=”/faculty.xhtml”/>

</rule>

</navigation>

</page>

 

You can now provide the details required to create a new faculty. Note the s:decorate around each field. This allows us to specify how the fields will be laid, defined in a template file. It also enables validation of fields based on Hibernate Validator annotations defined on fields of an entity eg the @Email and @Length annotations. The a4j:support tag forces this validation to be done by AJAX, based on the occurrence of some events, in this case “onblur”. Adding AJAX support to JSF components is quite easy – the RichFaces documentation shows you how.

Ajaxified editing

 

Validated edit

Clicking on the “Save” button causes the “facultyManager.saveFaculty” method to be called, forcing us to now persist the entity to the database. To update the list of faculties being displayed on the “facultyList.xhtml” page, we set the “faculties” DtaModel to null. This forces Seam to repopulate it by calling the Factory method initializing the list again. Returning “success” causes the redisplay of the facultyList.xhtml facelet with the reloaded faculties and the job is done.

Updated list

 

I believe that with this it will be easy to implement the Departments and Courses list as well. We’ll continue next time.