Pages

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.

Wednesday, July 29, 2009

Summing up the photo gallery (part 6)

I started building a photo gallery app., flickr in mind, as a means to learn the seam framework. To sum up here is my previous posts :
1. "little restfull photo gallery example, with seam, which seams fine", here.
2. "seamy photo gallery, securing it (part 2)", here.
3. "seamy photo gallery, securing it (part 2)", here.
4. "seamy photo gallery, resting easier (part 4)", here.
5. "seamy photo gallery, writing an authentication filter (part 5)", here.
Here is what I did on last couple of days:
Firstly I publish the source code here on google code. Named it jhoto rather hastely. This will probably be an internal name :)
Polished it a little so that it has a original look. I ended up creating some simple bubbley look using paint and some css. Here is how it looks now :
And lastly using jquery to gave the bubbles some animation so that they wiggle a little:
        <script type="text/javascript">
$(document).ready(function() {
var animationLoop = function(it) {
it.animate({
opacity: 0.5 + Math.random() / 2,
marginLeft: (Math.round(Math.random()*10) - 5)+"px",
marginTop: (Math.round(Math.random()*10) - 5)+"px"
}, 1500, "linear",
function() {
animationLoop($(this));
});
};
$("table.aframe").each(function() {
animationLoop($(this));
});
});
</script>
What the above code does is move my bubbles (tables) randomly whit in some threshold.
Will probably do more on this...

Thursday, July 2, 2009

Groovy Impressions

Groovy is a superset of the Java programming language with dynamic language constructs. Here are my notes on Groovy.
1. Java is Groovy
Every Java sentence is a valid Groovy sentence but not the other way around. Which means you can use every Java library out there with Groovy classes. Infact Groovy classes in the end compile into Java code.
2. Loose Syntax
No need for a main method. No more a class should be defined in its own named file requirement. Following is a complete "Hello, World!" program for Groovy:
println "Hello, World!"
We don't need the System.out.... or the semicolon ending commands. Though we could have used them also.
3. Integrated Template Engine
It has a embeded templating engine which does all sort of things. And here is the "Hello, World" of templating :
world = "World"
println "Hello, ${world}!"
4. Constructers, Getters and Setters
Getters and Setters are automatically generated for properties of the class and there is a simple property initialization mechanism. And the example :
new Salutor(hello:true,who:"World")
5. Safe Navigation & Elvis Operators
With Java Often we may have to these null checks :
if(state != null &&
state.getTransitions() != null &&
state.getTransitions().size() > 0) {
states = state.getTransitions().values();
...
With groovy we can navigate with the '?' operator safely with out cluttered if checks :
states = state?.transitions?.values()
And the Elvis operator is used for assigning default values other than null :
name = user.name ?: "Anonymous"
As far as I know these will be available in Java 7.
6. Closures
The folowing closure (the thing between curly brackets) finds even integers inside the int array.
ints?.find {n -> n % 2 == 0}
Closures are passable function block. You can also check out the commons-collections api to see how similar code could be written in Java.
7. Meta Programming
e = new Euro()
prop="value";
op="plus";
e."${prop}"= 5;
e."${prop}"=e."${prop}"."${op}"(1)
println e
The above example succesfully computes to 6.
8. Build DSL's
Using the MetaClass api you can create simple inline DSL's. Here is a example whit euros:
package tr.mca.dsl;
import static tr.mca.dsl.MoneyDomain.*;

println "1 euro + 2 euro :" + money {
1.euro + 2.euro
}
Here whit in the money block we create "new Euro(3)" but we are doing it in a more brain friendly way.
There is two ways I know to achive that:
a. DelegatingMetaClass
DelegatingMetaClass helps us to intercept the method and property accesses. Here is the extended version I crated for money example :
public class MoneyDelegatingMetaClass extends DelegatingMetaClass {

MoneyDelegatingMetaClass(Class delegate) {
super(delegate);
}

public Object getProperty(Object obj, String property) {
if (isDynamicProperty(property)) {
return new Euro(obj);
}
return super.getProperty(obj, property);
}

private boolean isDynamicProperty(String property) {
return "euro".equals(property) || "€".equals(property)
}

}
We are able to intercept the "euro" property access and upon access we create the Euro object. Here is the code that activates this interceptor for a given code block :
class MoneyDomain {

static Object money(Closure closure) {
def orgMetaClass = InvokerHelper.metaRegistry.getMetaClass(Integer.class)
MoneyDelegatingMetaClass myMetaClass = new MoneyDelegatingMetaClass(Integer.class)
InvokerHelper.metaRegistry.setMetaClass(Integer.class, myMetaClass)
try {
return closure.call()
} finally {
InvokerHelper.metaRegistry.setMetaClass(Integer.class, orgMetaClass)
}
}

}
InvokerHelper.metaRegistry.setMetaClass call lets us register and unregister when we are done.
b. ProxyMetaClass
Another way of doing is using the ProxyMetaClass api. We again wrote a similar interceptor :
class MoneyDomainInterceptor implements PropertyAccessInterceptor {

public Object beforeGet(Object obj, String property) {
if ("euro".equals(property)) {
return new Euro(obj);
} else {
return obj.getProperties().get(property);
}
}

public void beforeSet(Object obj, String property, Object newValue) {
}
}
This time we implemented the PropertyAccessInterceptor. And here is how we gonna use it :
class MoneyDomain {

def static proxy = ProxyMetaClass.getInstance(Integer.class);
static {
proxy.interceptor = new MoneyDomainInterceptor();
}

static void moneyProxy(closure) {
proxy.use(closure);
}
}
}
And thats my short journey of the Groovy language.