Platinum Partner
java,gwt,google web toolkit,genuitec,skyway software,myeclipse for spring,spring scaffolding

Generating Enterprise Class GWT Applications for Spring

MyEclipse for Spring 8.6

Genuitec and Skyway Software recently announced the production release of MyEclipse for Spring 8.6. The latest release expands upon a set of advanced accelerators for Spring development, providing new options for rapidly generating Adobe Flex, Spring MVC, Google Web Toolkit (GWT), Spring Web Flow and iPhone Web applications. The release also introduces a new set of Spring development editors, Code Assistants, that facilitate the annotation-based development of Spring and JAX-WS artifacts.

MyEclipse for Spring (ME4S) 8.6 now supports the generation of reusable software components based on your data model. Whether you are starting from RDBMS tables, POJOs, JPA Entities, or WSDLs, ME4S can give you a lot of great technology to use in your project. You can see these components put to use in a basic, running CRUD-based application right after you finish filling out a simple wizard, but a lot of the value really comes from being able to leverage all of this technology as you build out other parts of your project. If you have an existing project and you want to get out of the business of maintaining the JPA/DAO/Service layer by hand, ME4S can also take on this responsibility for you.

With the 8.6 release, we added a variety of new UI generation options because we are hearing consistently from Java developers that as they explore the use of technologies like Flex and Google Web Toolkit (GWT), it is sometimes hard to find great examples. Developers have told us that as they begin the process of evaluating these technologies, it would be nice to be able to demonstrate them running contextually against their own data for their internal and external partners. ME4S lets you take an existing data model from an application that needs to be modernized, and very quickly generate the basic services you need on the back end, as well as building out nice clean UI components that are tailored for your data model.

If you have built software using almost anything that ends in WT, you’ll know that a lot of the time is spent integrating the Windowing Toolkit UI components to the data model and setting up the application to use best practices for that UI technology. ME4S does a lot of this for you and as always, makes sure you have a running example at each stage of the process.

GWT

In this article, I am going to cover what is generated from the GWT generation capability in some detail. I will review the Spring back-end generation options at a high level, since this stack is used by all of our generated UI’s, and then dive into the Java code that is generated for the front-end. It is important to note, however, that the GWT front-end can also be generated to be agnostic to the persistence layer so that you can tie your GWT front-end to any back-end implementation that you wish.

Prerequisites

If you have not already read the ME4S tutorial on GWT Scaffolding, you should read it now here. This tutorial takes you step-by-step through the process of using the software to generate your GWT application. Once you are comfortable with this information, we can dive in a bit into the code that was actually generated.

Design Philosophy

The GWT integration in MyEclipse for Spring is targeted specifically at the GA version of GWT and the most widely adopted versions of Spring (both 2.5 and 3.0). We wanted to make sure that developers had tooling options that supported the technologies that are available to them right now for use in production applications. ME4S currently supports GWT 2.0.4, which is generally available at the time of the 8.6 release. We intend to support GWT 2.1 as quickly as possible as it moves towards general availability. The code that is generated from ME4S is intended to follow the best practices for GWT 2.0 as prescribed by Ray Ryan’s Google I/O presentation.

We also thought it was important to include as few 3rd party GWT projects as possible in the default implementation. There are a few great projects out there, and several great commercial GWT component providers, but we wanted to be sure that we didn’t make too many decisions for you in this case, and that what we built for GWT was based on what you could get straight from Google.

Summary of Goals

Goal Description
Use existing technology assets Java Beans, RDBMS, JPA, WSDL
MVP Architecture Follow a Model View Presenter Approach
UIBinder Define UI’s using GWT’s UIBinder
Command Pattern Encapsulate using commands as described in Ray Ryan’s Google I/O presentation
DTO Use Data Transfer objects to encapsulate the data that should be sent to the client, and to control relationship management
Loose and Lazy Relationships Promote a design pattern that defers the loading of related data until it is needed with loose Server based relationship management
Back End Agnostic Tie the GWT front end to an automatically generated Spring/JPA persistence layer, or just generate a Service stub and then hand code the persistence to integrate with any back end.
I18N Support Generate UI’s that are already set up to be localized
Client Bundles Use Client Bundles for optimization

The Application

In the GWT tutorial we used the sandbox Derby database that comes with ME4S to build out a GWT application that manages customers and payments using the Customer and Payment tables as inputs to the process. The resulting application looks something like this:

This application gives you the basic CRUD capabilities for managing your Customers and Payments and has a few nice capabilities built-in, including sortable, paginating lists, “Pickers” for adding and removing elements from relationships, multi-tabbed editing, etc. This UI is really a composition of several nice, reusable components that can be re-purposed into other designs. Because we are using a Command Pattern, Event Bus, and MVP based architecture, it is easy to wire these components together into different application patterns down the road.

Understanding the Architecture

After you have watched the Google I/O presentation on architecting GWT Applications, you will find the following illustration helpful in building a mental picture of the architecture that is being employed. The key architectural benefits are the clean separation between the Model, which is dumb, and the View, which is also dumb, and the Presenter, which isolates the logical (and testable) code in your application. The Actions and Events being used on the EventBus allow the code in your application to be extremely loosely coupled. The RPC Service Layer and Server Side GWT Remote Service act as an asynchronous information service. In this case, the GWT Service is backed by the generated Spring / JPA backend.

Reusable Software Components

The following diagram illustrates the reusable software components that have been generated into your project as a result of the GWT scaffolding execution. The Scaffolding Wizard allows the developer to pick the layers that they wish to generate and those they wish to exclude. In this case, we generated a standard Spring layered server side architecture with a Service, DAO and Domain layer, as well as a Web layer that is build upon GWT. The GWT Components generated offer additional detail regarding the code that is used to implement the Architecture as it was illustrated above.

Project Layout

The ME4S Scaffolding Wizard gives you options for where you would like to put your code, how it is packaged, etc. Let’s take a look at the default project layout for the application described above.

If we take the defaults, all of the generated code and configuration will go into a folder called “generated”. You can still build all of your own code in the existing src folder and leverage the code in the generated src folder. The generated code has absolutely no tie back to the tooling or generation technology. You can take this code and do what you like with it at this point. If you want to be able to run the scaffolding repetitively, you should avoid making changes in the generated .java files, although there are options to deal with re-generation which we will detail in a separate blog.

The “server side” components are put in the com.show. – (dao, domain, and service) packages. The packages that start with gwt.- are the gwt software components. ME4S generates a separate GWT module for each Domain object so that you can mix and match them later, plus a common module with utility classes, and an entry point module that rolls them all up into an example GWT application.

Exploring the Customer GWT Model

Let’s take a closer look at one of the generated GWT modules for the Customer domain object. This module contains all of the boiler plate code that you would normally write to build a GWT application using the standards and best practices listed above.

Top GWT Module Packages

The first two packages in the Customer module are the gwt.customer and gwt.customer.client packages.

The gwt.customer package simply contains the GWT Module.xml definition file for the Customer module.

The gwt.customer.client module contains the DTO Object representation for Customer, an ID class for uniquely identifying a Customer, the Service and Async Service interfaces, and the CSS and I18N messages that are used by the Customer UI.

The Actions package

The actions package contains the Actions or Commands that can be passed back and forth to the Server to accomplish specific tasks. There are actions for loading, storing, and deleting customers as well as Actions for managing relationships TO customer. This is an important point because the Actions for managing relationships are generic such that you can use the same Action to manage the relationship between SalesRep and Customer, and Product and Customer. This approach also allows us to make the screens for managing relationships to Customer more OO. You will also notice that for each Action, there is the Action, a Response Object, and a Action”ed” classes. This approach helps to encapsulate the code to pass these actions and receive their asynchronous callbacks. We will take a look at a specific example further on.

The Events package

The events package declares a set of Events that can be listened for on the EventBus. The UI Components that are generated automatically register themselves to listen on the Event bus for certain events in order to deal with changes to the data. If you want to hang some new behavior off the side of a Customer being deleted for example, all you have to do is add a CustomerDeleted handler to the Event bus and your code will be notified.

The Server package

The Server package contains the code that is executed on the server side of the application. This code can contain references to classes that cannot be compiled by GWT and allows us to integrate with the Service , DAO, and Domain layers. If you choose not to scaffold the Service and DAO layers in the Wizard, the Service Implementation will be generated with stubbed out methods that you can later implement to call your own back end implementation. The GWTCustomerUtil class is a utility class that can do the conversion from your DTO Objects coming in from the GWT client back to the persistent version of those Objects on the Server, and back. The default implementation takes care of merging the Data and using the DAO and Service layers to handle persistence. This approach does not require any 3rd party projects that attempt to map JPA to GWT for example and leaves the developer open to implement other approaches to persistence.

The Components package

The components package contains the GWT UI Components that are designed to provide the developer with course grained java objects that can be used to build UI’s that work with Customers in this case. These components generally use UIBinder, are prewired to work with the EventBus, Actions and Events that are generated in the other packages, and they allow the implementing Actions to be dependency injected into the Presenter in order to allow them to remain loosely coupled and testable. There are paginated tables for both “listing” objects in a table and a table for “selecting” objects with only a few columns as you may see in a “Picker”. There are general Edit widgets which provide you with Form based input and display of the Objects fields and properties. There are Relationship widgets for managing relationships TO customer, both Single or (One) sided relationships, or (Many) sided relationships. There are also Dialogs for your convenience for Editing or Picking customers. The tables are all specific implementations of the PagingScrollTable from the GWT Incubator project.

The Code

The best way to get a feel for the code is to download MyEclipse for Spring and walk through the GWT Tutorial. Let’s take a quick look at some of the generated code to get a feel for it. We are absolutely welcome to feedback from the community as to how we may continue to improve the product and so if you have thoughts please post them on our forums.

Server Side Classes

Customer

The Customer class is the JPA Entity that was generated in this case from our RDBMS table definition. You can see that we automatically generate @NamedQuery annotations for the common named queries you may need to search for Customers. Each field has been annotated based on information derived from the database, generally pretty standard stuff.

package com.showme.domain;

import java.io.Serializable;

import java.lang.StringBuilder;

import java.math.BigDecimal;

import java.util.LinkedHashSet;
import java.util.Set;

import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;

import javax.xml.bind.annotation.*;

import javax.persistence.*;

/**
 */

@Entity
@NamedQueries( {
		@NamedQuery(name = "findAllCustomers", query = "select myCustomer from Customer myCustomer"),
		@NamedQuery(name = "findCustomerByAddressline1", query = "select myCustomer from Customer myCustomer where myCustomer.addressline1 = ?1"),
		@NamedQuery(name = "findCustomerByAddressline1Containing", query = "select myCustomer from Customer myCustomer where myCustomer.addressline1 like ?1"),
		@NamedQuery(name = "findCustomerByAddressline2", query = "select myCustomer from Customer myCustomer where myCustomer.addressline2 = ?1"),
		@NamedQuery(name = "findCustomerByAddressline2Containing", query = "select myCustomer from Customer myCustomer where myCustomer.addressline2 like ?1"),
		@NamedQuery(name = "findCustomerByCity", query = "select myCustomer from Customer myCustomer where myCustomer.city = ?1"),
		@NamedQuery(name = "findCustomerByCityContaining", query = "select myCustomer from Customer myCustomer where myCustomer.city like ?1"),
		@NamedQuery(name = "findCustomerByContactfirstname", query = "select myCustomer from Customer myCustomer where myCustomer.contactfirstname = ?1"),
		@NamedQuery(name = "findCustomerByContactfirstnameContaining", query = "select myCustomer from Customer myCustomer where myCustomer.contactfirstname like ?1"),
		@NamedQuery(name = "findCustomerByContactlastname", query = "select myCustomer from Customer myCustomer where myCustomer.contactlastname = ?1"),
		@NamedQuery(name = "findCustomerByContactlastnameContaining", query = "select myCustomer from Customer myCustomer where myCustomer.contactlastname like ?1"),
		@NamedQuery(name = "findCustomerByCountry", query = "select myCustomer from Customer myCustomer where myCustomer.country = ?1"),
		@NamedQuery(name = "findCustomerByCountryContaining", query = "select myCustomer from Customer myCustomer where myCustomer.country like ?1"),
		@NamedQuery(name = "findCustomerByCreditlimit", query = "select myCustomer from Customer myCustomer where myCustomer.creditlimit = ?1"),
		@NamedQuery(name = "findCustomerByCustomername", query = "select myCustomer from Customer myCustomer where myCustomer.customername = ?1"),
		@NamedQuery(name = "findCustomerByCustomernameContaining", query = "select myCustomer from Customer myCustomer where myCustomer.customername like ?1"),
		@NamedQuery(name = "findCustomerByCustomernumber", query = "select myCustomer from Customer myCustomer where myCustomer.customernumber = ?1"),
		@NamedQuery(name = "findCustomerByPhone", query = "select myCustomer from Customer myCustomer where myCustomer.phone = ?1"),
		@NamedQuery(name = "findCustomerByPhoneContaining", query = "select myCustomer from Customer myCustomer where myCustomer.phone like ?1"),
		@NamedQuery(name = "findCustomerByPostalcode", query = "select myCustomer from Customer myCustomer where myCustomer.postalcode = ?1"),
		@NamedQuery(name = "findCustomerByPostalcodeContaining", query = "select myCustomer from Customer myCustomer where myCustomer.postalcode like ?1"),
		@NamedQuery(name = "findCustomerByPrimaryKey", query = "select myCustomer from Customer myCustomer where myCustomer.customernumber = ?1"),
		@NamedQuery(name = "findCustomerBySalesrepemployeenumber", query = "select myCustomer from Customer myCustomer where myCustomer.salesrepemployeenumber = ?1"),
		@NamedQuery(name = "findCustomerByState", query = "select myCustomer from Customer myCustomer where myCustomer.state = ?1"),
		@NamedQuery(name = "findCustomerByStateContaining", query = "select myCustomer from Customer myCustomer where myCustomer.state like ?1") })
@Table(schema = "CLASSICCARS", name = "CUSTOMER")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace = "ShowMeTheMoney/com/showme/domain", name = "Customer")
@XmlRootElement(namespace = "ShowMeTheMoney/com/showme/domain")
public class Customer implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 */

	@Column(name = "CUSTOMERNUMBER", nullable = false)
	@Basic(fetch = FetchType.EAGER)
	@Id
	@XmlElement
	Integer customernumber;
	/**
	 */

	@Column(name = "CUSTOMERNAME", length = 50)
	@Basic(fetch = FetchType.EAGER)
	@XmlElement
	String customername;
//** This is only a partial listing of the generated file **//
Full listing of Customer.java

CustomerDAOImpl

The CustomerDAOImpl class is the implementation of the CustomerDAO interface which defines the behaviors required to persist Customers. This class is an annotated Spring @Repository and which has @Transactional annotations for transaction management. The EntityManager is injected by Spring. There are methods for each of the NamedQueries from the Customer JPA Object. This class is used by the Service Layer to manage the persistence of Customers.

package com.showme.dao;

import com.showme.domain.Customer;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.skyway.spring.util.dao.AbstractJpaDao;

import org.springframework.dao.DataAccessException;

import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;

/**
 * DAO to manage Customer entities.
 * 
 */
@Repository("CustomerDAO")
@Transactional
public class CustomerDAOImpl extends AbstractJpaDao implements CustomerDAO {

	/**
	 * Set of entity classes managed by this DAO.  Typically a DAO manages a single entity.
	 *
	 */
	private final static Set> dataTypes = new HashSet>(Arrays.asList(new Class[] { Customer.class }));

	/**
	 * EntityManager injected by Spring for persistence unit MyEclipse_Derby
	 *
	 */
	@PersistenceContext(unitName = "MyEclipse_Derby")
	private EntityManager entityManager;

	/**
	 * Instantiates a new CustomerDAOImpl
	 *
	 */
	public CustomerDAOImpl() {
		super();
	}

	/**
	 * Get the entity manager that manages persistence unit MyEclipse_Derby
	 *
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * Returns the set of entity classes managed by this DAO.
	 *
	 */
	public Set> getTypes() {
		return dataTypes;
	}

	/**
	 * JPQL Query - findCustomerByCreditlimit
	 *
	 */
	@Transactional
	public Set findCustomerByCreditlimit(java.math.BigDecimal creditlimit) throws DataAccessException {

		return findCustomerByCreditlimit(creditlimit, -1, -1);
	}

	/**
	 * JPQL Query - findCustomerByCreditlimit
	 *
	 */

	@SuppressWarnings("unchecked")
	@Transactional
	public Set findCustomerByCreditlimit(java.math.BigDecimal creditlimit, int startResult, int maxRows) throws DataAccessException {
		Query query = createNamedQuery("findCustomerByCreditlimit", startResult, maxRows, creditlimit);
		return new LinkedHashSet(query.getResultList());
	}

Full listing of CustomerDAOImpl.java

CustomerServiceImpl

The CustomerServiceImpl class is the implementation for the CustomerService interface which defines the behavior for a CRUD service for Customer. This class is a Session scoped bean and is annotated as a Spring @Service. This class has the DAO’s it needs injected by Spring and has methods to manage the basic CRUD operations as well as dependency management for Customer.

package com.showme.service;

import com.showme.dao.CustomerDAO;
import com.showme.dao.PaymentDAO;

import com.showme.domain.Customer;
import com.showme.domain.Payment;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Customer entities
 * 
 */
@Scope("session")
@Service("CustomerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {

	/**
	 * DAO injected by Spring that manages Customer entities
	 * 
	 */
	@Autowired
	private CustomerDAO customerDAO;

	/**
	 * DAO injected by Spring that manages Payment entities
	 * 
	 */
	@Autowired
	private PaymentDAO paymentDAO;

	/**
	 * Instantiates a new CustomerServiceImpl.
	 *
	 */
	public CustomerServiceImpl() {
	}

	/**
	 * Load an existing Customer entity
	 * 
	 */
	@Transactional
	public Set loadCustomers() {
		return customerDAO.findAllCustomers();
	}

	/**
	 * Save an existing Customer entity
	 * 
	 */
	@Transactional
	public void saveCustomer(Customer customer) {
		customer = customerDAO.store(customer);
		customerDAO.flush();
	}
//** This is only a partial listing of the generated file **//
Full listing of CustomerServiceImpl.java

Client Side Classes

GWTCustomer

The GWTCustomerClass is the automatically generated DTO Object that is used to transfer information about a Customer from the client to the server and is also the DTO Object that is bound to all of the UI Components that have been generated in support of Customer. The DTO Object does NOT contain relationships of any kind. Instead, the GWTService for Customer contains methods to load relationships lazily and there are Actions, Events, and UI Components that support the management of relationships for each Data Type in the Domain model.

package gwt.customer.client;


import java.io.Serializable;

import java.lang.StringBuilder;


/**
 * A lightweight POJO without relationships that can be used for RPC style remote calls with GWT.
 * The GWT Services have methods for adding, removing and loading Objects and for managing relationships on Objects.
 * This approach encourages loose coupling between objects and asynchronous loading of related data
 * 
 * @see  Customer 
 */
public class GWTCustomer implements Serializable{
	private static final long serialVersionUID = 1L;

		/**
		* Declare customernumber
		*/
		 Integer customernumber;
		/**
		* Declare customername
		*/
		 String customername;
		/**
		* Declare contactlastname
		*/
		 String contactlastname;
		/**
		* Declare contactfirstname
		*/
		 String contactfirstname;
		/**
		* Declare phone
		*/
		 String phone;
		/**
		* Declare addressline1
		*/
		 String addressline1;
		/**
		* Declare addressline2
		*/
		 String addressline2;
		/**
		* Declare city
		*/
		 String city;
		/**
		* Declare state
		*/
		 String state;
		/**
		* Declare postalcode
		*/
		 String postalcode;
		/**
		* Declare country
		*/
		 String country;
		/**
		* Declare salesrepemployeenumber
		*/
		 Integer salesrepemployeenumber;
		/**
		* Declare creditlimit
		*/
		 Double creditlimit;
	

		/**
		* Setter for customernumber
		 */
		public void setCustomernumber(Integer customernumber) {
			this.customernumber = customernumber;
		}

//** This is only a partial listing of the generated file **//
Full listing of GWTCustomer.java

GWTCustomerServiceImpl

The GWTCustomerServiceImpl class is the implementation of the GWT RemoteServiceServlet class which enables the GWT RPC layer. The purpose of this class is to handle the requests from the GWT Client which arrive at the server in the form of Actions (or Commands) . This class implements provides an implementation of the execute(Action<T> action) method and then delegates those actions to appropriate handlers which use the CustomerUtil class to convert back and forth from DTO Object to JPA Object and perform the basic CRUD and Relationship management operations.

package gwt.customer.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.showme.dao.CustomerDAO;
import com.showme.dao.PaymentDAO;

import com.showme.service.CustomerService;

import gwt.common.client.Action;
import gwt.common.client.CrudException;
import gwt.common.client.Response;

import gwt.customer.client.GWTCustomer;
import gwt.customer.client.GWTCustomerID;
import gwt.customer.client.GWTCustomerService;

import gwt.customer.client.actions.DeleteCustomer;
import gwt.customer.client.actions.DeleteCustomerResponse;
import gwt.customer.client.actions.LoadCustomer;
import gwt.customer.client.actions.LoadCustomerResponse;
import gwt.customer.client.actions.StoreCustomer;
import gwt.customer.client.actions.StoreCustomerResponse;

import gwt.payment.client.GWTPayment;

import gwt.payment.client.actions.AddPaymentToRelated;
import gwt.payment.client.actions.AddPaymentToRelatedResponse;
import gwt.payment.client.actions.LoadRelatedPayment;
import gwt.payment.client.actions.LoadRelatedPaymentResponse;
import gwt.payment.client.actions.RemovePaymentFromRelated;
import gwt.payment.client.actions.RemovePaymentFromRelatedResponse;

import gwt.payment.server.GWTPaymentUtil;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.ConvertUtils;

import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.CalendarConverter;
import org.apache.commons.beanutils.converters.DateConverter;

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.servlet.support.RequestContextUtils;




/**
 * Remote Service implementation for CRUD based operations for Customer
 * @see com.showme.domain.Customer
 */
public class GWTCustomerServiceImpl extends RemoteServiceServlet implements GWTCustomerService {
		
	/**
	 * Default constructor.
 	 */
	public GWTCustomerServiceImpl() {
		java.util.Date defaultValue = null;
		java.util.Calendar defaultCalendarValue = null;
		java.math.BigDecimal defaultBigDecimalValue = null;
		
		DateConverter dateConverter = new DateConverter(defaultValue);
		CalendarConverter calendarConverter = new CalendarConverter (defaultCalendarValue);
		BigDecimalConverter bigDecimalConverter = new BigDecimalConverter (defaultBigDecimalValue);
			
		ConvertUtils.register(dateConverter, java.util.Date.class);
		ConvertUtils.register(calendarConverter, java.util.Calendar.class);
		ConvertUtils.register(bigDecimalConverter, java.math.BigDecimal.class);
	}

	/**
	 * Default execute method for Actions passed to this Service
	 * See the MVP approach and the use of the Command Pattern GWT Best Practices
	 *
	 */
	 @SuppressWarnings("unchecked")
	public  T execute(Action action) throws CrudException{
		if (action instanceof DeleteCustomer)
			return (T)execute ((DeleteCustomer)action);
		else if (action instanceof LoadCustomer)
			return (T)execute ((LoadCustomer)action);
		else if (action instanceof StoreCustomer)
			return (T)execute ((StoreCustomer)action);
		else if (action instanceof AddPaymentToRelated)
			return (T)execute ((AddPaymentToRelated)action);
		else if (action instanceof LoadRelatedPayment)
			return (T)execute ((LoadRelatedPayment)action);
		else if (action instanceof RemovePaymentFromRelated)
			return (T)execute ((RemovePaymentFromRelated)action);
	
	
		throw new CrudException ("Invalid Action, no handler specified:" + action); 
	}
	
	/**
	 * Get the DataUtil handler to convert Objects from GWT DTOs to their persisted version, and back
	*/
	private GWTCustomerUtil dataUtils() {
		return new GWTCustomerUtil(getDAO());
	}
	
	/**
	 * Default implementation loads all 
	 */
	private LoadCustomerResponse execute (gwt.customer.client.actions.LoadCustomer action) throws CrudException{
		return new LoadCustomerResponse (dataUtils().toGWT(getService().loadCustomers()));		}
	
	/**
	*/
	private DeleteCustomerResponse execute (gwt.customer.client.actions.DeleteCustomer action) throws CrudException {
		try {
			for (GWTCustomer customer: action.getCustomers()) {
				getService().deleteCustomer(dataUtils().toPersisted(customer));
			}
		}
		catch (javax.persistence.EntityExistsException ex) {
			throw new CrudException ("Unable to delete this Customer, it may be associated with a another record", ex);
		}
		catch (Exception e) {
			throw new CrudException ("Unable to delete this Customer", e);
		}
		return new DeleteCustomerResponse(action.getCustomers());
	}
	

//** This is only a partial listing of the generated file **//
Full listing of GWTCustomerServiceImpl.java

CustomerEditor

CustomerEditor is the Presenter in the MVP Pattern for Customer objects. At the top you will notice that the Presenter defines an interface called Display that defines the API that must be met to be a “View” for this presenter. Also notice the use of HasValue<x> instead of specific UI Components. This approach makes it easy to pass in mock displays and leaves the UI implementation a lot of flexibility for how it implements the contract with the presenter. The bindDisplay method takes care of getting elements from the Display and adding event handlers, etc where necessary. The edit and save methods do exactly what you would probably expect, they bind data in and out of the UI to the model, and take care of invoking the execute method on the server by passing in the StoreCustomer action.

package gwt.customer.client.components;

import com.google.gwt.core.client.GWT;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;

import com.google.gwt.user.client.Window;

import com.google.gwt.user.client.ui.HasValue;

import gwt.common.client.EventBus;

import gwt.customer.client.CustomerMessages;
import gwt.customer.client.GWTCustomer;
import gwt.customer.client.GWTCustomerID;
import gwt.customer.client.GWTCustomerService;
import gwt.customer.client.GWTCustomerServiceAsync;

import gwt.customer.client.actions.StoreCustomer;
import gwt.customer.client.actions.StoredCustomer;

import gwt.customer.client.events.CustomerStoredEvent;
import gwt.customer.client.events.CustomerStoredHandler;

/**
 * Presenter for GWTCustomer editing
 */
public class CustomerEditor {
	// Display Interface that must be implemented to bind a Display to this
	// editor
	interface Display {
		public HasValue getCustomernumberBox();

		public HasValue getCustomernameBox();

		public HasValue getContactlastnameBox();

		public HasValue getContactfirstnameBox();

		public HasValue getPhoneBox();

		public HasValue getAddressline1Box();

		public HasValue getAddressline2Box();

		public HasValue getCityBox();

		public HasValue getStateBox();

		public HasValue getPostalcodeBox();

		public HasValue getCountryBox();

		public HasValue getSalesrepemployeenumberBox();

		public HasValue getCreditlimitBox();

		public HasClickHandlers getCancelButton();

		public HasClickHandlers getSaveButton();

		public void setIsNew(boolean isNew);

		public boolean isValid();
	}

	/**
	 * Reference to the Display that is bound to this presenter
	 */
	private Display display;

	/**
	 * The GWTCustomer being edited
	 */
	private GWTCustomer customer;

	/**
	 * The Crud Service used to handle saves from this Editor
	 */
	private GWTCustomerServiceAsync service;

	/**
	 * The I18N Messages
	 */
	private final static CustomerMessages messages = (CustomerMessages) GWT
			.create(CustomerMessages.class);

	/**
	 * Constructor that takes an instance of the Display to bind to this
	 * presenter
	 */
	public CustomerEditor(Display display) {
		this(display, GWTCustomerService.Util.getInstance());
	}

	/**
	 * Constructor that takes an instance of the Display to bind to this
	 * presenter, and an override to disable calls through to the server This
	 * constructor just avoids creating an instance of the Default crud Service.
	 * The Editor will only perform saves if the Async Crud Service is present
	 * 
	 */
	public CustomerEditor(Display display, boolean performSave) {
		bindDisplay(display);
		if (performSave)
			this.service = GWTCustomerService.Util.getInstance();
	}

	/**
	 * Constructor that takes the Display to bind to this presenter, and the
	 * Async Service to use for saving
	 */
	public CustomerEditor(Display display, GWTCustomerServiceAsync service) {
		bindDisplay(display);
		this.service = service;
	}

	/**
	 * Binds the view to the presenter
	 */
	void bindDisplay(final Display display) {
		this.display = display;

		if (display.getSaveButton() != null) {
			display.getSaveButton().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					if (display.isValid())
						doSave();
					else
						doError();
				}
			});
		}

		if (display.getCancelButton() != null) {
			display.getCancelButton().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					doCancel();
				}
			});
		}

		EventBus.get().addHandler(CustomerStoredEvent.TYPE,
				new CustomerStoredHandler() {
					public void onCustomerStored(CustomerStoredEvent event) {
						if (new GWTCustomerID(event.getCustomer())
								.equals(new GWTCustomerID(customer)))
							edit(event.getCustomer());
					}
				});
	}

//** This is only a partial listing of the generated file **//
Full listing of CustomerEditor.java

CustomerEditWidget

CustomerEditWidget is the class responsible for loading the UI using UIBinder. It implements the interface Display from CustomerEditor. You can see the code at the top of the class that specifies the UIBinder xml definition file and loads it through GWT.create(). The @UIField annotations allow UIElements defined in the XML file to be bound to the Java code in the CustomerEditWidget. The generated edit widgets offer “dumb” UI capabilities like enabling and disabling as well as very BASIC validation that the form fields are valid enough to be bound to the data model.

package gwt.customer.client.components;

import com.google.gwt.core.client.GWT;

import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;

import gwt.common.client.DecimalBox;
import gwt.common.client.IntegerBox;


/**
 * The view for editing GWTCustomer
 * This view is constructed using UIBinder
 */
public class CustomerEditWidget extends Composite implements  CustomerEditor.Display {
	
	/**
	* Interface for UIBinder extension
	*/ 
	@UiTemplate("CustomerEditWidget.ui.xml")
	interface EditBinder extends UiBinder{}
	
	/**
	* Instance of EditBinder interface loaded through GWT.create
	*/ 
	private static EditBinder binder = GWT.create(EditBinder.class);
	
		/**
		* UI Input for customernumber
		*/ 
		@UiField
		IntegerBox customernumberBox;
		/**
		* UI Input for customername
		*/ 
		@UiField
		TextBox customernameBox;
		/**
		* UI Input for contactlastname
		*/ 
		@UiField
		TextBox contactlastnameBox;
		/**
		* UI Input for contactfirstname
		*/ 
		@UiField
		TextBox contactfirstnameBox;
		/**
		* UI Input for phone
		*/ 
		@UiField
		TextBox phoneBox;
		/**
		* UI Input for addressline1
		*/ 
		@UiField
		TextBox addressline1Box;
		/**
		* UI Input for addressline2
		*/ 
		@UiField
		TextBox addressline2Box;
		/**
		* UI Input for city
		*/ 
		@UiField
		TextBox cityBox;
		/**
		* UI Input for state
		*/ 
		@UiField
		TextBox stateBox;
		/**
		* UI Input for postalcode
		*/ 
		@UiField
		TextBox postalcodeBox;
		/**
		* UI Input for country
		*/ 
		@UiField
		TextBox countryBox;
		/**
		* UI Input for salesrepemployeenumber
		*/ 
		@UiField
		IntegerBox salesrepemployeenumberBox;
		/**
		* UI Input for creditlimit
		*/ 
		@UiField
		DecimalBox creditlimitBox;
	
	/**
	* Cancel button
	*/ 
	@UiField
	Button cancelButton;
	
	/**
	* Save button
	*/ 
	@UiField
	Button saveButton;

//** This is only a partial listing of the generated file **//
Full listing of CustomerEditWidget.java

CustomerEditWidget.ui.xml

This file defines the UI for the EditWidget using a blend of HTML and GWT Tags. This approach ensures a very clean separation between the UI definition and the java code. The default implementation takes care of dropping in the <ui:msg> tags which can be used by the GWT compiler to generate I18N files for localization.

<ui:UiBinder
  ui:generateFormat='com.google.gwt.i18n.rebind.format.PropertiesFormat'
  ui:generateKeys="com.google.gwt.i18n.rebind.keygen.MD5KeyGenerator"
  ui:generateLocales="default"
  xmlns:ui='urn:ui:com.google.gwt.uibinder'
  xmlns:dp='urn:import:com.google.gwt.user.datepicker.client'
  xmlns:gc='urn:import:gwt.common.client'
	xmlns:payments='urn:import:gwt.payment.client.components'
  xmlns:g='urn:import:com.google.gwt.user.client.ui'>
  <ui:style src='../Customer.css'/>

  <g:HTMLPanel addStyleNames="{style.gwt-CrudEdit}">
  <table cellpadding="0" cellspacing="0" id="viewTable">
	<tr><td class="label" valign="top"><ui:msg description="customernumberLabel">Customernumber:</ui:msg></td><td><gc:IntegerBox ui:field="customernumberBox"></gc:IntegerBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="customernameLabel">Customername:</ui:msg></td><td><g:TextBox ui:field="customernameBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="contactlastnameLabel">Contactlastname:</ui:msg></td><td><g:TextBox ui:field="contactlastnameBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="contactfirstnameLabel">Contactfirstname:</ui:msg></td><td><g:TextBox ui:field="contactfirstnameBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="phoneLabel">Phone:</ui:msg></td><td><g:TextBox ui:field="phoneBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="addressline1Label">Addressline1:</ui:msg></td><td><g:TextBox ui:field="addressline1Box"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="addressline2Label">Addressline2:</ui:msg></td><td><g:TextBox ui:field="addressline2Box"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="cityLabel">City:</ui:msg></td><td><g:TextBox ui:field="cityBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="stateLabel">State:</ui:msg></td><td><g:TextBox ui:field="stateBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="postalcodeLabel">Postalcode:</ui:msg></td><td><g:TextBox ui:field="postalcodeBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="countryLabel">Country:</ui:msg></td><td><g:TextBox ui:field="countryBox"></g:TextBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="salesrepemployeenumberLabel">Salesrepemployeenumber:</ui:msg></td><td><gc:IntegerBox ui:field="salesrepemployeenumberBox"></gc:IntegerBox></td></tr>
	<tr><td class="label" valign="top"><ui:msg description="creditlimitLabel">Creditlimit:</ui:msg></td><td><gc:DecimalBox ui:field="creditlimitBox"></gc:DecimalBox></td></tr>
  </table>
  <g:HorizontalPanel ui:field="buttonPanel">
  <g:Button addStyleNames="{style.gwt-CrudEditSaveButton}" ui:field="saveButton"><ui:msg description="SaveButton">Save</ui:msg></g:Button>
  <g:Button addStyleNames="{style.gwt-CrudEditCancelButton}" ui:field="cancelButton"><ui:msg description="CancelButton">Cancel</ui:msg></g:Button>
  </g:HorizontalPanel>
  </g:HTMLPanel>
</ui:UiBinder>
Full listing of CustomerEditWidget.ui.xml

Let us know what you think

We hope that you found this article informative and that you are able to get a good sense for the code that is being generated using MyEclipse For Spring, specifically as it relates to our GWT integration. As excited as we are about this new feature, we are eager to hear what the developer community thinks about our GWT scaffolding capability. You can download MyEclipse for Spring 8.6 here. Please post all feedback, questions and issues to the MyEclipse for Spring section of the MyEclipse forums.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}