Showing posts with label flash builder. Show all posts
Showing posts with label flash builder. Show all posts

Thursday, September 1, 2011

Accessing the Twitter Streaming API from Adobe Flex/AIR

Over the weekend I discovered an interesting new hobby, so being the geek that I am I wrote a mobile application to support it. I found that I really like watching the pictures people post on Twitter in real-time. This was based around hurricane #irene so seeing the incoming photos was awesome, although I suppose it could also be applied to even more interesting endeavors like #friskyfriday (NSFW) ;) In the application I wrote I wanted to connect to the Twitter live stream instead of using search. Although it doesn't send you the full firehose of tweets, I wanted everything in real-time for geek-ability.

I won't post all the gory details of getting this application up and running, but there were two things that anyone developing for this API will need to do, and here they are:

1. Connect to the Streaming API


I had tried to do this in the past and had much more luck using curl or Java to coax the tweets out of the Streaming API, but this time I wanted to do it all in ActionScript as I didn't want to keep track of anything in a database. I wanted real-time streaming of data as it came in, and nothing historical. To do this I used the URLStream class. URLStream opens a HTTP request and then downloads the received data as it comes. URLStream is especially suited to this type of request as the download does not have to finish before you can access the downloaded bytes. This means two things: 1) You can read the bytes as they come and maintain the connection to keep receiving bytes, and 2) you must be super careful, as the Streaming API sends chunks of data. This means that the last chunk you received from Twitter might not be a complete object. You can imagine what this does to the parser (more on this later).

The Streaming API current supports both basic and OAuth authentication. Twitter says that basic authentication is deprecated, so use at your own risk. This article will use basic auth as OAuth and Twitter has been done to death on
other blogs.

While setting up the stream controller, we will create a property that will hold our URLStream. This must exist in the scope of the controller as all of the events will interact with this stream as the URLRequest is processed.

private var stream:URLStream;
After instantiating the class we need to set up our URLStream. This is accomplished by defining a new request, setting the URI we want to hit, setting the basic auth parameters and finally adding event handlers to react to the data streaming in or any errors that might occur.

public function startStream():void {
  stream = new URLStream();
  var request:URLRequest;
      
  request = new URLRequest("http://stream.twitter.com/1/statuses/filter.json?track=&include_entities=1");
  
  // set up basic auth
  var encoder:Base64Encoder = new Base64Encoder();
  encoder.encode(appController.username + ":" + appController.password);
  var credentials:String = encoder.toString();
  var authHeader:URLRequestHeader = new URLRequestHeader("Authorization","Basic " + credentials);
  //add the header to request
  request.requestHeaders.push(authHeader);
  request.method = URLRequestMethod.POST;
  
  // in a real app I would also recommend handlers for SecurityErrorEvent.SECURITY_ERROR, IOErrorEvent.IO_ERROR at a minimum
  stream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
  
  try {
    stream.load(request);
  } catch (error:Error) {
    trace("Bad URL.");
  }
}
A few notes about the code above... First, there is a track parameter being passed but it is currently empty. This allows you to filter your request. For my example I let the user enter this in on a prior view and passed it in via an application controller. Second, we are only listening for a single event, ProgressEvent.PROGRESS. In the real application I suggest you listen for at least security errors and input errors. You can also listen for HTTP status codes. This is important and Twitter would like for you to watch those codes and throttle your requests accordingly. Please make sure to do this or they will terminate your stream. Lastly, please note that we are requesting the response to be JSON. The streaming API only allows you to request JSON. Next, we need to define our handler. The one I am concerned with for this tutorial is the progress handler (it handles the ProgressEvent.PROGRESS event). When a progress event is received you can check the Stream object to see if enough bytes have been loaded to process the stream's data. In this application I didn't care how much data had been sent as I was more concerned with if the data available had any complete tweets (JSON objects) in it. To do this I fire off an event to another controller which processes the data.

private function progressHandler(event:ProgressEvent):void {
  // read the bytes
  var x:ByteArray = new ByteArray();
  stream.readBytes(x, 0, stream.bytesAvailable);
  
  // create an event to create the picTweets from the JSON
  var te:TweetEvent = new TweetEvent( TweetEvent.NEW_TWEET_RECEIVED );
  te.json = x.toString();
  // I'm using Swiz to dispatch my events - perhaps you should be also ;)
  dispatcher.dispatchEvent(te);
  
  trace("Progress Event Handled.");
}
We read the bytes from the stream as a ByteArray. The ByteArray data is then sent across to the other controller as a string using a custom event. The custom event looks like this:
package events
{
  import flash.events.Event;
  
  public class TweetEvent extends Event
  {
    public static const NEW_TWEET_RECEIVED:String = "events.TweetEvent.NEW_TWEET_RECEIVED";
    
    public var json:String;
    
    public function TweetEvent(type:String, bubbles:Boolean=true, cancelable:Boolean=false)
    {
      super(type, bubbles, cancelable);
    }
  }
}

2. Parse the resulting data


The handler for this event takes the JSON response and adds it to any other text left over in the buffer from prior requests. We then need to parse the JSON text to look for complete objects to deserialize. Twitter made this easy. They send along a newline character at the end of each JSON object. Simply split() the JSON text on newline and you'll have an array of objects. By trying to deserialize any of these objects using the JSON class (available from the
as3corelib package) we can create tweet objects. Any text that can't be deserialized will be put back into the String variable that is holding the JSON data to be parsed with the next data stream response.

public function handleNewTweet(json:String):void {
  // add the new json to the text storage - this is a private var for this controller
  jsonText += json;
  
  // now parse through the text for newline chars, which denote the end of a JSON object
  var aJSON:Array = jsonText.split(/\n/);
  
  
  if ( aJSON.length ) {
    // clear the jsonText for appending any partial objects
    jsonText = '';
    
    for ( var i:String in aJSON ) {
      // try to deserialize, if we error, we dont have a complete object in that array, add it back to the queue (it will always be the last item in the array that fails, if any)
      // deserialize the JSON
      if ( aJSON[i].length ) {
        try {
          var tweet:Object = JSON.decode(aJSON[i]);
          
          var j:String;
          
          // HERE IS WHERE YOU CAN ACTUALLY PROCESS THE TWEET
          
        } catch ( e:Error ) {
          // here is where we add the partial object back into the jsonText variable - will be appended to the next response
          if ( aJSON[i].length && aJSON[i].indexOf('\r') != 0 ) { jsonText += aJSON[i]; }
        }
      }
    }
  }
}
For my purposes I just parsed the entities for media and displayed it within my application. You have the full status object to play with for your application. Have fun, and if you use this drop me a comment so I can check it out!

Sunday, August 14, 2011

Android Mobile Application Connection Issues with Flash Remoting and ColdFusion

I was debugging an application tonight that uses Flex to connect an Android mobile application to ColdFusion via Flash Remoting. Every time I tried to call the remote method via the RemoteObject I got the message:

Channel.Connect.Failed error NetConnection.Call.Failed: HTTP: Failed

So I checked my LAN settings and then played around with my Mac firewall control panel. It was disabled so I was baffled. I then came across this post that hinted that it could be my usage of the CheckPoint VPN-1 SecureClient. Disabling and closing the client had no effect, so eventually I figured out I had to just disable the security policy (Tools > Disable security policy). I hope this helps someone out there from ruining an otherwise perfectly good evening of coding!

Sunday, August 7, 2011

Intro to Swiz Framework for Flex - Presentation Slides

Thanks to all of those who attended my session at RIACon.  Here are my presentation slides for reference.


Friday, October 22, 2010

Flex Skins Demystified (for Developers)

As a developer, I can always appreciate when languages make it easy to provide a clear separation of model and view (think MVC).  In ColdFusion we utilize a framework to produce these results.  Flex also allows us to use frameworks or apply common design patterns to our code for a separation of concerns.  Flex 4 introduced a native way to separate model from view utilizing spark skins.  This is largely to improve separation of workflow between designers and developers, but for MVC nuts, it serves us well.

I've trodded through several examples online and am assembling this tutorial a as way for developers to get started utilizing skins.  There are two primary types of skinning to get started with.  The first is skinning a native Flex component.  This takes place when you want to skin an existing component such as the spark.components.Button class.

The second type of skinning is for Flex custom components.  Skinning a custom component is much the same as skinning a native Flex component.  Your custom component can extend any class that extends SkinnableComponent.  When using Spark components, this is pretty much any visual component (another great reason for you to deprecate using mx based components in your apps for their spark counterparts).  A recent example I needed to skin was a button with multiple images.  I was able to create a subclass of spark.components.Button and add my images easily, unlike the hoops Flex 3 imposed.

Spark introduced a few new base containers for our use.  spark.components.SkinnableContainer works like a Canvas, but it is a subclass of SkinnableComponent (note that Group is the spark counterpart to Canvas, but is not skinnable).  For our example we will be extending SkinnableContainer to create a custom 'mirror' component.  For kicks we are also skinning a Button. This example is easy so as not to delve to deeply at first, but should get you started to more in-depth topics like skin states.  The final product looks like this:


First, we are going to tackle the Button skin. Flash Builder's workflow for creating a skin is very straightforward.  Name your skin and pick what component (or component skin it models, and Flash Builder will copy the contents of the base skin into your new file.  To create our button skin in Flash Builder, we select New > MXML Skin.  After naming our skin we can select the host component.


The skin includes many sections, two of which we will focus on immediately:

32:  [HostComponent("spark.components.Button")]  

HostComponent tells the skin what component we are basing our skin on, and therefore gives us access to the properties of that class for use within the skin itself like style definitions.  You can technically refer to any property including data proerties, but since we are trying to separate our view layer, that seems counterintuitive ;)  The Button class itself defines SkinParts, which are a powerful way to separate all data from the design (more on SkinParts in our other example below).  For our button we want to add an image, which is very easy to do.  We could also change any SkinPart (like shadow) or state (like down or over), or even modify SkinParts only within a specific state (like what the shadow looks like when you hover over the button).

The second part we will look at is the MXML that defines the Button component view.  In a Skin we can add any markup.  Within a Skin each component has "includeIn" and "excludeFrom" attributes to determine when a component should be visible.  If the component should be visible at all times, do not use either attribute.  To add an image we use the spark.primitives.BitMapImage class:

209:  <s:BitmapImage source="@Embed('assets/nav_refresh_blue.png')" top="5" bottom="5" left="5" />  

Now that our button skin is ready to go, we need to create our ImageButton component. We are creating the ImageButton component as an MXML file in this instance, but could also create it in ActionScript (which is shown in the next example).

ImageButton.mxml
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"   
3:       xmlns:s="library://ns.adobe.com/flex/spark"   
4:       xmlns:mx="library://ns.adobe.com/flex/mx" skinClass="com.nictunney.skindemo.view.skins.ImageButtonSkin">  
5:  </s:Button>  
6:    

Skins are bound to components using the "skinClass" attribute.  There is absolutely nothing else to note here now, but we could add any properties or functionality in this file. Implementation of this ImageButton class will be shown at the end of this post.

For the next example we will be skinning a custom Flex component named MirrorGroup. The component doesn't do much other than display text, and then mirror the text back on the same line, reversed. To show that the component does not have to be created in MXML, this example uses all ActionScript. Our custom component extends SkinnableComponent so we can inherit the skinnable actions and parts of that base class.  The component itself is simple, with caveats:

MirrorGroup.as
1:    
2:  package com.nictunney.skindemo.view  
3:  {  
4:    import com.nictunney.skindemo.view.skins.MirrorGroupSkin;  
5:      
6:    import spark.components.Label;  
7:    import spark.components.supportClasses.SkinnableComponent;  
8:      
9:    public class MirrorGroup extends SkinnableComponent  
10:    {  
11:      [SkinPart(required="true")]  
12:      public var plainText:Label;  
13:      [SkinPart(required="true")]  
14:      public var mirrorText:Label;  
15:        
16:      public var content:String;  
17:        
18:      override public function stylesInitialized():void {  
19:        super.stylesInitialized();  
20:        this.setStyle("skinClass",Class(com.nictunney.skindemo.view.skins.MirrorGroupSkin));  
21:      }  
22:        
23:      override protected function partAdded(partName:String, instance:Object):void  
24:      {  
25:        super.partAdded(partName, instance);  
26:          
27:        if( instance == plainText || instance == mirrorText )  
28:        {  
29:          instance.text = content;  
30:        }  
31:      }  
32:        
33:    }  
34:  }  

SkinParts are really cool (lines 11-14). What they define is a contract between the designer and the developer. The developer provides a list of SkinParts to the designer as IDs, Flex component type, and if they must implement the SkinPart. The designer then creates the skin with those matching IDs and types. The SkinPart metadata tag in the MirrorGroup component tells Flex to join them up, hence linking data to view at runtime. I know this workflow was completely developer focused and backwards, but you get the idea ;)

The caveats to using an AS3 class instead of MXML that just plain sucked (until I found the right blog posts):
  1. Since we are attaching the skin in ActionScript, we must override the public stylesInitialized() method (lines 18-21).  This code comes from SEFOL.  In ImageButton.mxml this was not necessary as we specified the skinClass attribute in the component definition.
  2. We need to override the protected partAdded() method and delay processing of any properties of a SkinPart until they are added to our component from the Skin (lines 23-31).  If you do not do this you will get errors complaining about null references.  This code comes from Ryan Stewart.
The next step is to create the Skin.  Selecting New > MXML Skin in Flash Builder allows us to provide two important pieces of info:

The differences from when we created the button example are that we can specify the custom component MirrorGroup as the HostComponent, and we specify that it should create our Skin file as a copy of SkinnableContainerSkin, which is the default skin for SkinnableContainer, which we extended to create MirrorGroup.  Using the base skin gets us light years ahead.  Here is the finished Skin:

MirrorGroupSkin.mxml (stripped out boilerplate comments and ActionScript for brevity)
1:  <?xml version="1.0" encoding="utf-8"?>  
2:    
3:  <s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark"   
4:    xmlns:fb="http://ns.adobe.com/flashbuilder/2009" alpha.disabled="0.5">  
5:    <fx:Metadata>[HostComponent("com.nictunney.skindemo.view.MirrorGroup")]</fx:Metadata>  
6:    
7:    <s:states>  
8:      <s:State name="normal" />  
9:      <s:State name="disabled" />  
10:    </s:states>  
11:      
12:    <!--- Defines the appearance of the SkinnableContainer class's background. -->  
13:    <s:Rect id="background" left="0" right="0" top="0" bottom="0">  
14:      <s:fill>  
15:        <!--- @private -->  
16:        <s:SolidColor id="bgFill" color="#FFFFFF"/>  
17:      </s:fill>  
18:    </s:Rect>  
19:      
20:    <s:HGroup id="contentGroup" left="10" right="0" top="10" bottom="0" minWidth="0" minHeight="0">  
21:      <s:Label id="plainText" />  
22:      <s:Label id="mirrorText" layoutDirection="rtl" alpha="0.3" />  
23:    </s:HGroup>  
24:    
25:  </s:Skin>  
26:    

Line 5 shows the HostComponent has been properly referenced. The standard SkinnableContainerSkin that was copied for us comes loaded with a spark Group with a basic layout.  We have replaced this with a HGroup and two labels.  Notice all of our styling has been implemented in the skin, but our values are nowhere to be seen?  The SkinParts we defined in MirrorGroup are seen here (matching IDs are a must) as "plainText" and "mirrorText".

The final step is to create an application and use the custom components and skins.

1:    
2:  <?xml version="1.0" encoding="utf-8"?>  
3:  <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"   
4:          xmlns:s="library://ns.adobe.com/flex/spark"   
5:          xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"  
6:          xmlns:view="com.nictunney.skindemo.view.*">  
7:      
8:    <s:VGroup top="10" left="10">  
9:      <view:ImageButton label="Toggle Mirror Visibility" click="mirrorGroup.visible = !mirrorGroup.visible" />  
10:      <view:MirrorGroup id="mirrorGroup" content="This is my text to mirror" />  
11:    </s:VGroup>  
12:      
13:  </s:Application>  
14:    

That's it! We are telling the button what to do when it is clicked (toggle visibility of the MirrorGroup). The text is also being passed into the MirrorGroup as its content property. Flex handles the rest!

Full code here