Thursday, November 27, 2008

Integrate Grails with Extjs

0/1 -> C -> C++ -> Java -> ? (Assume it is: Grails + extjs)

Extjs acts as front-end, grails works as back-end. Both Grails and Extjs can handle JSON very well. Grails has built-in support for JSON. This is not surprise that JSON will be communication tool between them.

However, in Grails official documentation, there is not enough statement for how to generate JSON. Here comes some of my example to create JSON with Grails (List, Create, Update, Delete), and this JSON data will be feed into extjs (i.e: extjs sexy part - grid).

Feeling: Grails saved me lots of time to write backend code - not need any config and I do not need write hibernate mapping, this is amazing. It really let developer focus on application business logic (Still remember 2000 when EJB come and said this - it really did not). Just Eclipse does not well support grails at this moment, hopefully it come soon.

See open source calendar app: www.cubedrive.com/myCalendar

0: Update with NetBeans IDE6.5 [Update Dec 24]

Recently I played this with NetBeans IDE6.5. Seems this one better than Eclipse, you just download the latest Netbeans package (250 M - huge). And Netbeans already have grails plugin. And you can simple click run button to make grails project run. Worth to have a try - I guess I will stay in Netbeans for a while in grails project.

1: Quick setup


2: list in Grail controller and extjs
/**
* Copyright (c) 2005 - 2008 FeyaSoft Corp. All Rights Reserved.
*/
import grails.converters.*

import com.feyasoft.myActivity.domain.account.*

/**
* @author Fenqiang Zhuang
* @Dec 1, 2008
*
* This file is used to define the account controller action
* This will provides the service for UI level.
* Most important actions are list, save, update, delete
*/
class AccountController {

// the delete, save and update actions only accept POST requests - maybe not necessary
def allowedMethods = [delete:'POST', update:'POST', create:'POST']

/**
* Mapping url: http://localhost:8080/fileMgr/account/list
*
* This will lost of accounts in the system based on search result.
* Return result will be in JSON format.
*
*/
def list = {
// log information
log.info(params: params)
if(!params.max) params.max = 20

// get a list of result based on params.
def accounts = Account.list(params)

// return a bunch of json data with metadata.
def json = [
metaData: [
totalProperty: 'totalCount',
root: 'results',
id: 'id',
fields: [
[name: "id", type: "int"],
[name: "firstname"],
[name: "lastname"],
[name: "username"],
[name: "email"]
]
],
totalCount: accounts.size,
results: accounts
]

render json as JSON
}

/**
* * Mapping url: http://localhost:8080/fileMgr/account/save
*
* create account method - get passed parameter from extjs and call save() function
* If everything ok, it will return success message for form.
*/
def create = {
def account = new Account(params)

// default error msg
def json = [failure : "true", errorInfo : "Internal Error, please try again"]

// check whether something wrong in save
if(!account.hasErrors()) {
// check username already exist or not
if (Account.findAllByUsername(account.username).size()>0) {
json = [failure : "true", errorInfo: "This username already existed, please choose another one"]
} else if (account.save()) {
json = [success : "true", info : "You have success creat this account"]
} else {
def errors = "Error is: "
account.errors.allErrors.each {
errors = errors + it
}
json = [failure : "true", errorInfo: errors]
}
}

// return json data
render json as JSON
}

/**
* This will load existing account information based on id from UI.
* Return back a json string.
*
* JSON like this:
*
* {"success":"true","data":[{"id":4,"class":"Account","createDate":new Date(1227909694000),
* "email":"","firstname":"jj","lastModifiedDate":new Date(1227909694000),"lastname":"j",
* "password":"kkkk","username":"llkl"}]}
*/
def load = {
def account = Account.get(params.id)

if(account) {
def json = [success: "true", data: [account]]
render json as JSON
} else {
// default error msg
def json = [failure : "true", errorInfo : "Internal Error, please try again"]
render json as JSON
}
}

/**
* This will update the passed parameter from UI level
* Called by the Edit.js file.
*/
def update = {
def account = Account.get( params.id )

// default error msg
def json = [failure : "true", errorInfo : "Internal Error, please try again"]

if(account) {
account.properties = params
if(!account.hasErrors()) {
if (account.save()){
json = [success : "true", info : "You have success update this account"]
} else {
def errors = "Error is: "
account.errors.allErrors.each {
errors = errors + it
}
json = [failure : "true", errorInfo: errors]
}
}
}

// return json data
render json as JSON
}

/**
* Delete this related account by id - passed by
*/
def delete = {
def json = [failure : "true", errorInfo : "Internal Error, please try again"]

// check whether del parameter is passed - if yes, delete first
if (params.delData != null) {
def jsonArray = JSON.parse(params.delData)
jsonArray.each {
log.info("start to delete account with id: ${it.id}")
def delAccount = Account.get(new Long("${it.id}"))
if (delAccount) {
delAccount.delete()
json = [success : "true", info : "You have success delete this account"]
}
}
}

render json as JSON
}
}
Here is the extjs side code:
    feyaSoft.account.List = function() {

Ext.QuickTips.init();

// define default rowsPerPage = 10;
var myPageSize = 20;

var accountCM = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
{id: 'id', header: "Identify", dataIndex: 'id', width: 150, hidden: true},
{header: "First Name", dataIndex: 'firstname',width: 150},
{header: "Last Name", dataIndex: 'lastname',width: 150},
{header: "Username", dataIndex: 'username',width: 150},
{header: "Email", dataIndex: 'email',width: 150}
]);
accountCM.defaultSortable = false;

/************************************************************
* connect to backend - grid - core part
* create the Data Store
* connect with backend and list the result in page
* through JSON format
************************************************************/
this.dataStore = new Ext.data.JsonStore({
url: 'account/list',
remoteSort: true,
fields: [] // initialized from json metadata
});
this.dataStore.setDefaultSort('lastname', 'ASC');

/************************************************************
* Define menubar now in here
* add and delete functions
************************************************************/
var menubar = [{
text:'Add New Account',
tooltip:'Add a new account information',
iconCls:'addItem',
handler: function(){
// add new user now - call another JS class
new feyaSoft.account.Create();
}
},'-',{
text:'Archive',
tooltip:'Archive the selected items',
iconCls:'remove',
handler: function(){
//new feyaSoft.util.DeleteItem({panel: 'listAccount-panel'});
}
}];

var pagingbar = new Ext.ux.PagingToolbar({
pageSize: myPageSize,
store: this.dataStore,
displayInfo: true,
displayMsg: 'Displaying items {0} - {1} of {2}',
emptyMsg: "not result to display"
});

/************************************************************
* define grid panel now
* For more detail parameters, you can find from extjs API
************************************************************/
feyaSoft.account.List.superclass.constructor.call(this, {
id: 'list-account-panel',
ds: this.dataStore,
cm: accountCM,
viewConfig: {forceFit:true},
tbar: menubar,
bbar: pagingbar,
height:400,
width:800,
frame: true,
autoScroll:true
});

// trigger the data store load
this.dataStore.load({params:{start:0, limit:myPageSize}});

};

Ext.extend(feyaSoft.account.List, Ext.grid.GridPanel, {

// reload datasource
reload : function () {
this.dataStore.load();
},

remove : function (row) {
this.dataStore.remove(row);
},

deleteData : function (jsonData) {
this.dataStore.load({params:{start:0, delData:jsonData}});
}
});

Some hints maybe help for your to use Grails:

1: Get latest version Grail 1.0.4 and setup GRAIL_HOME in your ENV: http://grails.org/

2: Create a grails project through Eclipse.

3: Update

You do not need create tables - using dbCreate="create" for first time and grails will create DB table for us (you do need create database name). Go to:
grails-app/conf/DataSource.groovy file, you need update:
 dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
username = "root"
password = "XXXXXX"
}

development {
dataSource {
dbCreate = "update" // one of 'create', 'create-drop', 'update' - first time, please use 'create'
url = "jdbc:mysql://localhost:3306/demo?tcpKeepAlive=true&useUnicode=true&characterEncoding=UTF8"
}
}

4: Run

come to the project folder: cd yourProjectFolder // using cmd

> grails clean <--- sometimes compiled code are not cleaned and behavior weird - clean will help
> grails run-app

You can also run this through ant in Eclipse. However, I do not know how to stop Jetty under Eclipse (Finally I kill it through Ctrl + Alt + del and find task manager - kill all of Java running thread.).

Wednesday, November 05, 2008

Extjs based Calendar 1.0 release

After a while (6 month later), we finially have some time and move our calendar forward again. In this release 1.0, you will see the following feature:
  • Fully integrated in Ext
  • different views (day, week, month)
  • create/delete/change entries -- contextMenu and doubleClick
  • drag and drop to shift entries
  • Event overlaps
  • event south resizeable
  • edit entries in a window
  • colorable event
The project structure is still:

Extjs + spring MVC Json View + Spring + hibernate + Mysql

To view demo, please visit: www.feyasoft.com

Monday, October 20, 2008

Adobe AIR + extjs for desktop application

For building desktop application, there have .Net and Java Swing solution. However, there seems not that elegant for me. Recently we are trying to use following structure to build own desktop application:

Adobe AIR (SQLite buildin) + extjs

This is the general steps we process to build extjs + AIR project:

1: Download develop tool which will use to edit/package adobe air project (Adobe air and Aptana studio)


2: Start Aptana and install plugin

Click the icon (4th or 5th icon in second line): "Open Plugin View", you will find:
  • Adobe Air support
  • extjs support
Install those 2 plugin.

3: Now start Aptana - create new project

File -> New -> project -> Adobe Air Project

You can create some example project - such as: Tasks. And you will find 2 important files: tasks.html and application.xml

4: Hit: Run -> Run ...

You will see your example running ...

5: Export/deploy air project.

You need setup certificate. Every AIR application requires certificate signing in order to be built and deployed.See this link for more information:

http://www.adobe.com/devnet/air/ajax/articles/building_on_air_in_aptana_05.html

Some problem ...

* If you see "invocation forwarded to primary instance"
You need go to your task manager and kill manually ADL.EXE

Wednesday, June 04, 2008

DWR or Spring MVC + JSONView

To build extjs based application. At first glance, you will find that DWR is pretty neat. You do not need MVC level code and client side can talk direct to service layer. Seems this will save lots of time and code.

Wait.... Is this really true? (perfect solution = time cosuming ?)

After fight with DWR problem for a while, I decide move back to Spring MVC JsonView.

Extjs have a pretty good interface to hanlde JSON data. By using DWR, you need decide whether you still use JSON data, or pass trhough object (maybe parameter). You need write your own reader to understand passed object. At least you need write: DWRTreeProxy, DWRListProxy, DWRComboProxy. True, you can copy those proxy from forum, there are lots of examples. However, those example does not have quality guarantee, and it drive me crazy to debug line by line.

I try to save time when I move to DWR, finally I found I spent more time that using Spring MVC + JsonView.

Suggestion: if you know really well for extjs and DWR, you can try using DWR. Jack said that he had a really success porject with Extjs + DWR. However, Jack is Jack. Otherwise, keep Extjs + JsonView. This will save your lots of time. (honestly, Extjs + JsonView already really beautiful, DWR seems a perfect solution, however it will take your long time if you are not as smart as Jack - oh ya, I am only 10% smart as Jack)

Friday, March 28, 2008

Spring MVC JSON view

For Ajax-based web application, one of the most popular ways for message transfer is JSON (JavaScript Object Notation). JSON provides a pretty name/value pair data format which is easy to generate and parse.

With the popular using Spring framework. It would be really useful to integrate Spring MVC view with JSON. Spring already provides several view resolvers, which enable us to render models in a browser, such as: JSPs, Velocity templates and XSLT views.

To add JSON view to the Spring MVC, we need create a class: JSONView

public class JSONView implements View {
private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json";
private static final String DEFAULT_JAVASCRIPT_TYPE = "text/javascript";
private JSONObject jsonObject;

public JSONView(JSONObject jsonObject) {
super();
this.jsonObject = jsonObject;
}

public JSONView() {
super();
this.jsonObject = null;
}

public String getContentType() {
return DEFAULT_JSON_CONTENT_TYPE;
}

public void render(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
if (this.jsonObject == null) {
this.jsonObject = JsonUtil.fromMap(model);
}

boolean scriptTag = false;
String cb = request.getParameter("callback");
if (cb != null) {
scriptTag = true;
response.setContentType(DEFAULT_JAVASCRIPT_TYPE);
} else {
response.setContentType(DEFAULT_JSON_CONTENT_TYPE);
}

PrintWriter out = response.getWriter();
if (scriptTag) {
out.write(cb + "(");
}
out.write(this.jsonObject.toString());
if (scriptTag) {
out.write(");");
}
}
}

And this is fromMap function in JsonUtil

public static JSONObject fromMap(Map model) {
JSONObject jsonObject = new JSONObject();

try {
Iterator ite = model.keySet().iterator();
while (ite.hasNext()) {
String key = ite.next();
jsonObject.put(key, model.get(key));
}
} catch (Exception e) {
log.error("call fromMap failed ");
}

return jsonObject;
}

And in the controller side, we can pass JOSNObject to create a JSONView. Or we can also pass MAP to create JSONView.

Map map = new HashMap();
map.put("success", "true");
map.put("info", "Succeed create this audit object");
return new ModelAndView(new JSONView(), map);
OR

BaseSearchResult searchResult = auditService.getList(listAuditInfo);
AuditUtil auditUtil = new AuditUtil(searchResult);
return new ModelAndView(new JSONView(auditUtil.toJSONObject()));

Thursday, February 28, 2008

FeyaSoft MyActivity

After awhile, FeyaSoft MyActivity 1.0 is released now. It includes the following features:
  • My Calendar
  • My Documents
  • My TimeSheet
  • My Task (1.1 release)
The main purpose for this application is try to make your daily activity smooth and easily. And it is pretty easy plugin to your existing system.

To view it, please go to the following link self-register and login:

http://www.feyasoft.com/myActivity

The whole system is built with:

EXTJS + Acegi Security + Spring MVC(JSON View) + Spring + Hibernate(Annotation) + mysql

Simple, qualify and affordable. ENJOY

Saturday, December 29, 2007

Extjs Calendar

After fought for 2 weeks, extjs calendar Beta0.1 is released today. It has the following features:
  • create/delete/change entries (one click for create new entry; double click for edit and delete entry)
  • drag and drop to shift entries
  • edit entries in a window (double click)
  • resize the entry in south direction
This design is based on the EXTJS ajax framework. To view the demo, please see the following link:

http://www.feyasoft.com -> click 'My Calendar' icon on the desktop.

Sunday, December 02, 2007

Ajax based (EXTJS) application authentication

For Ajax based authentication, it's not a whole lot different than providing a traditional web infrastructure. What we're aiming for is to guarantee our session is secure and there is an established and persistent authentication object for all requests. There are a number of ways to accomplish this.

First is to secure the wire. This means whatever we do, make sure the user can never get to the website via regular HTTP and always uses HTTPS. It's pretty simple to setup Apache to do this.

Next is the authentication mechanism. The objective here is to generate and cache a session object that is guaranteed to be correct between the web server and the web browser for the duration of that web browser's session or until a session timeout occurs. This can easily be provided in one of two ways: HTTP authentication or HTTP sessions.

The positives of HTTP authentication is that it's standards based and provides transparent authentication after an initial authentication is complete. We get headers for the username, password, and realm for every invocation to the web service after this is completed. This includes invocations with our embedded ajax components. The negatives is that it's not secure, so we absolutely need to push it over HTTPS if you're going to use it. In addition, there's no authorization mechanism built in, so we need to roll own for authorization levels. And finally, we can't log out if using HTTP authentication. Once a user is authenticated, there's no means to unauthenticate them other than closing the browser and starting over.

Session-based authentication provides similar functionality to HTTP authentication, but we need to manage the session information. It does not provide a means to do authorization levels either, requiring we to roll our authorization levels. The benefit of session-based authentication is that we can log out from a session by removing the session variable at the web server. The disadvantages of using session-based authentication is that we have to figure out a mechanism to store passwords in other than cleartext format. This is because we're not sent the username/password combo in the headers, but instead we get a sessionid for the established session.

A basic rule of thumb, provided we're not doing persistent cookie session information, is that until a user establishes a known authentication session with web server, there are no credentials available with which to guarantee their access. Typically the ONLY place I need to make absolutely certain that authentication has happened is on the server, since that's where all of the data will be housed. The browser is just a window into that data.

From a technical perspective, here's how a session-based authentication would work:
  • User starts a brand new browser and connects to ajax-enabled app.
  • Application then posts some type of dialog box requiring a login to the server
  • The user enters their username/password into that dialog and clicks the login button
  • Javascript should hook the login button and send an ajax request to whatever login script/service/servlet/whatever is running on the server side
  • The server takes the parameters and passes them through whatever authentication system using on the server.
  • If the credentials work, the server creates a sessionid storage area for this new sessionid and returns a positive response to the ajax client. Part of the http headers for this response is the sessionid for maintaining session information between the client and the server. In the sessionid storage area on the server, we can store whatever variables we want to store.
  • The HTTP stack in the browser maintains the sessionid for each successive invocation to the web server that it's talking to and ONLY for that web server. As long as the browser is running, the sessionid is maintained. Once the browser goes away, the sessionid goes away with it. There are known session hijacking hacks out there, but they can be averted by providing a bit more information within the variables attached to the sessionid on the server.
  • Each of the successive xmlhttprequest objects that ask for data from the server pass the sessionid with it. In our application on the server, the first thing we need do for EVERY invocation is validate that the sessionid is still valid. There are mechanisms in most server application frameworks to provide session expiration by a variety of means. We just need to validate their sessionid with whatever framework you're using.

Monday, November 26, 2007

Friday, October 26, 2007

Light J2EE Application High Level Architecture Diagram


For Web Application, industry are pretty close agree to use light J2EE (Spring + hibernate) loose coupling concepts in business logic tier. However, there are not clear blueprint for presentation tie. Do we still need use thin-client or rich-client? I believe it is time to move (at least think) rich client. In here, I introduce a model for thick client:

1: Download Client-side application to user browser. (For example: extjs)
2: Client-side logic flow
3: Data exchange through AJAX in JSON format (client-server event driver)

For thin client, we can not respect "data" exchange between client and server. Maybe it just a kind of "String" exchange. For thick client, it is real data (JSON).

Reference
:
1: Put JSF to work -- Build a real-world Web application with JavaServer Faces, the Spring Framework, and Hibernate; Derek Yang Shen, JavaWorld.com;

Tuesday, September 18, 2007

Improve pages performance - 2 cents

  • Reduces the number of HTTP requests - Reducing the number of components to be downloaded.
  • Moving stylesheets to the document HEAD - makes pages load faster.
  • Move scripts from the top to as low in the page as possible - enable progressive rendering.
  • Avoid CSS expression.
  • Reduce DNS lookup.
  • Avoid page redirect.
  • Clean Scripts code - remove duplicate code.

Sunday, August 19, 2007

Javascript files Directory Structure

Currently there does not exist any standard structure for javascript files directory. In here, I just follow the Java file structure and create a similar file structure for javascript.

As you see, I create a dir 'javascript' which is used to hold all of JS files. And I also create a project related dir 'FEYA' which is used to hold all of my JS file. Any 3rd-party JS lib are parallel to this dir.

Under 'FEYA' dir, 'FEYA.js' is used to define namespace. Any other my JS file will call it to define package. And here comes my example html code to include those JS files:





Tuesday, July 24, 2007

Javascript package/public/private method

Perhaps a very uncommon approach to developing web applications that require JavaScript is namespacing your scripts. And how to define a scope (public/private) to the method and variable. This blog introduces a simple singleton pattern for achieving this discipline.

First I define a base JS class which will be included in any page to define a package (or you can call it 'namespace'). See right figure for detail source code.

Second, I will call this method in any JS class - define the package just like java class.
/**
* Copyright(c) 2006-2007 ...
*/
package("FEYA.util");

/**
* This JS is used to define a bunch of util class
*
* @author fzhuang
* @Date July 26, 2007
*/
FEYA.util.common = function(){
// private variable/function. Not accessible from outside
var count = 0;
var increaseCount = function(){count++;};

// Priviledged method. Can be called from outside
return {
formatDate: function(value){
return value ? value.dateFormat('D, M d Y') : '';
}
}
}();
Third, I can call following public functions from any JS class.
FEYA.util.common.formatDate

Saturday, June 16, 2007

YUI-Ext tutorial for List, create, update, delete

Today I posted the following tutorial in YUI-EXT, please see the link:

Using Ext grid + form + dialog to achieve paging list, create, edit, delete function

This tutorial mainly focus on using EXT grid/form/dialog functions to achieve general paging action (list, create, update, delete). It provides a different pattern to build page instead of J2EE MVC pattern.

Thursday, May 10, 2007

Web 2.0 application: Ajax replace MVC framework

We have played Struts/JSF/Spring/hibernate for Enterprise application, doing transaction etc for a while. Now it is time move to web 2.0 (readable) and face AJAX.

In web application, Struts/JSF MVC framework are pretty popular. However, Ajax-based web application can make this process simpler. As the following figure shows, Ajax based application only need a simple servelet to transfer data. Compare with MVC framework, this is a small job. At the same time, a good Ajax Util framework will create rich GUI in the client browser with simple javascript/html code. In general Ajax can be separated as 3 parts:


First part is client-side Ajax, such as animation, drag-and-drop, rich editor etc. YUI, dojo, rico provide lots of great examples.

Second part is the bridge between browser side and Java server side, like bunch of RPC frameworks, DWR, prototype, YUI etc.

Third part is general Ajax Util framework (templates) which can be applied to most applications, such as search function, paging function, CRUD/List function etc. We can think them as glue tool between browser and server, and it will dramatically reduce code by using those utils. YUI extension provides great example for this.

Sunday, April 29, 2007

JSON speed up Ajax

The JavaScript Object Notation, or JSON, is a lightweight syntax for representing data. JSON has structure with nesting of data elements, just as XML does. JSON is also text-based and use Unicode. It is just as readable by humans as XML is. Here comes a simple example for Json:
{"totalCount":2,
"results":[{"bh":"100","sm":"hello"},{"bh":"101","sm":"me" }]}
The big different about JSON and XML is that JSON is a subset of JavaScript. I can use JavaScript's own compiler to do just that by calling eval. Parsing JSON is a one-liner! Moreover, navigating an object synthesized from JSON is identical to navigating any JavaScript object. It's far easier than navigating through the DOM tree.

To create a JSON object in server side with Java. We can use the lib in "json.org". It provides a quick API to parse POJO and list etc. See the following example code:
public JSONObject toJSONObject() throws Exception {
JSONObject json = new JSONObject();
json.put("totalCount", totalCount);

JSONArray jsonItems = new JSONArray();
for (Iterator iter = results.iterator(); iter.hasNext();) {
jsonItems.put(iter.next().toJSONObject());
}
json.put("results", jsonItems);

return json;
}
To parse JSON data from JS in serve side, please see the following example:
JSONArray jsonArray = JsonUtil.getJsonArray(jsonString);
// JsonUtil.getJsonArray(jsonString) just do this ->
// jsonArray = new JSONArray(jsonString);

// loop through - get from json and update
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
}

Saturday, April 28, 2007

YUI extension

Jack Slocum launch YUI extension 1.0 recently in extjs.com. It provides a strong framework for Ajax project. YUI extension has the following interesting functions:
  • Online Grid editor (really convenience one - JSON)
  • Dialogs (Message dialog, progress dialog etc)
  • Menu (drop menu)
  • Tree
  • Resizable
  • Layout
EXTJS.com is very well documented and follows great OO principles and GUI design patterns. Furthermore, it provides really great example to show those functions. Although, the example is never enough for cover every cases.

Here comes one of my examples:

Monday, April 16, 2007

Ajax Request Compare

Currently, there exists several non-commercial AJAX frameworks for request during the development of a dynamic call-center application.
  • Prototype
  • Dojo
  • Direct Web Remoting (DWR)
  • Yahoo! User Interface (YUI) Toolkit
  • EXT JS
  • Google Web Toolkit (GWT)
Prototype is one of the most popular AJAX frameworks around.
postMsg : function(url, actId) {
var myAjax = new Ajax.Request(url,{
method: 'post',
parameters: 'actId='+escape(actId),
onComplete:handlerResult
});
},

Dojo is a popular, complete open source framework with broad support not only for Web widgets but also other important aspects of Web
application development such as interaction with backend systems.

dojo.io.bind({
url: url,
method: "post",
content: {actId: "123456"},
load: function(type, data, evt){/* callback code */ },
error: function(type, error){/* error handling callback */ },
mimetype: "text/plain"
});

DWR focus is making browser client/server interaction as simple and natural as possible.
public class PhoneService {
public String getCallerName(int callerNumber){...}
}
..script.. type="text/javascript" src="SVProvider/dwr/interface/PhoneService.js ..script..
PhoneService.getCallerName(18003456700, processPBXResponse)

YUI is an extremely rich, well documented, stable, and lush framework for AJAX-based development. YUI code is really professor feeling.
var requestFromObject = YAHOO.util.Connect.asynRequest('post', uri ,
callback , postData);
var callback = {
success: handleSuccess
failure: handleFailure
argument: {callerName: "N/A"}
};
Ext JS is another very popular Ajax framework. It also provides a XHR wrapper allowing quickly and efficiently perform AJAX requests.
Ext.Ajax.request({
url : '../listActivity.do' ,
params : { action : 'loadData' },
method: 'GET',
success: function ( result, request ) {
Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText);
},
failure: function ( result, request) {
Ext.MessageBox.alert('Failed', 'Successfully posted form: '+action.date);
}
});

Monday, April 02, 2007

JSF, Spring, iBatis integrate

Recently I created an application with JSF, Spring and iBatis. It seems pretty easy to integrate them together. Following list the system environment:
  • Tomcat - 5.5.23
  • Java - 1.5
  • JSF - 1.2
  • Spring - 2.0.3
  • iBatis - 2.3.0
  • database - Oracle
The system includes 3 simple configure file: applicationContext.xml, face-config.xml and sql-config.xml.



JSF have the following different features:
  • Swing-like object-oriented Web application development
  • Backing-bean management
  • Extensible UI component model
  • Flexible rendering model
  • Extensible conversion and validation model
However, one JSF thing that I really do not like is its huge configure file. For a big project, it huge configure file will make maintanance pretty hard.

A serviceLocator class is created in system to glue the JSF with Spring.



Like other persistence layers, iBATIS strives to ease the development of data-driven applications by abstracting the low-level details involved in database communication, as well as providing higher-level ORM capabilities. iBatis SQL Maps is a straightforward data access tool, working at the SQL level like JDBC code, but externalizing SQL statements and their result and parameter mappings into an XML file. Above figure shows the simple example for iBatis.

Thursday, March 01, 2007

Open JMS with Tomcat

In a loosely coupled and asynchronous communication, an application sends a message, and then continues program execution without waiting for a response. The sending program might not even know where or what the recipient is, because the communication between software components takes place via messaging. The Java Messaging Service (JMS) is the only messaging API supported by J2EE.

OpenJMS, a SourceForge project, is a free open source implementation of Sun Microsystems' JMS API specification.

Tuesday, February 06, 2007

iBATIS vs Hibernate

iBATIS works well when you need to integrate with an existing database.
Hibernate works well when you control the data model.

iBATIS maps Java Objects to the results of SQL Queries, whereas Hibernate maps Java Objects directly to database tables, traditional Object-Relational Mapping. The benefits of Hibernate are that it automatically generates all the SQL for your and the cache invalidation can be more fine grained. iBATIS is more flexible especially if you are a strong SQL query writer. You have control over exactly how the SQL queries are written.

Compared with Hibernate, iBATIS is more flexible, has a shorter learning curve, but can take more time to develop and maintain, since you have to write all your queries and if your object model changes you have to go through all your queries and make sure to make all the necessary changes to reflect the changes in your object model.

Tuesday, January 30, 2007

DWR integrate with Spring

DWR is a Java open source library which allows you to write Ajax web sites.

DWR consists of two main parts:

  • A Java Servlet running on the server that processes requests and sends responses back to the browser.
  • JavaScript running in the browser that sends requests and can dynamically update the webpage.
Why DWR:
  • mostly used Ajax framework
  • integrate best with Spring
  • RPC style Ajax
  • Java <--> Javascript marshalling (using Javascript objects)
  • Support most browser

Saturday, January 06, 2007

Yahoo YUI Calendar

Recently I start to look Yahoo YUI for rich UI. One feature is about Calendar. In general, YUI works pretty well with my application. However, one bug related to IE took me 2 days to figure it out.

When I click any date in Calendar. It subscribe to YUI render:
YAHOO.example.calendar.cal1.selectEvent.subscribe(mySelectDate, YAHOO.example.calendar.cal1, true);
YAHOO.example.calendar.cal1.addRenderer(txtDate1.value, YAHOO.example.calendar.cal1.renderCellStyleHighlight2);
YAHOO.example.calendar.cal1.render();
In my application, I need send new request to the server and get result for this specific date. It works well in Firefox, however, it does not always work in IE6. After dig for a while, there exist this code in YUI calendar.js:
YAHOO.widget.Calendar.prototype.renderCellDefault = function(workingDate, cell)
Exist: javascript:void(null) in href
IE does not pass javascript:void(null) in href.

href="javascript: ", onclick="javascript:" There is no such thing as a JavaScript protocol on the web. Links use protocols to connect documents.

Tuesday, January 02, 2007

Authentication and authorization - Acegi and More

Most of our web application are based on the form-based authorization and authentication - role based access control. Form-based authentication is the most popular web authentication mechanism in use. It provides us with the greatest control over the look and fell of the “login screen”.

Acegi provides a quick/simple/good solution for this. However, acegi also have some limitation:

1: Authentication

Acegi uses AuthenticationProcessingFilter. The AuthenticationProcessingFilter handles the Authentication Request Check (“logging into the application”). It uses the AuthenticationManager to do its work. One dsiadvantage is that we need create our login table based on the Acegi's wishes. And we also need access DB directly using SQL code.

2: Authorization

Acegi is based on the URL authorization. Secure URLs by role with regular expressions or ant-style pattern. First, role can not be added dynamically. Some actions (view and edit) use the same URLs, this bring problem for authorization.

To fix the above problem, we can build self simple security system.

Following list the tables relationship:



For each customer, it can create its own role and assign account to this role. For each service, there includes many features. And for each feature, it can be different privilege (verb: CRUD List etc). We can assign role to different privilege.

In each button/link field, we need add a parameter "privilegeCode", for example: privilegeCode=editAccount. We just need write a filter, this filter will check privilegeCode and login user privilege. If login user has this privilege, continue. Otherwise, permission deny.

Simple, easy and quick to fix the authorization issue in Acegi

Thursday, December 28, 2006

Acegi 1.0.3 - security framework

Acegi is an open source security framework that allows us to keep business logic free from security code. Acegi Security provides comprehensive security services for J2EE-based enterprise software applications.

Recently we decided to move security part from SecurityFilter to Acegi. It took me 3 days to finish switch. Seems Acegi integrate to our current system pretty well.

Currently our environment is: Tomcat5.5, Spring2, mySQL5, Hibernate3, Java1.5. Following list some simple steps:

web.xml

security-acegi-security.xml
filterInvocationDefinitionSource - httpSessionContextIntegrationFilter, authenticationProcessingFilter, exceptionTranslationFilter, filterSecurityInterceptor

Sunday, December 03, 2006

BIRT v.s. JasperReport

BIRT is an Eclipse-based open source reporting system for web applications, especially those based on Java and J2EE.

Jasper Report is a powerful open source Java reporting tool that has the ability to deliver rich content onto the screen, to the printer or into PDF, HTML, XLS, CSV and XML files.

JasperReports
- Easiest integrate to application and flexible from a developers standpoint.
- Supports a large number of export formats.
- Do not have free report designer tool.

Eclipse BIRT
- Excellent report designer and charting support. I can get create reports in a matter of minutes with great ease.
- Great support for reports with multiple datasources. However, it is also tedious to maintain extra datasource just for report.
- Harder to integrate into currently application.

Currently, when I deploy report to BIRT under tomcat environment. I need deploy it to a separate application. This application is totally used to handle all reports. For small application, it makes things complex and I am strong worry about its security. I also try to integrate BIRT report to my application, however it makes my WAR file pretty big (20M more).

BIRT is still a relatively young project and there lots more work that needs to be done. Maybe I need wait for next BIRT release.

Because my application is using spring framework. It does support a view to pretty easy integrate my JasperReport. This allow me to focus on my report design instead of other stuff. At the same time, code is pretty small and clean. So I decide to choose JasperReport as my report engine temporary.

Pro Spring has a good example shows how to integrate JasperReport into your application.



The order of this configure file is pretty important. First, it should be general viewResolver, then comes japserReportViewResolver.

Friday, October 20, 2006

J2EE without EJB feature lists

Tomcat - Application Server
Spring 2.0 - J2EE framework
Hibernate/iBatis - ORM
JSF/Spring/WebWork - Multi-Action Web Framework
JSP - View Template
Dojo, YUI/Extension, Rico, Prototype - Rich Client Widgets
Acegi - Authentication and authorization.
SiteMesh - Web page layout and decoration framework.
Quartz - Enterprise job scheduler.
Log4j - Logging Tool
OSCache - Simple Cache and Web Cache solution
Jasper Report - Report Engine
Lucene - Search engine
ExtremeTable - JSP Table Tag Libraries.
Junit - unit test

Friday, September 15, 2006

AOP and OOP

AOP - Aspect Oriented Programming provides us the ability to interpose customer behavor before/after invocations on any object. This enable us to address crosscutting enterprise concerns that apply to multiple object.

OOP works well in general, AOP is a complementing rather than competing with OOP. For example, if we have to apply the same transactional behavior to multiple objects and methods, we need cut/paste the same code into each method. AOP give us a better way to pack such concerns into ASPECTS.

Tuesday, July 04, 2006

How to bind and validate in MultiActionController

In Spring framework, it provides several controller in MVC model. Personaly, I like the MultiActionController best. And I do not like SimpleFormController because it only one "onSubmit" method. For WEB page, I do not think any page just have one button, i.e: "Save" or "Update". However, SimpleFormController have strong validator ability. But I still hate lots of configure in SimpleFormController.

In Spring MultiActionController, it already provides bind method, however, this method just throws Exception when it find the invalidate error message. To catch this error, we need write a new method to override it.

The goal is to use both MultiActionController and SimpleFormController

Solution: bind and validate in MultiActionController.

In XML, you can write your MultiActionController as normal define.



Now we need bind the form and validator it.

I will use a save action as example:

First create a bindObject method in your BaseContoller (extends MultiActionController)

protected BindException bindObject(HttpServletRequest request,
Object command, Validator validator) throws Exception {
preBind(request, command);
ServletRequestDataBinder binder = createBinder(request, command);
binder.bind(request);

BindException errors = new BindException(command,
getCommandName(command));
if (validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validator, command, errors);
}

return errors;
}

Now in the save action, you can use this method as normal.

public ModelAndView save(HttpServletRequest request,
HttpServletResponse response, PhoneInfo command) throws Exception {
ModelAndView addPhoneView = new ModelAndView(LIST_VIEW, "phones",
phones);
addPhoneView.addObject("phoneInfo", command);

// add validator and call bindobject to get the result
BindException errors = super.bindObject(request, command, new PhoneInfoValidator());
if (errors.hasErrors()) {
addPhoneView.addAllObjects(errors.getModel());
return addPhoneView;
}

// otherwise --- save this object...
return addPhoneView;
}

In this way, I can easy to fix my problem when I use MultiActionController. I can bind and validate any object as I like.

Friday, June 30, 2006

Hibernate ?

Hibernate is a good ORM tool. However, there also have some issue in here:

1: Criteria API, QueryObject are not as strong as sql language.

2: Lazy load or not... only define one time in XML

3: POJO ? too much use ?

Friday, June 02, 2006

RIM Blackberry and J2ME

Programming the BlackBerry With J2ME

Thursday, May 18, 2006

Google Ajax

http://code.google.com/webtoolkit/

Some good tool for Ajax

prototype.js is a JavaScript library written by Sam Stephenson. This amazingly well thought and well written piece of standards-compliant code takes a lot of the burden associated with creating rich, highly interactive web pages that characterize the Web 2.0 off your back.

Thursday, April 20, 2006

Spring lightweight?

Today, indeed Spring cannot be considered as “lightweight” when comparing it to other light solutions out there. this is mainly due to the vast amount of solutions it provides in almost all aspects of enterprise development. I guess “lightweight”, when taking it by its literal meaning, is somewhat inappropriate nowadays… perhaps “simple and comprehensive” is more suitable to describe Spring. But this term (I think) is not interpreted by its literal meaning. I think it’s still associated with its original meaning when it was compared with the heavy EJB containers.

Wednesday, February 22, 2006

Jasper and Open Reports

In the end we compared Crystal reports with Jasper Reports, and Jasper was picked. Jasper is not only free, but also is proven in the Java world, and has a lot of users. It is customizable, since its Java and open source, and has support for using Collections or Lists of Business Objects, such as those populated via Hibernate.

Once Jasper was chosen, I tested several GUI’s to help build the reports instead of editing them strictly in their native XML. JasperAssistant was found to be the best of all of them, and integrates seamlessly with Eclipse. If you are an Eclipse fan as I am, then you’ll love using JasperAssistant. It even allows you to preview the report against your database right in Eclipse.

Monday, January 16, 2006

Connecting Apache's Web Server to Multiple Instances of Tomcat

Connecting Apache's Web Server to Multiple Instances of Tomcat

http://www.linuxjournal.com/node/8561/print

Thursday, January 12, 2006

Quick Reference Card

http://www.digilife.be/quickreferences/quickrefs.htm

Wednesday, January 11, 2006

Voice Application with J2EE

I'm convinced that J2EE lightweight container architecture is the right way to go for the majority of voice applications. However, there needs to be some tweaks in the way the UI tier utilizes it, compared to what we're used to seeing with HTML-based applications.

The standard platform architecture for Voice Application is to have 100 or so browser instances sitting on a server. The browser is not located on the client, because the client is a POT (Plain Old Telephone). The caller dials up a computer with a Dialogic or NMS card, or a SIP gateway, and the call is routed to one of the browser instances running on a server. This may be the same server that's running the app server, or it may just be on the same LAN.

So now the browser cache becomes much, much more important. If I have a few thousand phone calls coming in every hour to those 100 browsers, and they're all running the same application, the absolute worst thing I can do is a lot of dynamic page rendering. That would involve parsing the JSP into VoiceXML, and parsing the VoiceXML into runnable code, on every request.

So, component libraries like Tapestry or JSF are out. MVC frameworks like struts could be okay, as long as they're redirecting to static VoiceXML pages, instead of forwarding to JSPs.

Reusable Dialog Component (RDC) for voice application

A Reusable Dialog Component (RDC) is basically a JSP 2.0 tag, which generates VoiceXML at runtime. RDCs are part of the RDC Tag Library open source Jakarta project. Version 1.0 of the RDC Taglib was released in July 2005. The RDC Taglib projects implifies the development of server-side code in order to generate Voice XML. The RDC Taglib project includes a set of RDCs, which are a collection of JSP 2.0 tags that assist in the development of Voice applications. The RDC tags generate VoiceXML at runtime, which can execute on any VoiceXML 2.0 compliant platform. The RDC Taglib also provides a framework for implementing additional RDCs. The framework helps in orchestrating each individual RDC making sure the user data is collected, verified, and canonicalized. The collection of RDCs included in the Taglib project is made up of both, atomic and composite RDCs. Atomic RDCs collect a single piece of information from the user. For example, date, time, or zipCode are atomic RDCs. Composite RDCs collect multiple pieces of information from a user. These are usually done by using atomic RDCs or aggregating a composite with other atomic RDCs.

Friday, December 02, 2005

File transfer between .NET and J2EE

Web service seems a good solution for file transfer between .NET and J2EE platform. However, .NET environment is only support DIME format for attachment.

Direct Internet Message Encapsulation (DIME) is a new specification for sending and receiving SOAP messages along with additional attachments, like binary files, XML fragments, and even other SOAP messages, using standard transport protocols like HTTP.

Thursday, November 10, 2005

Session and sessionContext

In the 2.0 version of the Servlet API, you could get hold of a HttpSessionContext object by calling getSessionContext() off an HttpSession. For example:

HttpSessionContext sessionContext = theSession.getSessionContext();

Although HttpSessionContext seems like a useful class for getting easy access to all client sessions, it appears Sun thought access to such private data was too easy. In version 2.1 of the Servlet API the HttpSessionContext class was deprecated for security reasons by Sun, with no plans for a replacement. In short, steer clear of HttpSessionContext!

Wednesday, October 19, 2005

print.google.com

Come here to view any book. You will be happy.

Monday, October 17, 2005

Lucene - text search engine

Apache Lucene is a high-performance, full-featured text search engine Information Retrieval (IR) library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform. It lets you add indexing and searching capabilities to your applications.

Monday, October 10, 2005

Saturday, October 08, 2005

Quick Solution for Existing Web Application Security

Web applications are becoming more popular software for the customer. As web application go online, security parts need to be pay attention to. Problems arise when the application can not distinguish between legitimate and illegitimate requests coming from a browser.

Through a Web browser, I touch my account information. I also touch your account information. Web application server need to validate whether I have permission to touch your account information. However, server side form date validation is really time consuming and sometimes it is nearly impossible, especially for existing web application system.

In this paper, an DES two-ways encryption/decryption are introduced in the form data validate in the web application.

Using GET/POST, some sensitive data are display in the user HTML forms or URL. For example:

http://www.yourdomain.com/accounts/editAccount.do?aId=5

Anyone can easily change the aId value and submit the changed URL to the server. One solution for this is check this user permission on the server side. Another way, we also can check whether client changed the aId, I means the aId I passed and the aId I receive.

To see whether client changes the sensitive data, the DES encrypting algorithm is used in the system. The example code is list at the end of this paper[1]:

For the above URL, I encrypted the sensitive data with the DES algorithm before passing it to the remote client. Now the client browser get the following URL:

http://www.yourdomain.com/accounts/editAccount.do?aId=SMsDoJFsmlc=5

As above example, the encrypt result is “SMsDoJFsmlc=”, the original value is “5”. When the client submit this URL to the server side, I get the encrypted aId from the request, call the decrypt(String) and get the original value.

Now suppose we change the aId as something else, this will make the decrypt result and original data value does not match. We know the client changed the value and just reject the client request.

Thursday, October 06, 2005

Securing the application with SecurityFilter

Enterprise-level business applications need rigorous security regulations with varying roles; each role also requires its own set of access control lists. These roles become more important in Web-based applications, which are accessible to a wider audience. In most cases, application security must control access to each attribute that's visible on the screen.

When access to web applications needs to be restricted to certain users and groups, Tomcat provides its realm implementations. A realm groups a collection of web resources together and puts a protection mechanism around them that requires users who wish to access them to authenticate themselves, and for Tomcat to check their authorization. However, tomcat does not did enough for real application. Here comes SecurityFilter which built on the top of tomcat.

SecurityFilter is a Java Servlet Filter that mimics container managed security. It provides robust security and automatic authentication services for web applications.

Wednesday, October 05, 2005

Unit Testing with JUnit

JUnit provides the following features:

It provides an API that allows us to create a repeatable unit test with a clear pass/fail result.

It includes tools for running our tests and presenting the results.

It allows multiple tests to be grouped together to run in a batch.

It is very lightweight and simple to use. It takes little time to learn how it works.

It is extensible. It's the de facto unit testing framework for Java. There is a large community pf developers using it. Many free extensions are available to help us use it in specific situation. Plus, countless articles and books on the subject are avaibale.

Page Decorate with SiteMesh

SiteMesh is a web-page layout and decoration framework and web- application integration framework to aid in creating large sites consisting of many pages for which a consistent look/feel, navigation and layout scheme is required.

SiteMesh intercepts requests to any static or dynamically generated HTML page requested through the web-server, parses the page, obtains properties and data from the content and generates an appropriate final page with modifications to the original. This is based upon the well-known GangOfFour Decorator design pattern.

SiteMesh can also include entire HTML pages as a Panel within another page. This is similar to a Server-Side Include, except that the HTML document will be modified to create a visual window (using the document's Meta-data as an aid) within a page. Using this feature, Portal type web sites can be built very quickly and effectively. This is based upon the well-known GangOfFour Composite design pattern.

SiteMesh is built using Java 2 with Servlet, JSP and XML technologies. This makes it ideal for use with J2EE applications, however it can be integrated with server-side web architectures that are not Java based such as CGI (Perl/Python/C/C++/etc), PHP, Cold Fusion, etc...

SiteMesh is very extensible and is designed in a way in which it is easy to extend for custom needs.

http://www.opensymphony.com/sitemesh/

Web Application Framework Compare

Apache Struts framework

Pros:
The “Standard” - lots of Struts jobs
Lots of information and examples
HTML tag library is one of the best
Cons:
ActionForms - they’re a pain
Can’t unit test - StrutsTestCase only does integration
Project has been rumored as “dead”
Spring MVC

Pros:
Lifecyle for overriding binding, validation, etc.
Integrates with many view options seamlessly: JSP/JSTL, Tiles, Velocity, FreeMarker, Excel, XSL, PDF
Inversion of Control makes it easy to test
Cons:
Configuration intensive - lots of XML
Requires writing lots of code in JSPs
Almost too flexible - no common parent Controller
WebWork

Pros:
Simple architecture - easy to extend
Tag Library is easy to customize - backed by Velocity
Interceptors are pretty slick
Cons:
Small Community
Documentation only recently written, few examples
Client-side validation immature
Java Server Faces

Pros:
J2EE Standard - lots of demand and jobs
Fast and easy to develop with
Rich Navigation framework
Cons:
Tag soup for JSPs
Immature technology - doesn’t come with everything
No single source for implementation

Why use Hibernate?

One of the most complicated and time-consuming tasks of developing an enterprise application is writing the code to store and load data from a database at the appropriate times. Hibernate is the right tool to remedy this.

Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition, and the Java collections framework. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with Java-based Criteria and Example objects.

Hibernate allows us mapping an object model to a relational schema, keeping object model and database schema in sync. It also makes us easy persisting and retrieving an object from database.

www.hibernate.org