Flex | Granite Data Services


Archive for Flex:

Granite Data Services 3.0.0.M1 and Apache Flex 4.8.0

By Franck November 28th, 2012 Flex, GraniteDS No Comments
Please, feature an image for this post.

The last 3.0.0.M1 release of GraniteDS (see announcement here) is compatible with the last 4.8.0 release of . The two GraniteDS SWCs compiled with Apache Flex 4.8.0 can be found here:

We didn’t have time to include those SWCs in our binary release, but we will include them in the next upcoming release (or milestone). Keep in mind that GraniteDS 3.0.0.M1 is still in a beta stage and that you can experience unexpected gitchs (report them in our ).

Build them yourself

If you want to build yourself GraniteDS SWCs against the Apache Flex release, proceed as follows:

1. Download Apache Flex(R) 4.8.0 and unzip/untar it somewhere (say “flex48″). 2. Spawn a command shell and type (Apache Ant must be installed):

cd flex48/framework
ant thirdparty-downloads

Answer yes to all questions.

3. Download GraniteDS 3.0.0.M1 sources and unzip it somewhere (say “gds30″). 4. Edit env.properties and env45.properties, and fix the FLEX_HOME variable (absolute path to flex48). 5. Then run:

cd gds30
ant -f build.xml
ant -f build-flex45.xml

The first build will fail after building granite-essentials.swc, when trying to compile granite.swc: just ignore that error and proceed with build-flex45.xml.

The two GraniteDS SWCs buit against Apache Flex 4.8.0 should be in the build directory (granite-essentials.swc and granite-flex45.swc): just rename them to granite-essentials-flex48.swc and granite-flex48.swc, you’re done.

Flex, GraniteDS and the Future of RIA

By Franck December 6th, 2011 Flex, GraniteDS 4 Comments
Please, feature an image for this post.

After the recent announcements from Adobe regarding the future of the Flex framework (see, for example, this ) and, unofficially, from Microsoft about Silverlight (see ), the RIA world have been deeply shaken up and it is now time to look at the viable solutions left to the developers.

Before digging into what we, at GraniteDS, think about the Flex and RIA future and how it is influencing our platform roadmap, let’s see who are the different players in this area:

  • Flex (Adobe / Apache Foundation): one of best RIA solution right now, based on the Flash plugin.
  • Silverlight (Microsoft): another very good RIA solution, based on the plugin of the same name.
  • JavaFX (Sun / Oracle): emerging, based on the Java plugin, could be a good alternative if it comes on time.
  • GWT (Google), ExtJS (Sencha) and a plethora of others: good or emerging RIA solutions, no plugin required, targeted at HTML / JavaScript and the pending HTML5 specification.

Now let’s see what Flex brings to the table that makes it such a compelling solution for enterprise applications: a very good IDE and tooling, a strong language (ActionScript3), very good performance and cross-browser compatibility thanks to the Flash Player runtime, a great UI framework with plenty of advanced features (sophisticated component lifecycle, data binding, modularity, skinning, media capabilities, etc.), a good set of built-in, open source and for-pay components, and recently the ability to build cross-platform iOS / Android mobile applications from the same source code with the AIR runtime. All things that made possible for us to build our GraniteDS platform on a strong foundation.

All those capabilities are at worst inexistent, at best very partially matched by the existing alternatives. Without Flex and Silverlight, enterprise RIA developers are left with good but (while at different extents) emerging or less featured frameworks. There is not any doubt that it is possible to build enterprise applications with them, but the development will be much slower than with Flex or Silverlight, less maintainable, missing many advanced features and will require long and extensive testing on the various target browsers. Moreover the landscape of client technologies is evolving at an extremely fast pace with new frameworks, JavaScript evolutions or replacements such as Google Dart or ECMAScript 6 (Harmony), announced almost every day, and it’s very difficult to make a perennial choice right now.

You might have noticed that we only marginally mention HTML5 as an alternative. Indeed we think that HTML5 as it currently exists really is more an alternative to the Flash Player than to the Flex framework. You will always need complementary frameworks and component libraries to get a really usable development platform, and a big issue is that there is no common standard component model that ensures that all this stuff will work happily together. And while some of these HTML5-based frameworks will certainly become strong RIA platforms in the future, they are right now simply not as feature rich and stable as Flex and Silverlight can be, and most likely won’t be in the coming years. There is simply nothing that can replace Flex today.

What Future for the Flex Framework?

According to Adobe, the entire Flex framework will be soon given to the Apache Foundation. This is great news, from an openness and licensing point of vue, but it could also lead to a slow death of this great solution if nobody is truly committed into its development and maintenance. While Adobe seems to be willing to bind some of its own resources on the framework future, we think that a large part of the Flex community should be involved and we are very exited with the idea of participating to the Flex framework evolution.

While a participation as simple contributors is very likely, we wish to take a bigger part in the governance of the project. Of course this is subject to the choices of Adobe and the Apache Foundation concerning the people involved in this governance but, as a significant player in the Flex area, the GraniteDS team should be one of the natural choices in this community selection process.

If Flex as an Apache Foundation project is widely open to community contributors, we believe that it will remain the most powerful RIA platform in the future and may lead the industry for years to come until HTML5 or one of its next iterations can finally provide a credible solution. Flex is not going to disappear in the foreseeable future and is still the better choice for developing rich enterprise applications.

LCDS, BlazeDS and GraniteDS

GraniteDS has been the main alternative to LCDS (Livecycle Data Services) from the beginning and, after more than 5 years of polishing and improvements, it is a widely used, stable, production-ready, open-source and feature-rich solution for enterprise Flex / Java EE developments. It is also known as offering many strong advantages over BlazeDS and you will find a detailed comparison between GraniteDS and BlazeDS here, as well as a step-by-step migration guide.

According to another recent , Adobe is unlikely going to publish any new major release of LCDS, speaking only about supporting existing customers and applications. LCDS isn’t anymore bundled as a standalone product but is now sold as a module of a much larger platform, the . From its part, BlazeDS hasn’t really evolved during the last 1 or 2 years, and its maturation as an Apache Foundation project is at least questionable.

From an architectural point of vue, GraniteDS has always promoted a strong server-side approach, based on remote services that implement the most significant part of the business logic and a client application that is mostly a presentation layer. The main advantages of this approach are the independence of the server application from the client-side technology (Flex or any other) and the ability to leverage the full power of existing Java EE frameworks such as Spring, JBoss Seam, EJB3 and now CDI. This clearly differs from the classical client-server architecture promoted by LCDS, where almost all the business logic goes to the client-side, the server being not much more than a database frontend.

Another obvious advantage of this approach is the ability to migrate an existing Flex application to another RIA technology without having to change anything on the server application. The same applies when there is a need to create multi-headed client applications, targeted at different platforms (Flex, Android, iOS, HTML5, etc.). Using GraniteDS makes your application as future-proof as possible in this quickly evolving technology environment, while still benefiting from all its advanced enterprise features (lazy-loading, paging, real-time data push, etc.)

GraniteDS Roadmap

After the recent release of the 2.3.0.GA version of our platform (see details here) and a new Eclipse wizard plugin that dramatically simplifies GraniteDS’ projects creation (see here), we are moving to a major evolution of the framework. Among several other new features and improvements, the next 3.0 version will focus on the following areas:

  • Client libraries for iOS (Objective-C), Android (Java) and HTML5 (JavaScript): the purpose of these libraries is to implement the most salient features of the Flex / GraniteDS client framework in other technological contexts. Remoting, real-time messaging and data management will be available for each of these targeted platforms, without changing anything to the server-side implementation of current GraniteDS / Flex applications.
  • Code generation improvements (Gas3): generated code won’t be only targeted at ActionScript3, but also at Objective-C, Java and JavaScript.
  • Clean separation between data management and dependency injection features (Tide): this will allow an easier integration of Flex client framework (Spring ActionScript, Cairngorm, Parsley, Swiz, etc.) with GraniteDS’ data management module, and greatly simplify the implementation of data management for other client technologies.
  • An improved implementation of the real-time messaging system (Gravity): support of clustered and durable JMS subscriptions, reduced data transfers and WebSocket support.
  • Full OSGi / Java EE 6 compliance: GraniteDS conforms to standard and popular specifications, in order to be compatible with all application servers.
  • New distribution model (Community Platform): packaged as a ready-to-run test drive, it will greatly improve the getting started experience of the framework.

Overall, these new features are aiming to improve GraniteDS ease of use, enlarge its features and target platforms perimeter and help users in leveraging today’s and tomorrow’s best technical solutions.

Moving Forward

From all of the above, we believe that the GraniteDS platform, with its enterprise-grade features, uncompromised Java EE integration, professional support and openness to a wide range of client technologies can be considered as one of the best available platform for perennial RIA developments.

Through its continuous move toward new client technologies, GraniteDS will stay open to strong partnerships with IDE and graphical components providers, and committed to offer an open-source, comprehensive and powerful solution for Java EE developers willing to leverage the best of this renewed RIA world.

GraniteDS Data Management Tutorial

By William December 5th, 2011 Flex, GraniteDS 5 Comments
Please, feature an image for this post.

We have setup a simple example project that demonstrates most features of GraniteDS when used in a Spring/Hibernate technology stack.

The project is available on GitHub at and requires Maven 3.x for building.

Just issue the following commands to try it :

git clone git://github.com/wdrai/wineshop-admin.git
cd wineshop-admin
mvn clean install
cd webapp
mvn jetty:run-war

Now you can browse . You can log in with admin/admin or user/user.

It’s a simple CRUD example which allows searching, creating and modifying vineyards and the vines they produce. The application is definitely ugly but its goal is simply to demonstrate the following features :

  • Basic CRUD with a Spring service
  • Support for lazy-loading of JPA x-to-many associations
  • Dirty-checking
  • Client validation
  • Real-time push
  • Reverse lazy-loading

Each step corresponds to a tag on the GitHub project so you can see what has been changed at each step.

Let’s rebuild this project from scratch.

Step 1 : Create the project with the Maven archetype

This is the easiest one :

mvn archetype:generate<br />
    -DarchetypeGroupId=org.graniteds.archetypes<br />
    -DarchetypeArtifactId=org.graniteds-tide-spring-jpa<br />
    -DarchetypeVersion=1.1.0.GA<br />
    -DgroupId=com.wineshop<br />
    -DartifactId=wineshop-admin<br />
    -Dversion=1.0-SNAPSHOT<br />

Then check that the initial project is working :

cd wineshop-admin<br />
mvn clean install<br />
cd webapp<br />
mvn jetty:run-war<br />

And browse . You will get the default hello world application.

Step 2 : Implement basic CRUD functionality

This is the longer step as we are going to build most of the application : the JPA entity model, the Spring service and a basic Flex client. Here is the entity model, there is nothing special here.

public class Vineyard extends AbstractEntity {
    private static final long serialVersionUID = 1L;
    private String name;
    @OneToMany(cascade=CascadeType.ALL, mappedBy="vineyard",
    private Set<Wine> wines;
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;<br />
    public Set<Wine> getWines() {
        return wines;<br />
    public void setWines(Set<Wine> wines) {
        this.wines = wines;
public class Wine extends AbstractEntity {

    private static final long serialVersionUID = 1L;

    public static enum Type {

    private Vineyard vineyard;

    private String name;

    private Integer year;

    private Type type;

    public Vineyard getVineyard() {
        return vineyard;
    public void setVineyard(Vineyard vineyard) {
        this.vineyard = vineyard;<br />
    public Integer getYear() {
        return year;<br />
    public void setYear(Integer annee) {
        this.year = annee;<br />
    public String getName() {
        return name;<br />
    public void setName(String nom) {
        this.name = nom;
    public Type getType() {
        return type;
    public void setType(Type type) {
        this.type = type;

The Spring service interface to handle this model :

public interface WineshopService {
    public void save(Vineyard vineyard);
    public void remove(Long vineyardId);
    public Map<String, Object> list(Vineyard filter,
        int first, int max, String[] sort, boolean[] asc);

As you can see, there are two specific annotations on the service. @RemoteDestination indicates that the service is exposed to the Flex application, and that an ActionScript3 proxy will be generated for the service. @DataEnabled indicates that GraniteDS will track the JPA updates on the entities and report them automatically to the relevant clients.

Then the implementation :

public class WineshopServiceImpl implements WineshopService {

    private EntityManager entityManager;

    public void save(Vineyard vineyard) {

    public void remove(Long vineyardId) {
    	Vineyard vineyard = entityManager.find(Vineyard.class, vineyardId);

    public Map<String, Object> list(Vineyard filter,
            int first, int max, String[] sort, boolean[] asc) {

    	StringBuilder sb = new StringBuilder("from Vineyard vy ");
    	if (filter.getName() != null)
    		sb.append("where vy.name like '%' || :name || '%'");
    	if (sort != null && sort.length > 0) {
    		sb.append("order by ");
    	        for (int i = 0; i < sort.length; i++)
    		      sb.append(sort[i]).append(" ").append(asc[i] ? " asc" : " desc");
    	Query qcount = entityManager.createQuery("select count(vy) "
             + sb.toString());
    	Query qlist = entityManager.createQuery("select vy "
             + sb.toString()).setFirstResult(first).setMaxResults(max);
    	if (filter.getName() != null) {
    		qcount.setParameter("name", filter.getName());
    		qlist.setParameter("name", filter.getName());
    	Map<String, Object> result = new HashMap<String, Object>(4);
    	result.put("resultCount", (Long)qcount.getSingleResult());
    	result.put("resultList", qlist.getResultList());
    	result.put("firstResult", first);
    	result.put("maxResults", max);
    	return result;

This is a classic Spring JPA service. There are two particularities however :

  • It uses merge to update the entities. This is important as objects that are transferred between Flex and Java are considered as detached objects.
  • The method list has the specific signature (filter, first, max, sort[], asc[]) so it can be easily used from the GraniteDS paged collection implementation.

Note however that there is no particular dependency on GraniteDS, this service can be used by any other client.

Finally the Flex client application in Home.mxml :

<?xml version="1.0" encoding="utf-8"?>

    width="100%" height="100%">


            import mx.collections.ArrayCollection;

            import org.granite.tide.spring.Spring;
            import org.granite.tide.collections.PagedQuery;
            import org.granite.tide.events.TideResultEvent;
            import org.granite.tide.events.TideFaultEvent;

            import com.wineshop.entities.Vineyard;
            import com.wineshop.entities.Wine;
            import com.wineshop.entities.Wine$Type;
            import com.wineshop.services.WineshopService;

            Spring.getInstance().addComponentWithFactory("vineyards", PagedQuery,
                { filterClass: Vineyard, elementClass: Vineyard, remoteComponentClass: WineshopService, methodName: "list", maxResults: 12 }

            [In] [Bindable]
            public var vineyards:PagedQuery;

            public var wineshopService:WineshopService;

            private function save():void {

            private function remove():void {
                wineshopService.remove(vineyard.id, function(event:TideResultEvent):void {

            private function selectVineyard(vineyard:Vineyard):void {
                this.vineyard = vineyard;
                vineyardsList.selectedItem = vineyard;

		<e:Vineyard id="vineyard"/>

	<s:VGroup paddingLeft="10" paddingRight="10" paddingTop="10" paddingBottom="10" width="800">
		<s:HGroup id="filter">
			<s:TextInput id="filterName" text="@{vineyards.filter.name}"/>
			<s:Button id="search" label="Search" click="vineyards.refresh()"/>

		<s:List id="vineyardsList" labelField="name" width="100%" height="200"
			<s:dataProvider><s:AsyncListView list="{vineyards}"/></s:dataProvider>

		<s:Button id="newVineyard" label="New" click="selectVineyard(new Vineyard())"/>

	<s:VGroup paddingLeft="10" paddingRight="10" paddingTop="10" paddingBottom="10" width="800">
		<mx:Form id="formVineyard">
			<mx:FormHeading label="{isNaN(vineyard.id) ? 'Create vineyard' : 'Edit vineyard'}"/>
			<mx:FormItem label="Name">
				<s:Label text="{vineyard.id}"/>
				<s:TextInput id="formName" text="@{vineyard.name}"/>
					<s:Button id="saveVineyard" label="Save"
					<s:Button id="removeVineyard" label="Remove"
							  enabled="{!isNaN(vineyard.id)}" click="remove()"/>


This is no major complexity here, but there are some things that can be noted :

  • It uses the PagedQuery component to display the list of existing vineyards. The configuration section at the beginning (addComponentWithFactory…) links the client component to the service method we have define in our Spring service, so each time the component needs to fetch data, it will call the remote service transparently. This component also handles paging, so it will fetch next elements on demand when there are lots of data on the server and the user scrolls the list. This is also why it is wrapped in an AsyncListView collection view.
  • The PagedQuery also handles transparently filtering and sorting. Here we simply bind a TextInput to the filter object that is passed to the server method. When the user clicks on ‘Search’, we simply have to refresh the collection, as we would have done for a client filter. Sorting is even easier and is handled completely transparently when the collection is bound to a UI component that allows sorting, for example DataGrid.
  • The remote service invocation is completely typesafe thanks to the ActionScript 3 generator and the [Inject] annotation. If you refactor the service, you will instantly detect the inconsistency between the client and the server at build time. You can also benefit from code completion in the IDE.
  • The CRUD operations are completely ‘fire and forget’. You just call the server method, and GraniteDS will automatically handle the updates, you don’t have to do anything yourself. There is not even a result handler and the server method do not return anything. In fact GraniteDS listens to all JPA events though the DataPublishListener in AbstractEntity and dispatches them transparently to the Flex clients, including the client from which the call originates. The local caching does everything else and GraniteDS is able to match and merge the result with the initial object on the client. The remove operation also works transparently because the PagedQuery is able to handle the remove events and update itself. It we were using simple collections, we would have to handle manually the persist and remove events.

Now you can build the application with mvn clean install, restart jetty and check your changes.

Step 3 : Support for JPA lazy associations

There is nothing much to do, simply add a form item allowing to edit the list of wines for the selected vineyard. We can for example use a list with an item renderer containing editors for the properties of the Wine entity :

<s:FormItem label="Wines">
    <s:HGroup gap="10">
        <s:List id="formWines" dataProvider="{vineyard.wines}">
                        <s:states><s:State name="normal"/></s:states>
                        <s:HGroup id="wineEdit">
                            <s:TextInput text="@{data.name}"/>
                            <s:TextInput text="@{data.year}"/>

        <s:VGroup gap="10">
            <s:Button label="+"
                click="vineyard.wines.addItem(new Wine(vineyard))"/>
            <s:Button label="-"

We just miss two minor things : add an argument to the constructor of Wine to be able to associate it to a Vineyard (here used for the add operation) :

public function Wine(vineyard:Vineyard = null):void {
    this.vineyard = vineyard;

And initialize the collection of wines for a new vineyard :

public function Vineyard():void {
    this.wines = new ArrayCollection();

Again, build the application with mvn install, restart jetty and check your changes.

As you can see, this is purely client code. We rely on cascading to persist the changes in the database, and GraniteDS is able to cleanly transfer lazy associations without much hassle.

More, when entities are fetched in the list of vineyards, their collections of wines are still not loaded. When the user selects a vineyard, the binding {vineyard.wines} on the list automatically triggers the loading of the collection from the server. This is completely transparent so you don’t even have to think about it !!

Step 4 : Dirty checking / Undo

If you have played with the application you may have noticed that using bidirectional bindings leads to strange behaviour. Even without saving your changes, the local objects are still modified. GraniteDS tracks all updates made on the managed entities and is able to easily restore the last known stable state of the objects (usually the last fetch from the server).

It’s also easily possible to enable or disable the ‘Save’ button depending on the fact that the user has modified something or not.

To achieve this, we have to ensure that the entity bound to the form is managed by GraniteDS (in particular for newly created entities because entities retrieved from the server are always managed). We have just to add a few lines when the user selects another element in the main list to restore the state of the previously edited element :

import org.granite.tide.spring.Context;

[Inject] [Bindable]
public var tideContext:Context;

private function selectVineyard(vineyard:Vineyard):void {
    tideContext.vineyard = this.vineyard = vineyard;
    vineyardsList.selectedItem = vineyard;

Then we can use the meta_dirty property of the Tide context to enable/disable the ‘Save’ button :

<s:Button id="saveVineyard" label="Save"
     enabled="{tideContext.meta_dirty}" click="save()"/>

mvn install, jetty, …

Step 5 : Validation

Great, we can now create, edit and search in our database. Now we would like to ensure that the data is consistent. Instead of manually defining Flex validators on each field, we are going to use the Bean Validation API on the server and its GraniteDS implementation on the client.

First let’s add a few Bean Validation annotations on the model :

@Size(min=5, max=100,
    message="The name must be between {min} and {max} characters")
private String name;

    message="The year must be greater than {value}")
    message="The year must be less than {value}")
private Integer year;

private Type type;
@Size(min=5, max=100,
    message="The name must be between {min} and {max} characters")
private String name;

    mappedBy="vineyard", orphanRemoval=true)
private Set<Wine> wines;

This will at least ensure that we cannot save invalid entities. However we would like that our user is informed that the operation has failed. One ugly way would be to add a fault handler on the save operation call with an alert. Instead we are simply going to use the FormValidator component that will validate the entity locally and interpret server exceptions to propagate the error messages to the correct input field.

First you have to register the validation exception handler that will process the validation errors coming from the server. This is not required in this example because all the constraints can be processed locally on the client, but it’s always useful in case the server has additional constraints. Just add this in the init method of Main.mxml.


In Home.mxml, add the v namespace and define a FormValidation attached to the edit form and the bound entity :

    width="100%" height="100%"
    initialize="selectVineyard(new Vineyard())">
    <e:Vineyard id="vineyard"/>
    <s:ArrayCollection id="wineTypes" source="{Wine$Type.constants}"/>
    <v:FormValidator id="formValidator"

We can also define a FormValidator for the item renderer :

                <v:FormValidator id="wineValidator"
                    form="{wineEdit}" entity="{data}"/>

            <s:states><s:State name="normal"/></s:states>
            <s:HGroup id="wineEdit">
                <s:TextInput text="@{data.name}"/>
                <s:TextInput text="@{data.year}"/>

These two declarations will allow to display error messages on the field during editing. The FormValidator takes advantage of the replication of the Bean Validation annotations to ActionScript 3 to know what validations have to be applied on the client data.

Finally we can keep the user from trying to save an invalid object by adding the following line :

private function save():void {
	if (formValidator.validateEntity())

mvn install, jetty, …

Step 6 : Real-time data push

Enabling data push is just a question of configuration. There are 4 things to check :

  • Declare a topic messaging destination in the Spring configuration app-config.xml
  • <graniteds:messaging-destination id="wineshopTopic"
        no-local="true" session-selector="true"/>
  • Declare the topic and publish mode on the @DataEnabled annotation on the exposed services
  • @RemoteDestination
    @DataEnabled(topic="wineshopTopic", publish=PublishMode.ON_SUCCESS)
    public interface WineshopService {
  • Declare the DataObserver for this topic in Main.mxml
  • Spring.getInstance().addComponent("wineshopTopic", DataObserver);
        "wineshopTopic", "subscribe");
        "wineshopTopic", "unsubscribe");

Of course the three declarations should use the same topic name, but this is all you need to enable data push.

mvn install, jetty, …

Now if you open many browsers, all the changes made in one browser should be dispatched to all other browsers.

Step 7 : Conflict handling

In any multiuser application, there may be cases where different users do changes on the same entity concurrently. Using optimistic locking is a common technique to handle these cases and avoid database inconsistencies. GraniteDS is able to handle these errors cleanly in either normal remoting operations or with real-time data push.

This is quite simple to configure, you just need to register an exception handler for the JPA OptimistickLockException and an event listener on the Tide context that will be called when a concurrent modification conflict occurs :

private function init():void {

        TideDataConflictsEvent.DATA_CONFLICTS, conflictsHandler);

private function conflictsHandler(event:TideDataConflictsEvent):void {
    Alert.show("Someone has modified this vineyard at the same time\n. "
        + "Keep your changes ?",
        "Conflict", Alert.YES | Alert.NO, null, function(ce:CloseEvent):void {
        if (ce.detail == Alert.YES)

The most difficult part is to actually obtain a conflict. After your rebuild and restart jetty, open two browsers. Create a vineyard in one of the browsers, it will appear in the second one. Edit it in the second browser and change something, for example its name, without saving. Then in the first browser, change the name to a different value and save. An alert should appear in the second browser.

Step 8 : Reverse lazy loading

This final feature is not very visual, but it can improve a lot the performance of your application. The support for server-to-client lazy loading ensures that the amount of data transferred in this direction is limited, but a problem can arise in the other direction (client-to-server). Once all your object graph is loaded on the client by transparent loading or manual operations, the complete loaded object graph will be sent back to the server even when only a property of the root object has been changed. With very deep and complex object graphs, this can really kill the performance of write operations.

GraniteDS now provides a new feature called reverse lazy loading that allows to fold the object graph before transmitting it to the server. It will take in account the changes made locally by the user to fold all parts of the graph that have not been updated, and still send the parts of the graph containing the changes.

This can be setup as follows : in the initialization method of the application, register an argument preprocessor :


And then in the service methods that update entities, simply add the @Lazy annotation to the incoming arguments :

public void save(@Lazy Vineyard vineyard);

To really see what happens, you have to run mvn jetty:run-war in debug mode from the Eclipse M2E plugin, and put a breakpoint in the method save(). Then create a vineyard and some wines, and save it. Close and reopen the browser to restart from a clean state, edit and change the name of the vineyard you just created and click on Save. By inspecting the incoming Vineyard object on the debugger, you can see that the collection of wines is marked uninitialized. Now change the name of one of the wine and click on Save. This time the collection will be initialized and contain the Wine object you just updated.

Or you can just trust that it works and that it’s better to use it than not…


We’re done with this tutorial on the data management features. You are now be able to see what you can do with GraniteDS and how it can simplify your developments, and even bring new possibilities for your applications.

Quick start with GraniteDS

By William December 2nd, 2011 Flex, GraniteDS 14 Comments
Please, feature an image for this post.

You have now two very easy ways to quickly create a new GraniteDS project – or to get quickly started with the platform if you are not familiar with it: a dedicated Eclipse wizard and four Maven archetypes. Both allow to create fully functional projects with only few clicks or command-line options, resulting in pre-configured, ready to deploy, skeleton applications with most of the major features you would use in a real-world project: Flash Builder configuration, Ant build file, JavaEE framework and JPA provider integration, code generation setup, real-time messaging configuration, etc.

If you are a Maven user, you can start with the archetypes that work with embedded servers ( Jetty or Embedded GlassFish), see this paragraph below. Using the wizard can however be helpful in defining proper configurations for other target application servers and environments such as Tomcat or JBoss.

Using the Eclipse Wizard

First, you need to install the GraniteDS wizard and builder plugins in Eclipse. From Eclipse, you can use the Eclipse Marketplace dialog (search for “GraniteDS�?) or add the GraniteDS update site () to the list of available software sites:

You will need to install both the GraniteDS Builder and the GraniteDS Wizard plugins. It will register a GraniteDS / GraniteDS Project wizard with three default templates:

  • The Pojo template is a simple template that creates a project configured for basic remoting to a Java service.
  • The Chat template is a simple template that creates a project configured for basic client-to-client messaging with a default chat application.
  • The Spring/EJB/Seam/CDI template is a bit more advanced and allows to create a project configured with a complete Flex, Java and GraniteDS technology stack, including popular Java frameworks such as Spring and EJB3, JPA support and real-time data push.

The three templates generate a combined Flex/Java project that can be easily converted to an Eclipse WTP project and deployed to a local or remote application server. If you use Flash Builder, the necessary configuration files can be optionally generated so the project can be immediately compiled in Flash Builder. Finally a minimal ant build file will be produced so you can build the project manually if needed.

Let’s see how this works in a few steps:

First select the menu File / New / Other.. (or just type Ctrl+N) then lookup the GraniteDS section and select GraniteDS Project.

Select a template, for example the last one and click Next.

Choose a name for your project, choose your preferred technologies, for example choose Spring 3, Tomcat 7 and Hibernate. Fill up the other information, in particular your Flex SDK home directory (it should be ideally a Flex 4.5 SDK) and the deployment folder of the application server (for example something like /home/dev/apache-tomcat-7.0.22/webapps for Tomcat 7). Keep default values for the others, check Flash Builder and Ant+Ivy build options and click on Finish.

The creation of the new project in the workspace can take some time because the wizard will fetch all necessary libraries on the central Maven repository. If you are using Flash Builder 4.5, you may get the following warning because the generated configuration files are targeted at Flash Builder 4, so just select Flex SDK 4.5+.

With Flash Builder, you will always have an error about HTML wrapper files after the project is built (this is a known Flash Builder issue). Just right click on the error message as suggested and select Recreate HTML templates.

If you don’t use Flash Builder, you can simply use the target build.flex of the generated build.xml ant file that will run the compilation of the Flex application.

At this point, you already have a working project, fully configured for the technologies and server you have chosen in the wizard page. You have now two options to deploy it to your server: run the deploy.war target of the generated ant build.xml file or use Eclipse WTP.

In order to use WTP, you first have to convert the project to a faceted project by right clicking on the project and selecting the menu Configure / Convert to Faceted Form…

On the next page, select Dynamic Web Project with the correct version (3.0 for Tomcat 7 or JBoss 6/7, 2.5 for Tomcat 6 or JBoss 4/5) and select a corresponding server runtime.

Finally, right click on the project and select Debug / Debug on Server…

On the last screen, just check that the correct server is selected (here it should be Tomcat 7) and click on Finish.

Eclipse will start the application server and open a Web browser on the application welcome page. You should get something like this:

You can log in with admin:admin or user:user, and try to enter a few names. If you open a second browser (and not only another tab or window of the same browser!) and point it to the same page (), you should see your modifications reflected in real-time in both browsers.

If you setup automatic publishing in Eclipse WTP (that should be the case by default), any change you make on the Flex application will be automatically deployed on the server. You can simply refresh the page to check your changes once compiled, no need to redeploy anything to develop your UI!

Using the Maven archetypes

If you are a Maven user, it’s likely that you will prefer to start with an archetype. There are four existing GraniteDS archetypes available on the Maven central repository:

archetypeGroupId: org.graniteds.archetypes archetypeVersion: 1.1.0.GA archetypeArtifactId:

  • graniteds-spring-jpa-hibernate: Flex 4.5 + Spring 3 + Hibernate 3.6 + GraniteDS 2.3 with standard RemoteObject API
  • graniteds-tide-spring-jpa-hibernate: Flex 4.5 + Spring 3 + Hibernate 3.6 + GraniteDS 2.3 with Tide API
  • graniteds-tide-seam-jpa-hibernate: Flex 4.5 + Seam 2.2 + Hibernate 3.6 + GraniteDS 2.3 with Tide API
  • graniteds-tide-cdi-jpa: Flex 4.5 + CDI/Weld 1.1 + JPA 2.0 + GraniteDS 2.3 with Tide API

The Tide archetypes are equivalent to what you get with the Spring/EJB/Seam/CDI template of the Eclipse Wizard we have seen if the first paragraph. The main differences are that you don’t need to have a Flex SDK installed as it will be retrieved from the Maven repository and that you get 3 separate projects: a Java project, a Flex project and a Webapp project.

Let’s reproduce what we did with the Eclipse Wizard, first with a command line (Maven 3.x required):

mvn archetype:generate

Once the archetype is created, you can build the project with:

cd springgds
mvn clean package

And finally run the embedded jetty server with:

cd webapp
mvn jetty:run-war

You can now browse  and check that the application works.

The CDI archetype requires a Java EE 6 server and uses an embedded GlassFish that you can run with:

cd webapp
mvn embedded-glassfish:run

With the Eclipse Maven integration (the M2E plugin), you can simply choose one of the archetypes when doing New Maven Project.

To deploy the application to a real server, you can use the following goal to build a war file:

mvn war:war

Note however that when doing this you may have to change the configuration of the application. In general you have to change the name of the Gravity servlet in web.xml and most likely update your JPA configuration. You can use the Eclipse Wizard to generate a configuration corresponding to your case.


It now takes literally 5 minutes (and less than 1 minute after the first run) to start a new Flex / Java project with GraniteDS. You no longer have any excuse not to try it!

Maven archetypes updated to GraniteDS 2.3.0, Flex 4.5 and Flexmojos 4

By William November 21st, 2011 Annoucements, Flex, GraniteDS No Comments
Please, feature an image for this post.

Following the release of GraniteDS 2.3.0.GA, we have updated the Maven archetypes, now in version 1.1.0.GA.

Here are the changes :

  • Upgrade to GDS 2.3.0.GA
  • Upgrade to Flexmojos 4.0-RC2
  • Upgrade to Flex SDK 4.5.1
  • Fixed some issues in POMs when used in Eclipse with the m2e plugin
  • Fixed Tide/Seam archetype

As a reminder, here is how you can use the archetype to build a simple project with Flex/GraniteDS/Spring and Hibernate :

mvn archetype:generate 

There are still 4 existing archetypes, all of which are now based on Flex 4.5 and Spark components :

  • graniteds-spring-jpa-hibernate: Spring 3 + JPA/Hibernate + GraniteDS with RemoteObject API
  • graniteds-tide-spring-jpa-hibernate: Spring 3 + JPA/Hibernate + GraniteDS with Tide API
  • graniteds-tide-seam-jpa-hibernate: Seam 2.2 + JPA/Hibernate + GraniteDS with Tide API
  • graniteds-tide-cdi-jpa: CDI/Weld 1.1 + JPA + GraniteDS with Tide API

Once the project is created, you can build it easily with

mvn install

And then run it in Jetty (Spring or Seam) with :

cd webapp
mvn jetty:run-war

Or in the Embedded GlassFish 3.1.1 (CDI) with :

cd webapp
mvn embedded-glassfish:run

Once started you can access the default generated application at . By default there are two users created that can access the application : admin / admin and user / user.

You can then easily build a war with :

mvn war:war

Note that in this case you may have to change the configuration if your application server target is not the same as the embedded maven plugin. For example, if you target Tomcat, you will have to adapt the Gravity servlet in web.xml accordingly. Also note that the default configuration uses an embedded H2 database and locally defined security.

More details on the new features in GraniteDS 2.3

By William October 12th, 2011 Flex, GraniteDS No Comments
Please, feature an image for this post.

GraniteDS 2.3.0 RC1 is mostly a bugfix and incremental improvements release but contains a few new features :

Support for JBoss AS 7 / Hibernate 4

JBoss have once again changed their VFS internal implementation in AS 7, breaking the class scanner in GraniteDS. It was still possible to run GraniteDS in non-scan mode but this is now fixed and you can now benefit from the very fast JBoss AS 7 with GDS 2.3.

Another issue with JBoss AS 7 is its deep integration with Hibernate 4 which makes very painful to deploy Hibernate 3.x applications (i.e. all Hibernate applications). There are a few workarounds described on the Hibernate blog . However it’s recommended to upgrade to H4 as soon as possible, and GraniteDS now fully supports Hibernate 4. Just use the granite-hibernate4.jar instead of granite-hibernate.jar and you’re done.

Support for Flex 4.5+

Flex 4.5 broke a few APIs and there were two main issues with Tide :

  • The client libraries crashed when run in a mobile application
  • The PagedQuery was unusable

These two issues are now fixed and you will find a version of the granite-flex45.swc client libraries compiled with the Flex SDK 4.5 . Unfortunately it is not yet available with the ‘normal’ distribution because our build system was not able to build with two different versions of the Flex SDK. The library can be found only in the new distribution (which will be the default distribution format starting from GraniteDS 3.0). For the final release we will try to add it manually and it should be also available as a maven artifact.

Reverse lazy-loading

The support of lazy-loaded associations when retrieving detached entities from the server is an important feature of GraniteDS and greatly helps limiting the amount of data transferred through the network. However it works only in the server to client direction. The problem is that once you have loaded all associations on the client, passing an object as an argument of a remote method call will send the whole loaded object graph to the server, even if you have only changed a simple property.

public function savePerson():void {
    person.lastName = "Test";
    personService.save(person);   // This will send all loaded collections associated to the Person object

Obviously this is not very efficient, so you can now ask Tide to uninitialize the object graph before sending it. You can do it manually with :

var uperson:Person = new EntityGraphUnintializer(tideContext).uninitializeEntityGraph(person) as Person;

Here all loaded collections of the Person object will be uninitialized so uperson contains only the minimum of data to correctly merge your changes in the server persistence context. If there is a change deeper in the object graph, the uninitializer is able to detect it and will not uninitialize the corresponding graph so the server receives all changes.

person.contacts.getItemAt(0).email = '[email protected]';
var uperson:Person = new EntityGraphUnintializer(tideContext).uninitializeEntityGraph(person) as Person;

Here uperson will still contain the loaded collection of contacts, but if there are other collections, they will be uninitialized.

If you want to uninitialize more than one argument, you have to use the same EntityGraphUninitializer for all so they share the same context :

var egu:EntityGraphUnintializer = new EntityGraphUninitialize(tideContext);
uperson1 = egu.uninitializeEntityGraph(person1);
uperson2 = egu.uninitializeEntityGraph(person2);
personService.save(uperson1, uperson2);

Calling the EntityGraphUninitializer manually is a bit tedious and ugly, so there is a cleaner possibility when you are using generated typesafe service proxies. You can annotate your service method arguments with @org.granite.tide.data.Lazy :

public void save(@Lazy Person person) {

Gas3 will then generate a [Lazy] annotation on your service methods (so take care that you need to add the [Lazy] annotation to your Flex metadata compilation configuration). Next in the Flex application, register the UninitializeArgumentPreprocessor component in Tide.


Once you have done this, all calls to PersonService.save() will use an uninitialized version of the person argument.

It is important to note that it will not uninitialize the associations in your ‘normal’ Tide context and that there will not be any change to your client entities. Tide will simply copy the necessary entities in a temporary context, uninitialize the associations of the copies before the passing them as arguments to the remote call and then discard everything.

Unfortunately this new feature cannot yet work with Seam context variables (and thus with the Home component). Only method arguments can be processed, but this should cover be the vast majority of use cases. Support for context variables requires a major refactoring and will come with GDS 3.0.

Injection of the Gravity singleton

In GDS 2.2 you needed a ServletContext to retrieve the Gravity singleton from a server application, which is not always possible or suitable and implies a dependency on the Servlet API. With GDS 2.3, the singleton is available in the framework context and can simply be injected.

With Spring or CDI :

private Gravity gravity;

With Seam :

private Gravity gravity;

The DI capabilities of EJB3 are too limited to allow something like this. If you need to be independent from the Gravity API, just use a JMS topic and send messages with the JMS API.

Improved support for transparent data push (ON_COMMIT mode and non-GDS threads)

GraniteDS provides a data push feature allowing to track updates on JPA entities and transparently dispatch them in real-time through Gravity to Flex clients. However in GDS 2.2 there were two limitations : the updates could be tracked only from a thread managed by GraniteDS (an HTTP remoting or messaging request), and the ON_COMMIT mode allowing transactional dispatch of the updates through JMS was not supported out-of-the-box.

GraniteDS 2.3 comes with a set of interceptors (unfortunately one for each technology : Spring, Seam, EJB3 and CDI ; so much for interoperability for such a basic thing as an interceptor) managing the ON_COMMIT mode that can also be used to track the updates on any non-GraniteDS thread.

The setup is simple, just add the useInterceptor=true parameter on the @DataEnabled annotation and use either ON_SUCCESS or ON_COMMIT. ON_SUCCESS is the default mode and simply means that the dispatch will occur for all successful calls. ON_COMMIT means that the dispatch will occur when the transaction commits, it ensures that the dispatch is transactional when used in conjuction with a transacted JMS topic.

Then configure the interceptor for your target framework :

For Spring, add this in your context :


Take care that you have to use the latest xsd :

xsi:schemaLocation="http://www.graniteds.org/config http://www.graniteds.org/public/dtd/2.3.0/granite-config-2.3.xsd"

For Seam, nothing to do, the interceptor is implicitly setup when the @DataEnabled(useInterceptor=true) annotation is applied.

For CDI, just enable the interceptor in beans.xml :

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">	 

For EJB3, you have to setup the interceptor on each EJB :

@DataEnabled(topic="myTopic", publish=PublishMode.ON_COMMIT, useInterceptor=true)
public class MyServiceBean {

Or globally in ejb-jar.xml :


Get GraniteDS News and Tutorials in Portuguese!

By admin October 11th, 2011 Flex, GraniteDS 1 Comment
Please, feature an image for this post.

For all of our Portuguese speaking users, the brilliant Fabiano Frizzo has been putting up a blog about GraniteDS in Brazil! Fabiano is a very talented programmer and avid user of the GraniteDS framework. By publishing news and updates in Portuguese, Fabiano hopes that more developers in Brazil and around the globe will be able to discover the benefits of the GraniteDS framework. Thanks Fabiano!

Fabiano’s blog is up and running at – go visit, bookmark and tweet about it now if you know Flex developers in Brazil.

How GraniteDS compares to BlazeDS

By admin September 13th, 2011 Flex, GraniteDS 3 Comments
Please, feature an image for this post.

We get a lot of questions from developers and architects about some of the major differences between BlazeDS and GraniteDS. They are quite significant. You can compare some differences already in a quick comparison table on our website, but we’ve created a more detailed comparison in the presentation below. Please feel free to share this presentation!

The presentation highlights some of the main advantages of GraniteDS in the following areas:

  • Licensing and Support
  • JPA Integration
  • Remoting
  • Real-Time Messaging
  • Client Frameworks
  • Validation and Numeric Types
  • Mobile Platforms Support

What do you think, did we forget anything? Let us know your thoughts in the comments.

Flex Connector 1.1 for Nuxeo Released With GraniteDS

By admin August 31st, 2011 Flex, GraniteDS No Comments

Nuxeo is a global leader in Open Source Enterprise Content Management (ECM), that enables architects and developers to easily build, deploy, and run state of the art applications. The Nuxeo Enterprise Platform (Nuxeo EP) is a Java-based content infrastructure designed to be used as a development environment for content- and case-based applications. Nuxeo EP is an extensible and configurable set of ECM services and modular plug-ins that allows an organization to build out specific horizontal or vertical applications.

Nuxeo has just version 1.1. of its Flex connector that lets Flex applications interact with Nuxeo using AMF, the binary format used to serialize ActionScript objects. The Nuxeo Flex Connector relies on GraniteDS to enable to easily read, search, create, update documents stored in Nuxeo, manage workflows and tasks, use conversion services, manage users and send notifications, etc. The following image highlights the integration:

To learn how to use the connector, please refer to the Wiki – . The Flex connector comes with several samples that will help you get started quickly.

So what’s up next? Nuxeos first goal is to update GraniteDS and the Flex SDK. The current implementation will have to be updated to the lastest 2.2 version of GraniteDS and all sample applications will be built on Flex4.

We are happy to see GraniteDS in use and look forward to powering the Nuxeo Flex applications!