Pages

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 :

Tuesday, September 1, 2009

What should new JEE developers learn

We now started a new Enterprise project for Telecom and my first job is helping the new team get started. We are using, and seems will be using, the JSF, Spring and Hibernate technology stack. I am told that although some of them know some of the technologies we use, none know all.
So what should they learn and where to start;

JEE
  • The request & response lifecycle,
  • State on AS. How does Session works.
  • Servlet's and Filter's
  • JSPs, JSTLs and Custom Tags
  • A simple blogging application can be created with the above.
Spring Framework
  • The "Dependecy Injection" Pattern
  • Creating & managing Beans with Xml or Annotations
  • Proxying and Interceptors
  • JDBC Support
  • We can improve our app. with the above. Move the data to spring beans, and actually use database at this point.
  • Although we don't use the MVC it could be introduced here and see how much it will help with our app.
JSF
  • The components
  • JSF Lifecycle and how its manupilated with immediate attribute...
  • How facelets add to JSF
  • At this point we can improve app. with the JSF
  • Introduce the ajax and ajax enabled components
  • How to create custom JSF components
WebFlow
  • How state machine logic helps the navigation
  • New scopes the webflow introduces
  • Improve the app.
Hibernate
  • ORM concept
  • JPA annotations
  • Startegies to manage the hibernate session
  • Improve the app.
Reporting
  • We are using JasperReports which I don't know much about that at the moment :)
After this point I am thinking that new requirements could be introduced and the team could work on them as pairs. Pairs will be swapped often and there could be nightly reviews.
As for learning these one also needs some nice examples, one is mesir developed by my buddy Mert. It's a showcase of most of the technologies I wrote above.
For "Dependecy Injection" pattern Martin Fowler has this paper.
As for me Spring's and Hibernate's reference and api documentation is pretty solid.
For JSF Richard Hightower's "JSF for Non Believers" and "JSF fits facelets like glove" are quite fun to read articles.
On extreme programming practices here is a article at objectmentor site which demonstrates a session between two programmers.
Although pretty boring, working for sun certificates are helpful and good to learn the basics (SCJP and SCWCD).
These are what comes to my mind.

Monday, August 31, 2009

a ping-pong game (1)

One of the goals that I postponed long ago was learning OpenGL and creating games with it. I started learning OpenGL, and started building a toy project on the process.
I decided to build a ping-pong game which will be simply a ball moving and hitting around. A simple 2D toy project.
I chose to develop on my mac with XCode & Objective-C. XCode is a simple IDE that works fast and Objective-C is a Object Oriented programming language much simpler that C++. A mac comes with a OpenGL so on a Mac there is not any prerequisite to start developing. Although the source code is written on such platform it wont be hard to port to other platforms.
Code is on svn here.
I have also tagged bar and bars versions which I will be blogging about now.
Setting Up the OpenGL
This is how (code snippets from main.m) :
1:  glutInit(&argc, argv);
glutInit function initializes the GLUT. Parameters are for the underlying Windowing System.
1:       glutInitWindowPosition(400,100);
2: glutInitWindowSize(400,300);
We initialize the windows size & position.
1:       glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
We use a single buffer & rgb values for now.
1:       glutCreateWindow("Intro");
This sets the title of the window.
1:       glClearColor(0.0,0.0,0.0,0.0);
This function is like setting the background color.
Setting the Callback Functions
OpenGL is designed with the "Hollywood Principle"; "Don't call me, I'll call you...". To draw on screen and listen to events you register a set of callback functions (from BarCallbacks.m);
1:       glutDisplayFunc(display);
2: glutReshapeFunc(reshape);
3: glutKeyboardFunc(keyHandler);
4: glutKeyboardUpFunc(keyUp);
Display callback function is for actually drawing on screen. Reshape function is for redisplaying after the window moves or resizes. Keyboard functions are for detecting key strokes of the user.
These callback function are 'C' functions and this means that you can not use Objective-C methods directly. To use the Objective-C methods you have to use a static variable. I set up a pattern where the 'C' callback functions delegate to Objects and their appropriate methods. This way I can take advantage of the object oriented paradigm.
I created a BarCallbacks Object which is simply responsible of drawing rectangles on screen. Here is the display function and its delegate;
1:  static BarCallbacks * workingCallback;
2: void display() {
3: glClear(GL_COLOR_BUFFER_BIT);
4: [workingCallback display];
5: glFlush();
6: }
7: -(void) display {
8: // loads the identity matrix
9: glLoadIdentity();
10: // floating point red, green, blue values
11: // 0 to 1 probably but may change I guess 3if ?
12: glColor3f(0.0,0.0,1.0);
13: glRectf(box.x - box.xr, box.y - box.yr, box.x + box.xr, box.y + box.yr);
14: }
workingCallback is the static variable used to delegate from the C function to the Object method.
glClear function (line 3) clears the screen with the color we previously specified. Then we draw the rectangle. glColor3f (line 12) sets the drawing color to blue and glRectf draws the rectangle to specified coordinates.
Another thing we need to setup is the perspective. There are two types of perspectives. I used the Orthogonal Perspective which is I think is easier to use for this kind of app.
1:  glOrtho(0, x, y, 0, 0, 1);
x and y are the width and height of the window. Since this will be a 2D app. I gave the Z-index 1. This function is called from the reshape function.
MainLoop
After setting up the callbacks OpenGL system, machine is more appropriate I think, is started with;
1:  glutMainLoop();
Our rectangle will be displayed, if you put break points you will observe that user key-strokes are caught. I tagged all the code up to this point as bar.
With the BarCallbacks Object we created, I wanted to make some walls where our ball will bounce around. Here are the changes I made to delegating system so that we can use multiple BarCallbacks;
1:  static NSMutableArray * callbacks;
2: void display() {
3: glClear(GL_COLOR_BUFFER_BIT);
4: for( int i = 0; i < callbacks.count; i++) {
5: BarCallbacks * cb = [callbacks objectAtIndex:i];
6: [cb display];
7: }
8: glFlush();
9: }
I changed the static variable to an mutable array. Then looped on on callback methods and delegated.
Here is my three walls;
1:       [[BarCallbacks alloc] initWithRect:390 y1:10 w:10 h:280];
2: [[BarCallbacks alloc] initWithRect:0 y1:10 w:10 h:280];
3: [[BarCallbacks alloc] initWithRect:0 y1:0 w:400 h:10];
And how it looks;Next we need a ball, a platform and some collision detection.