<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2009 PhilFlash - http://philflash.inway.fr - philflash@inway.fr

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

///// \\\\\
For more information, see the article : 
http://philflash.inway.fr/flex/xmlperf
and the readme.txt file

For your server, modify:
- variable serverURL in initApp
- two variables uri in services-config.xml (for amfphp et zend framework) 

If you create a new project 
Flex Builder 3 > Project > Properties > Flex Compiler > Additional compiler arguments
   -locale en_US -services "services-config.xml"
-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
    creationComplete="initApp()" paddingTop="5" paddingLeft="5" paddingRight="5" paddingBottom="5"
    pageTitle="HTTPService XML Performance"
 viewSourceURL="srcview/index.html">
<mx:Script>
    <![CDATA[
        import inway.CustomerVO;
        import flash.utils.getTimer;
        import mx.collections.ArrayCollection;
        import inway.TestResult;
        import mx.charts.AreaChart;
        import mx.controls.Alert;
        import mx.messaging.events.MessageAckEvent;
        import inway.Customer;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        
        [Bindable]
        public var numberRecords:Array = [ {data:1000}, {data:2000}, {data:3000}, {data:5000}, {data:7000}, {data:10000} ];
        
        public var serverURL:String = "";
        
        public var gzip:Boolean = false;
        // for AMF 
        [Bindable]
        public var methodAlaflex4:Boolean = false;
        // 
        public var startTime0:int;
        public var startTime:int;
        public var currentTestResult:TestResult;
        
        [Bindable]
        public var tests:ArrayCollection = new ArrayCollection();

        // -----   -----        
        private function initApp():void
        {
            //  must be terminated by a /
            serverURL = "http://www.inwayvideo.com/";
        }        

           // -----   -----
        public function doGetNodeAction(event:Event):void
        {
            currentTestResult = new TestResult();
            currentTestResult.name = "e4x_node"+(gzip ? "_gzip" : "");
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithNode();    
        }
        public function doGetAttributeAction(event:Event):void
        {  
            currentTestResult = new TestResult();
            currentTestResult.name = "e4x_attribute"+(gzip ? "_gzip" : "");
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithAttribute();          
        }
        public function doGetShortAttributeAction(event:Event):void
        { 
            currentTestResult = new TestResult();
            currentTestResult.name = "e4x_short_attribute"+(gzip ? "_gzip" : "");
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithShortAttribute();          
        }
        public function doGetCacheAttributeAction(event:Event):void
        {
            currentTestResult = new TestResult();
            currentTestResult.name = "e4x_cache_attribute"+(gzip ? "_gzip" : "");
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithCacheAttribute();          
        }
        public function doGetZendAction(event:Event):void
        {  
            currentTestResult = new TestResult();
            currentTestResult.name = "zend"+(methodAlaflex4 ? "_flex4" : "");
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithZend();          
        }
        public function doGetAmfphpAction(event:Event):void
        {
            currentTestResult = new TestResult();
            currentTestResult.name = "amfphp";
            tests.addItem(currentTestResult);
            startTime=getTimer();    
            startTime0=startTime;
            getDataWithAmfphp();          
        }       
        // -----   -----        
        public function getDataWithNode():void
        {
            var siteURL:String;
            if (gzip)
            {
                siteURL= serverURL + "xmlperf/ws_gzip/gzipcustomerNode.php";
            }
            else
            {
                siteURL= serverURL + "xmlperf/ws_nogzip/customerNode.php";    
            }
            var parameters:String = "?max="+(numberCB.selectedItem.data.toString());
            getDataNodeSvc.url = siteURL+parameters;
            getDataNodeSvc.contentType = "application/xml";
            getDataNodeSvc.send();
            //getDataNodeSvc.channelSet.messageAgents[0].addEventListener(MessageAckEvent.ACKNOWLEDGE,loadDone);
        }    
        
        private function getDataNodeSvc_result(event:ResultEvent) : void
        {
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.transferTime = time;
            startTime = timer;
            var resultXml:XML = event.result as XML;
            // -- --
            var aNode:XML;
            var list:Array = new Array();
            for each (aNode in resultXml..customer)
            {
                var object:Customer = new Customer();
                // -- --
                object.id = Number(aNode.id);
                object.lastname = aNode.lastname;
                object.firstname = aNode.firstname;
                object.sex = Number(aNode.sex);
                object.address = aNode.address;
                object.city = aNode.city;
                list.push(object);
            }    
            timer = getTimer();
            time = timer-startTime;
            currentTestResult.parseTime = time;
            startTime = timer;
            dataAC.source = list;
        }

        // -----   -----        
        public function getDataWithAttribute():void
        {
            var siteURL:String;
            if (gzip)
            {
                siteURL= serverURL + "xmlperf/ws_gzip/gzipcustomerAttribute.php";
            }
            else
            {
                siteURL= serverURL + "xmlperf/ws_nogzip/customerAttribute.php";    
            }
            var parameters:String = "?max="+(numberCB.selectedItem.data.toString());
            getDataAttributeSvc.url = siteURL+parameters;
            getDataAttributeSvc.contentType = "application/xml";
            getDataAttributeSvc.send();
            //getDataAttributeSvc.channelSet.messageAgents[0].addEventListener(MessageAckEvent.ACKNOWLEDGE,loadDone);
        }    
        
        private function getDataAttributeSvc_result(event:ResultEvent) : void
        {
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.transferTime = time;
            startTime = timer;
            var resultXml:XML = event.result as XML;
            // -- --
            var aNode:XML;
            var list:Array = new Array();
            // -- --
            for each (aNode in resultXml..customer)
            {
                var object:Customer = new Customer();
                // -- --
                object.id = Number(aNode.@id);
                object.lastname = aNode.@lastname;
                object.firstname = aNode.@firstname;
                object.sex = Number(aNode.@sex);
                object.address = aNode.@address;
                object.city = aNode.@city;
                list.push(object);
            }    
            timer = getTimer();
            time = timer-startTime;
            currentTestResult.parseTime = time;
            startTime = timer;
            dataAC.source = list;
        }

        // -----   -----        
        public function getDataWithShortAttribute():void
        {
            // -- --
            var siteURL:String;
            if (gzip)
            {
                siteURL= serverURL + "xmlperf/ws_gzip/gzipcustomerShortAttribute.php";
            }
            else
            {
                siteURL= serverURL + "xmlperf/ws_nogzip/customerShortAttribute.php";    
            }
            var parameters:String = "?max="+(numberCB.selectedItem.data.toString());
            getDataShortAttributeSvc.url = siteURL+parameters;        
            getDataShortAttributeSvc.contentType = "application/xml";
            getDataShortAttributeSvc.send();
            //getDataShortAttributeSvc.channelSet.messageAgents[0].addEventListener(MessageAckEvent.ACKNOWLEDGE,loadDone);
        }        
        private function getDataShortAttributeSvc_result(event:ResultEvent) : void
        {
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.transferTime = time;
            startTime = timer;
            //
            var resultXml:XML = event.result as XML;
            // -- --
            var aNode:XML;
            var list:Array = new Array();
            var object:Customer;
            // -- --
            // we use resultXml.children() (and not resultXml..customer)
            for each (aNode in resultXml.children())
            {
                object = new Customer();
                // -- --
                object.id = Number(aNode.@id);
                object.lastname = aNode.@ln;
                object.firstname = aNode.@fn;
                object.sex = Number(aNode.@s);
                object.address = aNode.@ad;
                object.city = aNode.@ci;
                list.push(object);
            }
            timer = getTimer();
            time = timer-startTime;
            currentTestResult.parseTime = time;
            startTime = timer;
            dataAC.source = list;
        }        
        
        // -----   -----    
        // For cache, contentType is text/xml and method is GET    
        // WARNING : If the contentType is application/xml, HTTPservice change the method GET in method POST
        //           See send method in mx.rpc.http.HTTPService (in Flex 3 with SDK 3.3)
        //            or sendBody in mx.rpc.http.AbstractOperation (in Flash Builder 4 with SDK 3.5.0)
        //         public static const CONTENT_TYPE_XML:String = "application/xml";
        //         if (contentType == CONTENT_TYPE_XML && message.method == HTTPRequestMessage.GET_METHOD)
        //              message.method = HTTPRequestMessage.POST_METHOD;
        
        // For no cache, call this method with
        // var parameters:String = "?max="+(numberCB.selectedItem.data.toString());
        // if(noCache) {
        //         var cacheBuster:Number = Math.random();
        //      parameters = parameters + "&cb="+cacheBuster;
        // }
        // getDataCacheAttributeSvc.url = siteURL+parameters;
        public function getDataWithCacheAttribute():void
        {
            // -- --
            var siteURL:String;
            siteURL= serverURL + "xmlperf/ws_gzip/gzipcustomerCacheAttribute.php";
            var parameters:String = "?max="+(numberCB.selectedItem.data.toString());
            getDataCacheAttributeSvc.url = siteURL+parameters;        
            getDataCacheAttributeSvc.contentType = "text/xml";
            getDataCacheAttributeSvc.method = "GET";
            getDataCacheAttributeSvc.send();
            //getDataCacheAttributeSvc.channelSet.messageAgents[0].addEventListener(MessageAckEvent.ACKNOWLEDGE,loadDone);
        }        
        private function getDataCacheAttributeSvc_result(event:ResultEvent) : void
        {
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.transferTime = time;
            startTime = timer;
            //
            var resultXml:XML = event.result as XML;
            // -- --
            var aNode:XML;
            var list:Array = new Array();
            var object:Customer;
            // -- --
            for each (aNode in resultXml.children())
            {
                object = new Customer();
                // -- --
                object.id = Number(aNode.@id);
                object.lastname = aNode.@ln;
                object.firstname = aNode.@fn;
                object.sex = Number(aNode.@s);
                object.address = aNode.@ad;
                object.city = aNode.@ci;
                list.push(object);
            }
            timer = getTimer();
            time = timer-startTime;
            currentTestResult.parseTime = time;
            startTime = timer;
            dataAC.source = list;
        }
    
        // -----   -----        
        public function getDataWithZend():void
        {    
            var max:Number = numberCB.selectedItem.data;
            if (!methodAlaflex4)
                zendRemote.getData(max);    
            else
                zendRemote.getDataFlex4(max);    
        }
        
        // -----   -----        
        public function getDataWithAmfphp():void
        {    
            var max:Number = numberCB.selectedItem.data;
            amfphpRemote.getData(max);    
        }
        // -----   -----
        private function loadDone(event:MessageAckEvent) : void
        {    
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.serverExecTime = time;
            startTime = timer;
        }

        private function datagridDone() : void
        {    
            var timer:int = getTimer();
            var time1:int = timer-startTime;
            var time2:int = timer-startTime0;
            if (currentTestResult && dataAC.length > 0)
            {
                currentTestResult.renderTime = time1;
                currentTestResult.totalTime = time2;
                currentTestResult.check();
            }            
        }
        
        private function getDataSvc_fault(event:FaultEvent):void
        {        
            Alert.show("Error with HTTPServices:"+event, "Erreur/Error");
        }
        // -----   -----
        private function getDataListener(event:ResultEvent):void {
            var timer:int = getTimer();
            var time:int = timer-startTime;
            currentTestResult.transferTime = time;
            startTime = timer;
            dataAC.source = event.result as Array;
        }
        private function faultListener(event:FaultEvent):void {
            Alert.show(event.fault.message, "Error");
        }
        // -----   -----        
        public function doChangeData(event:Event):void
        {
            var target:DataGrid = event.target as DataGrid;
            var selectedItem:Object = target.selectedItem;
            if (selectedItem != null) 
            {
                if (selectedItem is CustomerVO)
                {
                    var custVO:CustomerVO = selectedItem as CustomerVO;
                    firstnameLabel.text = custVO.firstname;
                    lastnameLabel.text = custVO.lastname;
                }
                else if (selectedItem is Customer)
                {
                    var cust:Customer = selectedItem as Customer;
                    firstnameLabel.text = cust.firstname;
                    lastnameLabel.text = cust.lastname;
                }
                else 
                {
                    firstnameLabel.text = "**ERROR**";
                    lastnameLabel.text =  "**ERROR**";            
                }
            }
            else 
            {
                firstnameLabel.text = "";
                lastnameLabel.text = "";                
            }
        }
        // -----   -----        
        private function doClearAll():void
        {
            tests.source = new Array();
            dataAC.source = new Array();
        }
    ]]>
</mx:Script>    
      <mx:SeriesInterpolate id="interpolate"/>
    <mx:ArrayCollection id="dataAC" />
    
    <mx:HTTPService id="getDataNodeSvc" url=""  showBusyCursor="true" useProxy="false" resultFormat="e4x" 
         fault="getDataSvc_fault(event)" 
         result="getDataNodeSvc_result(event)"
         />
         
     <mx:HTTPService id="getDataAttributeSvc" url=""  showBusyCursor="true" useProxy="false" resultFormat="e4x" 
         fault="getDataSvc_fault(event)" 
         result="getDataAttributeSvc_result(event)"
         />
         
       <mx:HTTPService id="getDataShortAttributeSvc" url=""  showBusyCursor="true" useProxy="false" resultFormat="e4x" 
         fault="getDataSvc_fault(event)" 
         result="getDataShortAttributeSvc_result(event)"
         />
         
      <mx:HTTPService id="getDataCacheAttributeSvc" url=""  showBusyCursor="true" useProxy="false" resultFormat="e4x" 
         fault="getDataSvc_fault(event)" 
         result="getDataCacheAttributeSvc_result(event)"
         />
         
     <mx:RemoteObject id="zendRemote" destination="zend" source="CustomerService" showBusyCursor="true" fault="faultListener(event)">
        <mx:method name="getData" result="getDataListener(event)"/>
        <mx:method name="getDataFlex4" result="getDataListener(event)"/>
    </mx:RemoteObject>

     <mx:RemoteObject id="amfphpRemote" destination="amfphp" source="CustomerService" showBusyCursor="true" fault="faultListener(event)">
        <mx:method name="getData" result="getDataListener(event)"/>
        <mx:method name="getDataFlex4" result="getDataListener(event)"/>
    </mx:RemoteObject>
    
    <mx:HBox width="100%">
        <mx:Label text="1 - Select number of rows: " fontWeight="bold"/>
        <mx:ComboBox id="numberCB" dataProvider="{numberRecords}" selectedIndex="3" labelField="data" rowCount="{numberRecords.length}"/>
        <mx:Spacer width="200"/>
        <mx:Button label="Clear all" click="doClearAll()" />
    </mx:HBox>
    <mx:HBox width="100%">
        <mx:Label text="2 - Select method: " fontWeight="bold"/>
    </mx:HBox>
    <mx:HBox width="100%" paddingLeft="20">
        <mx:Label width="80" text="XML" fontWeight="bold"/>
        <mx:Button id="dataNodeButton" width="180" label="Node" click="gzip=false;doGetNodeAction(event)"/>
        <mx:Button id="dataAttributeButton" width="180" label="Attribute" click="gzip=false;doGetAttributeAction(event)"/>
        <mx:Button id="dataShortAttributeButton" width="180" label="Short Attribute" click="gzip=false;doGetShortAttributeAction(event)"/>
    </mx:HBox>
    <mx:HBox width="100%" paddingLeft="20">
        <mx:Label width="80" text="XML (GZIP)" fontWeight="bold"/>
        <mx:Button id="dataGzipNodeButton" width="180" label="Node (GZIP)" click="gzip=true;doGetNodeAction(event)"/>
        <mx:Button id="dataGzipAttributeButton" width="180" label="Attribute (GZIP)" click="gzip=true;doGetAttributeAction(event)"/>
        <mx:Button id="dataGzipCacheAttributeButton" width="180" label="Short Attribute (GZIP)" click="gzip=true;doGetShortAttributeAction(event)"/>
        <mx:Button id="dataCacheAttributeButton" label="Short Attribute (GZIP) with Cache" click="gzip=true;doGetCacheAttributeAction(event)"/>
    </mx:HBox>
    <mx:HBox width="100%" paddingLeft="20">
        <mx:Label width="80" text="AMF" fontWeight="bold"/>
        <mx:Button id="dataZendButton" width="180" label="Zend AMF" click="methodAlaflex4=false;doGetZendAction(event)"/>
        <mx:Button id="data2ZendButton" width="180" label="Zend AMF (à la Flex4)" click="methodAlaflex4=true;doGetZendAction(event)"/>
        <mx:Button id="dataAmfphpButton" width="180" label="amfphp" click="methodAlaflex4=false;doGetAmfphpAction(event)"/>
    </mx:HBox>
    <mx:Spacer height="20"/>
    <mx:ToggleButtonBar id="tbb" dataProvider="{mainView}"/>
    <mx:ViewStack id="mainView" width="100%" height="100%" creationPolicy="all">
         <mx:VBox width="100%" height="100%" label="Performance">
            <mx:BarChart id="loadTimeChart" width="100%" height="100%" 
                    type="stacked" dataProvider="{tests}" showDataTips="true">
                <mx:verticalAxis>
                  <mx:CategoryAxis categoryField="name"/>
                </mx:verticalAxis> 
                <mx:series>
                <!--
                    <mx:BarSeries xField="serverExecTime"  showDataEffect="{interpolate}" displayName="Server Exec Time">
                      <mx:fill>
                          <mx:SolidColor color="#E48701"/>
                      </mx:fill>
                   </mx:BarSeries>
                -->
                  <mx:BarSeries xField="transferTime"  showDataEffect="{interpolate}" displayName="Transfer Time">
                      <mx:fill>
                          <mx:SolidColor color="#A5BC4E"/>
                      </mx:fill>
                  </mx:BarSeries>
                  <mx:BarSeries xField="parseTime" showDataEffect="{interpolate}" displayName="Parse Time">
                      <mx:fill>
                          <mx:SolidColor color="#1B95D9"/>
                      </mx:fill>              
                  </mx:BarSeries>
                  <mx:BarSeries xField="renderTime"  showDataEffect="{interpolate}" displayName="Render Time">
                      <mx:fill>
                          <mx:SolidColor color="#CACA9E"/>
                      </mx:fill>
                  </mx:BarSeries>
                </mx:series>
               
            </mx:BarChart>
            <mx:Legend dataProvider="{loadTimeChart}" direction="horizontal"/>
        </mx:VBox>        
   
        <mx:VBox width="100%" height="100%" label="Data">
             <mx:DataGrid id="data_dg" width="100%" height="100%"
                        dataProvider="{dataAC}" editable="false"
                        updateComplete="datagridDone()"
                        change="doChangeData(event)">
                <mx:columns>
                    <mx:DataGridColumn headerText="" width="20" dataField="id" />
                    <mx:DataGridColumn headerText="" width="20" dataField="sex" />
                    <mx:DataGridColumn headerText="LastName"  width="70" dataField="lastname"/>
                    <mx:DataGridColumn headerText="FirstName" width="70" dataField="firstname"/>
                    <mx:DataGridColumn headerText="City" width="150" dataField="city"/>
                    <mx:DataGridColumn headerText="Address" width="150" dataField="address"/>
                </mx:columns>        
            </mx:DataGrid>
            <mx:HBox width="100%">
                <mx:Label text="Firstname:"/>
                <mx:Label id="firstnameLabel" width="200"/>
                <mx:Label text="Lastname:"/>
                <mx:Label id="lastnameLabel" width="200"/>                
            </mx:HBox>
        </mx:VBox>    
    </mx:ViewStack>

</mx:Application>