Pagine

Wednesday, September 21, 2011

About a month ago the final release of Gaelyk 1.0, the lightweight Groovy toolkit for Google App Engine, has been released. I'm a fan of the Groovy programming language, even if it is challenging to involve customers inthis paradigm shift. This post illustrates a simple CRUD application, (available here), written with Gaelyk and theDHTMLX Tag library. There is a school of thought that considers tag libraries to be evil and another one which does not. Between the two schools there are those who believe that tag libraries can be useful, if you don't turn them into a monster. In a discussion about Gaelyk and tag libraries support,Guillaume Laforge, made a very smart point about this subject (see here):

Gaelyk templates are really just one view option. You can still continue using Groovlets, but delegate to JSP views, using JSP taglibs. Gaelyk doesn't try to reinvent the wheel here.

Gaelyk provides templates (GTPL) similar to JSPs, which are pages containing scriptlets of code. In the same way in which you can mix Java and Groovy code for classes, Gaelyk let you use a combination of GTPL and JSP pages. In this sample application there are two pages, the first one based on a dhtmlxGrid, which presents the list of records, and second uses a dhtmlxForm to display and edit the data.See screenshot hereBoth pages have been created using the DHTMLX Tag Designer, which makes it pretty simple to prototype the layout.

To take the advantage of Gaelyk templates the JSPs are included within the GTPL:

war/WEB-INF/pages/index.gtpl

<% include '/WEB-INF/includes/header.gtpl' %>

<% include '/WEB-INF/jsp/list.jsp' %>

<% include '/WEB-INF/includes/footer.gtpl' %>

war/WEB-INF/pages/edit.gtpl

<% include '/WEB-INF/includes/header.gtpl' %>

<% include '/WEB-INF/jsp/form.jsp' %>

<% include '/WEB-INF/includes/footer.gtpl' %>

The section about the grid page is missing, because it is very similar to a previous post, and the focus here is on the form based edit page. The source code is below:

The initialization attaches a handler to the onButtonClick form button event, which updates the message on top of the form, and posts the save operation to the application. The second step of the code sets up the validation, binding validators to the object form fields, and provides the onBeforeValidate and onValidateError event handlers to update the text message box.

The final step invokes the load method on the form, it triggers an Ajax call to the book Groovlet to retrieve the data and fill the form.

The routes.groovy defines the URL mapping :

war/WEB-INF/routes.groovy

get"/", forward: "/WEB-INF/pages/index.gtpl"

get"/book/@task/@id", forward: "/book.groovy?id=@id&task=@task"

post "/book/processor", forward: "/processor.groovy"

In the case above, path variables are translated in order to route different task to a single Groovlet. The book.groovyGroovlet performs the list, show and edit operations.

war/WEB-INF/groovy/book.groovy

importcom.google.appengine.api.datastore.Entity

importcom.google.appengine.api.datastore.Key

importcom.google.appengine.api.datastore.KeyFactory

switch(params."task"){

case"list":

log.info"list : getting book list "

int entityCount = datastore.execute{ select count from books }

params.offset= params.posStart?Integer.parseInt( params.posStart) : 0

params.max= params.count?Integer.parseInt( params.count) : 20

params.sort

= params.orderby? params.orderby : "sales"

params.order= params.dir?(params.dir=="des"?"desc" : "asc") : "asc"

def books = datastore.execute{

from books

limit params.max offset params.offset

sort params.order by params.sort

}

response.setContentType("text/xml")

html.rows(total_count: entityCount , pos: params.offset){

books.each{ book ->

html.row(id: book.key.id){

html.cell( book.sales)

html.cell( book.title)

html.cell( book.author)

html.cell( book.price)

}

}

}

break

case"edit":

log.info"edit: editing a book"

request.setAttribute'id', params.id

forward '/WEB-INF/pages/edit.gtpl'

break

case"show":

log.info"show: getting book data"

def id =Long.parseLong(params.id)

Key key =KeyFactory.createKey("books", id)

def book = datastore.get(key)

response.setContentType("text/xml")

html.data{

author {

mkp.yieldUnescaped("<![CDATA["+ book.author+"]]>")

}

price {

mkp.yieldUnescaped("<![CDATA["+ book.price+"]]>")

}

sales {

mkp.yieldUnescaped("<![CDATA["+ book.sales+"]]>")

}

title {

mkp.yieldUnescaped("<![CDATA["+ book.title+"]]>")

}

}

break

default:

break

}

The data processor POST requests are routed to the Groovlet named processor.groovy, which handles the insert, update, delete operations, and persist changes to the entity. Gaelyk’s abstractions for the datastore make them quite straight forward to implement.

Tuesday, September 6, 2011

Developers building applications on top of the Google App Engine for Java can choose between several frameworks to build rich user interfaces. This post illustrates how to create a simple CRUD application, usingDHTMLX Java Tag Library and JPA. The sample provided starts by creating a UI skeleton, which incorporates the DHTMLX widgets, with the use of JavaScript, to integrate the widgets with server side code.

The User Interface

The application major features are:

Dynamic Loading

Keeping thousand of records in a data grid is a common requirement for most applications. Smart Rendering increases overall performance with big amounts of data, activating a dynamic loading to fetch data from the server when needed.

Edit in place

In the great book Designing Web Interface, written by Bill Scott and Theresa Neil, they underline the value of the Make It Direct principle, allowing the user to directly edit content in place.

Right Click Context Menu

The Fitts's Law highlights the value to keep the tools close, to improve the user interaction. This principle has been applied providing a context menu, so that the user can select a row and access the related functions (delete and insert in this case) using the right click.

Client

To create the user interface the DHTMLX Java Tag Designer has been used (useful but not mandatory). You can find step by step instructions here. Below the HTML code of the page.

<%@ taglib uri="http://www.mylaensys.com/dhtmlx" prefix="dhtmlx" %>

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"/>

<title></title>

<linkhref="dhtmlx.css"rel="stylesheet"type="text/css"/>

<linkhref="dhtmlx_custom.css"rel="stylesheet"type="text/css"/>

<style></style>

</head>

<scripttype="text/javascript"src="dhtmlx.js"/>

<body>

<!-- body -->

</body>

</html>

<dhtmlx:body name='initializeDHTMLX' imagePath='imgs/'>

<dhtmlx:layout name='layout'id='content' pattern='1C' >

<dhtmlx:layoutcell name='a'text='a' hideHeader='true'>

<dhtmlx:toolbar name='toolbar'>

<dhtmlx:toolbarButton id='button_ins'text='Insert Row'/>

<dhtmlx:toolbarButton id='button_del'text='Delete Row'/>

</dhtmlx:toolbar>

<dhtmlx:grid name='grid'>

<dhtmlx:column name='sales' header='Sales'type='ed'/>

<dhtmlx:column name='title' header='Title'type='ed'/>

<dhtmlx:column name='author' header='Author'type='ed'/>

<dhtmlx:column name='price' header='Price'type='ed'/>

<dhtmlx:menu name='grid_menu'>

<dhtmlx:menuChild id='button_ins'text='Insert Row'/>

<dhtmlx:menuChild id='button_del'text='Delete Row'/>

</dhtmlx:menu >

</dhtmlx:grid>

<dhtmlx:statusbar name="status"/>

</dhtmlx:layoutcell>

</dhtmlx:layout>

</dhtmlx:body>

<scriptlanguage='JavaScript'type='text/javascript'>

function initialize() {

initializeDHTMLX();

}

dhtmlxEvent(window,'load', initialize);

</script>

The user interface is declared within the <dhtmlx:body> tags, using a Layout component as container for the Toolbar, Status Bar, and Grid.

var busy =false,sort_c ="",sort_d ="";

function initialize(){

initializeDHTMLX();

toolbar.attachEvent("onClick", on_click );

grid_menu.attachEvent("onClick", on_click );

grid.attachEvent("onBeforeSorting",function(ind,type,direction){

if(!busy){

sort_c =this.getColumnId(ind);

sort_d =((sort_d =="des")?"asc":"des");

load_data();

grid.setSortImgState(true,ind,direction);

}

returnfalse;

});

grid.enableSmartRendering(true);

grid.enableValidation(true,true,true,true);

grid.setColValidators("ValidInteger,NotEmpty,NotEmpty,ValidInteger");

load_data();

dp =new dataProcessor("controller");

dp.setTransactionMode("POST");

dp.setUpdateMode("cell");

dp.enableDataNames(true);

dp.init(grid);

}

In first step, the event handlers for toolbar and menu are attached to the components. The initialization proceed with the grid setup, enabling the SmartRendering, setting up the validation, and loading the data. OnBeforeSorting event handler attached to the grid provides the support for server side sort processing.

Last step of initialization, is the data processor configuration, which takes care to send back to the server updates that occurred on the grid; calling enableDataNames ensures that the column names will be included as parameters in the POST request.

The load_data function resets the grid component and sends an ajax request (GET) to the server to retrieve the data. The on_click detects which button or menu item has been selected by the user and performs the corresponding operation.

Server

On the server side, the Java class Book is annotated for persistence, getter and setter omitted for short. You can see that the names of the attributes match the names of the columns.

@PersistenceCapable(detachable = "true")

publicclassBook{

@PrimaryKey

@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)

privateLong id;

@Persistent

privateInteger sales;

@Persistent

privateString title;

@Persistent

privateString author;

@Persistent

privateBigDecimal price;

}

The doGet method of the servlet retrieves the data and feeds the grid.

The smart rendering option, enabled during grid initialization, adds as parameters the starting position of the record (posStart) and the number of records to be returned (count). The doGet method processes these parameters plus sort parameters, if any, executes the query on the data store, and returns the retrieved rows as XML.

Update operations are performed in the doPost method of the ControllerServlet :

DHTMLX data processor component has its own protocol to exchange information with the server (additional information is available on DHTMLX website). This sample implementation, detects the operation triggered by the data processor and performs the appropriate data store operation.