This new release comes with several bugfixes and improvements (see the complete changelog on Jira ). Here are some highlights of the most interesting new features in GraniteDS 2.3.2 GA:
You can update Gas3 (together with the Wizard) through our Eclipse .
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:
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.
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.
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.)
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:
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.
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.
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 :
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.
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.
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.
@Entity public class Vineyard extends AbstractEntity { private static final long serialVersionUID = 1L; @Basic private String name; @OneToMany(cascade=CascadeType.ALL, mappedBy="vineyard", orphanRemoval=true) 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; } }
@Entity public class Wine extends AbstractEntity { private static final long serialVersionUID = 1L; public static enum Type { RED, WHITE, ROSE } @ManyToOne private Vineyard vineyard; @Basic private String name; @Basic private Integer year; @Enumerated(EnumType.STRING) 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 :
@RemoteDestination @DataEnabled(topic="") 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 :
@Service public class WineshopServiceImpl implements WineshopService { @PersistenceContext private EntityManager entityManager; @Transactional public void save(Vineyard vineyard) { entityManager.merge(vineyard); entityManager.flush(); } @Transactional public void remove(Long vineyardId) { Vineyard vineyard = entityManager.find(Vineyard.class, vineyardId); entityManager.remove(vineyard); entityManager.flush(); } @Transactional(readOnly=true) 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 :
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"?> <s:VGroup xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:e="com.wineshop.entities.*" xmlns="*" width="100%" height="100%"> <fx:Metadata>[Name]</fx:Metadata> <fx:Script> <![CDATA[ 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; [Inject] public var wineshopService:WineshopService; private function save():void { wineshopService.save(vineyard); } private function remove():void { wineshopService.remove(vineyard.id, function(event:TideResultEvent):void { selectVineyard(null); }); } private function selectVineyard(vineyard:Vineyard):void { this.vineyard = vineyard; vineyardsList.selectedItem = vineyard; } ]]> </fx:Script> <fx:Declarations> <e:Vineyard id="vineyard"/> </fx:Declarations> <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:HGroup> <s:List id="vineyardsList" labelField="name" width="100%" height="200" change="selectVineyard(vineyardsList.selectedItem)"> <s:dataProvider><s:AsyncListView list="{vineyards}"/></s:dataProvider> </s:List> <s:Button id="newVineyard" label="New" click="selectVineyard(new Vineyard())"/> </s:VGroup> <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}"/> </mx:FormItem> <mx:FormItem> <s:HGroup> <s:Button id="saveVineyard" label="Save" click="save()"/> <s:Button id="removeVineyard" label="Remove" enabled="{!isNaN(vineyard.id)}" click="remove()"/> </s:HGroup> </mx:FormItem> </mx:Form> </s:VGroup> </s:VGroup>
This is no major complexity here, but there are some things that can be noted :
Now you can build the application with mvn clean install, restart jetty and check your changes.
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:itemRenderer> <fx:Component> <s:ItemRenderer> <s:states><s:State name="normal"/></s:states> <s:HGroup id="wineEdit"> <s:TextInput text="@{data.name}"/> <s:TextInput text="@{data.year}"/> <s:DropDownList selectedItem="@{data.type}" requireSelection="true" dataProvider="{outerDocument.wineTypes}" labelField="name"/> </s:HGroup> </s:ItemRenderer> </fx:Component> </s:itemRenderer> </s:List> <s:VGroup gap="10"> <s:Button label="+" click="vineyard.wines.addItem(new Wine(vineyard))"/> <s:Button label="-" enabled="{Boolean(formWines.selectedItem)}" click="vineyard.wines.removeItemAt(formWines.selectedIndex)"/> </s:VGroup> </s:HGroup> </s:FormItem>
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 !!
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 { Managed.resetEntity(this.vineyard); 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, …
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 :
@Basic @Size(min=5, max=100, message="The name must be between {min} and {max} characters") private String name; @Basic @Min(value=1900, message="The year must be greater than {value}") @Max(value=2050, message="The year must be less than {value}") private Integer year; @Enumerated(EnumType.STRING) @NotNull private Type type;
@Basic @Size(min=5, max=100, message="The name must be between {min} and {max} characters") private String name; @OneToMany(cascade=CascadeType.ALL, mappedBy="vineyard", orphanRemoval=true) @Valid 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.
Spring.getInstance().addExceptionHandler(ValidatorExceptionHandler);
In Home.mxml, add the v namespace and define a FormValidation attached to the edit form and the bound entity :
<s:VGroup xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:v="org.granite.validation.*" xmlns:e="com.wineshop.entities.*" xmlns="*" width="100%" height="100%" initialize="selectVineyard(new Vineyard())"> ...
<fx:Declarations> <e:Vineyard id="vineyard"/> <s:ArrayCollection id="wineTypes" source="{Wine$Type.constants}"/> <v:FormValidator id="formValidator" entity="{vineyard}" form="{formVineyard}"/> </fx:Declarations>
We can also define a FormValidator for the item renderer :
<s:itemRenderer> <fx:Component> <s:ItemRenderer> <fx:Declarations> <v:FormValidator id="wineValidator" form="{wineEdit}" entity="{data}"/> </fx:Declarations> <s:states><s:State name="normal"/></s:states> <s:HGroup id="wineEdit"> <s:TextInput text="@{data.name}"/> <s:TextInput text="@{data.year}"/> <s:DropDownList selectedItem="@{data.type}" requireSelection="true" dataProvider="{outerDocument.wineTypes}" labelField="name"/> </s:HGroup> </s:ItemRenderer> </fx:Component> </s:itemRenderer>
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()) wineshopService.save(vineyard); }
mvn install, jetty, …
Enabling data push is just a question of configuration. There are 4 things to check :
<graniteds:messaging-destination id="wineshopTopic" no-local="true" session-selector="true"/>
@RemoteDestination @DataEnabled(topic="wineshopTopic", publish=PublishMode.ON_SUCCESS) public interface WineshopService {
Spring.getInstance().addComponent("wineshopTopic", DataObserver); Spring.getInstance().addEventObserver("org.granite.tide.login", "wineshopTopic", "subscribe"); Spring.getInstance().addEventObserver("org.granite.tide.logout", "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.
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 { ... Spring.getInstance().addExceptionHandler(OptimisticLockExceptionHandler); Spring.getInstance().getSpringContext().addEventListener( 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) event.conflicts.acceptAllClient(); else event.conflicts.acceptAllServer(); }); }
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.
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 :
Spring.getInstance().addComponents([UninitializeArgumentPreprocessor]);
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.
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.
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 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.
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!
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:
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 -DarchetypeGroupId=org.graniteds.archetypes -DarchetypeArtifactId=graniteds-tide-spring-jpa-hibernate -DarchetypeVersion=1.1.0.GA -DgroupId=org.example -DartifactId=springgds -Dversion=1.0-SNAPSHOT
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!
Here are the changes :
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 -DarchetypeGroupId=org.graniteds.archetypes -DarchetypeArtifactId=graniteds-tide-spring-jpa-hibernate -DarchetypeVersion=1.1.0.GA -DgroupId=com.myapp -DartifactId=example -Dversion=1.0-SNAPSHOT
There are still 4 existing archetypes, all of which are now based on Flex 4.5 and Spark components :
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.
Granite Data Services 2.3.0 GA (final) is out and available for download here: . Maven artifacts have been uploaded and should be shortly available as well.
This final release comes with fixes for the few issues that were discovered in the recent 2.3.0 RC1. The full change log can be found on .
Among many other things, GraniteDS 2.3.0 brings:
See also this post about these new features / improvements: More details on the new features in GraniteDS 2.3.
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.
Flex 4.5 broke a few APIs and there were two main issues with Tide :
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.
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; personService.save(uperson);
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;
personService.save(uperson);
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.
Tide.getInstance().addComponents([UninitializeArgumentPreprocessor]);
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.
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 :
@Inject private Gravity gravity;
With Seam :
@In("org.granite.seam.gravity") 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.
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 :
<graniteds:tide-data-publishing-advice/>
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 :
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> <interceptors> <class>org.granite.tide.cdi.TideDataPublishingInterceptor</class> </interceptors> </beans>
For EJB3, you have to setup the interceptor on each EJB :
@Stateless @Local(MyService.class) @Interceptors(TideDataPublishingInterceptor.class) @DataEnabled(topic="myTopic", publish=PublishMode.ON_COMMIT, useInterceptor=true) public class MyServiceBean { ... }
Or globally in ejb-jar.xml :
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>org.granite.tide.ejb.TideDataPublishingInterceptor</interceptor-class>
</interceptor-binding>
...
</assembly-descriptor>
Granite Data Services 2.3.0 Release Candidate 1 is out and available for download here: .
Many (59!) bugfixes, improvements and new features are coming with this new release and the full change log can be found on GraniteDS’ Jira: .
Among many other things, GraniteDS 2.3.0 brings:
Maven artifacts are coming as well. In the next few days, we will be discussing many of the new features and improvements in more detail. So stay tuned!
Fabiano’s blog is up and running at – go visit, bookmark and tweet about it now if you know Flex developers in Brazil.
The presentation highlights some of the main advantages of GraniteDS in the following areas:
What do you think, did we forget anything? Let us know your thoughts in the comments.