Skip to main content

Posts

Showing posts from 2010

End of Java EE 6 show

Since last 2 days I have had lot of issues integrating JPA2 with my SLSB. Some of these are attributed to my new learning curve in Java EE 6. However with my quick exploration in last few days I can safely say that there are still serious holes in Java EE 6 world. It is slim trim and good for rapid development (unless you are on some unstable open source server) but lacks full power to drive a highly customizable and external configuration driven flexible application. These are some of my observations: Open source servers – Geronimo 3 and JBOSS 6 not yet ready. JBOSS 6 is still better. Guys for better adoption of open source we need documentation. Open source product and closed documentation will not promote this good products. Directly injecting persistence unit / entity manager results in severe cross cutting concerns. I take back my earlier word, although speed of development is important, good design goes a long way in maintenance. After writing some code in my session bean with

Adding and injecting the EJB3 session bean

In the last post the managed bean was creating the data. As a good practice the get method should never ideally do load from database or do complex time consuming operations. Its time to move the data retrieval code to a session bean( subsequently use JPA) method. In Java EE 6 it is no longer required to put the ejbs in jar files with tons of deployment descriptors. The ear file is no longer mandatory in Java EE 6. You can put your EJBs in the same war file as the web components. Ah! life is so easy and simple. The stateless session beans(SLSB) are POJOs and can be marked as SLSB with the @Stateless annotation. Things are even easier with EJB 3.1. You no longer require the business interface. Just a concrete class will do. Although program to interface is a great principle, but for simplicity, speed of development and ease of maintenance I will stick to the new ways. The purists may frown but I cannot think when I changed an implementation midway or in later stages of a project for wh

JSF 2.0 – First Managed Bean

The window shop, landing page is not complete. I have not shown the new product arrivals for this month in the center of the screen. In order to do that we need a managed bean which will retrieve data from the database. Later on we will integrate EJB 3.x stateless session beans to fetch the data for us. For now our managed bean will cook up the data to set the ball rolling. In this process we also discover the first domain object – Product. Going forward this will be turned into a JPA entity for CRUD operations. Here is how the domain object looks like: /** * */ package com.windowshop.domain.entities; import java.util.Date; import org.apache.commons.lang.builder.ToStringBuilder; /** * @author Dhrubo * */ public class Product { private int productId; private String productName; private Date createdDate; private String thumnailLocation; private String model; private double price; private String currency; public Product() {} public Product(int productId, String productName, Date

Servlet 3.0 – Add frameworks as Plugins

With Servlet 3.0, it is now possible to include external or 3rd party frameworks as plug-ins to the web application. This is made possible by the ServletContainerInitializer interface. The documentation says that the implementation of this interface - “allows a library/runtime to be notified of a web application's startup phase and perform any required programmatic registration of servlets, filters, and listeners in response to it”. The servlet container finds the ServletContainerInitializer using the JAR services API during application startup. The framework implementing the ServletContainerInitializer needs to add a file named javax.servlet.ServletContainerInitializer in the META-INF/services directory of the JAR file. This file points to the implementation class of the ServletContainerInitializer.The JSF 2 Majorra implementation has used this feature. If we check the JSF-IMPL-2.x jar this file is located in META-INF/services folder and points to the class -  com.sun.faces.config

First Java EE 6 application

to create a Maven 2 Java EE 6 application. This will be primarily the UI part build with JSF. Primefaces is the library of choice to build the “windowshop” application. I will try to build a landing page similar to oscommerce. The figure 1 below shows a screenshot of the landing page mock up. Figure 1 – Landing page prototype Now let us create a Maven 2 web project using the - “maven-archetype-webapp”. The listing below shows the pom.xml Listing 1 – pom.xml <project xmlns=" http://maven.apache.org/POM/4.0.0" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >     <modelVersion>4.0.0</modelVersion>     <groupId>com.windowshop</groupId>     <artifactId>shopweb</artifactId>     <packaging>war</packaging>     <version>1.0.0</version>     <name>shopweb Maven Webapp</name>  

Rolling out Java EE 6 development environment

Step 0 – Download and install JDK 6 Download JDK 6 from the link - http://www.oracle.com/technetwork/java/javase/downloads/index.html . Install it under c:\java. Step 1 – Download and install JBOSS 6 JBOSS6M5 can be downloaded from the following link - http://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.M5 . Once downloaded unzip the file to c:\jboss6. Step 2 – Download and install Eclipse Eclipse Helios 3.6.1 can be downloaded from the following link - http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/helios/SR1/eclipse-jee-helios-SR1-win32.zip . Once downloaded unzip the file to c:/eclipse Step 3 – Install Maven 2 plug-in and extras I will prefer to use Maven 2 as my build tool. This is very useful if we also have some continuous integration system set up in future. The Maven 2 eclipse plug-in update sites are located at - http://m2eclipse.sonatype.org/installing-m2eclipse.html . Launch Eclipse and install the plug-in core and extra

Exploring Java EE 6

I have been using, learning and writing about Spring framework for last 5+ years now. It has done loads of good work to simplify life back in J2EE days. But off late I am seeing and participating in discussions where I see a transition back to the platform again. The reason being the Java EE 6 has adopted good ideas from frameworks like Spring, Hibernate etc and have come out with a lean and thin platform. This has not gone unnoticed in developer world. Also in last couple of years Spring’s evolution has a framework has stalled to an extent. The core framework and extensions viz Spring MVC, Security etc being stable the guys at Spring Source have focused more on servers, OSGi, cloud and adding more products to Spring Source portfolio via acquisition route. The company itself was acquired by VMWare. So lots of things happening but nothing new or exciting enough in the core area to keep the developers attracted. This is really one bad thing that runs deep inside the Java developers’ vei

Removing the border from header layout unit

As you have seen the layout contains layout units. You can put any element inside a layout unit. Now there is a border for each layout unit. For our online store, I do not want the border and the header title. In order to remove the border, you will need to override the CSS style and to remove the header just remove the header attribute (header="TOP") from the layout unit tag. This is shown in listing below <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui"> <f:view contentType="text/html"> <h:head> <title>Simple Store - Home</title> <link type="text/css" rel="stylesheet" href="#{request.contextPath}/themes/cupertino/skin.css" /> <style> .ui-layout-unit-top .ui-layout-bd { border: 0; } </style> </h:head> <h:body> &

Creating the layout

Any web site has a layout. Layouts can be created with HTML tables, divs and with CSS with Javascript tricks. Prime Faces provides out of the box support for border layout. A border layout typically has 5 parts as shown below TOP / HEADER LEFT CENTER RIGHT BOTTOM / FOOTER This border layout works well for most websites. Prime faces border layout can be either applied to a full page or a specific element. It can respond to expand, collapse, close and resize events of each layout unit with ajax listeners. Let us create a full page layout for a simple shopping cart application similar to OSCOMMERCE - http://demo.oscommerce.com/ The listing below shows the modified home.xhtml code. Listing 1 – home.xhtml <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui"> <f:view contentType="text/html"> <h:head> <

Adding color to Prime Faces

In my last post you have seen a command button. This command button uses the default Prime faces skin and is shown in grey. Let me now make things a bit colorful, by showing how to use the skins provided by Prime faces. Prime faces skins are all based on Jquery themeroller CSS framework. I am interested in cupertino font and I will download the same from - http://www.primefaces.org/themes/cupertino.zip . You can download lots of other ready made themes from - http://www.primefaces.org/themes.html . In later posts I will show how to create, install and use custom theme or skin. Once downloaded unzip the theme to webapps/themes folder. This is shown in the figure below: Prime faces theme consists of a skin.css file and a set of images placed in images folder. Now modify your web.xml to tell Prime faces that it should no longer use the default theme sam. Here is the modified web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5"

Getting started with Prime faces 2

Prime faces is an amazing JSF framework from Cagatay Civici ( http://cagataycivici.wordpress.com/ ). Its wonderful because it is easy to use, minimal dependencies, has probably the widest set of controls among all JSF frameworks, easy to integrate with Spring (including Spring Security) , Java EE EJBs, and last but not the least mobile UI support. So I decided to give Prime faces a try, before selecting it to use in my projects. Step 1 – Create Maven 2 project As a first step to integrating Prime faces, create a Maven 2 project in Eclipse. You will need to select ‘maven-archetype-webapp’. Step 2 – Add repositories and dependencies in pom.xml I will be using Prime faces 2 with JSF 2 on Tomcat 6. Since the dependencies for Prime Faces and JSF 2 (JSF 2.0.3 is required) are available on different repositories, I will add them to my pom file first. The listing below shows my pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/X

Load your Spring beans as plug-ins

There are different ways of loading Spring beans in a web application – viz using the dispatcher servlet or the context loader listener. A more modular and flexible approach (which also allows you to minimize coupling and dependencies in your applications) is to load the barebones of your application with the core context loaders and load the rest of your beans in a pluggable way. For example you may be interested in loading your page controllers, business tier and data access code as three separate modules. Off course you can do this and then use import in a main spring config file or a comma separate list in your web.xml where you configure the spring bean definition xmls. But what if you just wanted to drop in a jar with Spring beans and be sure they will be loaded and registered in the container. This also eases the pain of swapping an implementation. The goal is to put all your Spring beans in a particular layer, package it as a jar with one or more configuration file(with one fol

CKEDITOR 3.x - Simplest Ajax Submit Plugin

  I have assumed that you have downloaded and got started with CKEDITOR. Step 1 – The html file is shown below: <html> <head> <title>Writer</title> <meta content="text/html; charset=utf-8" http-equiv="content-type" /> <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <style> .cke_contents { height: 400px !important; } </style> </head> <body> <form action="sample_posteddata.php" method="post"> <textarea id="editor" > </textarea> <script type="text/javascript"> //<![CDATA[ CKEDITOR.replace( 'editor', { fullPage : true, uiColor : '#9AB8F3', toolbar : 'MyToolbar' }); //]]> </script> </form> </body> </html> Note that the jquery js

Part V : A Simple and Smart Result Mapper

The examples so far only deal with single table. But it is very much possible to join multiple tables and still use this mapper. As an example consider three entities as shown below: T_REPOSITORY REPOSITORY_ID int REPOSITORY_NAME varchar CONNECTOR_ID int T_CONNECTOR CONNECTOR_ID int CONNECTOR_NAME varchar URL varchar OWNER_ID int T_OWNER OWNER_ID int OWNER_NAME varchar OWNER_KEY varchar The relationship is clear - a repository has a connector and a connector has a owner. So how can you populate a Repository object containing a Connector Object which in turn has an Owner object. This is just simple. Execute this query. SELECT r.repository_id "repositoryId", r.repository_name "repositoryName", c.connector_id "connector.connectorId", c.connector_name "connector.connectorName", c.url "connector.url", o.owner_id "connector.owner.ownerId", o.owner_name "connector.owner.ownerName&

Part IV : A Simple and Smart Result Mapper

In my last post, I have shown how the dao support class changed to convert list of maps to list of domain objects. Now the DAO implementation class must also change to use these new methods. Here is the modified DAO class. Listing – UserDaoImpl.java package net.sf.dms.security.dao.impl; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.dms.security.dao.api.UserDao; import net.sf.dms.security.domain.User; import net.sf.spring.dao.AbstractBaseDaoSupport; /** * @author dhrubo * */ public class UserDaoImpl extends AbstractBaseDaoSupport implements UserDao { private Logger logger = LoggerFactory.getLogger(UserDaoImpl.class); @Override public List<User> listUsers() { return (List<User>)this.queryForList("listUsers", User.class); } @Override public void save(User user) { this.insert("saveUser", user.getEmail(), user.getPassword(), user.getFirstName(), user.getLastName()); } @Override public void update(User use

Part III : A Simple and Smart Result Mapper

Now a days we make extensive use of Annotations. Whether it is a good or bad practice to mix configuration meta data with code is debatable, but its better than proprietary XML tags. Since we are so used to mixing meta data in our Java code, why not make use of same tactics in building our data mapper. SQL statements in all databases supports something called an alias for column names. I will use this to map a SQL result column to a property in my bean. This is better because even if my column name changes but my alias remains same my bean will be populated properly. I use JODD bean utils. You can download the JODD distribution here .  A problem with JODD is that it is not available in any of the global maven repositories. So you need install the same in your local repository by running the following command  C:\&gt;mvn install:install-file -Dfile=jodd-3.0.9.jar&nbsp; -DgroupId=jodd -DartifactId= jodd -Dversion=3.0.9 -Dpackaging=jar  Use the GUI screens if you are using

Part II : A Simple and Smart Result Mapper

I am a big fan of Spring JDBC. The reasons are simple - Full control over SQL. I can optimize, tweak and tune them to my free will. Let me think in terms of those tables and not objects. Cuts down my DAO code significantly. Takes care of all boilerplate code. Integrates well with other parts of my application which mostly uses other Spring components. Simple and easy to setup and get running at high speed Minimal learning curve One area where Spring framework does not do a good job is that of list/finder queries returning n number of records. Lets say you want to find the employees in a certain department. The query is executed and you get a map of records, but then you need to return a list of domain objects to the business tier. You will loop through the map list returned by Spring JDBC, for each of your record create a Javabean populate each field and then add to another list which will be finally returned. So there is lot of boilerplate code here.  Look at the example code b

Part I : A Simple and Smart SQL Result Mapper

I am not at all a fan of ORM solutions/frameworks like Hibernate. I have already written and presented my view on different forums and discussions the reasons for my disliking. I truly empathize with Ted Neward that ORM are “Vietnam of Computer Science”. http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx Followup - http://blogs.tedneward.com/2006/06/27/Thoughts+On+Vietnam+Commentary.aspx http://stackoverflow.com/questions/404083/is-orm-still-the-vietnam-of-computer-science Some counter punches http://www.codeproject.com/KB/architecture/ORM_Vietnam.aspx?display=Print I am not convinced as to why should I learn HQL or similar QLs provided by other OR Mapping solutions? Why should I not write and benefit from SQLs which have been proven to be so powerful over the ages and often outlive the lifetime of an application. So many times I have seen SQLs and

A custom plug-in system for web applications

Recently I was trying to put together a plugin system for web applications. The idea is similar to Eclipse plugins. Where you bundle your extension in a jar and then drop them in Eclipse-Home/plugins folder, restart Eclipse and you are ready to use it. Note that Eclipse plugins are OSGi plugins. So my initial effort was to see if I could build a pluggable web application with OSGi. After few experiments with Equinox (the Eclipse OSGi engine) and Felix, I moved on to check out Spring DM as well as Spring DM server. But all I all I felt that OSGi / DM involves significant learning curve. The web server bundles are “probably” not of enterprise strength. Still trying to gel with JEE. Significant extra effort required to port applications to OSGi platform. All in all  OSGi / DM has to go few more miles before we build Enterprise server apps using those containers / bundles. But its a very good start and promises a lot in the future. So what to do? I started digging dip into Spring frame

SecurityContextPersistenceFilter

This bean is configured as shown below: <bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/> This bean has two main tasks and they are very important In a typical web application like Skyphoto the user will login once and then subsequently do several operations or click several links and buttons generating several authenticated requests to the server. Since the user was authenticated once it is important to store the security context somewhere and by some means. Otherwise he/she has to authenticate for each request and will sooner or later never use Skyphoto. In a typical web application you will store an user object in HttpSession and each time a request comes in, the server identifies this session with a session id and you get the user object. It is the responsibility of the server to cache/store and manage these session objects during the lifetime of the session. “In Spring Secur