highest safe dose of levitralevitra takecompare levitra cialis viagrageneric levitra onlinecheap herbal vardenafillevitra online uklevitra increases sperm countwomen\s vardenafillevitra samplelevitra slide kitmail order levitralevitra prescription onlinesoft levitraPurchase Levitra pillthe buy levitrageneric levitra canadaproduct team levitravardenafil 90 pills Buylevitra sale 32free sample prescription for levitralevitra trial offermedication levitranon prescription vardenafillevitra online shop in uklevitra medicareinformation levitralevitra on line saleslevitra japanqry vardenafilSale vardenafil 20 pillscheap herbal levitraidentify vardenafillevitra alternative lavitraflomax levitraGeneric Levitra 20 mg Salelevitra couponus vardenafilbuy levitra 10mglevitra commercial modelsforum levitraOnline vardenafil Courier shipping10 mg vs 20 mg levitralevitra dosage directionstoo much levitrawhere to puchase vardenafil onlinecheap levitra on linecialis levitra vardenafilhow levitra workqueen levitravardenafil 180 pills orderlevitra beogradlevitra birth control pillslevitra orallow cost alternatives and vardenafilLevitra 120 pills BuyBuy vardenafil Free Airmail shippingordering levitra onlinecialis levitra viagra comparebuy vardenafil online australiaorder levitra cheap pricevardenafil saleanyone tried generic levitravardenafil softabsbuy levitra viagra onlinelevitra user reviewneed for increasing amounts of levitralevitra online purchasewhat is vardenafilvardenafil rrp australia costvardenafil fast shippingvardenafil no prescriptionlevitra online gamblingviva levitrawomen taking levitradiscount vardenafil onlinelevitra sampleslowest price levitra generic onlinelevitra penslevitra and flomaxpurchase levitra 60 pillslevitra side effectorder Levitra 10 mgalternative to levitraby levitra priceBuy vardenafil Courier shippinguk alternative vardenafillevitra sarasota floridaprice on levitralevitra or viagra which is betterlevitra from canadalevitra ad reviewtry levitra for freeacheter du levitrawholesale vardenafillevitra where to buycomparison levitra cialistoo much vardenafilcomparison of levitra and viagradosage for levitrageneric mexican levitrahow to buy levitragenuine vardenafilcialis levitra viagra which is bettervardenafil onlinerelative costs of cialis levitraget vardenafil drug onlinelevitra vs viagra vs cialisorder levitra 30 pillssample of vardenafildiscount cialis levitra online canadanatural equivelant ingredient in levitraorder levitravardenafil 20 pills onlinecialis vardenafilreviews of viagra cialis and levitraeuropean vardenafilcanada in levitraPurchase Generic vardenafil 20 mglevitra 100mglevitra propafenoneinfo levitrauk levitra saleswoman\s levitraOnline Levitra 120 pillspurchase vardenafil 10 mggeneric levitra tab 20mgvardenafil australiacompare viagra to levitravardenafil 6 free samplesvardenafil canadian drugslevitra generikaOnline Levitra 20 mgwhat does vardenafil dovardenafil uterine thicknesslevitra hourslevitra cost of salesGeneric Levitra 10 mg ordervardenafil lengthvardenafil sideviagra cyalis levitra comparedlevitra pictureslevitra for salevardenafil online cheapLevitra 20 pills BuyLevitra Free Airmail shipping onlinebuy levitra online atgeneric levitra manufacturermaximum dosage levitravardenafil Courier shipping SaleSale vardenafil 10 pillswhat is better levitra or viagradifference between cialis levitra viagralevitracialis compare levitramedical drug levitravardenafil patent levitraprice levitralevitra tablevardenafil vs cialisvardenafil 180 pills Buyeffects of levitraget levitra drug onlinedreampharmaceuticals from levitranew erectile drug vardenafilover the counter levitrabuy levitra australiangeneric vardenafil indiacialis dysfunction erectile levitralevitra side effects visiondiscount levitra pillsOnline vardenafil Free Insurancecanadian pharmacy levitralevitra low costlevitra reviewsPurchase Generic Levitranew erectile drug levitravardenafil usevardenafil pricinglevitra herb alternativeOrder Generic vardenafil 20 mgvardenafil max complaintsfree vardenafil sampleslevitra or viagraSale Levitra 10 mglevitra lowest pricecheap vardenafil siproblems with levitralevitra suppliers in the ukwatermelon levitralevitra to buy new zealandmedicine levitralevitra 10 mg tabletbuy levitra online dream pharmaceuticalsoft levitra mastercardlevitra ingredientsvardenafil perscription onlinegeneric levitra cheapcanadian vardenafillevitra and price listvardenafil hcl 20 mgbayer levitra onlinefree trial of vardenafilbuy levitra delived fed exrecreational levitra usekey buy levitra onlinelevitrabuy cheap levitra onlineGeneric vardenafil 10 mg onlineorder cheap levitra faslevitra by bayervardenafil 30 pills onlineship free vardenafil sampleregalis vardenafilbuy levitra usvardenafil super activeLevitra 180 pills Buydrug levitra newvardenafil purchasevardenafil 30 pills orderprofessional levitra627 discount levitra online 903levitra and premature ejaculationpfizer vardenafilcialis levitra or viagralevitra twice a daysnorting levitraorder 50mg levitrabuy Levitra 10mgLevitra pills Buybuy cheap levitra onlinelevitra vs cialis reviewbrand name levitratake levitralevitra pill pricevardenafil optionslevitra cialis for womenhow to get levitravardenafil alternativespharmacy vardenafilbuy levitra ukvardenafil hcl 20mg tab side effectsbuy levitra in ukgeneric levitra professionallevitra efectosgeneric levitra effectiveorder vardenafil 10 mg2buy levitra online viagralevitra worksflomax and levitraSale Levitra Airmail shippingclinical data levitrageneric levitra soft tab fasti have levitrarx levitravardenafil 120 pillsbuy vardenafil meds onlinevardenafil online no prescriptionis vardenafil professional realcheap vardenafil walmartuk levitrabuy levitra in canadavardenafil from indiafree sample pack of levitramature vardenafilhow long is levitra effectivelevitra price comparisonlevitra storyvardenafil effekter biverkningarvardenafil for teenscheapest levitra in ukfda on levitralevitra fedexgeneric vardenafil mexicosample levitralevitra best resultslevitra substitutelevitra generic soft tabsafe maximum levitra dosagelevitra online cheapLevitra pills onlinevardenafil free sampleslevitra dysfunction erectilelevitra rxlevitra from mexicovardenafil drug prescriptionvardenafil discountsOrder vardenafil Free Insurancelevitra precautionsbuy buy cheap cheap levitra levitralevitra v s levitravardenafil sex dominationlevitra success storieslevitra for womanvardenafil 20 mg paypallevitra sverigecheap levitra overnightOrder Levitra Airmail shippingbuy vardenafil 10 pillscounterfeit levitrabuy levitra 30 pillsvardenafil suppliers in the ukvardenafil effective timeLevitra Courier shipping orderorder levitra from canadabuy drug satellite tv levitralevitra 20order vardenafillevitra wholesale onlinelevitra fast overnight delivery usa onlyuser review levitracialis and levitra generic brandgeneric levitralevitracialis generic levitra viagralevitra online usdoes levitra look likebuy levitra lowest pricescompare viagra levitralevitra on linesample of levitraviagra cialis levitra candian pharmacy safecheap vardenafil nzprice of vardenafilbuy online vardenafilnatural levitrageneric levitra pillsnatural equivalent ingredient in vardenafilordering vardenafillevitra free pillsbuy vardenafil in uklevitra order2buy generic levitralevitra pay with paypalvardenafil in uk onlineglaxo levitravardenafil and commercialvardenafil 50 mglevitra with lisinoprilwhat does levitra dobuy levitra medicationlevitra couchcan a woman take levitravardenafil 10mgreal levitralevitra offervardenafil 10 pills Buylowest prices for levitracanada vardenafilfree levitra pillscheapest online cost for levitravardenafil generic pricevardenafil gelvardenafil mexicovardenafil ukon levitralevitra discussiongeneric name of levitrabuy vardenafil 30 pillslevitra price walmartlevitra time effectiveLevitra Free Airmail shipping Salevardenafil wholesale onlinelevitra andacheter levitra francecheap vardenafil 20 mgwoman in levitra commercialpill identification levitrageneric discount levitralevitra 20 mg dosagelevitra interactionsoriginal levitrapurchase vardenafil 10mgbuy levitra online in 24 hoursvardenafil for sale without a prescriptionlevitrabuy levitra onlineLevitra 10 mg onlineviagra medication prescription levitra cialis propecialevitra anwendungviagra cialis levitra vpxlcan woman take levitrabuy levitra upsLevitra 90 pills BuySale vardenafil pillovernight vardenafilvardenafil reviewslevitra drugswatermellon vardenafilbuy levitra without prescriptionquery lowest levitra price onlinebuying levitra onlinelevitra generic priceusing levitralevitra for freegeneric viagra levitra generic cialis pillsvardenafil testimonialGeneric Levitra 20 mg ordervardenafil on linevardenafil Free Airmail shipping onlinehow long will levitra lastq buy levitraorder discount levitraviagra levitra cialis offerslevitra and bayercheap pharmacy viagra cialis levitralevitra vs viagra reviewswomans levitraburing levitra onlinelevitra softbuy cheap levitralevitra drug prescriptionbuy levitra in englandvardenafil Salevardenafil for daily useactress in levitra commercialbuy levitra with pay palcheap vardenafil overnightindia vardenafilvardenafil pill orderbuy levitra online 35008 buylevitra pill cuttervardenafil sizevardenafil uk cost pillvardenafil 60 pills onlinegeneric soft tabs vardenafilkey buy levitra cheaplevitra cheap buy onlinelow price vardenafilcheap vardenafil tabletslevitra onlinevardenafil 20 mg orderblindness cialis levitravardenafil levitra onlinelevitra faqsplitting levitravardenafil in ukvardenafil lowest priceprozac interactions with viagra cialis levitrakeywords cialis levitra sales viagrahow quick does levitra workwhat is levitra productPurchase vardenafil Free Airmail shippingLevitra 20 mgcomparison of cialis levitra and viagraovernight shipping of professional vardenafilbenefits of levitralevitra vs viagra which is better2buy cheap levitra onlinelevitra prices american pharmaciesvardenafil online overnightdiscount levitra cialis viagrabuy cheap levitra xanax xenicalorder levitra onlinecheapest vardenafil substitute vardenafilbuy vardenafil cialasbuy cheap generic levitra pharmacy onlinelevitra soft tablevitra third quarter 2004 saleslevitra bestellenvardenafil fedexviva levitra commercialLevitra Courier shipping Salecheapest vardenafil professionalLevitra 10 pills Buycheap vardenafil canadaOnline Levitra Free Airmail shippingfull information levitradiscounted vardenafillevitra substitutesLevitra 20 mg Buylevitra 20 mg bayerbuy vardenafil delived fed exforeign cialis levitra pillswomen vardenafilvardenafil overnight shippingcan women use levitravardenafil Buyvardenafil propafenonelevitra provardenafil impotence drug eli lilly cobuy levitra viagralevitra web siteship free levitra sampleorder levitra without prescriptionfree levitra onlinesuper levitralevitra in ukcompare viagra 26 levitra2cheap levitra onlineOrder vardenafilvardenafil Courier shipping orderbuy vardenafilvardenafil storieslevitra successdiscount levitra purchasecheapest levitra substitute sildenafillevitra cialis viagra comparebuy vardenafil online in ukLevitra 20 mg onlineordering levitraconnecticut levitra vardenafillevitra productsLevitra Free Airmail shipping BuyGeneric vardenafil 10 mg Sale
intense creativity » Tutorial - Consuming REST web services in ActionScript 3 - Part 3

Tutorial - Consuming REST web services in ActionScript 3 - Part 3

Hi Everyone,

This is the third installment of the series, you can find the first two here:
Part 1 - http://blog.martinlegris.com/?p=87
Part 2 - http://blog.martinlegris.com/?p=90

Today I will develop on the data handling once the data is received from the webservice calls.
I will describe some methodologies I've developped that help mainstream data handling by using custom data types to hold the data, and custom iterators to access these data, and custom event types to transport the data.

Starting Point

In the last tutorial, we had a Singleton class calls WSClient which ran the request for us, then dispatched an event once the xml data was received.

Let's look at a sample XML file returned by a theoretical webservice. The webservice returns a list of songs contained in a particular playlist. Here is the structure for each song:

XML:
  1. <track>
  2.     <id>6428</id>
  3.     <title>Lucky You</title>
  4.     <creator>Darlingside</creator>
  5.     <location>http://panther.music.com/media1/7d7/5/19/15/f/46578a1d6dd25.mp3</location>
  6.     <info>http://music.com/music/darlingside/lucky-you</info>
  7.     <image>http://panther.music.com/media1/7d7/5/19/15/f/46578a1defb3a.jpg</image>
  8.     <tn>http://panther.music.com/media1/7d7/5/19/15/f/46578a1defb3a-thb.jpg</tn>
  9.     <type>audio</type>
  10.     <rating>4.54</rating>
  11. </track>

First thing to do here, is to create a data object to hold this data.

Actionscript:
  1. package data
  2. {
  3.     public class TrackData
  4.     {
  5.         protected var _id:Number;
  6.         protected var _title:String;
  7.         protected var _creator:String;
  8.         protected var _location:String;
  9.         protected var _info:String;
  10.         protected var _image:String;
  11.         protected var _tn:String;
  12.         protected var _type:String;
  13.         protected var _rating:Number;
  14.        
  15.         public function TrackData(id:Number = -1, title:String = "", creator:String = "", location:String = "", info:String = "", image:String = "", tn:String = "", type:String = "", rating:Number = 0)
  16.         {
  17.             _id = id;
  18.             _title = title;
  19.             _creator = creator;
  20.             _location = location;
  21.             _info = info;
  22.             _image = image;
  23.             _tn = tn;
  24.             _type = type;
  25.             _rating = rating;
  26.         }
  27.     }   
  28. }

Now let's add getter/setters for the properties

Actionscript:
  1. // ...
  2.         protected var _rating:Number;
  3.        
  4.         public function get id():Number { return _id; }  
  5.         public function set id(value:Number):void { _id = value; }
  6.         public function get title():String { return _title; }      
  7.         public function set title(value:String):void { _title = value; }       
  8.         public function get creator():String { return _creator; }   
  9.         public function set creator(value:String):void { _creator = value; }
  10.         public function get location():String { return _location; }  
  11.         public function set location(value:String):void { _location = value; }   
  12.         public function get info():String { return _info; }  
  13.         public function set info(value:String):void { _info = value; }   
  14.         public function get image():String { return _image; }      
  15.         public function set image(value:String):void { _image = value; }
  16.         public function get tn():String { return _tn; }  
  17.         public function set tn(value:String):void { _tn = value; }
  18.         public function get type():String { return _type; }  
  19.         public function set type(value:String):void { _type = value; }   
  20.         public function get rating():Number { return _rating; }
  21.         public function set rating(value:Number):void { _rating = value; }
  22.        
  23.         public function TrackData(....)

Now let's create a function which will convert the XML into our TrackData object.. I usually like to put this function inside of the data object itself, and make it static. I like to call it "fromXML".

Actionscript:
  1. // ...
  2.        
  3.         public static function fromXML(xml:XML):TrackData
  4.         {
  5.             var data:TrackData = new TrackData();
  6.             data.id = parseInt(xml.id.text());
  7.             data.title = xml.title.text();
  8.             data.location = xml.location.text();
  9.             data.info = xml.info.text();
  10.             data.image = xml.image.text();
  11.             data.tn = xml.tn.text();
  12.             data.type = xml.type.text();
  13.             data.rating = parseFloat(xml.rating.text());
  14.  
  15.             return data;
  16.         }
  17.        
  18.         // ....

To use this function we would do like so :

Actionscript:
  1. var xml:XML = XML(evt.target.data as String);
  2. var trackData:TrackData = TrackData.fromXML(xml);

And tada, we have "digested XML" to play with, a data object which is hard typed and easy to manipulate using auto-completion.

The Feed's Signature

Now, since in this case we are receiving a list, or sequence of songs contained inside a playlist, it would be nice to have a custom iterator to let us easily access the songs. You can also put them in an array, but since arrays in AS3 are not type'able, (they will be in AS4), I like to create custom iterators that I call feeds. Our feed will have the following signature:

Actionscript:
  1. package feeds
  2. {
  3.     public class TrackFeed
  4.     {
  5.         // access to it's pointer
  6.         public function get pointer():Number
  7.        
  8.         // access to the length of the trackfeed
  9.         public function get length():Number
  10.        
  11.         // the constructor, which receives xml..
  12.         public function TrackFeed(data:XML)
  13.        
  14.         // some of the standard iterator functions
  15.         public function first():TrackData
  16.         public function next():TrackData
  17.         public function last():TrackData
  18.         public function previous():TrackData
  19.        
  20.         // to get a specific one..
  21.         public function getAt(index:Number):TrackData
  22.        
  23.         // other functions which could be useful
  24.         public function getById(id:Number):TrackData
  25.        
  26.         // and in this case, a playlist could have a name, an author and a type
  27.         public function get name():String
  28.         public function get author():String
  29.         public function get type():String
  30.        
  31.     }
  32. }

Basically, what I call a Feed is an Iterator that has been adapted to a specific data type, and which lets you iterate through a list of data objects. In this case, I use it to parse XML from a webservice response and enable easy access to that data.

XML Data to be parsed

Our werservice returns a playlist. Here is what the xml looks like

XML:
  1. <playlist type="mixtape">
  2.    <name>MN Tech Picks</name>
  3.    <author>Music Nation</author>
  4.    <trackList>
  5.     <track>
  6.         <id>6428</id>
  7.         <title>Lucky You</title>
  8.         <creator>Darlingside</creator>
  9.         <location>http://panther.music.com/media1/7d7/5/19/15/f/46578a1d6dd25.mp3</location>
  10.         <info>http://music.com/music/darlingside/lucky-you</info>
  11.         <image>http://panther.music.com/media1/7d7/5/19/15/f/46578a1defb3a.jpg</image>
  12.         <tn>http://panther.music.com/media1/7d7/5/19/15/f/46578a1defb3a-thb.jpg</tn>
  13.         <type>audio</type>
  14.         <rating>4.54</rating>
  15.     </track>
  16.     <track>
  17.     <!-- .... -->
  18.     </track>
  19.     <!-- and so on -->
  20.    </trackList>
  21. </playlist>

There are two techniques I've identified to handle the data inside of the Feed. Either transform all the data right away to custom data types, or keep the data as XML and convert it on demand. I will, in this example, show the second method. I has proven to cause problems on large data sets, for example when receiving 80k + XML files from the Amazon Web Services. So if you do have problems, just convert everything to AS3 objects and don't keep a reference to the XML.

The Feed's Implementation

Actionscript:
  1. package feeds
  2. {
  3.     import data.TrackData;
  4.    
  5.     public class TrackFeed
  6.     {
  7.         protected var _pointer:Number = 0;
  8.         protected var _feed:XML;
  9.        
  10.         public function get length():Number
  11.         {
  12.             return _feed.trackList.track.length();
  13.         }      
  14.        
  15.         public function get pointer():Number
  16.         {
  17.             return _pointer;
  18.         }      
  19.        
  20.         public function TrackFeed(data:XML)
  21.         {
  22.            
  23.             _feed = data;
  24.         }      
  25.        
  26.         public function first():TrackData
  27.         {
  28.             return getAt(_pointer = 0);
  29.         }
  30.        
  31.         public function next():TrackData
  32.         {
  33.             if(_pointer>= count)
  34.             {
  35.                 _pointer = 0;
  36.                 return null;
  37.             }
  38.                
  39.             return getAt(_pointer++);
  40.         }
  41.        
  42.         public function last():TrackData
  43.         {
  44.             return getAt(_pointer = length-1);
  45.         }
  46.        
  47.         public function previous():TrackData
  48.         {
  49.             if(_pointer <= -1)
  50.             {
  51.                 _pointer = length-1;
  52.                 return null;
  53.             }
  54.                
  55.             return getAt(--_pointer);
  56.         }      
  57.        
  58.         public function get name():String
  59.         {
  60.             return _feed.name.text();
  61.         }
  62.        
  63.         public function get type():String
  64.         {
  65.             return _feed.@type.text();
  66.         }
  67.        
  68.         public function getAt(index:Number):TrackData
  69.         {
  70.             if(index>= count || index <0)
  71.                 return null;
  72.             else
  73.             {
  74.                 return TrackData.fromXML(_feed.trackList.track[index]);    
  75.             }
  76.         }
  77.        
  78.         // returns null if not found
  79.         public function getById(id:Number):TrackData
  80.         {
  81.             var oldPointer:Number = _pointer;
  82.             first();
  83.            
  84.             var data:TrackData;
  85.            
  86.             while(data = next())
  87.             {
  88.                 if(data.id == id)
  89.                     break;
  90.             }
  91.            
  92.             _pointer = oldPointer;
  93.             return data;
  94.         }
  95.     }
  96. }

As you can see, one of the class variables is _feed which is of type XML. Basically I keep the xml, and when needed I convert the data to TrackData for easy manipulation.

To use this feed, you would do like so :

Actionscript:
  1. // provided we are in the onComplete handler of the WS call, and the "evt" is of type Event.
  2.  
  3. var xml:XML = XML(evt.target.data as String);
  4. var feed:TrackFeed = new TrackFeed(xml);
  5.  
  6. trace("playlist is of type:"+feed.type);
  7. trace("playlist is called:"+feed.name);
  8. trace("playlist has "+feed.length+" elements);
  9. var track:TrackData;
  10. while(track = feed.next())
  11. {
  12.     trace("track ["+track.id+"] is "+track.title");
  13.     trace("track url is :"+track.location);
  14.     // and so on..
  15. }

As you see, it really easy! It requires a bit of coding up front, but down the line it's much clearer and simpler to use than Arrays or using data straight out of the XML.

The Custom Event

Now, from the function inside of the WSClient, which handles the Loader's Event.COMPLETE event, it would be nice to fire an event to carry this feed to all interested parties. Here is the implementation of the event:

Actionscript:
  1. package events
  2. {
  3.     import flash.events.Event;
  4.     import feeds.TrackFeed;
  5.    
  6.     public class PlaylistEvent extends Event   
  7.     {
  8.         public static const PLAYLIST_RECEIVED:String = "playlist_received";
  9.        
  10.         protected var _feed:TrackFeed;
  11.         public function get feed():lib.musicnation.feeds.TrackFeed { return _feed; }
  12.        
  13.         public function PlaylistEvent(type:String, feed:TrackFeed)
  14.         {
  15.             super(type);
  16.             _feed = feed;
  17.         }
  18.     }
  19. }

To dispatch this event from the WSClient:

Actionscript:
  1. // provided we are in the onComplete handler of the WS call, and the "evt" is of type Event.
  2.  
  3. var xml:XML = XML(evt.target.data as String);
  4. var feed:TrackFeed = new TrackFeed(xml);
  5. dispatchEvent(new PlaylistEvent(PlaylistEvent.PLAYLIST_RECEIVED, feed));

That's it for part 3 folks. In part 4 I will explain how to uniquely identify each request so that all multiple classes can use the WSClient singleton and ensure they do get THEIR results, and not the results asked for by another class.

Cheers!



Related posts (automatically generated):

  1. Tutorial - Consuming REST web services in ActionScript 3 - Part 1
  2. Tutorial - Consuming REST web services in ActionScript 3 - Part 2
  3. Tutorial - AS3 & REST web services with RESTProxy - Part 1
  4. Tutorial - Consuming REST web services in ActionScript 3 - Part 4


2 Responses to “Tutorial - Consuming REST web services in ActionScript 3 - Part 3”

  1. Pat says:

    Hi Martin,
    Your tutorials are owesome sources for Flash knowledge. I’ve a little request that I’m sure I’m not the first one to ask you for: could you provide a link of all your packages of classes for dowload? I’m not able to make your code working, maybe because I don’t create the packages structure the right way.
    Can you help?
    Thanks.

  2. Marc de Kwant says:

    Hi,

    THis is about a year late :), but I thought I should put up a reply. First of all. The tutorials are wonderful.
    Now for the comment part :). There are two classes which you could have used to clean up the code a bit. XMLEncoder en XMLDecoder. Two nice classes that can do the marshalling and unmarshalling for you instead of that handcoded fromXML() function.

    Kind regards

Leave a Reply