Three years ago we started working with GWT for the front of my web applications and have since lived the evolution of the library through the different versions,implementation of the MVP pattern, use of libraries as smartgwt widgets, etc …

For a year I’ve been considering myself a follower and lover of Grails and Groovy. Make use of groovy on the server think it is much more productive and agile than use java. For this reason I decided to use both technologies to develop web applications :

  • GWT for the front
  • Grails / Groovy for the server side
Ok, let’s go! I will create a small application as a quick use of both technologies:

Set up development environment

1 -First make sure Groovy, Grails, and GWT are installed.  In my case I use STS to create the grails project but is necessary install GWT (Set the environment variable GWT_HOME to your GWT distribution)

Grails Tools > Grails Plugin Manager > find and select Gwt Plugin.

2- Create GWT module

Open  Grails command prompt and type : create-gwt-module gwtGrails.Application

3-Create the page which exposes the module we just created

Open Grails command prompt and type:  
create-gwt-page main/index.gsp gwtGrails.Application

The prompt ask you if you want to create the main controller. Choose y for yes.

4- Edit grails-app/conf/UrlMappings.groovy. Change “/”(view:”/index”) to “/”(view:”/main/index”) to set default grails page our new gwt page.

Service – side RPC

When communicating with the server side, uses GWT RPC services. In aconventional application would need to create a GWT servlet for each RPC service interface that we implement. Using Grails integration with server side will use thetypical Grails services which will expose static property (in which we specify the package that hosts the service interface on the client  gwt:<package>) that allows us to link the interface of the RPC services with Grails service implementation on the server.

class DataService {

static transactional = true

static expose = [ ‘gwt:gwtGrails.client’ ]

String helloWorld() {

return “Hello Sergi!”

}

}

Next, this script will create the required normal and asynchronous interfaces under the src/java directory:

Open Grails command prompt and type : grails generate-gwt-rpc

Accessing the service from your client GWT code:

DataServiceAsync myService = (DataServiceAsync) GWT.create(DataService.class);

ServiceDefTarget endpoint = (ServiceDefTarget) myService;

// Note the URL where the RPC service is located! String moduleRelativeURL = GWT.getModuleBaseURL() + “rpc”; endpoint.setServiceEntryPoint(moduleRelativeURL);

// Call a method on the service!   myService.helloWorld()

String message = myService.helloWorld();

Compiling the GWT modules

Open Grails command prompt and type : grails compile-gwt-modules

Run the GWT hosted mode

Open Grails command prompt and type : grails run-gwt-client

Creating a WAR

Open Grails command prompt and type : grails war

The following link you can find a sample project where you can find both integrated technologies:

http://code.google.com/p/gwt-grails-app/

This is the first in a series of articles I will publish on writing effective groovy code.What better way to learn programming groovy than trying to avoid bad practice?

A tool you can use to check the quality of your code and detect bad practices, codeinconsistencies, defects, etc … is CodeNarc.

CodeNarc is a framework insipred by the wonderful PMD and Checkstyle Java static analysis tools, as well as the Groovy Extensive Inspections performed by IntelliJ IDEA.

Unnecessary collect call

Some method calls to Object.collect(Closure) can be replaced with the spread operator. For instance, list.collect it.multiply(2) can be replaced bylist*.multiply(2).

def list = [1, 2, 3, 4]
def strings = list.collect { it.toString() }
//could be groovier...
def strings = list*.toString()

Unnecessary call for last element

This rule checks for excessively verbose methods of accessing the last element of an array or list. For instance, it is possible to access the last element of an array by performing array[array.length - 1], in Groovy it is simpler to either call array.last() or array[-1].

def list = ['sergio', 'pepe', 'eva']
assert 'eva' == list.get(list.size()-1)
//perform this...
assert 'eva' == list[-1]
assert 'eva' == list.last()

Confusing ternary

In a ternary expression avoid negation in the test. For example, rephrase: (x != y) ? diff : same as: (x == y) ? same : diff. Consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as “does the error case go first?” or “does the common case go first?”.

    (x != y) ? diff : same      // bad practice
    (!x) ? diff : same          // bad practice

    (x == y) ? same : diff      // OK
    (x) ? same : diff           // OK

Returns null instead of empty array / collection 

If you have a method or closure that returns an array / collection , then when there are no results return a zero-length (empty) array / collection  rather than null. It is often a better design to return a zero-length array rather than a null reference to indicate that there are no results (i.e., an empty list of results). This way, no explicit check for null is needed by clients of the method.

It can be useful if you need to access Java Objects from Javascripts functions.

Example  to call method runMe() in Java class at com.sergio.prueba called CallMe.java

public native void callJavaObject() /*-{

@com.sergio.prueba.CallMe::runMe();

}

Pattern to call Java objects from javascript with GWT:

[instance-expr.]@class-name::method-name(param-signature)(arguments)

It is also possible to link a javascript method to a Java method or constructor.

A way to make this kind of relationship work is to assign the method via JSNI to an external, globally visible JavaScript name that can be referenced by your hand-crafted JavaScript code.

package mypackage;

public MyUtilityClass
{
public static int computeLoanInterest(int amt, float interestRate,
int term) { … }
public static native void exportStaticMethod() /*-{
$wnd.computeLoanInterest =
$entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
}

This way you can call Java object via Javascript.

I used this solution to synchronize Flash Player current Time with Slider widgeet in GWT.  😉

Links:  http://code.google.com/intl/es-AR/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html

WebLogic Server 10.3 and higher releases, client applications should use the wlfullclient.jar file to provide the WebLogic Server specific functionary previously provided in the weblogic.jar file.

You can generate the wlfullclient.jar file for client applications using the JarBuilder tool. 

HOW TO:

WebLogic Server 10.0 and higher releases, client applications should use the wlfullclient.jar file to provide the WebLogic Server specific functionary previously provided in the weblogic.jar file. You can generate thewlfullclient.jar file for client applications using the JarBuilder tool. Here is a Simple ANT script to Build the “wlfullclient.jar” JAR Using ANT Script.

Step1). Place the following “build.xml” file in WebLogic Installations Server/lib directory….
Example: “C:\bea103\wlserver_10.3\server\lib” place build.xml here

<project name=”JarBuilder” default=”run”>
<property name=”bea.home” value=”C:/bea103″/>
<property name=”wl.home” value=”${bea.home}/wlserver_10.3″/>
<path id=”main.class.path”>
<pathelement path=”${bea.home}/modules/com.bea.core.utils_1.4.0.0.jar”/>
<pathelement path=”${bea.home}/modules/com.bea.core.jarbuilder_1.2.0.0.jar”/>
<pathelement path=”${java.class.path}”/>
</path>
<target name=”run”>
<echo message=”***** This ANT Script should run from inside the ${wl.home}/server/lib *****” />
<echo message=”***** ********* ********* *****” />
<java classname=”com.bea.jarbuilder.JarBuilder”>
<classpath refid=”main.class.path”/>
<jvmarg value=”-d ${wl.home}/server/lib -jar wljarbuilder.jar”/>
</java>
</target>
</project>

Step2). Modify th Properties defined in the ANT script according to your Installation directory:

<property name=”bea.home” value=”C:/bea103″/>
<property name=”wl.home” value=”${bea.home}/wlserver_10.3″/>

Step3). Open a command prompt and the Run the ANT script…means open a command prompt run thesetWLSENV.cmd then run Ant…
Once the ant script executed successfully…you will find “wlfullclient.jar” is generated in “C:\bea103\wlserver_10.3\server\lib” location

En este post voy a explicar cómo desarrollar nuevos eventos en GWT 2.o.

De la misma manera que el widget Button dispara el evento onClick() o un TextBox puede disparar el evento KeyDown, es posible que necesitemos que nuestro nuevo widget dispare un nuevo evento definido por nosotros y disparado bajo las condiciones que necesitemos.

Por ejemplo, en mi caso, he desarrollado un widget Tabla cuyo comportamiento es como su propio nombre indica , una tabla que contiene elementos (filas) con varias propiedades (columnas) + un botón “Eliminar” que elimina la fila a la que está asociado.

Aparte de la funcionalidad de eliminar la fila al pulsar el botón “Eliminar” necesito que cada que se pulse dicho botón se dispare un evento el cual implementaré en el Presenter de la Vista dónde tengo definido mi widget Tabla.

HOW TO

En primer lugar definiremos en nuestro widget el objeto HandlerManager (com.google.gwt.event.shared.HandlerManager) que nos permitirá poder registrar los handlers  y disparar eventos.

public class NewWidget  {

final private HandlerManager handlerManager = new HandlerManager(this);

}

NOTA: el objeto que se pasa en el constructor del HandlerManager es la fuente de todos los eventos que podrá disparar el HandlerManager

A continuación definiremos el Handler de nuestro nuevo evento. Es una interfaz la cual define el método que implementará el comportamiento del evento cuando se capture.

public interface NewCustomHandler extends EventHandler {

void onCustomMethod(NewCustomEvent event);

}

A continuación definiremos una clase la cual extendera de GWTEvent:

public class NewCustomEvent extends GwtEvent {

private static final Type TYPE = new Type<NewCustomHandler>();

public NewCustomEvent() {

}

public static Type getType() {

return TYPE;

}

@Override  protected void dispatch(NewCustomHandler handler) {

handler.onCustomMethod(this);

}

@Override  public com.google.gwt.event.shared.GwtEvent.Type getAssociatedType() {

return TYPE;

}

}

Una vez definida la clase y la interfaz del Evento debemos especificar en que lugar del widget  se lanzará nuestro nuevo evento.

handlerManager.fireEvent(new NewCustomEvent());

Cuando se ejecuta fireEvent ,el HandlerManager en primer lugar llama a setSource en el objeto del evento y setea el valor que se pasa en el constructor del HandlerManager. A continuación, busca los controladores registrados en función del evento dado  y los llama en el orden en que fueron registrados.

Para registrar el controlador que tratará nuestro nuevo evento incluiremos el siguiente método en nuestro widger, el cual se encargará de registrar un nuevo manejador que implementará el evento que escucha.

public void addNewCustomHandler(NewCustomHandler handler){

handlerManager.addHandler(NewCustomHandler.getType(),handler)

}


Hoy he asistido al Spring 2GX Day que se celebraba en la Escuela Politécnica Superior de la Universidad CEU San Pablo, Madrid. El primer evento en España sobre tecnología Java, Spring framework y Grails.

He tenido la oportunidad de asistir a todas las ponencias que se han celebrado a lo largo de la jornada y la verdad que no ha tenido desperdicio alguno, destacando entre todas Spring Roo , Grails y el uso de Flex 4 + Grails.

Como cierre de ceremonia he asistido al workshop de Graeme Rocher, creador de Grails, y he salido deseando trastear de nuevo y retomar pruebas de concepto sobre Grails que dejé aparcadas en su día por falta de tiempo.

En definitiva, un día super aprovechado en el que he podido aprender, disfrutar y conocer compañeros de profesión con las mismas inquietudes con los que he intercambiado opiniones muy interesantes.

Ahora toca recapitular todas las ideas que he recolectado hoy y ponerme a trabajar con ellas. He decidido ponerme en los siguientes días a trabajar con los siguientes puntos:

  • Spring Roo
  • Grails + GWT (Google Web Toolkit)
  • Spring Security 3.0 como nueva pieza para futuros proyecto en mi trabajo.

Deseando que llegue el proximo Spring Day…. 😉