Blaze DS connectivityGiorgio Natili
Blog: www.mxml.it twitter: http://twitter.com/giorgionatili
During the session
I. IntroductionII. Blaze DS and Live Cycle DSIII. How to invoke Java from Flex
I. Setting up the environmentII. Create a simple script
IV. A centralized approachI. Service Connector (part of the nabiro class set)
I. The ActionScript classes involvedII. The analysis of the class
II. Model View PresenterV. Demo
It’s RIA time
• The adoption of Rich Internet Applications is increasing in a very different range of contexts
- Business- Education- Entertainment
• If your software has an architecture where the business logic is clearly separated from other layers, then you can use one of the available technologies (or mix all the best features of each technology) and develop a RIA
RIA solutions
• The main solution you can find on the market today for the front end implementation of a RIA are
– Java FX– Silverlight– Ajax– Flash
• Accordingly to your choice people can say:- He’s a real programmer- He’s good guy but too much related to MS- He’s a scripter- He’s a graphic designer, he can’t do a software
The snapshot
Java Programmer
.NET Programmer
Ajax Programmer
Flash Programmer
And then comes Flex...
• I totally agree with the first reaction of people with Flash, the skip intro nightmare is still live in my mind!
• But I have to be honest in my experience with the Flex framework you can get great cross platform result and reach a wide range of users because the Flash Player is omni present and a de facto standard in the web development
• The use of the Flash Player is not only related to Flex, each Flash application may be a good one or a bad one accordingly to the way you design it
Blaze DS and Live Cycle DS
• Blaze DS and Live Cycle DS (LCDS) represent today the two main choices developers can do when they are planning a new RIA connected with Java or Coldfusion
• The first one is open source (great!) and the second one is a close source (less great but a very good tool!) product with a greater set of functionalities
• There are obviously a lot of difference between the two solutions but the choice depends only on your needs
AMF communication
• One of the key point of these software is the communication over AMF
• Action Message Format (AMF) is a compact binary format that is used to serialize ActionScript object graphs
• Once serialized an AMF encoded object graph may be used to persist and retrieve the public state of an application across sessions or allow two endpoints to communicate through the exchange of strongly typed data
AMF 10 times faster, how?
• Is a compact binary format for data serialization / de-serialization and remote method invocation
• Object encoding controls how objects are represented in Action Message Format (AMF)
• Representation can be transferred over HTTP/HTTPS
• As data size increases the performance benefits of using Blaze DS increase exponentially
• Objects casting is performed on the server side part
Features comparison
FeaturesFeatures BlazeDS LCDS
DatamanagementServices Client‐Serversynchroniza3on xDatamanagementServicesConflictresolu3on x
DatamanagementServices
Datapaging x
DatamanagementServices
SQLadapter x
DatamanagementServices
Hibernateadapter xDocumentServices LiveCycleremo3ng xDocumentServices
RIA‐to‐PDFconversion xEnterprise‐ClassFlexapplica;onservices Dataaccess/remo3ng x xEnterprise‐ClassFlexapplica;onservices
Proxyservice x xEnterprise‐ClassFlexapplica;onservices
Automatedtes3ngsupport x
Enterprise‐ClassFlexapplica;onservices
SoFwareclustering x x
Enterprise‐ClassFlexapplica;onservices
Web3ercompiler x
EnterpriseIntegra;on WSRPgenera3on xEnterpriseIntegra;onAjaxdataservices x x
EnterpriseIntegra;on
Flex‐Ajaxbridge x x
EnterpriseIntegra;on
Run3meconfigura3on x x
EnterpriseIntegra;on
Openadapterarchitecture x x
EnterpriseIntegra;on
JMSadapter x x
EnterpriseIntegra;on
Server‐sidecomponentframeworkintegra3on x x
EnterpriseIntegra;on
ColdFusionintegra3on x
Features comparison
FeaturesFeatures BlazeDS LCDS
OfflineApplica;onSupport Offlinedatacache xOfflineApplica;onSupportLocalmessagequeuing x
Real‐TimeData PublishandSubscribemessaging x xReal‐3medataqualityofservice xRTMPtunneling x
And the performance?
• Accordingly to the features you are planning to use the performance can change
- RPC services over an AMF Channel -> NO difference- Data pushing -> A LOT of difference
Blaze DS LCDS
Why this difference?
• The reason why is that Blaze DS supports long-polling and streaming over HTTP to push data to the client but it manages this through the Servlet API which has the restriction right now of mandating blocking IO
• LCDS provides support for the RTMPChannel (direct duplex socket connection between the client and server) as well as non-blocking long-polling and streaming support over HTTP that bypasses the Servlet API and its blocking IO limitation
• All of these options in LCDS are built on top of the Java NIO APIs
Blaze benefits
• Blaze DS is open source and it’s extendable so you can add your modules or functionalities
• Supports the main Java servers– Tomcat– Jboss– Glassfish– Others…
• Blaze DS is shipped in bundle with Tomcat so it’s easy to start also without a Java background
Blaze effect
Java developers and Flash developers became friends and start to work together….
How to invoke Java from Flex
• In order to start with Java and Flex you can download and setup Blaze DS on your system from Adobe Labs http://labs.adobe.com/technologies/blazeds/
• In order to invoke Java methods from Flex application
I. Add a mapping to the Java class to services-config.xmlII. Map your RemoteObject (provided with Flex SDK) on the client side
to the destination configured in services-config.xmlIII. Invoke the method in your Java class using the RemoteObject
instance
It’s so simple
• In your Flex application use MXML in order to invoke a remote method you can use the following snippet of code
<mx:RemoteObject id=”remoteObj” destination=”testRpc” result=”Alert.show(event.result.toString());” fault=”Alert.show(event.fault.faultString);” /><mx:Button label=”Remote Service” click=”remoteObj.testRemoteMethod();”/>
• The destination is defined in your services-config.xml and the testRemoteMethod() is defined in your java class on the server and you can handle the result and fault event via MXML or via ActionScript for each remote object
Nothing against simple, but…
I totally agree with you, it seems to be the typical scriptapproach, the first questions that can came out probably are
I. And what happens in a large application?II. How long is the equivalent code in ActionScript?III. Why I have to learn this if I’m not sure of the results?IV. How many killer application really use it?V. Is it an application that use MXML to handle the
communication with the business logic really scalable?VI. Even more…
J2EE configuration (server)
• Start Eclipse and select the “Java EE” perspective• In the bottom panel, select the “Servers” tab• Right click on the panel and select “New->Server”• Select the server settings and point them to your newly
installed tomcat server. The installation directory should be “<base turnkey installation dir>\tomcat” (in my case this is “C:\tomcat”)
• Click Finish
J2EE configuration (Web Project)
• Create a new “Dynamic Web Project” with the following settings:– Project name: myBlazeProject
– Target Runtime: “Apache Tomcat x.x” (this is the server you created in the last section)
– Configuration: Default Configuration for Apache Tomcat x.x
• Click “Finish”
J2EE configuration (BlazeDS Configuration)
• Overwrite the contents of your “WebContent” directory with the BlazeDS directory structure “<base turnkey installation dir>\tomcat\webapps\blazeds
• Right click on your newly created “myBlazeProject” project and select “Properties”
• Select “Java Build Path” from the list in the left hand panel.• Set the “Default output folder” to “myBlazeProject/
WebContent/WEB-INF/classes”, this will cause your web server to automatically update every time you rebuild your project.
So complex?
Are you lost?
Simply unzip the Blaze DS distribution archive and use it as your server, it’s enough to start….
Hello world!
Demo
A centralized approach
• The development of enterprise application involves actually a large number of server side calls
• You can work with remote objects defined in each component handling the result and the fault event in each component or you can work in a centralized way with only one class that handle for you all the remote operations
• There is not a native solution in Flex, you have tor write down your own solution
The Service Connector
• The ServiceConnector class is not part of the Flex framework, it’s part of a set of utilities I created for my projects
• The packaging structure
– Events– Remote– Utils– Main classes
Service Connector features
• The ServiceConnector class is a Singleton in order to avoid multiple instances of the class in the same application and provides the public methods a developer needs in order to perform authenticated and anonymous call against java services deployed under Blaze DS
• The ServiceConnector class is also able to perform the login and the logout of a user, to handle the queue of multiple calls following a FIFO style and to recover a service using the name of the method you need to call
• The ServiceConnector class implements the IEventDispatcher interface and therefore is the responsible of the notification of all the events fired during the server side interaction
Used classes
– AMFChannel and SecureAMFChannel; provides the AMF support for messaging. You can configure this Channel to poll the server at an interval to approximate server push
– Channel; is the base message channel class that all channels in the messaging system must extend
– ChannelSet; is a set of Channels that are used to send messages to a target destination
– AbstractOperation; represents an individual method on a service
– AbstractService; is the base class for the WebService and RemoteObject classes
– AsyncResponder; allows the creator to associate data (a token) and methods that should be called when a request is completed
– AsyncToken; provides a place to set additional or token-level data for asynchronous RPC operations
Service Connector UML diagram
Service Connector dependencies
The dependencies of this outside the flex framework are:
– RemoteObjectWrapperEvent– IRemoteMethod– RemoteMethod– MethodsQueue– MethodsQueueElement– ServerSideCallEvent
The RemoteObjectWrapperEvent
• The RemoteObjectWrapperEvent class is a custom Event that uses two public static constants in order to define the FAULT and RESULT type of the event
• It’s the one that bring the data recovered out from the ServiceConnector to your application
• It’s the one that has the knowledge of the remote method (with an instance of the AbstractService) invoked that is used to notify the appropriate control that data are coming
The IRemoteMethod interface
The IRemoteMethod is the interface implemented by the remotemethod called trough the ServiceConnector class, each method needs todefine the following accessor methods (getters not shown for brevity)
function set name(value:String):void; function set arguments(value:Array):void; function set source(value:String):void; function set destination(value:String):void; function set returnObject(value:Class):void; function set isList(value:Boolean):void;
The IRemoteMethod interface
• The source and the destination are used in order to define the service to call
• The returnObject is the class type of the object / objects returned from the method invocation
• The isList is used in order to understand if the remote method returns a single value or an Array of values
• arguments is self explanatory
The RemoteMethod class
The RemoteMethod implements the IRemoteMethod interface, the use of an interface here is due to possible future enhancement of the micro architecture we use for the server side communication
The MethodQueue class
• The MethodsQueue class follows the Singleton design pattern, when the application calls more than one method from different components is trough this class that the queue of results is handled and the results are sent to the appropriate component
• Each item stored in the MethodQueue class is an instance of the class MethodsQueueElement that defines the method and abstract operation performed
The ServerSideCallEvent
• The ServerSideCallEvent is a bubbling event that in the Flex architecture (actually in the Flash Player) is able to reach an upper level component
• The ServerSideCallEvent is the one that drives to the ServiceConnector the method to call
The ServiceConnector in 5 steps (1/5)
• Create the ServiceConnector instance and specify which is the object that needs to receive the events dispatched from the classsc = ServiceConnector.getConnector(this);
• Set the default services for the ServiceConnector instancesc.defaultSource = "com.gnstudio.services.Admin";sc.defaultDestination = "Admin";
• Define the listeners for the eventssc.addEventListener(RemoteObjectWrapperEvent.FAULT, onFault)sc.addEventListener(RemoteObjectWrapperEvent.RESULT,
onResult)
The ServiceConnector in 5 steps (2/5)
• Define the listeners for the event that will generate the server side calls
addEventListener(ServerSideCallEvent.ANONYMOUS_CALL, onAnonymousCall);
addEventListener(ServerSideCallEvent.LOGGED_CALL, onLoggedCall);
• Create the hash map used to handle the queue of the server side calls, the map is the one used also to send the data to a specific component
hash = new HashMap();
The ServiceConnector in 5 steps (3/5)
Define the listener to anonymous calls, it initialize theconnector, perform the call and add the caller to the hashmap (@param e ServerSideCallEvent)
private function onAnonymousCall(e:ServerSideCallEvent):void{ var obj:AbstractService; try{ obj = sc.makeAnonymousCall(e.fakeObject as IRemoteMethod); }catch(err:Error){ sc.initializeConnector(baseUrl + SERVICES[0], connectorKind); obj = sc.makeAnonymousCall(e.fakeObject as IRemoteMethod); } hash.addItem({service: obj, target: IPresenter(e.target), nameSpace:
e.nameSpace})
}
The ServiceConnector in 5 steps (4/5)
Define the listener to logged calls, it initialize the connector,perform the call and add the caller to the hash map (@param eServerSideCallEvent)
private function onLoggedCall(e:ServerSideCallEvent):void{
try{ obj = sc.makeLoggedCall(e.fakeObject as RemoteMethod); hash.addItem({service: obj, target:
IPresenter(e.target), nameSpace: e.nameSpace}); }catch(err:Error){ Alert.show("You need to be logged on the system", "Attention!"); }}
The ServiceConnector in 5 steps (5/5)
• Define the Listener to the general result event, it's able to update the UI component that performed the request (@param e RemoteObjectWrapperEvent)
private function onResult(e:RemoteObjectWrapperEvent):void{var tg:IPresenter; if(hash.getItem("service", e.currentService)){tg = hash.getItem("service", e.currentService).target as IPresenter;var ns:Namespace;if(hash.getItem("service", e.currentService).nameSpace){ ns = hash.getItem("service", e.currentService).nameSpace; }tg.setDataSet(e.eventData, ns);hash.remove("service", e.currentService); }}
How to put everything in action
• Use the Model View Presenter for your component• Make a comparison between Model View Presenter and
Model View Controller• Understand why in an UI context the MVP is the best choice
with external data• Make a simple implementation
The MVP pattern
• The original implementation of the MVP is born in the 1979, its name was Thing Model View Editor and during these years there were a lot of different implementations between them the Taligent’s one (1996) was for sure the more sophisticated and the more powerful
• The Model-View-Presenter pattern is a variation on the Model-View-Controller pattern, and similarly separates the concerns of an application’s data, presentation, and user input into specialized components
The MVP diagram
The MVP actors
• The Model refers to the data and business functionality of the application
• Selections are components which specify what portion of the data within the Model is to be operated upon
• Commands are classes which define the operations which can be performed on the data
• The View is the visual representation of the Model and is comprised of the screens and widgets used within an application
• Interactors are classes which address how user events are mapped onto operations performed on the Model
• The Presenter is a component which orchestrates the overall interaction of the other components within the application
MVP and MVC (1/2)
MVC MVP
UI Presentation Pattern focus on separation of view with Model
Based on MVC (UI Presentation Pattern)
Separation of responsibility between three components:1. View - responsible for rendering UI
elements2. Controller - responsible for
responding to view actions3. Model - responsible for business
behavior and state management
Separation of responsibility between four components:1. View - responsible for rendering UI
elements2. View Interface - responsible for loose
coupling between view and model3. Presenter - responsible for view and
model interaction4. Model - responsible for business
behavior and state management
MVP and MVC (2/2)
MVC MVP
The three components would interact with each other, Controller would sometime also be responsible to update view (like Front Controller Pattern)
Presenter can also interact with View to access Model
Controller is behavior based and multiple views can share single controller
Usually one view have one presenter (1-1 mapping), multiple presenters would be associated with a complex view
Identifies which view to update Presenter will update its associated view
Let’s start with a demo!