SlideShare a Scribd company logo
1




       FLEX & JAVA USING
       BLAZEDS



Hien Luu   2009 Silicon Valley Code Camp
About Me
2


      Senior Software Engineer at Netflix
      Many years with developing web-based

       applications with Java technologies
      Instructor at UCSC-Extension school

           RIA with Flex & Java
           Spring Framework

           Design Patterns
Flex & Java Using BlazeDS
3


        Agenda
           BlazeDS   Overview
             What   & Why
           BlazeDS Tour
           BlazeDS Architecture
           BlazeDS Services
             Remoting
             Messaging
             Proxying
           Demo
Flex & Java Using BlazeDS
4




               Quick Survey
BlazeDS Overview
5


        Open source project from Adobe – 12/07
           Smaller   cousin of Adobe LifeCycle Data Services



                                   Servlet Container
                                       BlazeDS
                                                                Database
                                        Your
                                      Application
BlazeDS Overview
6


        Alternatives


                               Servlet Container

                                  Your Java        Database
                                  application


                                    PHP/Python




                    Granite, OpeAMF, Cinnamon,
AMF
7


        AMF (Action Message Format)
           Wire   protocol
             Fast,   small – 10x over XML
           AMF3      specification
        Open Source AMF Implementation
           AMFPHP

           OpenAMF

           rubyAMF

           PyAMF
BlazeDS Tour
8


        Download Turnkey version
           Include Tomcat 6.x
           BlazeDS sample applications

           Flex 3 SDK

        Unzip and start Tomcat and HSQL
           Come   with sample database – product and census data




                         http://localhost:8400/
BlazeDS Architecture
9

                           BlazeDS Services

    Access to enterprise
       functionality
                                 RPC Service


      Let Flex clients
     communicate with
        each other
                              Messaging Service
      asynchronously
                                                   Proxy service to
                                                  integrate multiple
                                                    services with a
                                Proxy Service     single application
BlazeDS Architecture
10


                           Flex Client Architecture

            Flex Client                               J2EE Server

     BlazeDS Component
                                                        BlazeDS
        RemoteObject
         HTTPService
         WebService
                                              HTTP
          Consumer
          Producer                        AMF/AMFX
                          Channel Set
                           M
                           A

                           F
                          H


                          P
                          T
                          T
BlazeDS Architecture
11

                                        BlazeDS Server Architecture

                              Message
     MessageBrokerServlet      Broker           Service          Destination           Adapter


     •  AMFEndPoint
                                 R         RemotingService      RemotingDestination
     • HTTPEndPoint              O
     • StreamingAMFEndPoint      U                                                    JavaAdapter
                                           HttpProxyService
                                 T                             HttpProxyDestination
                                 E
                                                                                       HttpProxy
                                           MessageService
                                                                                        Adapter
                                 M
                                 S                              MessageDestination

                                 G                                                    ActionScript
                                                                                       Adapter
                                                Security                                JMS
                                               Check point
                                                                                       Adapter
BlazeDS Configuration
12




     Filename              Description

     services-config.xml   Top level configuration file. Contains security constraints
                           definitions. Logging settings. Basically common configurations
                           across services.
     remoting-config.xml   Remoting service definitions, such as destination.


     proxy-config.xml      Proxy service definitions for working with web services, HTTP.


     remoting-config.xml   Messaging service for publish & subscribe
BlazeDS Channels & EndPoints
13


         Channel set fallback mechanism

          Channel                Endpoint                Description
          AMFChannel             AMFEndPoint             Transport data over HTTP in binary
                                                         AMF format. Use for Remoting.

          HTTPChannel            HTTPEndPoint            Transport data over HTTP in AMFX
                                                         format. User for Remoting.

          StreamingAMFChannel    StringAMFEndPoint       Streams data in real time over HTTP
                                                         in binary AMF format. User for
                                                         Messaging.
          StreamingHTTPChannel   StreamingHTTPEndPoint   Streams data over HTTP in AMFX
                                                         foramt.
BlazeDS Channels Behavior
14




     Channel                           Description
     Non-polling AMF & HTTP channel    Good for Remoting


     Piggybacking AMF & HTTP channel Enable queuing of messages along with responses to
                                     any messages from client.

     Polling AMF & HTTP channel        Simple polling mechanism from client side to request
                                       messages


     Long polling AMF & HTTP channel   To get pushed messages to client. Server parks the
                                       poll request until data arrives for client.

     Streaming channel                 Stream data in real-time. Available in HTTP 1.1 only.
                                       Make sure servers are capable of handling large
                                       concurrent connections
Remoting
15


       Invoke methods of Java objects on server side
       HTTP-based request/response data communication

       Use AMFChannel

       Advantages

            AMF   binary messaging protocol for exchanging data
            Serialization/de-serialization are handled automatically

            Natively supported by Flash Player

            Gateway services make easier to expose server side
             services
                           Why not use HTTPService or WebService?
Remoting
16


         RemoteObject – client side component
            destination– source of Remoting Service destination
            result – when service call successfully returns

            fault – when service call fails

            concurrency – how to handle multiple calls
              multiple – existing requests are not cancelled
              single – one at a time, multiple requests generate fault
              last – New request cancels any existing request
BlazeDS Architecture
17

                                      BlazeDS Server Architecture

                            Message
     MessageBrokerServlet    Broker          Service           Destination           Adapter


     •  AMFEndPoint
                               R         RemotingService      RemotingDestination
                               O
                               U                                                    JavaAdapter
                               T
                               E

                               M
                               S
                               G

                                              Security
                                             Check point
Remoting
18


     <mx:Script>
        private function getProducts() : void {
          ro.getProducts();
        }
        private function handleGetProdudctResult(event:ResultEvent) : void {
        }
        private function handleUpdateProdudctResult(event:ResultEvent) : void {
        }
        private function handleFault(event:FaultEvent) : void {
          Alert.show(event.fault.faultString);
        }
     </mx:Script>

     <mx:RemoteObject id="ro" destination="tutorial-product" showBusyCursor="true">
        <mx:method name="getProducts" fault="handleFault(event)"
             result="handleGetProductsResult(event)" />
        <mx:method name="updateProduct" fault="handleFault(event)"
             result="handleUpdateProductResult(event)" />
     </mx:RemoteObject>

     <mx:Button label=“Get Products” click=“getProduct()” />




                   http://localhost:8400/samples/blazeds-debug/Census.html
Remoting
19
                                remoting-config.xml
                    <destination id="tutorial-product">
                        <properties>
                            <source>tutorial.ProductDAO</source>
                        </properties>
                    </destination>


Java Class                                                                Java Class
package tutorial;                                 package tutorial;
public class ProductDAO {                         public class Product {
  public List<Product> getProducts() {              private int productId;
    // DB logic                                     private String name;
  }                                                 private double price;
                                                    private int qty;
     public void updateProduct(Product prod){
       // DB logic                                    // getters and setters for
     }                                                // above member variables
}                                                 }
Remoting
20


     <mx:Script>
        [Bindable]
         private var products:ArrayCollection
         private function handleGetProductsResult(event:ResultEvent) : void {
             products = event.result as ArrayCollection;
         }
         private function handleFault(event:FaultEvent) : void {
           Alert.show(event.toString());
         }
     </mx:Script>

     <mx:DataGrid dataProvider="{products}" width="100%" height="100%" id="dg" >
       <mx:columns>
         <mx:DataGridColumn headerText="Serial Number" dataField="productId" />
         <mx:DataGridColumn headerText="Name" dataField="name" />
         <mx:DataGridColumn headerText="Price" dataField="price" />
         <mx:DataGridColumn headerText="Quantity" dataField="qty" />
       </mx:columns>
     </mx:DataGrid>
Remoting
21


         Destination scope
            request  – server creates an instance of Java class per
             request (Default)
            application – one instance for entire application

            session - one instance per session




                       <destination id="tutorial-product">
                           <properties>
                               <source>tutorial.ProductDAO</source>
                               <scope>request</scope>
                           </properties>
                       </destination>
Remoting
22


         Concurrency
            multiple  – existing requests are not canceled
            Single – one at a time

            last – latest request cancels any existing request



     <mx:RemoteObject id="ro" destination="tutorial-product"
     showBusyCursor="true">
        <mx:method name="getProducts" fault="handleFault(event)"
             result="handleGetProductsResult(event)"
             concurrency=“multiple”/>
     </mx:RemoteObject>
Data Serialization
23




                          Servlet Container

             AS   Java
                               BlazeDS



             AS   Java      Your Application
Data Serialization
24


         Serializing Between ActionScript & Java
                        AS Type                                       Java
           Array(dense)                              java.util.List
           Array(sparse)                             java.util.Map
           Boolean                                   java.lang.Boolean
           Date                                      java.util.Date
           int/uint                                  java.lang.Integer
           Object                                    java.util.Map
           Typed Object                              Typed Object [RemoteClass]
           XML                                       org.w3c.dom.Document

            • Dense array – all numeric indexes are consecutive (no gap)
            • Sparse – gap between numeric indexes
Remoting
25


         AS Serialization Rule
            Public bean properties w/ getter/setter methods
            Public variables
            Private properties, constants are not serialized
         Client side
            Use   [RemoteClass(alias=“ “)] to map directly to Java object
         Custom Serialization
                                            package {
            Iexternallizable   interface     [Bindable]
                                              [RemoteClass(alias="tutorial.Product")]
         [Transient]                         public class Product {
                                                public var productId:int;
                                                public var name:String;
                                                public var price:Number;
                                                public var qty:int;
                                              }
                                            }
Remoting
26




                                       java.util.ArrayList

     ActionScript                                                    ActionScript
        Array                           java.util.TreeSet
                                                                    ArrayCollection

                                        java.util.TreeSet


              public class ProductService {
                 public void addProduct(java.util.Set products) {}

                    public void addProduct(java.util.SortedSet products) {}

                    public void addProduct(java.util.List products) {}
              }
Messaging
27


         Publish-subscribe messaging
            Among  multiple Flex clients
            Support bridging to JMS topics (only)

            Server can push message to client on its own.
                                                      Consumer

     Message
     Producer

                              Messaging                Consumer
                               Service
Messaging
28

                                      BlazeDS Server Architecture

                            Message
     MessageBrokerServlet    Broker          Service           Destination          Adapter


                               R         MessageService       MessageDestination
     •  Producer
                               O
     • Consumer                U                                                   ActionScript
                                                                                    Adapter
                               T
                               E
                                                                                      JMS
                               M                                                     Adapter
                               S
                               G                                                      Custom
                                                                                      Adapter
Messaging
29
                             messaging-config.xml
                 <destination id=’chat’>
                     <channels>
                         <channel ref=‘sample-amf’>
                     </channels>
                 </destination>


<mx:Application>
  <mx:Script>
     private function sendMessage(): void {
       var msg = new AsyncMesage();
       msg.body = “Hello there”
       producer.send(msg);
     }
     private function handler(event:MessageEvent) : void {
       Alert.show(“Got it: “ + event.message.body;
     }
  </mx:Script>
  <mx:Producer id=“producer” destination=“chat”>
  <mx:Consumer id=“consumer” destination=“chat”
    message=“handler(event)”>
</mx:Application>
Messaging
30


         Message filtering
            Through message header and subtopic information
            Subscriber defines the filter criteria
              Send   to server during the subscripting step
            Message    filtering is done on the server
<mx:Application>
  <mx:Script>
     private function sendMessage(): void {    <mx:Application>
       var msg = new AsyncMesage();              <mx:Script>
       msg.headers = new Array();                  …
       msg.headers[“user”]= “John”;              </mx:script>
       msg.body = “Hello there”;                 <mx:Consumer id=“consumer”
       producer.send(msg);                         destination=“chat”
     }                                             message=“handler(event)”
  </mx:script>                                     selector=“user = ‘John’”>
  …                                            </mx:Application>
</mx:Application>
Messaging
31



           Filtering through subtopic
              Usesubtopic property of AsyncMessage
              Support single-token wildcard in subtopic string
     <mx:Application>
       <mx:Script>
          private function sendMessage(): void {
             var msg = new AsyncMesage();
             msg.body = “Hello there”;
             producer.subtopic = “chat.gossip”;
             producer.send(msg);                   <mx:Application>
          }                                          <mx:Script>
       </mx:script>                                    …
       <mx:Producer id=“producer”                    </mx:script>
            destination=“chat”>                      <mx:Consumer id=“consumer”
       …                                               destination=“chat”
     </mx:Application>                                 message=“handler(event)”
                                                       subtopic=“chat.gossip”>
                                                   </mx:Application>
Messaging
32




               Enable destination to support subtopic

     <destination id=“chat” >
         <properties>
            <server>
               <allow-subtopics>true</allow-subtopics>
               <subtopic-separator>.</subtopic-separator>
         </properties>
         <channels>
              <channel ref=‘sample-amf’>
          </channels>
      </destination>
Messaging
33




                            Performance related settings

     Property                       Description
     throttle-inbound               Control # of inbound messages per second
     throttle-outbound              Control # of outbound messages per second
     message-time-to-live           How long server should keep a message pending
                                    delivery before being discarded as undeliverable



                                Additional settings for security
Messaging
34


         Measuring message processing performance
            Message  size
            Sever processing time

            Network travel time

            Message waiting time

       Ensure clients & server clocks are synchronized
       Enable at the channel level
Messaging
35


     <channel-definition id="my-streaming-amf”
         class="mx.messaging.channels.StreamingAMFChannel">
      <endpoint
        url="http://{server.name}:{server.port}/{context.root}/
        messagebroker/streamingamf”
        class="flex.messaging.endpoints.StreamingAMFEndpoint"/>
      <properties>
        <record-message-times>true</record-message-times>
        <record-message-sizes>true</record-message-sizes>
      </properties>
     </channel-definition>
Messaging
36


             Use MessagePerformanceUtils to access processing
              metrics


     private function messageHandler(message:IMessage):void {
       log.text += message.headers["user"] + ": " +
       message.body.chatMessage + "n";

         var perfInfo:MessagePerformanceUtils = new
         MessagePerformanceUtils(message);
         Alert.show(perfInfo.prettyPrint());

     }
Proxy
37

                                 google.com




             Servlet Container
                 BlazeDS          yahoo.com

                  Your
                Application



                                 amazon.com
Proxy
38


           HTTPService
              REST  functionality
              All HTTP method
                PUT,   DELETE, HEAD, POST, GET
              Get response data when status code != 200
              URL alias control on server side


     <mx:HTTPService destination="CNNFeed" useProxy="true" id="topNewService"
        resultFormat="e4x” result="handleTopNewResult(event)"/>

     <!– using default proxy destination 
     <mx:HTTPService useProxy="true" id="searchService" resultFormat="e4x”
        result="handleSearchResult(event)” />
Proxy
39


         Proxy-config.xml
            Server   side configuration

     <destination id="DefaultHTTP">
       <properties>
         <dynamic-url>http://*</dynamic-url>
       </properties>
     </destination>

     <destination id="CNNFeed">
        <properties>
         <url>http://rss.cnn.com/rss/cnn_topstories.rss</url>
        </properties>
     </destination>
Resources
40


         BlazeDS
              http://opensource.adobe.com/wiki/display/blazeds/Overview
         AMF Benchmark
              http://www.jamesward.com/census
         Architecting RIAs with Flex Data Management Services
              http://www.adobe.com/devnet/flex/articles/architecting_rias.html

More Related Content

What's hot (20)

PPTX
WCF for begineers
Dhananjay Kumar
 
PPT
Flex And Java Integration
rssharma
 
PDF
BlazeDS
devaraj ns
 
PPT
Flex And Java Integration
ravinxg
 
PPTX
10 Tricks and Tips for WCF
Barry Dorrans
 
PDF
Windows Communication Foundation (WCF)
Peter R. Egli
 
PPT
WCF
Duy Do Phan
 
PPT
WCF
Vishwa Mohan
 
PPT
Interoperability and Windows Communication Foundation (WCF) Overview
Jorgen Thelin
 
PPTX
WCF Fundamentals
Safaa Farouk
 
PPTX
1. WCF Services - Exam 70-487
Bat Programmer
 
PDF
REST, JSON and RSS with WCF 3.5
Rob Windsor
 
PPTX
Biz talk summit 2013 - The new cloud related adapters
BizTalk360
 
PDF
Building RESTful Services with WCF 4.0
Saltmarch Media
 
PPT
Introduction to web services and how to in php
Amit Kumar Singh
 
PDF
Lecture 3 soap
Jetender Sambyal
 
PPTX
Cfalfresco
Yves Prignon
 
PDF
Mobicents Telscale and RestComm - FOSDEM 2012
telestax
 
PPT
Webservices
Gerard Sylvester
 
PPTX
Advanced WCF Workshop
Ido Flatow
 
WCF for begineers
Dhananjay Kumar
 
Flex And Java Integration
rssharma
 
BlazeDS
devaraj ns
 
Flex And Java Integration
ravinxg
 
10 Tricks and Tips for WCF
Barry Dorrans
 
Windows Communication Foundation (WCF)
Peter R. Egli
 
Interoperability and Windows Communication Foundation (WCF) Overview
Jorgen Thelin
 
WCF Fundamentals
Safaa Farouk
 
1. WCF Services - Exam 70-487
Bat Programmer
 
REST, JSON and RSS with WCF 3.5
Rob Windsor
 
Biz talk summit 2013 - The new cloud related adapters
BizTalk360
 
Building RESTful Services with WCF 4.0
Saltmarch Media
 
Introduction to web services and how to in php
Amit Kumar Singh
 
Lecture 3 soap
Jetender Sambyal
 
Cfalfresco
Yves Prignon
 
Mobicents Telscale and RestComm - FOSDEM 2012
telestax
 
Webservices
Gerard Sylvester
 
Advanced WCF Workshop
Ido Flatow
 

Similar to RIA With Flex & Java Using BlazeDS (20)

PDF
Giorgio Natilli - Blaze DS Connectivity Framework
360|Conferences
 
PPT
BlazeDS
Priyank
 
PDF
Jeremy Spring Source Blaze Ds
Skills Matter
 
PDF
Lcds & Blaze Ds by Corneliu Creanga
JUG Genova
 
PDF
Blaze Ds Slides
michael.labriola
 
PDF
Distributed Services - OSGi 4.2 and possible future enhancements
David Bosschaert
 
PDF
Google App Engine At A Glance
Stefan Christoph
 
PPTX
Consuming Web Services in Microsoft Silverlight 3
goodfriday
 
PDF
RIAs with Java, Spring, Hibernate, BlazeDS, and Flex
elliando dias
 
PDF
Enterprise Service Bus and JBI
Thanachart Numnonda
 
PPTX
Apache Camel: The Swiss Army Knife of Open Source Integration
prajods
 
PDF
Build A Flexible Application Infrastructure Environment Web Sphere Connectivi...
Carly Snodgrass
 
PDF
What's new in the OSGi 4.2 Enterprise Release
David Bosschaert
 
PPTX
Enterprise Service Bus Part 2
Return on Intelligence
 
PDF
OSGi Remote Services With Sca
mfrancis
 
PPT
Enterprise Service Bus Part 1
Return on Intelligence
 
PDF
How LCDS works
Yash Mody
 
PPTX
Building Scalable and Robust Solutions with Service Bus in Cloud and Server
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
PPTX
Solving Enterprise Integration Challenges With Biz Talk Server
rsnarayanan
 
PDF
Kaazing
Alexander Ainslie
 
Giorgio Natilli - Blaze DS Connectivity Framework
360|Conferences
 
BlazeDS
Priyank
 
Jeremy Spring Source Blaze Ds
Skills Matter
 
Lcds & Blaze Ds by Corneliu Creanga
JUG Genova
 
Blaze Ds Slides
michael.labriola
 
Distributed Services - OSGi 4.2 and possible future enhancements
David Bosschaert
 
Google App Engine At A Glance
Stefan Christoph
 
Consuming Web Services in Microsoft Silverlight 3
goodfriday
 
RIAs with Java, Spring, Hibernate, BlazeDS, and Flex
elliando dias
 
Enterprise Service Bus and JBI
Thanachart Numnonda
 
Apache Camel: The Swiss Army Knife of Open Source Integration
prajods
 
Build A Flexible Application Infrastructure Environment Web Sphere Connectivi...
Carly Snodgrass
 
What's new in the OSGi 4.2 Enterprise Release
David Bosschaert
 
Enterprise Service Bus Part 2
Return on Intelligence
 
OSGi Remote Services With Sca
mfrancis
 
Enterprise Service Bus Part 1
Return on Intelligence
 
How LCDS works
Yash Mody
 
Building Scalable and Robust Solutions with Service Bus in Cloud and Server
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Solving Enterprise Integration Challenges With Biz Talk Server
rsnarayanan
 
Ad

Recently uploaded (20)

PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
July Patch Tuesday
Ivanti
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Ad

RIA With Flex & Java Using BlazeDS

  • 1. 1 FLEX & JAVA USING BLAZEDS Hien Luu 2009 Silicon Valley Code Camp
  • 2. About Me 2   Senior Software Engineer at Netflix   Many years with developing web-based applications with Java technologies   Instructor at UCSC-Extension school   RIA with Flex & Java   Spring Framework   Design Patterns
  • 3. Flex & Java Using BlazeDS 3   Agenda   BlazeDS Overview   What & Why   BlazeDS Tour   BlazeDS Architecture   BlazeDS Services   Remoting   Messaging   Proxying   Demo
  • 4. Flex & Java Using BlazeDS 4 Quick Survey
  • 5. BlazeDS Overview 5   Open source project from Adobe – 12/07   Smaller cousin of Adobe LifeCycle Data Services Servlet Container BlazeDS Database Your Application
  • 6. BlazeDS Overview 6   Alternatives Servlet Container Your Java Database application PHP/Python Granite, OpeAMF, Cinnamon,
  • 7. AMF 7   AMF (Action Message Format)   Wire protocol   Fast, small – 10x over XML   AMF3 specification   Open Source AMF Implementation   AMFPHP   OpenAMF   rubyAMF   PyAMF
  • 8. BlazeDS Tour 8   Download Turnkey version   Include Tomcat 6.x   BlazeDS sample applications   Flex 3 SDK   Unzip and start Tomcat and HSQL   Come with sample database – product and census data http://localhost:8400/
  • 9. BlazeDS Architecture 9 BlazeDS Services Access to enterprise functionality RPC Service Let Flex clients communicate with each other Messaging Service asynchronously Proxy service to integrate multiple services with a Proxy Service single application
  • 10. BlazeDS Architecture 10 Flex Client Architecture Flex Client J2EE Server BlazeDS Component BlazeDS RemoteObject HTTPService WebService HTTP Consumer Producer AMF/AMFX Channel Set M A F H P T T
  • 11. BlazeDS Architecture 11 BlazeDS Server Architecture Message MessageBrokerServlet Broker Service Destination Adapter •  AMFEndPoint R RemotingService RemotingDestination • HTTPEndPoint O • StreamingAMFEndPoint U JavaAdapter HttpProxyService T HttpProxyDestination E HttpProxy MessageService Adapter M S MessageDestination G ActionScript Adapter Security JMS Check point Adapter
  • 12. BlazeDS Configuration 12 Filename Description services-config.xml Top level configuration file. Contains security constraints definitions. Logging settings. Basically common configurations across services. remoting-config.xml Remoting service definitions, such as destination. proxy-config.xml Proxy service definitions for working with web services, HTTP. remoting-config.xml Messaging service for publish & subscribe
  • 13. BlazeDS Channels & EndPoints 13   Channel set fallback mechanism Channel Endpoint Description AMFChannel AMFEndPoint Transport data over HTTP in binary AMF format. Use for Remoting. HTTPChannel HTTPEndPoint Transport data over HTTP in AMFX format. User for Remoting. StreamingAMFChannel StringAMFEndPoint Streams data in real time over HTTP in binary AMF format. User for Messaging. StreamingHTTPChannel StreamingHTTPEndPoint Streams data over HTTP in AMFX foramt.
  • 14. BlazeDS Channels Behavior 14 Channel Description Non-polling AMF & HTTP channel Good for Remoting Piggybacking AMF & HTTP channel Enable queuing of messages along with responses to any messages from client. Polling AMF & HTTP channel Simple polling mechanism from client side to request messages Long polling AMF & HTTP channel To get pushed messages to client. Server parks the poll request until data arrives for client. Streaming channel Stream data in real-time. Available in HTTP 1.1 only. Make sure servers are capable of handling large concurrent connections
  • 15. Remoting 15   Invoke methods of Java objects on server side   HTTP-based request/response data communication   Use AMFChannel   Advantages   AMF binary messaging protocol for exchanging data   Serialization/de-serialization are handled automatically   Natively supported by Flash Player   Gateway services make easier to expose server side services Why not use HTTPService or WebService?
  • 16. Remoting 16   RemoteObject – client side component   destination– source of Remoting Service destination   result – when service call successfully returns   fault – when service call fails   concurrency – how to handle multiple calls   multiple – existing requests are not cancelled   single – one at a time, multiple requests generate fault   last – New request cancels any existing request
  • 17. BlazeDS Architecture 17 BlazeDS Server Architecture Message MessageBrokerServlet Broker Service Destination Adapter •  AMFEndPoint R RemotingService RemotingDestination O U JavaAdapter T E M S G Security Check point
  • 18. Remoting 18 <mx:Script> private function getProducts() : void { ro.getProducts(); } private function handleGetProdudctResult(event:ResultEvent) : void { } private function handleUpdateProdudctResult(event:ResultEvent) : void { } private function handleFault(event:FaultEvent) : void { Alert.show(event.fault.faultString); } </mx:Script> <mx:RemoteObject id="ro" destination="tutorial-product" showBusyCursor="true"> <mx:method name="getProducts" fault="handleFault(event)" result="handleGetProductsResult(event)" /> <mx:method name="updateProduct" fault="handleFault(event)" result="handleUpdateProductResult(event)" /> </mx:RemoteObject> <mx:Button label=“Get Products” click=“getProduct()” /> http://localhost:8400/samples/blazeds-debug/Census.html
  • 19. Remoting 19 remoting-config.xml <destination id="tutorial-product"> <properties> <source>tutorial.ProductDAO</source> </properties> </destination> Java Class Java Class package tutorial; package tutorial; public class ProductDAO { public class Product { public List<Product> getProducts() { private int productId; // DB logic private String name; } private double price; private int qty; public void updateProduct(Product prod){ // DB logic // getters and setters for } // above member variables } }
  • 20. Remoting 20 <mx:Script> [Bindable] private var products:ArrayCollection private function handleGetProductsResult(event:ResultEvent) : void { products = event.result as ArrayCollection; } private function handleFault(event:FaultEvent) : void { Alert.show(event.toString()); } </mx:Script> <mx:DataGrid dataProvider="{products}" width="100%" height="100%" id="dg" > <mx:columns> <mx:DataGridColumn headerText="Serial Number" dataField="productId" /> <mx:DataGridColumn headerText="Name" dataField="name" /> <mx:DataGridColumn headerText="Price" dataField="price" /> <mx:DataGridColumn headerText="Quantity" dataField="qty" /> </mx:columns> </mx:DataGrid>
  • 21. Remoting 21   Destination scope   request – server creates an instance of Java class per request (Default)   application – one instance for entire application   session - one instance per session <destination id="tutorial-product"> <properties> <source>tutorial.ProductDAO</source> <scope>request</scope> </properties> </destination>
  • 22. Remoting 22   Concurrency   multiple – existing requests are not canceled   Single – one at a time   last – latest request cancels any existing request <mx:RemoteObject id="ro" destination="tutorial-product" showBusyCursor="true"> <mx:method name="getProducts" fault="handleFault(event)" result="handleGetProductsResult(event)" concurrency=“multiple”/> </mx:RemoteObject>
  • 23. Data Serialization 23 Servlet Container AS Java BlazeDS AS Java Your Application
  • 24. Data Serialization 24   Serializing Between ActionScript & Java AS Type Java Array(dense) java.util.List Array(sparse) java.util.Map Boolean java.lang.Boolean Date java.util.Date int/uint java.lang.Integer Object java.util.Map Typed Object Typed Object [RemoteClass] XML org.w3c.dom.Document • Dense array – all numeric indexes are consecutive (no gap) • Sparse – gap between numeric indexes
  • 25. Remoting 25   AS Serialization Rule   Public bean properties w/ getter/setter methods   Public variables   Private properties, constants are not serialized   Client side   Use [RemoteClass(alias=“ “)] to map directly to Java object   Custom Serialization package {   Iexternallizable interface [Bindable] [RemoteClass(alias="tutorial.Product")]   [Transient] public class Product { public var productId:int; public var name:String; public var price:Number; public var qty:int; } }
  • 26. Remoting 26 java.util.ArrayList ActionScript ActionScript Array java.util.TreeSet ArrayCollection java.util.TreeSet public class ProductService { public void addProduct(java.util.Set products) {} public void addProduct(java.util.SortedSet products) {} public void addProduct(java.util.List products) {} }
  • 27. Messaging 27   Publish-subscribe messaging   Among multiple Flex clients   Support bridging to JMS topics (only)   Server can push message to client on its own. Consumer Message Producer Messaging Consumer Service
  • 28. Messaging 28 BlazeDS Server Architecture Message MessageBrokerServlet Broker Service Destination Adapter R MessageService MessageDestination •  Producer O • Consumer U ActionScript Adapter T E JMS M Adapter S G Custom Adapter
  • 29. Messaging 29 messaging-config.xml <destination id=’chat’> <channels> <channel ref=‘sample-amf’> </channels> </destination> <mx:Application> <mx:Script> private function sendMessage(): void { var msg = new AsyncMesage(); msg.body = “Hello there” producer.send(msg); } private function handler(event:MessageEvent) : void { Alert.show(“Got it: “ + event.message.body; } </mx:Script> <mx:Producer id=“producer” destination=“chat”> <mx:Consumer id=“consumer” destination=“chat” message=“handler(event)”> </mx:Application>
  • 30. Messaging 30   Message filtering   Through message header and subtopic information   Subscriber defines the filter criteria   Send to server during the subscripting step   Message filtering is done on the server <mx:Application> <mx:Script> private function sendMessage(): void { <mx:Application> var msg = new AsyncMesage(); <mx:Script> msg.headers = new Array(); … msg.headers[“user”]= “John”; </mx:script> msg.body = “Hello there”; <mx:Consumer id=“consumer” producer.send(msg); destination=“chat” } message=“handler(event)” </mx:script> selector=“user = ‘John’”> … </mx:Application> </mx:Application>
  • 31. Messaging 31   Filtering through subtopic   Usesubtopic property of AsyncMessage   Support single-token wildcard in subtopic string <mx:Application> <mx:Script> private function sendMessage(): void { var msg = new AsyncMesage(); msg.body = “Hello there”; producer.subtopic = “chat.gossip”; producer.send(msg); <mx:Application> } <mx:Script> </mx:script> … <mx:Producer id=“producer” </mx:script> destination=“chat”> <mx:Consumer id=“consumer” … destination=“chat” </mx:Application> message=“handler(event)” subtopic=“chat.gossip”> </mx:Application>
  • 32. Messaging 32 Enable destination to support subtopic <destination id=“chat” > <properties> <server> <allow-subtopics>true</allow-subtopics> <subtopic-separator>.</subtopic-separator> </properties> <channels> <channel ref=‘sample-amf’> </channels> </destination>
  • 33. Messaging 33 Performance related settings Property Description throttle-inbound Control # of inbound messages per second throttle-outbound Control # of outbound messages per second message-time-to-live How long server should keep a message pending delivery before being discarded as undeliverable Additional settings for security
  • 34. Messaging 34   Measuring message processing performance   Message size   Sever processing time   Network travel time   Message waiting time   Ensure clients & server clocks are synchronized   Enable at the channel level
  • 35. Messaging 35 <channel-definition id="my-streaming-amf” class="mx.messaging.channels.StreamingAMFChannel"> <endpoint url="http://{server.name}:{server.port}/{context.root}/ messagebroker/streamingamf” class="flex.messaging.endpoints.StreamingAMFEndpoint"/> <properties> <record-message-times>true</record-message-times> <record-message-sizes>true</record-message-sizes> </properties> </channel-definition>
  • 36. Messaging 36   Use MessagePerformanceUtils to access processing metrics private function messageHandler(message:IMessage):void { log.text += message.headers["user"] + ": " + message.body.chatMessage + "n"; var perfInfo:MessagePerformanceUtils = new MessagePerformanceUtils(message); Alert.show(perfInfo.prettyPrint()); }
  • 37. Proxy 37 google.com Servlet Container BlazeDS yahoo.com Your Application amazon.com
  • 38. Proxy 38   HTTPService   REST functionality   All HTTP method   PUT, DELETE, HEAD, POST, GET   Get response data when status code != 200   URL alias control on server side <mx:HTTPService destination="CNNFeed" useProxy="true" id="topNewService" resultFormat="e4x” result="handleTopNewResult(event)"/> <!– using default proxy destination  <mx:HTTPService useProxy="true" id="searchService" resultFormat="e4x” result="handleSearchResult(event)” />
  • 39. Proxy 39   Proxy-config.xml   Server side configuration <destination id="DefaultHTTP"> <properties> <dynamic-url>http://*</dynamic-url> </properties> </destination> <destination id="CNNFeed"> <properties> <url>http://rss.cnn.com/rss/cnn_topstories.rss</url> </properties> </destination>
  • 40. Resources 40   BlazeDS   http://opensource.adobe.com/wiki/display/blazeds/Overview   AMF Benchmark   http://www.jamesward.com/census   Architecting RIAs with Flex Data Management Services   http://www.adobe.com/devnet/flex/articles/architecting_rias.html