Using setter injection to provide a view for base mediators in Robotlegs

 

Yesterday, I came across an issue with an app I’m developing with Robotlegs. The app uses what I call “canvases” to represent each section. There’s some similar functionality between the canvases, so I decided to create a base mediator and extend it for the more specific functionality. A problem arose when I needed to access the view in the base mediator, while injecting it as the subclass in the extending mediator. At first, I tried this ghetto solution, since I only needed the view for one handler:

But as time went on, I added more handlers to the base mediator. The more handlers I added, the uglier the code became, with the AS2-reminiscent this['view'] in each function. I remembered reading something about injection types other than property-based, so I ventured out and discovered setter injection. With it, I can inject the subclass view into the subclass mediator, but still access the base view from the base mediator—classy! Here’s the implementation:

Though this works perfectly fine when extending a base mediator once, I already came across an issue—what do you do when your base mediator is extended twice? I suppose you could use a private getter in the in-between subclass, but if anyone has suggestions, feel free to drop them in the comments.

Encoding for OAuth using AS3

 

AS3 has a few useful URL-related methods, like escape/unescape and encodeURI/decodeURI, but it doesn’t have a plain-and-simple encodeUTF8 function. The encodeURIComponent method encodes a string to UTF-8, but URL-encodes it as well, requiring the unescape method to wrap the call. Many developers have resorted to writing their own encodeUTF8 method, looping through each character and converting with bitwise. I’ve found this to be unreliable at times after pinpointing an issue with the OAuth lib I use(d) with TwitterAspirin. I came across a number of problems, specifically dealing with POST methods and incorrect signatures, so I decided to take a night to write my own OAuth request signer.

In a search to better understand the OAuth spec, I came across this terrific tutorial on OAuth by Eran Hammer-Lahav on Hueniverse. It is hands-down the most useful tutorial I have found on the subject, translating the OAuth spec for the “English-speaking” and providing a foolproof explanation for each step. The tutorial also provides input fields for each step, so you can manually input your keys, secrets, and tokens, and see if your result matches up.

The main reason this tutorial is so helpful is its emphasis on the UTF-8 encoding. Sure, the OAuth spec indicates the unreserved characters, but this tutorial stresses that most languages do not share the same unreserved characters—this is true for AS3. The following characters are listed as unreserved in the OAuth Core 1.0 spec:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - . _ ~

Compare this with the unreserved characters of AS3’s escape method:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 @ - _ . * + /

And again with the unreserved characters of AS3’s encodeURIComponent method:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - _ . ! ~ * ' ( )

As you can see, a solid amount of work is needed to match the unreserved characters listed in the OAuth spec. At the moment, this is the gargantuan series of method calls I use to properly encode the parameters used in an OAuth-related request:

1
2
3
protected function encode(str:String):String {
	return escape(unescape(encodeURIComponent(str))).replace(/%7E/g, '~').replace(/@/g, '%40').replace(/\*/g, '%2A').replace(/\+/g, '%2B').replace(/\//g, '%2F');
}

I know what you’re thinking—Jonnie has lost his marbles and the proof is that unescape method call wrapped in the escape method call. Believe me when I tell you it’s necessary. Why?—because of the additional unreserved characters in the encodeURIComponent method. The unescape method removes the URL encoding, so it’s just UTF-8 encoded at this point. Then, the escape method re-URL-encodes the string, but this time converts the additional unreserved characters as well. Now, I’m left with a half dozen replace method calls to convert the last few characters that aren’t in the OAuth spec. (If you know a way to combine all of these replace method calls into one, let me know! Regular expressions are slow in AS3)

I really hope this helps those venturing into the dark world of OAuth, and as always, my OAuth request signer can be found among the changes pushed to TwitterAspirin on GitHub. I also updated TwitterAspirinDemo to show how to use the library. Feel free to watch or fork either repo—both will see a lot of activity over the next few weeks.

EventMap.mapListener bug (and fix!) in RobotLegs

 

This past week, I experienced a bug with RobotLegs where the EventMap.mapListener method would add the listener multiple times if called multiple times. Yesterday, I had some free time to dig a little deeper and managed to pinpoint the problematic code. It turns out the method didn’t check to see if the listener existed prior to adding to the array. This explains why a button click handler in my code would respond twice.

Thanks to the oh-so-wonderful GitHub, I was able to fork the repository, implement the fix, write a unit test to verify it’s safe, and find in the morning that it has been integrated into the actual RobotLegs repository—just like that. If you experienced the bug, be sure to pull the latest commit.

Now, if you’re not on GitHub, do yourself a favor and join today. In the few months I’ve been a member, I’ve met a handful of incredible developers and now feel compelled to share code when I can. Everyone benefits when you share what you know.

Introducing TwitterAspirin: an AS3 Twitter API painkiller

 

A couple months ago, I started working on a Twitter component for my current project at Adobe. I went into this knowing I’d have to finally face the beast… OAuth. Just about every well-known Twitter client out there uses Basic Auth—and for a reason. It’s easy, what the user expects, and gives your app more credibility—there’s no requirement to leave to authenticate through the browser like with OAuth.

About five or six months ago, Twitter decided to enforce the transition. From then on, any application that uses the API must use OAuth in order to see “via [your app]” on tweets published with it—otherwise, it would display “via API.” Since “via” is where apps get probably 90% of their referrals, this was a big deal. Luckily for me, DestroyTwitter existed before that time and Twitter decided not to push the change on the veteran apps. Recently, however, the bad news spread that Basic Auth would be deprecated in June. This means every Twitter app must transition to the pain that is OAuth.

After developing the MAX Companion this past fall and now the more generalized version, I found myself rewriting the Twitter component each time. After a while, the Twitter API code I wrote for DestroyTwitter began to merge with the actual implementation, so it was no longer a standalone library that could easily be used by other projects. These past few months, I’ve been learning a great deal about framework architecture and design patterns. It has led me to realize I need to start fresh.

With all that being said, I’d like introduce a library I started working on two days ago. I call it TwitterAspirin. It’s an AS3 Twitter API library that eases the pain, providing developers with a very powerful tool for communicating with Twitter. Though it’s still a newborn at the moment, I see potential already. The library is built on RobotLegs and uses AS3 Signals instead of events. It’s hosted on GitHub, so the source code will always be available to the public. And, after last night’s commit, its OAuth functionality is complete. Here’s how to use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package {
	import com.destroytoday.twitteraspirin.Twitter;
 
	import flash.display.Sprite;
 
	public class Test extends Sprite {
		// set application consumer key and secret
		public var twitter:Twitter = new Twitter(consumerKey, consumerSecret);
 
		public function Test() {
			// add signal listeners
			twitter.oauth.requestTokenSignal.add(requestTokenHandler);
			twitter.oauth.accessTokenSignal.add(accessTokenHandler);
			twitter.oauth.verifyAccessTokenSignal.add(verifyAccessTokenHandler);
		}
 
		// click the 'Authorize' button to get the request token
		protected function authorizeClickHandler():void {
			twitter.oauth.getRequestToken();
		}
 
		// upon receiving the request token, open Twitter in the browser to authorize
		protected function requestTokenHandler(oauth:OAuth, token:OAuthToken):void {
			navigateToURL(new URLRequest(oauth.getAuthorizeURL()));
		}
 
		// return with the provided pin and click the 'Activate' button to get the access token
		protected function activateClickHandler():void {
			twitter.oauth.getAccessToken(pin);
		}
 
		// upon receiving the access token, verify it
		protected function accessTokenHandler(oauth:OAuth, token:OAuthToken):void {
			oauth.verifyAccessToken(token);
		}
 
		// done
		protected function verifyAccessTokenHandler(oauth:OAuth, token:OAuthToken):void {
		}
	}
}

As you can see, it’s extremely easy to use. Not only that, it provides great flexibility. Many libraries are simple to implement, but don’t allow the developer access to certain aspects of the process. With TwitterAspirin, each method returns the loader involved with the operation, giving developers the ability to listen for errors, cancel the operation, or attain the raw API data. The library also uses loader pools to recycle instances, so you can submit a tweet and, while it’s loading, submit another—you don’t have to wait for the first operation to finish. Then, once the operation is complete, the loader is disposed and returned to the pool, which optimizes performance and memory usage.

I’m really excited to see where TwitterAspirin goes and I have nothing but great expectations. Be sure to follow along with development and fork whenever you like.

Introducing the XMLLoader class

 

I started the XMLLoader class a few months back, but didn’t post right away because it needed a lot of cleanup. Not cleanup in the sense of performance improvement or refactoring—it simply used my old programming style, full of dollar signs and underscores. If anyone remembers seeing my code in that form, I deeply apologize for the pain it must have caused your eyes.

So why an XMLLoader class?—because 99% of the data I load with AS3/AIR is in XML format. I stay far from JSON when possible because in AS3 it’s slower than a slug on its day off. XML is native and uses E4X, which lets developers navigate its information just like you would an AS3 tree. I load XML so often, I found myself copying and pasting the same code each time I’d need it—this is the clearest indicator that a class must be written.

Parsing String data to XML poses an issue that many don’t know about. I only discovered it because of the Twitter API. The API is so janked, it sometimes returns the HTML error page instead of the XML response. It wouldn’t be so bad if it weren’t for an image tag in the HTML that isn’t closed. This immediately throws an “XML parser failure: element is malformed” error. Using try/catch is the only way to avoid this. That’s why I wrote it into XMLLoader. It automatically handles the data, attempts to parse it, and, if there are any errors, the load stops and dispatches an error signal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package {
	import com.destroytoday.net.XMLLoader;
 
	import flash.display.Sprite;
 
	public class Test extends Sprite {
		public var loader:XMLLoader;
 
		public function Test() {
			loader = new XMLLoader();
 
			loader.retryCount = 2;
			loader.includeResponseInfo = true;
 
			loader.openSignal.add(loaderOpenHandler);
			loader.completeSignal.add(loaderCompleteHandler);
			loader.errorSignal.add(loaderErrorHandler);
 
			loader.load("http://search.twitter.com/search.atom?q=destroytoday");
		}
 
		protected function loaderOpenHandler(loader:XMLLoader):void {
			trace(loader);
		}
 
		protected function loaderCompleteHandler(loader:XMLLoader, data:XML):void {
			trace(loader, data);
		}
 
		protected function loaderErrorHandler(loader:XMLLoader, error:String, message:String):void {
			trace(loader, error, message);
			trace(loader.responseStatus);
		}
	}
}

Speaking of signals, XMLLoader is the first class in DestroyFramework to use Robert Penner’s AS3 Signals instead of events. If you have to ask why, you haven’t been programming in AS3 long enough. Each XMLLoader instance has signals for open, complete, error, and cancel. The class also includes a retryCount property that indicates how many times to attempt to load a URL before calling it quits. Since some APIs can be down one second, then up the next, this feature really comes in handy. It’s mainly intended for handling the beloved fail whale.

The last two features include a cancel method and an includeResponseInfo property. Sure, URLLoader has a cancel method, close, but an exception is thrown if you call close when no operation is in progress. This makes sense, but the runtime shouldn’t close down shop when it happens. XMLLoader instead cancels and dispatches the cancel signal when the cancel method is called, and if no operations are in progress, it simply does nothing.

The includeResponseInfo property is an incredibly easy way to tell the loader to return the response status code and headers upon success or fail. Without XMLLoader, you could get this information with an event listener and the appropriate handler, but it’s far easier to flick a switch. In all honesty, I’ve neglected to retrieve this info using URLLoader in the past simply because it’s such a verbose process. Now that it only requires setting the property to true, I know I’ll use it more often than not.

As always, the source code is available on GitHub. Be sure to keep watch—my account will be pretty active these next few weeks.

Introducing the AsyncLoop class

 

Out of my recent work, I’m especially proud of and excited about the AsyncLoop class. It’s a serious performance enhancer that takes heavy processes and spreads them out over time, preventing stalls and possible lockups. I originally wrote it to deal with a for loop that contained a complex process and iterated 1000 times. Needless to say, the beach ball made an extended stay each time the loop ran. After implementing AsyncLoop, the beach ball disappeared and animations played smooth throughout.

AsyncLoop works around a timer limit. The developer sets the maximum number of milliseconds to loop through the process function. Once the timer exceeds that limit, it carries over to the next frame and repeats. The loop can be ended a number of ways, providing great flexibility. A limit can be placed on the loop count, mimicking common for loop usage. The loop can return the AsyncLoopAction.BREAK constant. When using that method, AsyncLoopAction.CONTINUE is used to tell the loop to continue to the next tick. Each loop provides analytics, keeping track of its duration, loop count, and frame count. Here are two ways you can use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// new AsyncLoop(callback:Function, countLimit:int = -1, timerLimit:int = 20);
var loop:AsyncLoop = new AsyncLoop(tick, 1000);
 
loop.addEventListener(Event.OPEN, loopOpenHandler);
loop.addEventListener(Event.CHANGE, loopChangeHandler);
loop.addEventListener(Event.COMPLETE, loopCompleteHandler);
 
loop.start();
 
function tick():void {
	// heavy process
}
 
function loopOpenHandler(event:Event):void {
	// loop started
}
function loopChangeHandler(event:Event):void {
	// loop carries over to next frame
 
	trace(loop.duration); // incomplete loop running time
	trace(loop.currentCount); // number of callback calls
}
function loopCompleteHandler(event:Event):void {
	// loop complete
 
	trace(loop.duration); // completed loop duration
	trace(loop.frameCount); // frames needed to complete
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var loop:AsyncLoop = new AsyncLoop(tick);
 
loop.start();
 
stage.addEventListener(MouseEvent.CLICK, clickHandler);
stage.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);
 
function tick():String {
	// heavy process
 
	if (loopShouldEnd) {
		return AsyncLoopAction.BREAK;
	}
 
	return AsyncLoopAction.CONTINUE;
}
 
function clickHandler(event:MouseEvent):void {
	if (loop.running) {
		loop.pause();
	} else {
		loop.start();
	}
}
function doubleClickHandler(event:MouseEvent):void {
	loop.cancel();
}

I’m really happy with the class and how far it has come since its original form as fLoop. As always, the source code is on GitHub, so take it and run! If you find it useful, feel free to share how you used it, or simply let me know what you think.

Introducing the ApplicationUtil class

 

Yesterday, during my weekly football “service”, I spent a few minutes starting the ApplicationUtil class. So far, it consists of only two methods, getVersion and closeOpenWindows. The first accesses the application descriptor and returns the application’s version. closeOpenWindows is a necessity I learned in the Apollo days from Christian Cantrell. I had issues with my first AIR app, DestroyFlickr, where it wouldn’t quit, even if all of the visible windows were closed. I commonly use window visibility to show/hide utility windows, so the invisible ones were hanging around, keeping the app open. This method runs a quick loop to close all open windows, visible or not. It also includes an andQuit argument that, when true, sets autoExit to true, which quits the app upon close of the windows. Here’s some unnecessary example code to give this post more character:

1
2
3
4
5
6
7
8
9
10
var version:String = ApplicationUtil.getVersion();
trace(version); // v1
 
trace(NativeApplication.nativeApplication.openedWindows.length); // 3
ApplicationUtil.closeOpenWindows();
trace(NativeApplication.nativeApplication.openedWindows.length); // 0
 
// suppose three windows are open again
ApplicationUtil.closeOpenWindows(true); // closes windows and quits before trace is called
trace(NativeApplication.nativeApplication.openedWindows.length);

Introducing the Scale9Bitmap class

 

scale9bitmap

The Scale9Bitmap class applies a scale9Grid to a Bitmap. It takes advantage of a technique I used for DestroyTwitter’s window drop shadow, scaling nine Bitmap instances. When developing the MAX Companion, I tried Didier Brun’s ScaleBitmap class, but discovered a costly memory leak in which it instantiates a new BitmapData instance with every resize call. This wouldn’t be a big deal for a once-and-done resize, but as a window drop shadow, memory skyrockets.

I decided to start from scratch and develop a class that is super fast and slim as can be. The Bitmaps are only updated when the BitmapData is set. After that, the only process that takes place is the resizing of each Bitmap—no BitmapData manipulation needed. Setup requires a single method to set the BitmapData and the Rectangle that indicates the stretchable portion of the Bitmap. BitmapData can be changed on the fly and there is a scale property that sets both scaleX and scaleY.

The source code is on GitHub, so feel free to give it a whirl.

Introducing the Console class and debug package

 

I realized I need a more…official…way of debugging my apps, so I wrote the Console class. It’s primary function is to record activity to a specified log file. So far, I have a few methods that write entries—success, error, cancel, and print. I definitely plan to add more, but these are the main ones I intend to use in the near future. Since the name “trace” is off limits in AS3, I referenced my PHP background and named the trace method, “print”.

The class also includes the ability to automatically trace entries to Eclipse’s console along with writing them to a file. Files are written asynchronously, but I also added a delay property that combines entries, so the writing process is less likely to slow down the app. Taking advantage of AIR 2.0’s UncaughtErrors feature, the Console automatically logs fatal errors and their stack traces, if possible. Here’s an example of its usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var path:String = File.applicationStorageDirectory.nativePath;
 
// params: log file path, LoaderInfo
// automatically writes a session start entry to the log
Console.init(path, loaderInfo);
 
Console.delay = 1000;
Console.traceError = true;
 
// params: id, message
Console.success("wp post", "wrote blog post");
 
// params: id, message
Console.error("wp post", "previous post was depressing");
 
// params: id, message
Console.cancel("Christmas", "why would you want to do that?");
 
// params: message
Console.print("this is a test");
[Fri Dec 18 00:31:31 GMT-0500 2009] Session Start
[Fri Dec 18 00:31:31 GMT-0500 2009] [success] [wp post] wrote blog post
[Fri Dec 18 00:31:31 GMT-0500 2009] [error] [wp post] previous post was depressing
[Fri Dec 18 00:31:31 GMT-0500 2009] [cancel] [Christmas] why would you want to do that?
[Fri Dec 18 00:31:31 GMT-0500 2009] [print] this is a test

I do expect to build the class over time, eventually adding TextField support. In the meantime, the source code is available on GitHub.

Outroducing Introducing the CurrentDate class

 

Always test, never assume. I was so caught up with how cool typing CurrentDate.time looks, I forgot to test the class for performance. Kristopher Schultz pointed out in the comments that instantiating a new Date instance is much faster than any method in the CurrentDate class. Taking it one step further, I tested it for memory and found similar results.

CurrentDate will be removed from DestroyFramework, but it will always have a place in my heart.

[note] I know “outroducing” is not a word, but it damn well should be.

I’m working on a debug package for DestroyFramework and found the need, in my Log class, to retrieve the current timestamp whenever entries are made. I looked through the almost laughably redundant Date class and found no methods for updating the instance to show the current date and time. Since I’m an avid recycler, there was no way I would instantiate a Date instance each call. Immediately, I thought of the getTimer method. Because it tallies the number of milliseconds since the SWF or AIR app starts, I should be able to add that to the Date.milliseconds property to return the current date. It worked!

1
2
3
4
5
var date:Date = new Date();
 
// delay a few seconds
 
date.milliseconds += getTimer();

Since I can’t assume a CurrentDate method will be called when getTimer() == 0, all I needed to do was include an offsetTimestamp variable that records getTimer when the Date instance is instantiated. I then subtract that variable from getTimer and I have the right number of milliseconds to update the Date instance with.

1
2
3
4
5
6
var offsetTimestamp:int = getTimer();
var date:Date = new Date();
 
// delay a few seconds
 
date.milliseconds += getTimer() - offsetTimestamp;

The class itself is as easy as pie to use. All of the methods are static, so you can simply call CurrentDate.time and it returns the Date.time property for the current time. I included every get and toString method found in Date. I also included two extra methods, antemeridian and postmeridian that indicate whether the current time is AM or PM. Since it can be formatted in different ways, I made the return values boolean.

1
2
3
4
5
6
CurrentDate.month; // 11 (months start at 0)
CurrentDate.date; // 15
CurrentDate.fullYear; // 2009
CurrentDate.toString(); // Tue Dec 15 8:13:08 GMT-0500 2009
CurrentDate.antemeridian; // true
CurrentDate.postmeridian; // false

As always, the source code for the new class can be found on GitHub.