Bees Are Social By Nature

Transcribed thoughts and experiences about computer programming.

I have changed my blog site to http://blog.bumblemachine.com

While I am still using wordpress and all of it’s wonderful features, I have decided to get my own domain and host my blog locally.  The new location of my blog, where you will see all of my future posts, is located at http://blog.bumblemachine.com .  If you end up heading over there, check out my latest entry that discusses my first experience with writing a program using the Android SDK.

November 17, 2007 Posted by | android, Uncategorized | Leave a comment

Creating a Simple MP3 Player using ActionScript 3.0 and Flex 2

After creating a Simple FLV Player using ActionScript 3.0, I decided to extend my learning by going through the process of creating a simple MP3 player using ActionScript 3.0 and Flex 2. For requirements, all I wanted my MP3 player to do was play from a static list of MP3 files and have controls allowing me to play, pause, stop, go to the next song in playlist, and go to a previous song in the playlist. I have seen quite a few of these floating around the internet, so I figured it should be pretty easy and, as expected, it was.

Prerequisites:

Flex 2 SDK: http://www.adobe.com/products/flex/sdk/
Public Domain MP3 Files: http://www.publicdomain4u.com/

1) Install Flex 2 SDK

After downloading the flex_sdk_2.zip, I just unzipped the contents in to a work folder, c:\flex_sdk_2. The key resources I used from this package with were the compiler, bin\mxmlc.exe, and the debug Flash player (player\debug\SAFlashPlayer.exe).

2) I generated the following source in my favorite text editor, please note that I decided to go with the “source is the documentation” style of documentation for what and why I did:

The ActionScript source for the mp3 player class, SimpleSimpleMP3Player.as:

package { 
    import mx.containers.Panel; 
    import mx.controls.Button; 
    import flash.events.*; 
    import flash.media.Sound; 
    import flash.media.SoundChannel; 
    import flash.net.URLRequest; 
    import flash.utils.Timer;     

    public class SuperSimpleMP3Player extends Panel { 
    	// Song List 
    	private var songURLs:Array = 
    	    ["SongFromCottonField.MP3", 
	     "Bill_Cox--My_Rough_and_Rowdy_Ways.mp3", 
	     "Robert_Johnson-Love_In_Vain.mp3", 
	     "Andy_Iona-Naughty_Hula_Eyes.mp3", 
	     "AtlantaBound.MP3", 
	     "MamieSmithHerJazzHounds-CrazyBlues.mp3"];     

        // Current Song to Play 
        private var currentIndex:Number = 0;     

        // Sound Channel to monitor 
        private var song:SoundChannel;     

        // Request object for obtaining mp3 
        private var request:URLRequest     

        // Pause state management 
	private var paused:Boolean = true;     

	// Stopped state management 
	private var stopped:Boolean = false;     

	// Retains what position the song was in 
	// when it was paused, so we can go back to 
	// the same position when we hit play again. 
	private var position:Number;     

	// Sound... Factory for initializing our song. 
        private var soundFactory:Sound;     

	// The magic var that allows us to set the actual 
	// implementation of the play button from the Flex 
	// MXML.  This allows a custom component, see 
	// SimpleMP3.mxml, to set the actual button that 
	// playButton referres to, letting us change the 
	// label, or any other property of the button in 
	// our ActionScript. 
	public var playButton:Button;     

        public function SuperSimpleMP3Player() { 
            super(); 
	    playMP3(currentIndex);     

        }     

	// Play MP3 at specified index in songURLs array. 
	public function playMP3(mp3Index:Number):void { 
	    stopped = false; 
	    paused = false; 
	    position = 0; 
	    var request:URLRequest = 
	        new URLRequest(songURLs[mp3Index]); 
	    soundFactory = new Sound(); 
	    soundFactory.addEventListener(Event.ID3, id3Handler); 
	    soundFactory.load(request); 
	    song = soundFactory.play(); 
            song.addEventListener(Event.SOUND_COMPLETE, 
                soundCompleteHandler); 
	}     

        // Since the id3 information is not available until it 
        // is read off the string we need to make sure we have 
        // a way of updating the UI once it has been loaded. 
        // Having songName as a bindable allows us to do that, 
        // and the id3Handler will notify us when the information 
        // is ready to be displayed. 
        [Bindable("songNameChanged")] 
	public function get songName():String { 
		return soundFactory.id3.artist + 
			" - " + soundFactory.id3.songName; 
        }     

	// Alert songNameChanged bind when id3 information 
	// has been loaded. 
        private function id3Handler(event:Event):void { 
            dispatchEvent(new Event("songNameChanged")); 
        }     

	// Start the next song, once the current one has 
	// finished playing. 
	private function soundCompleteHandler(event:Event):void { 
	    position = 0; 
	    currentIndex++; 
	    if (currentIndex >= songURLs.length) { 
	        currentIndex = 0; 
	    } 
	    playMP3(currentIndex); 
        }     

	// Pause current song, or play song if already paused. 
	// Setting playButton label such that any GUI button 
	// that is attached will change with play or pause. 
	public function pause():void { 
	    if (!stopped) { 
	        if (!paused) { 
	    	    paused = true; 
		    position = song.position; 
		    song.stop(); 
		    playButton.label = ">"; 
	        } else { 
		    paused = false; 
		    song = soundFactory.play(position); 
		    song.addEventListener(Event.SOUND_COMPLETE, 
		    	soundCompleteHandler); 
		    playButton.label = "||"; 
	        } 
	    } else { 
	        playMP3(currentIndex); 
	        playButton.label = "||"; 
	    } 
        }     

	// Stop current song 
	public function stop():void { 
		stopped = true; 
		song.stop(); 
		position = 0; 
		playButton.label = ">"; 
	}     

	// Switch to Next Song 
	public function next():void { 
	    currentIndex++; 
	    if (currentIndex >= songURLs.length) { 
	        currentIndex = 0; 
	    }     

	    song.stop(); 
	    position = 0;     

	    // Track if player was already playing, 
	    // paused, or stopped. If stopped or 
	    // paused, still "play" so we can start 
	    // streaming and obtain the id3 info.     

	    var wasStopped:Boolean = stopped; 
	    var wasPaused:Boolean = paused;     

	    playMP3(currentIndex);     

	    if (wasStopped) { 
	        stop(); 
	        return; 
	    }     

	    if (wasPaused) 
            { 
		paused = true; 
		position = song.position; 
		song.stop(); 
            } 
	}     

	// Switch to Previous Song 
	public function prev():void { 
	    currentIndex--; 
	    if (currentIndex < 0) { 
	        currentIndex = songURLs.length - 1; 
	    }    

	    song.stop(); 
	    position = 0;    

	    // Track if player was already playing, 
	    // paused, or stopped. If stopped or 
	    // paused, still "play" so we can start 
	    // streaming and obtain the id3 info.    

	    var wasStopped:Boolean = stopped; 
	    var wasPaused:Boolean = paused;    

	    playMP3(currentIndex);    

	    if (wasStopped) { 
	    	stop(); 
	    	return; 
	    } 
	    if (wasPaused) { 
		paused = true; 
		position = song.position; 
		song.stop(); 
    	    } 
	} 
    } 
}

The MXML for the custom mp3 player component, SimpleMP3.mxml:

<?xml version="1.0"?> 
<!-- SimpleMP3.mxml --> 
<custom:SuperSimpleMP3Player 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:custom="*"> 
     <mx:Label text="{String(songName)}"/> 
     <mx:ControlBar horizontalAlign="center"> 
      <mx:Spacer width="100%"/> 
      <mx:Button id="prevButton" label="<<" click="prev()"/> 
      <mx:Button id="pauseButton" label="||" click="pause()"/> 
      <mx:Button id="stopButton" label="X" click="stop()"/> 
      <mx:Button id="nextButton" label=">>" click="next()"/> 
      <mx:Spacer width="100%"/> 
    </mx:ControlBar> 
</custom:SuperSimpleMP3Player>

The MXML for container application, SimpleMP3Player.mxml:

<xml version="1.0" encoding="utf-8"?> 
<mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml" 
    xmlns:custom="*" 
    layout="vertical" 
  <custom:SimpleMP3 id="myMP3" headerHeight="0"  width="400"/> 
</mx:Application>

4) From the command line I compiled the file:

c:/flex_sdk_2/learning>../bin/mxmlc.exe 
	-use-network=false 
	SimpleMP3Player.as

Note that I had to use the ‘-use-network=false’ directive. This told the compiler that I will not be using the network in my testing so don’t worry about sandbox issues when trying to load the flv from my local drives. Once I decide, if I decided, to deploy this to a website, I will need to recompile my code without this directive.

6) After compilation succeeded, I loaded the swf in the debug Flash Player:

c:/flex_sdk_2/learning>../player/debug/SAFlashPlayer.exe 
	SimpleMP3Player.swf

Success. However, please don’t think of this as the only way of doing or even close to the best way of doing. No best practices used here, like supplying some sort of packaging/namespacing for my custom code and components, just me documenting my learning experience. ;) I do hope this helps a few other with their own learning experiements and if you know of cleaner solutions, please feel free to leave some feedback in my comments section.

For reference, the source can also be downloaded from http://www.kriggio.com/mp3player/SuperSimpleMP3Player.zip

The following link, which may or may not be available depending if I have to take it down due to bandwidth issues, demonstrates the above code: http://www.kriggio.com/mp3player/mp3.html. Streaming mp3s = lots of bandwidth. :(

June 19, 2007 Posted by | ActionScript, flex, Programming, technology | 19 Comments

A Super Simple FLV Player using ActionScript 3.0

As part of my ongoing pursuit of learning a wide variety of technologies, I decided to see what ActionScript 3.0 was all about. As part of my learning, I decided I wanted to join the ever growing crowd of people that have “created” their own FLV Players. I knew people weren’t actually creating the video player and were really just setting up Video component in the UI and telling it what video to play, yet I still wanted to see how it was done. As such, my journey into ActionScript 3.0 began. Fair warning: I get real lazy about writing clean code, organizing my files, and setting up my development environment when I just start learning something. As such, the following embraces the lazy approach to getting things started.

Prerequisites:

Flex 2 SDK: http://www.adobe.com/products/flex/sdk/
Example FLV Files: http://www.mediacollege.com/flash/video/tutorial/example-flv.html

1) Install Flex 2 SDK

After downloading the flex_sdk_2.zip, I just unzipped the contents in to a work folder, c:\flex_sdk_2. The key resources I used from this package with were the compiler, bin\mxmlc.exe, and the debug Flash player (player\debug\SAFlashPlayer.exe).

2) As a ActionScript3 novice, I browsed a few tutorial sites. Then I went ahead and compiled and ran a few different tutorials. I found that the Beginners Guide to Getting Started with AS3 at http://www.senocular.com/flash/tutorials/as3withmxmlc/ to be very helpful, and you will find it goes into much greater detailon the use of the mxmlc.exe command line tool than I go into here. Next, I decided I want to be cool like everyone else and create an FLV Video Player. After doing a decent search, I noticed that most of the tutorials for creating FLV Video PLayers were using Flash Professional, which is outside of my “just learning” budget. However, I did find what I was looking for in the Adobe Flash Media Development Center. The tutorial taught me a lot more than I initially wanted, but it showed me exactly what I need to do to create my own.

3) Once I read the tutorial, I embarked on creating my own SuperSimpleFLVPlayer. In order to test whatever I ended up making, I needed an example FLV file and I found one at
http://www.mediacollege.com/flash/video/tutorial/example-flv.html. I downloaded ’20051210-w50s_56K.flv’ and saved it as c:\flex_sdk_2\learning\20051210-w50s_56K.flv.

4) Next, I generated the following source in my favorite text editor:

package { 
    import flash.display.Sprite; 
    import flash.net.NetConnection; 
    import flash.net.NetStream;  

    import flash.media.Video; 
    public class SuperSimpleFLVPlayer extends Sprite {  

        private var nc:NetConnection; 
        private var ns:NetStream; 
        private var vid:Video; 
        private var client:Object; 
        public function SuperSimpleFLVPlayer () { 
            // Initialize net stream 
            nc = new NetConnection(); 
            nc.connect (null); // Not using a media server. 
            ns = new NetStream(nc); 
            // Add video to stage 
            vid = new Video(320,240); 
            addChild (vid); 
            //vid.x = ( stage.stageWidth / 2) - ( vid.width / 2 ); 
            //vid.y = ( stage.stageHeight / 2) - ( vid.height / 2 ); 
            // Changed since when deployed the 
           // above set the video player nearly off the screen 
           // Since I am lazy, I am just going to 0 them 
           // out for now. Apparently, I have a lot more 
           // to learn. 
          vid.x = 0; 
          vid.y = 0;  

          // Add callback method for listening on 
          // NetStream meta data 
          client = new Object(); 
          ns.client = client; 
          client.onMetaData = nsMetaDataCallback; 
          // Play video 
          vid.attachNetStream ( ns ); 
          ns.play ( '20051210-w50s_56K.flv' ); 
        } 
        //MetaData 
        private function nsMetaDataCallback (mdata:Object):void { 
            trace (mdata.duration); 
        } 
    } 
}

I saved the source as c:\flex_sdk_2\learning\SuperSimpleFLVPlayer.as.

5) From the command line I compiled the file:

c:/flex_sdk_2/learning>../bin/mxmlc.exe 
        -use-network=false 
        SuperSimpleFLVPlayer.as

Note that I had to use the ‘-use-network=false’ directive. This told the compiler that I will not be using the network in my testing so don’t worry about sandbox issues when trying to load the flv from my local drives. Once I decide, if I decided, to deploy this to a website, I will need to recompile my code without this directive.

6) After compilation succeeded, I loaded the swf in the debug Flash Player:

c:/flex_sdk_2/learning>../player/debug/SAFlashPlayer.exe
        SuperSimpleFLVPlayer.swf

Success. Flash and ActionScript really is multimedia made easy.

Quick Update: I found that once I actually deployed this to a website it started behaving differently than it did in the debug tool, which I am none too happy about. However, for this quick and dirty learning experience, I just changed the vid.x and vid.y to both equal 0 and now it at least put the video into a visible part of the stage. For reference, feel free to check out what I deployed at: http://www.kriggio.com/tromstick/flv/index.html. By the way, feel free to tell me what I am doing wrong if you see anything, I really am just learning ActionScript 3.0 so any “constructive” criticism helps.

June 6, 2007 Posted by | ActionScript, Programming, technology | 22 Comments

A First Glance at jSeamless

After a few days of attempting to connect to http://www.jseamless.org, I was finally able to download the binaries and see if it was as wonderful as I hoped it would be. Since I had recently went through a quick implementation, though hack might be more appropriate, of a simple single player Blackjack game using Echo2, I thought it would be great to take the same logic and apply it to my first glance at jSeamless. I had the game, I just needed the user interface.

Using the HelloJSeamless Sample Application and the Eclipse Web Tools Platform, I was able to quickly get my development environment and my first project set up. I set the project to run on Tomcat 5.5, hit run, and the HelloJSeamless Sample Application was up and running. I am not a big fan of “Hello World” type applications as they don’t really show me much, but it was great that one was provided.

The next step for me was to see how easy it was to “port” my simple, and needlessly server-side, Blackjack game from Echo2 to jSeamless. As I started digging in, I realized that I had forgot to download any documentation or the source and found I was fumbling around in the dark, with nothing more than the jar containing the class files and the HelloJSeamless sample applications. I tried to go back to the website to get more information, yet the jSeamless site was experiencing technical difficulties to my great frustration, at which time I reminded myself that this is a Beta release. Being as determined as I am, I decided to work through to get some sort of working version by hoping my experience with Swing, QT, MFC, and other GUI Frameworks and the class files would allow me to come up with something that worked.

I quickly found classes like Window, Grid, Label, Button, Table, TableRow, TableCell, and Style and started to feel a little more comfortable. With some minor experimentation I was able to get a simple Window with some Labels and some Buttons. I set up the buttons to take my implementation of the ActionListener and implemented the action(ActionEvent) method and was confused because I couldn’t figure out how to drill down and get specific information about the ActionEvent that occured when a given button was pressed. My first pass at the code looked like:


public class JSeamlessBlackjack extends Application implements ActionListener {
...
public void initPane() {
...
hit = new Button("Hit");
hit.setEnabled(false);
hit.addActionListener(this);
...
}
public void action(ActionEvent e) {
// if () doHit(); I want to do some conditional on ActionEvent
// Since I don't have docs lets see what an ActionEvent has in it.
System.out.println(e.getType());
... more output statements
}
}

The results of this first pass, were simply Click and CLICK, with nothing to differentiate it from any other button that my ActionListener may have been listening to. As such, I was forced to implement as follows:

hit.addActionListener(new ActionListener() {
public void action(ActionEvent e) {
doHit(); }
});

While this isn’t “bad”, it’s just not my preferred way of implementing ActionListeners. Please note that I had no documentation at this point, so I had no idea if I had other options. I stumbled around for about an hour “porting” my Blackjack application, hit run, and I got decent results, which can be found at http://www.kriggio.com/JSeamlessBlackjack.

The performance of my first application was not as good as I had hoped and the lack of documentation made this first experiment much more painful that I would have hoped. I just went back to the site, about an hour prior to this posting, and found that the site was operational again and I immediately downloaded the source and the javadocs. I have hopes that they will provide greater insight into using the framework, but my expectations are fairly low, as I keep forgetting this is a Beta version.

In the end, I wasn’t as “wowed” as I hoped I would have been, but I must say that Matthew Hicks has done some excellent work with this project. I realize I may voice some level of disappointment, but I had extremely high expectations. While those expectations were not met in his Beta 3 version, this is still GREAT stuff and I look forward to future versions, and maybe after reading the Javadocs and Source files I will appreciate what he has accomplished with jSeamless even more.

My extremely ugly hackage I call my JSeamlessBlackjack source can be found at http://www.kriggio.com/EchoBlackjack/JSeamlessBlackjack.zip.

Update: Unfortunately, reading the Javadocs and Source for jSeamless provided no greater insight that just reading the byte-code.

May 30, 2007 Posted by | java, Programming, technology, Web 2.0 | 3 Comments

Introducing Myself to Echo2

On May 22, 2007, I read an article, jSeamless – UI Abstraction for Java, by Matthew Hicks, on TheServerSide.com that mentioned jSeamless 1.0 Beta 3 was available for download.  I had not been following these types of technologies, but the concept sounded extremely interesting to me.  As a former thick client developer, I thought the concept of developing an application without dealing with the mess of fusing HTML, JavaScript, CSS, and whatever backend I was dealing with at the moment, was very enticing.  As mentioned by Matthew Hicks, to also be able “develop your UI once and then deploy it as a web application and/or a desktop application without writing any additional code” got me very interested. 

With such a great introduction, I couldn’t help but immmediately head over to http://www.jseamless.org.  Unfortunately, it appeared that others had also read the article and the site was not accessible, I recieved a connection timeout every time I tried to reach the site. I could not contain my excitement though.  I started reading what other people had to say about jSeamless and I noticed a framework called Echo2 was frequently referenced.  Since I couldn’t see what jSeamless was all about, I quickly headed over to http://www.nextapp.com/platform/echo2/echo/

 While Echo2 did not offer the ability to deploy my application as something other than a web application, Echo2 does claim to “[remove] the developer from having to think in terms of ‘page-based’ applications and enables him/her to develop applications using the conventional object-oriented and event-driven paradigm for user interface development.” I thought this is what I am looking for, but I had my doubts as to it ability to deliver on this claim.  After taking a look at the demos on the site and doing some additional web search for tutorials using Echo2, I decided to try it out for myself.

For my first application, I decided to implement a simple single player Blackjack game.  The results, found at http://www.kriggio.com/EchoBlackjack, were great.  Within a few hours, I was able to get a simple Blackjack game working.  For my first experience, I was greatly impressed.

I am definitely going to play around with Echo2 some more, yet I am now even more curious how frameworks like jSeamless compare.

I was able to quickly get started using Echo2 thanks to Deitrich Kappe’s Tutorial, Ajax with Echo2 and Eclipse, located at http://www.pathf.com/echo2/Echo2-Part1.pdf.

For reference, I placed a zipped version of my code at http://www.kriggio.com/EchoBlackjack/EchoBlackjack.zip

May 29, 2007 Posted by | java, Programming, technology, Web 2.0 | 2 Comments

Old News: Java Checked vs. Unchecked Exceptions

I know this is beating a dead horse, but I was recently part of a  discussion with a fellow developer that did not see the value of checked exceptions.  I realize my position is arguable, but I see checked exceptions as a valuable part of the Java language. Checked exceptions communicate to the implementor that the method being called may return with unexpected results and it is the implementors responsibility to deal with it appropriately.

I am a proponent of Programming By Contract for designing computer software.   Checked exceptions are an essentional part of this contract, especially when the method being called depends on the availability of an external system, such as a database, file system, network, etc.  The contract establishes that the “supplier” will operate perfectly in an ideal condition, yet should something unexpected happen that he cannot control, such as an intermittent network failure, then the “client” should be prepared to handle it accordingly, enabling some level of Fault Tolerance.  It could be argued that this information does not need to be forced or communicated within the code, yet I am personally very grateful that the contract can be so eloquently documented within the code.

A friend of mine argued that many of the Checked Exceptions in Java are really fatal errors and should be categorized as RuntimeExceptions.  While I am not willing to speak for all of the possible checked exceptions, some of the exceptions named were SQLException, IOException, and NamingException.  I argue that each of the above named exceptions are accurately identified as checked exceptions within Java.  An SQLException might just be describing a transient failure within the system and a robust system should degrade gracefully, reporting the error and alerting the relevant parties.  I would even go so far to say that a robust system should even self recover, should the issue with the external system correct itself, depending on the system requirements.  I am not going to qualify IOException and NamingException in this weblog entry, but the same sort of proper exception handling and reason for the handling applies.

I think effective exception handling is a lost art, or at least poorly utilized in much of the code I have read.  I can see why many developers may feel that checked exceptions are a waste, especially when I repeatedly see code that looks like

try { 
  // do something that can throw an exception. 
} catch (Exception e) {}

I must say this is a worst case scenario, but with the exception (wow a pun) of maybe adding a logging statement, it happens to be one of the most common errors I find in code using static analyzers, like FindBugs or PMD.

In his article, Effective Java Exceptions, Barry Ruzek does an excellent job at describing how a Java developer can make effective use of the Java exception model.  I realize he implies that in many cases IOException, and other checked exceptions, are often not recoverable, which differs, in part, from my position, yet his article captures the essense of how and why exceptions should be handled.  From his abstract:

One of the most important architectural decisions a Java developer can make is how to use the Java exception model. Java exceptions have been the subject of considerable debate in the community. Some have argued that checked exceptions in the Java language are an experiment that failed. [Barry Ruzek's] article argues that the fault does not lie with the Java model, but with Java library designers who failed to acknowledge the two basic causes of method failure. It advocates a way of thinking about the nature of exceptional conditions and describes design patterns that will help your design. Finally, it discusses exception handling as a crosscutting concern in the Aspect Oriented Programming model. Java exceptions are a great benefit when they are used correctly. [Barry Ruzek's] article will help you do that.

I am sure I haven’t even touched the surface on this topic, but I think there is enough here to start a decent discussion. 

May 24, 2007 Posted by | java, Programming, technology | 8 Comments

Another fine mess!

What am I doing here? Another blog? What is it to be a successful blog writer? Actually, that is a poor question. Truly, I think the term blog sounds disgusting. For some reason it reminds me of vomit or barf, which amuses me to no end. To think of a blog as some form of regurgitation unfit for secondary consumption captures what I feel most blogs to be. Unfortunately, I think this of my own blogging.

January 25, 2007 Posted by | Uncategorized | 2 Comments

   

Follow

Get every new post delivered to your Inbox.