Pages

Thursday, November 19, 2009

Sinek, spreadsheet component, for JSF 2

Here are some notes on developing a spreadsheet component for JSF. Here is how it looks like :Cells contents are being updated with ajax, user is able to add rows/columns by clicking the buttons on the bottom-right corner. I am calling this component 'sinek'. Probably I will rename it later. To check the source code click here.
Here are the parts that make up the component :
  • org.mca.sinek.jsf
This package has 3 files that make up the main component. UISinek, SinekRenderer and WorkSheet.
  • WorkSheet is the datamodel. Its basically a two dimensioned array of Strings:
 public class WorkSheet {
List<List<String>> sheet;
public Integer getNumOfColumns() {
...
public int getNumOfRows() {
...
public List<String> addEmptyRow() {
...
public void addEmptyCol() {
...
}
It also has methods that return the number of rows, add rows/cols.
  • UISinek is the component that holds the state values. After its added to view it adds the sheet cells as its children. Cells are made up of inputtext components :
 @FacesComponent(value = "sinek")
@ListenerFor(systemEventClass = PostAddToViewEvent.class)
@ResourceDependency(name = "jsf.js", library = "javax.faces", target = "body")
public class UISinek extends UIInput {
...
@Override
public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
Map<String, String> requestParameterMap = getFacesContext().getExternalContext()
.getRequestParameterMap();
String exec = requestParameterMap.get("javax.faces.source");
if((getClientId()+ "_addr").equals(exec)) {
getWorkSheet().addEmptyRow();
} else if((getClientId()+ "_addc").equals(exec)) {
getWorkSheet().addEmptyCol();
}
int count = getChildCount();
createRows();
}
...
private void createRow(List<String> row, int rindex) {
ValueExpression ve = this.getValueExpression("value");
String exp = ve.getExpressionString();
exp = exp.substring(0, exp.length() - 1);
int cl = 0;
for (String cell : row) {
String id = getId() + "_" + rindex + "_" + cl;
if(findComponent(id) != null) {
continue;
}
HtmlInputText in = new HtmlInputText();
ValueExpression el = ELUtils.createValueExpression(exp + ".sheet[" + rindex + "][" + cl + "]}");
in.setId(id);
in.setValueExpression("value", el);
in.setLocalValueSet(true);
in.setOnkeyup("jsf.ajax.request(this,event);");
getChildren().add(in);
cl++;
}
}
}
We are annotating it with the @FaceComponent annotation. It listens for the PostAddToViewEvent with the @ListenFor annotation. When the event fires processEvent method will be fired. Process events creates HtmlInputText components whose values are backed up with the datamodel. Also sets up the ajax call which will update the component values. Because we will be using ajax we have to define it with the @ResourceDependency annotation. The "javax.faces.source" will be used to identify the add col/row events.
  • SinekRenderer is the renderer. It renders our cells into the cells of a table:
 @FacesRenderer(rendererType = "sinek", componentFamily = "javax.faces.Input")
@ResourceDependencies({
@ResourceDependency(name = "sinek.css", library = "org.mca", target = "head"),
@ResourceDependency(name = "jsf.js", library = "javax.faces", target = "body")})
public class SinekRenderer extends Renderer {
@Override
public void encodeBegin(FacesContext facesContext, UIComponent comp) throws IOException {
UISinek sinek = (UISinek) comp;
ResponseWriter writer = facesContext.getResponseWriter();
writer.write("<table id=\"" +sinek.getClientId()+"\" class=\"mctable\">");
int R = sinek.getWorkSheet().getNumOfColumns();
renderFooter(writer, R, sinek);
renderColumnHeaders(writer, R);
renderCells(facesContext, writer, sinek);
writer.write("</table>");
}
private void renderCells(FacesContext facesContext, ResponseWriter writer, UISinek sinek) throws IOException {
int i = 0;
int rno = 1;
int r = sinek.getWorkSheet().getNumOfColumns();
List<UIComponent> rows = sinek.getChildren();
for (UIComponent c : rows) {
if (i % r == 0) {
if (i % 2 == 1) {
writer.write("<tr class=\"altrow\">");
} else {
writer.write("<tr>");
}
rno = renderRowHeader(writer, rno);
}
writer.write("<td>");
c.encodeAll(facesContext);
c.setRendered(true);
writer.write("</td>");
if (i % r == (r - 1)) {
writer.write("</tr>");
}
i++;
}
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
}
@Override
public boolean getRendersChildren() {
return true;
}
}
Renderers are defined with the @FacesRenderer annotation and again @ResourceDependecy annotation is used for the css and ajax scripts. It renderers the children (cells) so we need to override the encodeChildren and getRendersChildren methods.
  • mca.taglib.xml : Defines the namespace and components.
  • sinek.css : Style sheet for our project.
My example also contains Hello class which is a example bean used on page index.xhtml.
Thats all for now drop me a line if you need more info and be sure to check-out the source.

Tuesday, November 10, 2009

JSF2 Notes

These are the notes I derived from blogs on JSF 2 :
  • Composite Components
Ed Burn's have a number of articles on developing 'composite components'. CC's are for creating true components that we can attach converters, listeners etc. Previously you could do the similar things with the help of the facelets, which was somewhat limited. Rick Hightower has an excelent series of articles about this, called 'Facelets fits JSF like glove'. Here is what a CC looks like in JSF2 :
 <cc:interface
name="inputtext"
displayName="label plus text"
expert="true"
hidden="false"
preferred="true">
<cc:attribute name="label" required="true" />
<cc:attribute name="id" required="true" />
<cc:attribute name="value" required="true" />
</cc:interface>
<cc:implementation>
<h:outputLabel id="lbl_#{cc.attrs.id}" for="#{cc.attrs.id}"
value="#{cc.attrs.label}" />
<h:inputText id="#{cc.attrs.id}" value="#{cc.attrs.value}" />
</cc:implementation>
This forms a common element with an inputtext and its label. Apparently there are many tricks to learn here. Its formed of two parts, first is the interface. As far as I can tell this is the UIComponent part. We define valueholders, attributes, actionsources that our CC will respond to. Second part is the implementation. This is like the renderer part. We glue the components together here.
One thing that I didn't like while trying out these was, with the facelets way I could use the CC with panelGrid component and the components forming the CC would be on different grids. This way I could easily align the components. Now on jsf2, CC truely acts like one component and all the sub components fit into the same grid.
  • We can define exception handlers on faces-config.
From Ryan Lubke's blog, http://blogs.sun.com/rlubke/
  • There is a javax.faces.PROJECT_STAGE context parameter we can play with which will make our application behave differently in different stages. Like on 'development' stage certain components will be added to the view root automatically like perhaps facestrace. We are able to access it through Application.getProjectStage()
  • There is a new Resource handling architecture. By default resources are searched under (webapp_root)/resource or (webapp_root)/META-INF/resources and there is a EL support to load them from the pages. #{resource['lion.jpg']} will generate a url to a image under these locations I mentioned. Spec also enables that different versions of the same resource be available to application.
  • Components can be annotated with @ResourceDependency annotation and provide the list of resources (css, js, images...) they need inorder to work. These resources might be rendered on different parts of the page with the help of h:body and h:head tags.
  • There is 'View Scope' which as long as the view is not changed. It's accessible using UIViewRoot.getViewMap and #{viewScope} through EL.
  • There is a system event listener api where you could listen to events like 'configuration complete'.
  • Now we have control over request parameters. We can validate convert them if needed.

Looks like JSF2 has more nice stuff in it like the 'View Declaration Language'. Spec it self seems to be the best resource at the moment though.

Tuesday, October 27, 2009

ICEFaces

Nice people at 'Packt Publishing' are sending me a copy of their new ICEfaces book, 'ICEfaces 1.8: Next Generation Enterprise Web Development', for me to review. You can check it out here.

Wednesday, October 21, 2009

Hibernate Journey

Now
So we have started our new project and by default (not my decision, not saying its a bad decision either, just saying that there could be a better decision) we are going to be using Hibernate.
For those who don't know Hibernate is 'the' ORM solution. ORM is for 'Object Relation Mapping' which is pretty much self explanatory. It maps your relational data model, such as a database schema, to the object model.
The Begining
Back in 2005 we started our project with Hibernate2. There were no annotations yet so we had to use XML files to map the object domain. So here is how the object domain looks like ;
 public class City {
private Long id;
private String name;
... more fields and getter / setters
Our object-domain is made of classes with complex (like other classes or lists...) or primitive (String, Long ...) fields and their getter / setter methods, which is called the 'POJO' (Plain Old Java Object). These POJOs will be representing the rows of a table. String's will be mapped to VARCHAR's on Oracle, complex types will be foreign keys to other tables. Of course we need to specify which POJO is related with which table or which field is mapped to what column. This is done in the mapping XML and here is how it might look like ;
 <class name="foo.City" table="CITY">
<id column="ID" name="id" type="java.lang.Long">
... some mechanism to generate id's
</id>
<property column="NAME" name="name" type="java.lang.String"/>
...
With this model we could save ( 'persist' ) our POJOs to databases with out us explicitly writing insert statements and query our object-domain with a special query language (similar to sql) HQL and get POJOs as result.
The Plugin
We were creating our POJOs through a class modeler (RSAs class diagram plugin) and we realised that we could write a plugin that could also generate the mapping XMLs. All we had to do was mark the class diagrams with some 'StereoType's that we have created;
The things with '<<...>>' are the stereotypes where we could add the table names and such through attributes.
The Evil
I was happily programming until I was told that we were to update to a newer version of Hibernate. Well after the update nothing worked :) . The main reson was that with this version all the relations were 'Lazy' by default (which is the correct way to work with hibernate by the way). To better understand the problem suppose that we are querying the City object. Now we might not be needing the Park's of the City so loading them since it will cause more selects or joins would not be desirable. This is what is trying to be achived with the 'Lazy'. Loading the partial object graph and loading the specific lazy relations only when required.
When we have a City with lazy parks we could load the parks at the time when its getter is called however the city object must have an open session (session is hibernate's transaction unit). If the hibernate session where the city object has been loaded was closed a LazyInitializationException is thrown. Here is a code piece which shows whats ok and whats not :
 session.open();
City aCity = session.load(City.class,1);
City anotherCity = session.load(City.class,2);
aCity().getParks(); <= OK to call parks here
session.commit();
session.close();
aCity().getParks(); <= Still OK to call parks here because its already initialized
anotherCity.getParks(); <= This will throw an exception !
The thing to note here is that Hibernate POJOs are not so 'Plain'. A POJO is actually wrapped with hibernate generated proxies to do the initializing when required. You should always think POJOs with the underlying session object. There are numerous patterns to manage the sessions like 'Session Per View', 'Session Per Conversation' pattern ... You should always think of the object graph you will be using and join the objects on your queries according to that.
5
With the Java 5 came the annotations and it replaced the need to have XMLs. XML is still supported but I don't see any reason why someone choose that to annotations. Here is how our POJO might look like with annotations:
 @Table(name="DIL")
@Entity
class City {
@Id
private Long id;
@Column(name="NAME")
private String name;
...
Back
Hibernate has a indexing integration (lucene) , a validation framework and caching frameworks. It should be used with care and respect :)

Wednesday, September 23, 2009

Choosing an Expression Language

On previous posts I talked about that I liked Jboss-EL. Here is an example of what you can do with jboss-el and not with the standard el:
1:  #{cityService.listCities(selectedCountry)}
This EL is usefull on scenerios where the user selects a country from a combo (selectedCountry) which fires a ajax call and witch returns the cities of the country listing them in a sub combo.
Since I relay wanted use this on my myfaces + spring project I searched googled and found this. Here is how you use Jboss-EL with MyFaces.
  1. We need the myfaces 1.2.7
  2. Add jboss-el to classpath
  3. Add to web.xml :
1:    <context-param>
2: <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
3: <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
4: </context-param>
If you are using RI :
1:  <context-param>
2: <param-name>com.sun.faces.expressionFactory</param-name>
3: <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
4: </context-param>
Should do the trick.

Monday, September 7, 2009

a ping-pong game (2)

Continuing where we left from part 1.
First we need a platform that the user control. Our platform will be a BarCallbacks with key handler. To control the movement of the objects we will introduce a new object 'World' which will handle the movement code. The world object is a timer object that will tick every few seconds and recalculate the coordinates of the registered vectors and redisplay the screen. Also the VectorBox object now will have distance and angle making it a real vector. VectorBox object here :
1:  @interface VectorBox : NSObject {
2: float x, y, xr, yr, distance, angle;
3: }
4: @property float x, y, xr, yr, distance, angle;
5: -(id) initWithX:(float)_x y:(float)_y xr:(float)_xr yr:(float)_yr;
6: -(id) initWithX:(float)_x y:(float)_y xr:(float)_xr yr:(float)_yr distance:(float) _d angle:(float) _a;
7: @end
Distance will determine how many pixels will the object travel with the tick of the clock. Angle is at what angle will the object move. The init function without the distance and angle will set these values to zero.
And the World object :

1:  @interface World : NSObject {
2: NSMutableArray * boxes;
3: NSUInteger milis;
4: }
5: @property (readonly) NSUInteger milis;
6: @property (readonly) NSMutableArray * boxes;
7: -(id) addVectorBox:(VectorBox *) vbox;
8: -(id) startTickingEveryMilis:(NSUInteger) milis;
9: +(id) world;
10: void worldTick(int value);
11: @end
The 'boxes' parameter will hold the vectors that will be animated. The 'milis' parameter is the number of milliseconds that our code will wait before firing to animate our vectors. addVectorBox method adds new vectors and startTickingEveryMilis method sets the timer. The world object is to be used as a 'singleton', one copy of it should be available at any time, and to access that instance we will use the static 'world' method. worldTick function is the our glut timer callback function. Its registered first as the startTickingEveryMilis method is called. worldTick function :
1:  void worldTick(int value) {
2: World * world = [World world];
3: int len = [world.boxes count];
4: for( int i = 0; i < len; i++) {
5: VectorBox * vbox =[world.boxes objectAtIndex:i];
6: vbox.x += vbox.distance*cos(vbox.angle);
7: vbox.y += vbox.distance*sin(vbox.angle);
8: }
9: glutPostRedisplay();
10: glutTimerFunc(world.milis,worldTick,1);
11: }
It traverses of the boxes array and moves them using a simple trigonometric function and updates the coordinate values. Then the glutPostRedisplay function is called so the screen is redrawn. Using the glutTimerFunc we reregister our callback function. PlatformCallbacks extends from the BarCallbacks it just adds the key handler code to it.
1:  -(void) keyHandler:(unsigned char) key x:(int) x y:(int) y {
2: if(key =='d') {
3: box.angle = 0;
4: box.distance = distance;
5: } else if(key =='a') {
6: box.angle = M_PI;
7: box.distance = distance;
8: }
9: }
10: -(void) keyUp:(unsigned char) key x:(int) x y:(int) y {
11: box.distance = 0;
12: }
Glut calls the keyHandler function as long as the key is pressed. So when the 'd' key is pressed we will set the registered vectors distance to move right. keyUp function is called when the key is released so we will use it to set the vectors distance to zero thus making it stop.
Now we need to implement our bouncing ball. First thing I am going to do is refactoring the code so that we may have a common base class for BarCallbacks and BallCallbacks. I will call it the BaseCallbacks. All my callbacks will extend from this base. OpenGL does not have circle driving function by default so we need to come up with a approximate formula :
 @implementation BallCallbacks
-(void) display {
// loads the identity matrix
glLoadIdentity();
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
for (int i = 0; i < 360; i++) {
float x1 = (cos((M_PI*i)/180) * box.xr) + box.x;
float y1 = (sin((M_PI*i)/180) * box.yr) + box.y;
glVertex3f(x1,y1,0);
}
glEnd();
}
@end
Using glBegin function we start drawing vertex to vertex. Our circle is actually a polygon with 360 vertexes. We end drawing with glEnd function. After initializing with distance and angle our ball will start moving. As its now our ball will pass through our walls. To make it bounce we need to detect collision and change the angle appropriately. We will be checking for collisions at every tick of the clock in the World object :
 void worldTick(int value) {
World * world = [World world];
int len = [world.boxes count];
for( int i = 0; i < len; i++) {
VectorBox * vbox =[world.boxes objectAtIndex:i];
vbox.x += vbox.distance*cos(vbox.angle);
vbox.y += vbox.distance*sin(vbox.angle);
}
for( int i = 0; i < len; i++) {
VectorBox * vbox =[world.boxes objectAtIndex:i];
if( !vbox.changesAngleAfterCollision) {
continue;
}
for( int j = 0; j < len; j++) {
if( i == j) {
continue;
}
VectorBox * obox =[world.boxes objectAtIndex:j];
[vbox detectCollision:obox];
}
}
glutPostRedisplay();
glutTimerFunc(world.milis,worldTick,1);
}
We check for collision with objects which changes its angle after collision. In our case we only need to check collision of ball and the other objects.
 -(id) detectCollision:(VectorBox *) obox {
// check if this object collides with other from bottom
if(obox.x + obox.xr > x && obox.x - obox.xr < x ) {
if(obox.y + obox.yr > y + yr && obox.y - obox.yr < y + yr) {
angle = 2*M_PI - angle;
}
}
if(obox.x + obox.xr > x && obox.x - obox.xr < x ) {
if(obox.y + obox.yr > y - yr && obox.y - obox.yr < y - yr) {
angle = 2*M_PI - angle;
}
}
if(obox.y + obox.yr > y && obox.y - obox.yr < y ) {
if(obox.x + obox.xr > x + xr && obox.x - obox.xr < x + xr) {
angle = 3*M_PI - angle;
}d
}
if(obox.y + obox.yr > y && obox.y - obox.yr < y ) {
if(obox.x + obox.xr > x - xr && obox.x - obox.xr < x - xr) {
angle = 3*M_PI - angle;
}
}
return self;
}
This works pretty smoothly most of the time but sometime ball gets stuck.
This is how it looks like in the end :