Sunday, December 7, 2008

Getting Started Project-GraniteDS with Spring,Hibernate and Cairngorm,part 3

Ok, finally i got to the third part of this series to create a flex client. So in this part we'll create a flex project in eclipse and run it inside the server that we created in the part2.

So in eclipse open the Flex Development Perspective and create a new Flex project as
Give the name GettingStarted_GDS_Client. And select the application server type as J2EE. Now the next step is to setup the J2EE server so below snapshot shows the three fields

1. Web Root : This is the folder inside your workspace .metadata folder where the eclipse put the server application. For example my workspace is in D:\blog. So if you have run your server successfully you can see GettingStarted_GDS folder inside so the Web Root for me would be
D:\blog\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps. Now set the Web Root to D:\blog\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\GettingStarted_GDS\WEB-INF
this is the location where it finds the configuration files from the server project.

2. Root URL : http://localhost:8080/GettingStarted_GDS
3. Output Folder: This is the location where the generated swf files are dumped so it should be the same folder D:\blog\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\GettingStarted_GDS

Now the next step is to use the libraries from graniteds there are few library swc files from from graniteds, Cairngorm etc.

Now the last step for project setup is to add few compiler arguments in flex project, right click the project and select Flex Compiler from the left panel and add these lines in the field Additional compiler arguments:
-locale en_US -services ../../GettingStarted_GDS/webapp/WEB-INF/flex/services-config.xml -include-libraries ../libs/granite.swc -include-libraries ../libs/granite-hibernate.swc

as shown
this is required otherwise the flex client won't be able to detect the destination defined in services-config.xml file of our server project. I bet the flex client won't be able to find the destination without this and i figured this out after quite a bit of research.

So we can write some code for simple ugly UI that just creates the contact and displays the contact in the grid using a Cairngorm framework.
So talking about Cairngorm it's an MVC based framework for the development of flex application. It is basically a blend of best practices that has been followed in J2EE applications over the years, to have the clear separation between model,view and the controller with events being the communicator between views and commands.

If i have to repeat the things here is what Caringorm framework provides.
1. Model represent data objects
2. Controller does the business logic.
3. Events triggers business logic in commands.

To achieve the above flow, the Cairngorm has 5 components so we create them in our code one by one
1. ModelLocator: Singleton class to hold the model objects

2.ServiceLocator:Also a singleton class, to locate the java service or remote objects. It's based on ServiceLocator pattern.We create a mxml file called Services.mxml and define all the remote objects.So whenever these backend java service has to be invoked by the client we use com.adobe.cairngorm.business.ServiceLocator singleton class and do a service lookup based on name.

Object contactService = ServiceLocator.getInstance().getService("contactServiceObject"); where "contactServiceObject" is the id of the RDS defined in Services.mxml file as



remember destination="contacts" should match the destination id="contacts" defined in services-config.xml file in our server.

so we invoke the service method as contactService.saveContact(contact);

3. Events: Cairngorm leverages the event delegation model of flex, so when the things happen in the view layer it can create and dispatch the events which is then delegated by the controller to its command or say business object to take the necessary action.

so we define an event called ContactEvent that extends com.adobe.cairngorm.control.CairngormEvent class
event should have id which is used to dispatch the event from the view.And also it wraps any model if associated with that event. In our case we give the id "saveContact" which is dispatched when we try to save contact and it wraps 'Contact.as' model.

so to dispatch the ContactEvent from the view we do it as

public function handleAdd(event:Event):void {
var contactEvent:ContactEvent = new ContactEvent();
var contact:Contact = new Contact();
contact.name = contactName.text;
contact.email = email.text;
contactEvent._contact = contact;
contactEvent.dispatch();
}


4. Commands: Commands contain all the business logic that is related to a particular event delegated to it. The command can update the models,perform necessary business logic and can also delegate the control to delgates for service method invocations if we want to that way but for this sample i will invoke the service method from command only.
the command implements com.adobe.cairngorm.commands.Command and implement execute() method

5. Controller: Last is the controller which extends FrontController from Cairngorm. Here we map the event to command as

addCommand(ContactEvent.EVENT_ID,ContactCommand);

Now we are ready to write the code to display a grid and simple form. The complete source can be found here. Now when you run the server as Run-> Run on Server. It should open up the browser with the page shown below.
checkout the source. Hope this is helpful to have a quickstart. Also can anyone please tell me how to include code in blog pots. nothing works for me.



Saturday, December 6, 2008

running eclipse with Java 6 on mac

mac book comes with Java 5 pre installed, so once you upgrade to Java 6 you will have trouble running eclipse since eclipse by default looks for Java 5. So to run eclipse with Java 6 you need to edit Info.plist file located somewhere around

/Applications/ganymede/Eclipse.app/Contents

so open Info.plist in your favourate editor and uncomment the line to enable eclipse to use Java 5 installation. See the snapshot

Thursday, August 28, 2008

Answer to an interview problem !!! My Favourite Interview Question!!

there is one interview problem posted in
http://johnheintz.blogspot.com/2008/08/my-favorite-inverview-question.html, found in dzone.

Here is my version of solution:

I'll rather move deer under animal as well since it's an animal and implement Food as the interface for all those which are eatable like Deer,Grass,Cow etc.. so now my Animal class would be like

public abstract class Animal {
EatBehavior behavior;
public Animal(EatBehavior behavior) {
this.behavior = behavior;
}
public String eatFood(Food food) {
return behavior.eatFood(food);
}
}

Since eating is some kind of action or behavior i'll use an interface EatBehavior to denot that action

public interface EatBehavior {
public String eatFood(Food food);
public boolean isEatable(Food food);
}



Now finally i will have EatBehaviorImpl that does the eating and checking thing if it can be eatable or not??

public class EatBehaviorImpl implements EatBehavior {
public String eatFood(Food food) {
if (isEatable(food)) {
return "i can eat";
} else {
return "ek cannot eat";
}
}
public boolean isEatable(Food food) {
// return if food is eatable
return false;
}
}

i think isEatable make sense since we know in advance what can an animal eat or cannot pretty much so we can have some kind of map instead of relying on our models. So finally our any animal would be like

public class Tiger extends Animal {
public EatBehavior behavior;
public Tiger(EatBehavior behavior) {
super(behavior);
}
}
remember Tiger do not need to implement Food as it's on the top of the food chain, other animals or say grass object have to implement food.
now in any subclass of animal we just need to pass the specific impl of EatingBehavior. So I hope this makes sense, do suggest me if i am totally thinking out of this world.

Saturday, August 23, 2008

Getting Started Project-GraniteDS with Spring,Hibernate and Cairngorm,part 2

This is the second post in the series for getting started project Flex with spring/hibernate stack using GraniteDS as remoting server. So in my first post i created sample_graniteds database with a single table "Contact"
Now we'll create a server project using eclipse which has a GraniteDS nature and it will contain all the server related code as well as configuration files for graniteds such as service configuration and granite configuration.

Note:You can add the graniteds nature to a project by Right click on the project and add graniteds nature.

Before doing that i assume that you already have your eclipse setup with WTP plugin for running tomcat from eclipse, Flex builder plugin, and also a plugin for gas3 generator from GraniteDS,
Download granite-eclipse-builder-1.1.0RC4 and unzip it in your eclipse plugin directory and restart the eclipse. Also download the tomcat server, tomcat 6 would be fine. Follow the following steps

1. Define a Server in eclipse, select Windows->Preference then select server and installed runtimes, now add the tomcat 6 server as an installed runtime, as shown in snapshot below.

2. Now Create a new server project, File->New->Project then create a dynamic web project say GettingStarted_GDS as shown in the snapshots below.

i) Select Dynamic Web Project

ii) Define the Project Name and the Server

iii) Select this default configuration.

iv) define context root, content directory and click finish.

3. Now we have the project setup it's time to create a packages and required folders, as shown in the snapshot below.

name of the packages and folders are quite intuitive and since this is not a maven project we need the required libraries, ya it's absurd to play with jar files in the world dominated by maven. I have placed the complete project here, you can download the project and copy the jar files from WEB-INF/lib folder and to your lib folder.

4. Now need to write some code Contact.java as model, ContatDao.java as dao interface, ContactDaoImpl.java as implementation of dao and similarly ContactManager.java and ContactManagerImpl.java for service layer. Since these code contain very simple code for a CRUD operation i won't define them in detail here instead you can look at them directly by downloading the source. Similarly define the configuration files like
applicationContext.xml, daoContext.xml, managerContext.xml and hibernate.cfg.xml files. You can browse all these very simple configuration files here
Note: you might need to change the user/password for your database in the daoContext.xml file

5. Till now we have most of the server code and configuration ready now we'll define graniteds specific configuration files. Basically there are two configuration files that are needed for graniteds to work with spring/hibernate stack and the flex client. One is services-config.xml where you define your services that are to be exposed to the client via spring destinations that is invoked by a client using a RemoteObject. So a service defintion typically include destination which specifies the java class or service, channels to use to expose that service and the actual source that represents the destination. so we define our services-config.xml inside folder /webapp/WEB-INF/flex/ as services-config.xml

Other file is graniteds-config.xml, where we define the configuration to externalize our hibernate POJOs without implementing the Externalizable interface in our POJOs. The whole point of externalizing an object is to have a complete control over the format and contents of the stream for an object its parent and childs, as we are (de)serializing the object using AMF3 format over AMFChannel provided by flex messaging. But AMF3 serialization/deserialization does not provide any way to transfer private or protected fields (this is the case with BlazeDS as well as LCDS) so to serialize/deserialize the private and protected fields we use externalization mechanism in graniteDS so lets define grante-config.xml inside
/webapp/WEB-INF/granite folder as granite-config.xml

basically in this configuration file we are asking grantieds to externalize the beans(Contact.java) that is annotated with javax.persistence.Entity. Now we have the graniteds ready to externalize our java beans so we will use a AS3 bean generator tool to generate the corresponding actionscript class for the externalized java bean from the compiled java classes. GAS3 is an ant task based tool that relieves you from the painful task of writing corresponding actionscript classes for all your externalized java bean or say hibernate POJOs in our case. Now create a build.xml ant file in the root folder of your project as build.xml

So this build file defines the target generate.gas3 which generates the actionscript classes in output directory "as" and use all the compiled java classes from the folder build/classes/com/gettingstarted/gds/model. For each of the java class it generates two actionscript class so in our case it will generate

  • com.gettingstarted.gds.model.ContactBase.as: this bean mainly contains fields, getters, setters and IExternalizable methods (readExternal/writeExternal). This file is generated if it does not exist or if it is outdated.
  • com.gettingstarted.gds.model.Contact.as: this bean inherits from the "Base" one and is only generated if it does not exist.
We'll execute this ant file when we work on the client module. For now we'll finally define the web.xml for our server as web.xml
here we just define the AMF servlet and filter from graniteds. Now we are ready to run the server,To make it easy just checkout the project from the svn location here
or do svn checkout http://gettingstarted-gds.googlecode.com/svn/trunk/
If everything is setup properly you can run the server as Run->Run on Server and it should start the server without throwing any errors in the console.

So this is it, in the third post i will create a rich flex client using a Cairngorm MVC pattern. Do comment if anything needs to be updated or if anything is wrong.



Tuesday, August 19, 2008

IE6 must be causing lot of money to corporates

i am working in one ecommerce project for almost more than 4 months now, and by now i have seen lots of UI bugs that actually happens in IE6 only, and these are the bugs that even a very good UI designer or developer hate to fix it, and one can imagine how much extra effort and money corporate has to invest on these so called IE6 bugs,
Yes i know IE6 is still the most popular browser.

I found one interesting article http://ryanfarley.com/blog/archive/2008/08/18/why-i-am-no-longer-supporting-ie6.aspx
regarding why he did not support IE6 that seems reasonable to me.

Sunday, August 17, 2008

Getting Started Project-GraniteDS with Spring,Hibernate and Cairngorm,part 1

I have been playing with flex for a couple of weeks now,and i am trying to use flex as the UI and keeping the backend in Java with as usal Spring,Hibernate stack.

So in this series i will create a getting started project(CRUD contact management) using Spring,Hibernate/MySQL,Cairngorm as the UI MVC framework,GraniteDS for remoting and Tomcat as the server . For now i will create an eclipse based project and later move that to maven. The base intention of this project is to setup a prototype with all the above technologies defined and explore all the aspects of GraniteDS features to serve as the POC for other developers if they are willing to try it.

There are few other similar example available on the web such as
http://sebastien-arbogast.com/2008/04/10/flex-spring-and-blazeds-the-full-stack/
but it's based on BlazeDS but i want to try and explore gas3 generator,hibernate lazy-loading support from GraniteDS,To know more about GraniteDS vs BlazeDS you can see http://http://www.infoq.com/news/2008/02/granite-data-services
similarly http://code.google.com/p/igenko/ is a very good open source project but i think they are using content repository.

Anyway these are the basic 3 steps that i'll cover
  1. Create a server, this will contain all the java code and configuration files for both backend stack and also graniteDS related configuration files.
  2. Create a flex client based on Cairngorm's framework, gas3 generator from GraniteDS for generating actionscript classes for corresponding hibernate POJOs
  3. Deploy and run this basic project using eclipse on Tomcat

And once this is complete i'll convert the same project to maven project, and eventually try more complex hibernate mappings to explore all the aspects of lazy-loading and AMF3 serialization/deserialization support provided by GraniteDS.

So lets get started, at first create a mysql database name sample_graniteds and table contact

create database sample_graniteds;
CREATE TABLE CONTACT (
id bigint(20) not null auto_increment primary key,
name varchar(30),
email varchar(50)
);



In the next post i'll create a server project that contains all the business code as well as configuration files for flex rich client.

Wednesday, August 13, 2008

best way to use eclipse-heap space management

in my office we are working on a huge ecommerce project and off course we do use eclipse as an IDE , but eclipse being heavily loaded with various plugins and the amount of codebase that a workspace contains my colleagues often complains of eclipse being slow.
By default eclipse uses 64MB by default as a heap space size, so we can increase that using the eclipse.ini file so this works really great for me

1. create a batch file lets say in your desktop with the contents
start C:\eclipse\eclipse.exe -clean -vmargs -Xms768m -Xmx1024m -XX:PermSize=128m -XX:MaxPermSize=256m
values may be defined based on memory available on your computer.

2. Once you open eclipse Select Window->Preferences and the check mark "Show heap status" option this will show the heap status in the bottom right corner of the eclipse window where you can run the garbage collector by clicking on the small icon to free some memory on time to time basis.

Monday, August 11, 2008

java equals and hashCode

I always wanted a good explaination about implementing equals and hashCode methods of Java Object class, here i found one today
http://www.geocities.com/technofundo/tech/java/equalhash.html

Tuesday, July 29, 2008

Nearly Failed in programming IQ Test

Today i tumbled upon one programming related IQ test by InfoWorld http://www.infoworld.com/tools/quiz/news/2008/programmingiqtest/programming-iq-quiz-1.php

and out of 20 questions each worth 5 points i just manage to secure 50 points, but i did made a few mistakes which i should not have, anyway i believe i still need to go a long way to improve myself..

Friday, July 25, 2008

what's next after social networking flood

I always wonder what's the next big shift in terms of how general people interact in the web. By general people i mean millions of users pouring and pounding just for fun, as now what's happening with all the social networking sites such as Facebook, Hi5, MySpace and many more. Couple of years back it was a real big shift in the idea of internet use for the users who just want to have fun and be connected to people when these social networking site started emerging. Now it's now more or less a part of every teen or young people.
Facebook came up with the application platform to allow users or say developers to develop application which in a way was an innovative move to be on top of the race among social networking giants. Though I don't really use these sites as such but i like to play with it sometimes and i enjoy it,but i always think what's next ?? similar to social networking sites or may be different than these or similar but not the same which again will provide a new dimension to users and lure millions of users to use it and which has a potential to make few more billionaire who can come up with this new internet buzz. I wonder if anyone can come up with something that let these millions of users do something productive or say collaborative with fun and cohesiveness with other users intact as an integral part rather than just sharing photos and writing on the wall.... but i am very sure one day some geek will come up with one or the other innovative inception to amaze me and other millions of internet users and me feel crap why the hell i did not think of that.... just have to wait and see.

Sunday, July 20, 2008

My First blog post

This is my first post, I know it's kinda late but i believe i belong to 80% category of the programmer (if you have read about famous 80-20 percent division). But everything has to start from the beginning. And this is it. :)