This morning, I found myself wanting to add a nice-looking, but quick loading indicator into a Flex application. In the Ajax world, it’s simple…just use an animated GIF that can be downloaded from any number of sites. In Flex, it’s not quite that easy. The default Image component in Flex does not support animated images, nor does Flex itself.

A quick Google search turned up the as3gif library, which provides support for playing animated GIFs. The download did not include a SWC, so I pulled the source code into Flex Builder and quickly compiled one, which I then included in my Flex project.

To enable animated GIF images, I extended the Image component to utilize as3gif as follows:

package iamjosh.samples.components
{
	import flash.net.URLRequest;

	import mx.controls.Image;
	import mx.core.UIComponent;

	import org.gif.player.GIFPlayer;

	public class AnimatedGIFImage extends Image
	{
		private var _gifImage  : UIComponent;

		public function AnimatedGIFImage()
		{
			super();
			this._gifImage  = new UIComponent();
		}

		override public function set source(value : Object) : void
		{
			if (!value is String)
			{
				throw new ArgumentError("Source must be of type String");
			}

			super.source = value;
		}

		override protected function createChildren() : void
		{
			super.createChildren();
			var player : GIFPlayer = new GIFPlayer();
			player.load(new URLRequest(this.source as String));
			this._gifImage.addChild(player);
		}

		override protected function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void
		{
			this.addChild(this._gifImage);
			super.updateDisplayList(unscaledWidth, unscaledHeight);
		}
	}
}

This class simply pulls in the source for the image and then utilizes the as3gif library. Using the AnimatedGIFImage component is as simple as:

<components:AnimatedGIFImage source="assets/images/loading.gif"/>

Although I have not tested it thoroughly, the class should also support the basic capabilities of the Image component as well.

jQuery makes striping an HTML table very simple with what amounts to a one line function.  First, let’s start with our HTML:


<table class="striped">
<tr>
<td>Lorem</td>
<td>ipsum</td>
</tr>
<tr>
<td>dolor</td>
<td>sit</td>
</tr>
<tr>
<td>amet</td>
<td>consectetur</td>
</tr>
</table>

Should be pretty straightforward.  Notice that we haven’t done anything bayond a simple table here, no styling, nothing.  Next, we can create a simple CSS style for our alternating rows:


tr.alt {
background-color: #ebe9dc;
}

Finally, let’s create a Javascript function that we can call to stripe the table:


jQuery.fn.stripe = function() {
return this.each(function(){
$('tbody > tr:even', this).addClass('alt');
});
};

Again, this function primarily boils down to one line, the rest is boilerplate jQuery plugin code that allows us to make calls to the function as follows $('table.striped').stripe.

The power here is the line $('tbody > tr:even', this).addClass('alt');. Here, we are using selectors mixed with the scope of “this” (i.e. table’s with class “striped”) to select the even rows in the table and apply the class “alt” which we defined earlier in our style sheet to them.

I wanted to use Cairngen in a recent project and quickly noticed that the standalone version of Flex Builder 3 does not have Ant support available by default.  Getting it set-up is pretty easy though:

  1. In Flex Builder, Help -> Software Updates -> Find and Install…
  2. Select “Search for new features to install” and click Next
  3. Pick “The Eclipse Project Updates” and click Finish
  4. Expand “The Eclipse Project Updates” and “Eclipse 3.3.2″
  5. Select “Eclipse Java Development Tools 3.3.2…” and click “Finish”
  6. When prompted, select “Install All”
  7. Restart Flex Builder

When Flex Builder starts up again, you will have Ant support available (e.g. any build.xml files will have a little ant on the icon).  You can also verify by selecting Window -> Other Views… and checked if an Ant directory exists.

I recently ran into user interface design that included a component better built in Flash than Flex due to the high degree of interaction required (my time is short these days as well, so one of our designers will be building it). This raised the question of how to embed a Flash movie in a Flex application and enable interaction between the two.

This is actually fairly straightforward when working with Flash Player 9 and ActionScript 3. I started by building a very simple Flash component (I know nothing about Flash) – it simply contains a slider and a label that changes with the value of the slider:

My goal is to embed this component in a simple Flex application that can read/display the current value of the slider.

Next, I created a new Flex application and included both the SWF and FLA file for my Flash component in the “src/assets” directory. I then used a SWFLoader to load the Flash component into the application and position it properly on the screen. I also added a few simple Flex components to display the currently selected value, etc.:

Now, we need to wire everything together. To do this, we need access to the Flash component from the SWFLoadervia the content property. With access to the component, we have access to public properties/methods, can listen for events, etc. In fact, to synchronize the currently selected value between Flash and Flex, the slider in the Flash component will dispatch an event on change that the Flex component listens for. Pertinent code snippets:

Flash Action Code (remember, I’m not a Flash programmer):

slider1.addEventListener(SliderEvent.CHANGE,dispatchSliderEvent);
function dispatchSliderEvent(evt : SliderEvent) : void
{
    dispatchEvent(new SliderEvent(SliderEvent.CHANGE, evt.value, null, null));
}
// returns the current value of the slider
function get sliderValue() : Number
{
    return slider1.value;
}

Flex

<mx:Script>
<![CDATA[
    import mx.events.SliderEvent;
    private var _mainTimeline : *;
    [Bindable] private var _sliderValue  : Number = 0;

    private function swfLoaded(event:Event) : void
    {
        this._mainTimeline = this.swfLoader.content;
        this._mainTimeline.addEventListener(SliderEvent.CHANGE, updateValue);
        this.updateValue();
    }

    private function updateValue(evt : Event=null) : void
    {
        this._sliderValue = this._mainTimeline.sliderValue;
    }
]]
</mx:Script>

<mx:SWFLoader id="swfLoader" y="73" x="10" source="assets/Simple Flash Component.swf"
    complete="swfLoaded(event);"/>

Two items of note:

  • I did not explicitly assign a type to the _mainTimeline object in order to be able to arbitrarily call methods on it (e.g. no compile-time checking)
  • There is a strange problem in trying to directly call the _mainTimeline.sliderValue() method in which the Flash component did not render properly, hence why I used an intermediate variable (_slideValue).

That’s it, it really is fairly straightforward. Although I have not tested it yet, Flex should be able to set values in the Flash component in much the same way.

References

I’ve been doing some research on AJAX best practices of late and found a few links worth sharing / archiving:

Yes, all are from Yahoo, but all seem to be useful, especially the tooling.

For a personal project, I am building a Rails site that has an administration section. Of course, I don’t want any nefarious person who snoops my network traffic to be able to login. SSL isn’t an easy option because (1) my site is on a shared host, (2) I don’t want to pay for an SSL certificate, and (3) I would prefer that my users do not need to accept a self-signed certificate.

Given these conditions, I felt that a private/public key pair would successfully obfuscate login credentials without SSL. At a high level, my Rails application generates a 1024-bit RSA key on the fly and shares a public version with the client. The client utilizes an open source RSA library for JavaScript to encrypt the credentials on the client before sending them back to the server, which then uses the private key to decrypt them. I’m not an encryption expert, but I think the worst that could happen is that someone could decrypt the credentials for the one request they capture (feel free to correct me though).

Let’s get to the code. To set the situation, I am following REST conventions for authentication, so I have a SessionsController with a new action and a create action. The former is responsible for setting up the login and the latter for processing the user’s input.

First, the “new” action, which creates the RSA key, provides the public components to the view template, and stores the key (in PEM format) in session:

  def new
    key = OpenSSL::PKey::RSA.new(1024)
    @public_modulus  = key.public_key.n.to_s(16)
    @public_exponent = key.public_key.e.to_s(16)
    session[:key] = key.to_pem
  end

Then in the view template (“new.html.erb”), we provide the public modulus and exponent (the necessary component of the public key) as well as input forms for the username and password:

  <%= javascript_include_tag('rsa/jsbn', 'rsa/prng4', 'rsa/rng', 'rsa/rsa', 'rsa/base64', :cache => true) %>

  <% form_tag session_path, :id => 'login' do -%>
  <fieldset>
    <legend>Please Login</legend>
    <label for="login" class="required">Login</label>
    <%= text_field_tag :username, params[:username] %><br />
    <label for="password" class="required">Password</label>
    <%= password_field_tag :upassword, params[:upassword] %><br />
    <%= hidden_field_tag :password, '' %>
  </fieldset>
  <%= submit_tag 'Log in' %>
  <% end -%>

  <%= hidden_field_tag :public_modulus, @public_modulus %>
  <%= hidden_field_tag :public_exponent, @public_exponent %>

Two things to note here. First, we are including the four necessary JavaScript libraries on this page only. Second, we use a hidden field to store/commit the password – this field is populate via JavaScript.

My application utilizes jQuery, so attaching a function to encrypt the password before form submission is straightforward:

  $(document).ready(function() {
    $("form#login").submit(function() {
      var rsa = new RSAKey();
      rsa.setPublic($('#public_modulus').val(), $('#public_exponent').val());
      var res = rsa.encrypt($('#upassword').val());
      if (res) {
        $('#password').val(hex2b64(res));
        $('#upassword').val('');
        return true;
      }
      return false;
    })
  });

Before submission occurs, we encrypt the value of the “upassword” field, store an encrypted Base64 version in “password,” and clear “upassword.” If there is a problem, the form is not submitted.

On the server-side, this form is submitted to the SessionsController#create action:

  def create
    key = OpenSSL::PKey::RSA.new(session[:key])
    password = key.private_decrypt(Base64.decode64(params[:password]))
    user = User.authenticate(params[:username], password)
    if user
      reset_session  # reset session after login
      session[:user_id] = user.id
      flash[:notice] = "Welcome back, #{user.username}"
      redirect_to admin_url
    else
      flash[:error] = 'Invalid username/password entered'
      new and render :action => 'new'
    end
  end

Here, we pull the key out of session and use it to decrypt the form input before attempting to authenticate the user. It is important to note the the private_decrypt method wants binary data, so we need decode the Base64 text passed in the request (using Base64 seemed more appropriate than binary data here). After the authenticate method is called, things proceed as usual.

So far, this is working fairly well. There are a few options for improvement – perhaps a before_filter to preprocess any encrypted data. I’d be interested in hearing other ideas on this topic as well.

References

All in all, jQuery is pretty cool. I just stated working with it for a personal project and have found it simple and fairly intuitive to use, not to mention the plethora of available plug-ins.

I wanted to focus on the first input element in a form using jQuery. I haven’t tested this extensively, but I came up with the following:

    $(document).ready(function() {
       // focus on the first text input field in the first field on the page
        $("input[type='text']:first", document.forms[0]).focus();
    });

We are simply using a selector to pick the first input element of type “text” in the first form on the page (that’s the “document.forms[0]” stuff) and then focus on it. Of course, this is limited only to text fields, but could be extended to other types as well. I’d be interested in hearing about alternatives.

Wow, it’s been a long time since my last Rails-related post (actually months). That’s because it’s been about that long since I’ve done much in the way of Rails development. Over the past few weeks, I’ve been rebuilding my personal website in Rails 2.0, which (per my wife’s requirements) will include a photo gallery.

My Photo class utilized attachment_fu to easily support image uploads. I also wanted to be able to display the date the photo was taken, not the date is was uploaded. This information is encoded in the JPEG image file by the digital camera, we just need to pull it out. Although there are several methods to do this, I chose to use RMagick as it is already included in my application for attachment_fu. We can use the get_exif_by_entry method to get this (as well as a great deal of other) information:

class Photo  < ActiveRecord::Base
  @@exif_date_format = '%Y:%m:%d %H:%M:%S'
  cattr_accessor :exif_date_format

  # some stuff

  def date_taken
    photo = Magick::Image.read(full_filename).first
    # the get_exif_by_entry method returns in the format: [["Make", "Canon"]]
    date  = photo.get_exif_by_entry('DateTime')[0][1]
    return unless date
    DateTime.strptime(date, exif_date_format)
  end

  #some more stuff
end

That’s it. Read the EXIF information, provide it’s format, and create a new DateTime object.

Out of the box, Flex provides a set of great validators for client-side validation of form input (e.g. for phone numbers), but for instances in which we need to involve the server, things become a bit trickier. Before we get into the how though, a quick discussion of the why. There are numerous situations in which server-side validation is not only nice, but a must. Consider an application that asks users to register themselves. The application might ask the user to create a username, but that username must be unique. We don’t want to send our entire list of username to the client, so instead we’ll utilize validation code on the server. In a previous post, I detailed my approach for server-side validation.

In general, the design follows a similar pattern to Rails – we store a map of errors in an object within the model object itself. Persistent classes that implements the Validateable interface can be validated by our framework and an instance of ValidateableErrors will be injected into the object with a map of validation errors. If the validation framework encounters an error, it halts execution and sends the invalid object (with errors) back to the client.

Once Flex receives the updated object, the application needs to be able to display those errors. To do this, we’ll utilize a custom implementation of the mx.validators.Validator class. Before we dig into the validator class, let’s take a quick look at the ActionScript implementation of the ValidateableErrors class:

    [Bindable]
    public class ValidateableErrors
    {
        private var _errors : Object;

        public function ValidateableErrors(errors : Object) : void
        {
            this._errors = errors;
        }

        public function getFieldErrors(field : String) : Array
        {
            return this._errors[field] == null ?
                [] : [ this.createValidationResult(this._errors[field]) ];
        }

        private function createValidationResult(msg : String) : ValidationResult
        {
            return new ValidationResult(true, "", "SERVER_ERROR", msg);
        }
    }

The first thing to note is that instead of using a Dictionary, we are in fact just using a plain old object as this is how LCDS deserializes Java Maps on the Flex side. Each of the keys in the map are now properties for this object. We can this utilize the “[]” notation to retrieve the value of a given property. The validation message is wrapped in a ValidationResult object, which is utilized by the validator to display error messages in the UI.

Let’s now take a quick look at the validator implementation:

    public class ServerErrorValidator extends Validator
    {
        private var _errors : ValidateableErrors;
        public var field : String;

        public function ServerErrorValidator()
        {
            this._errors = null;
            super();
        }

        public function set errors(errors : ValidateableErrors) : void
        {
            this._errors = errors;
            validate();
        }

        override protected function doValidation(value : Object) : Array
        {
            return this._errors.getFieldErrors(this.field);
        }
    }

Our validator simply accesses the ValidateableErrors object referenced by the “errors” property for a given field. It then displays the error message via the return ValidationResult object. We can make this a clearer by looking at an example:

    <validation:ServerErrorValidator id="firstNameValidator" field="firstName"
        errors="{ this._user.validationErrors }" listener="{ this.firstName }"/>
    <validation:ServerErrorValidator id="lastNameValidator" field="lastName"
        errors="{ this._user.validationErrors }" listener="{ this.lastName }"/>

    <mx:Label x="10" y="10" text="User Validation Test" fontSize="16" color="#FFFFFF" fontWeight="bold"/>
    <mx:Panel x="10" y="42" width="480" height="200" layout="absolute" title="Create User">
        <mx:Label x="10" y="10" text="First Name:"/>
        <mx:Label x="10" y="36" text="Last Name:"/>
        <mx:TextInput x="127" y="8" id="firstName"/>
        <mx:TextInput x="127" y="34" id="lastName"/>
        <mx:Button x="385" y="128" label="Create" click="createUser()"/>
    </mx:Panel>

The User instance (“_user“) is defined elsewhere. Although not ideal, we do need to instantiate one validator per field even though we only reference a single object. The response from the data service’s “createItem” method is an updated version of the user object with the associated validation errors. Flex takes care of updating the UI appropriately to display the errors.

This implementation has worked well thus far for my purposes; however, I do see room for improvement in displaying multiple errors messages per field and in making the solution as a whole more flexible. I do welcome feedback.

This will be the first of a two part series that discusses my approach towards validation in a data service application. The first part (this post) will cover the server-side aspects of the validation framework and the second (coming soon, I hope) will detail how validation information is shared with the Flex application.

In designing the validation component, I wanted the following:

  1. Little to no impact on business logic (e.g. no validation code inline with business logic)
  2. Minimal configuration
  3. Able to send validation errors to Flex client

The first design principal lends itself to aspect oriented programming, which enables us to handle “cross-cutting” concerns (see my previous post for more details). In short, we’ll be implementing a “Validator” class (an aspect) that is called upon to validate persistent objects whenever a create or update method is called in the data access layer. For this application, I have used Spring with @AspectJ annotations to build AOP components and have previously documented details on the AOP configuration for the Validator.

For the most part, the Validator class is fairly straightforward, with the exception of it being Spring application context aware (e.g. it has access to our Spring configuration). By making the Validator context aware, we can configure validation beans via Spring and dynamically load them as needed.

    @Aspect
    public final class Validator implements ApplicationContextAware
    {
        private ApplicationContext appContext;

        @Around("iamjosh.samples.util.SystemArchitecture.onCreateOrUpdate()"
            + " && args(validateable)")
        public void validate(ProceedingJoinPoint called, Validateable validateable) throws Throwable
        {
            // returns simple name, e.g. "user"
            String beanType = validateable.getSimpleName();

            // try to load a validator bean for this object
            org.springframework.validation.Validator validator
                    = this.loadValidatorBean(beanType);
            // if we didn't get a validator back, stop trying to validate
            if (validator == null) return;

            // run the validation
            ValidateableErrors errors =
                new ValidateableErrors(validateable, beanType);
            validator.validate(validateable, errors);

            // check the result of the validation -- if there are errors, assign
            // them to the validateable object
            if (errors.hasErrors())
                validateable.setErrors(errors);
            else
                // proceed if valid, be sure to pass the validateable on
                called.proceed(new Object[] { validateable });
        }

        // need to implement this method to be application context aware
        public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException
        {
            this.appContext = applicationcontext;
        }

        private org.springframework.validation.Validator loadValidatorBean(String validateableBeanName)
        {
            String validatorBeanName = validateableBeanName + "Validateable";
            org.springframework.validation.Validator validator = null;
            try
            {
                validator =
                    (org.springframework.validation.Validator)this.appContext.getBean(validatorBeanName);
            }
            catch(NoSuchBeanDefinitionException nsbde) { // do something }
            catch(BeansException be) { // do something }
            return validator;
        }
    }

In this case, I am favoring the idea of convention over configuration. The naming convention for my validator beans should be “modelClassNameValidator” or “userValidator” for the User class. This keeps things simple. In the future, I plan to add an option to override this default.

I won’t go into the details of the ValidateableErrors class, but it is just a wrapper around Spring’s BindingResult class that defers all method calls and adds a few others. For those familiar with Rails, this class and its relationship to the model are very similar to the Errors class in ActiveRecord classes. Each validateable model class has an “errors” property that references a ValidateableErrors object – this is what is eventually passed to Flex (more on this in a future post).

Any persistent model that is to be validated by our validation framework must implement the Validateable interface and extend the BaseValidateable abstract class.

Finally, a quick discussion of how the validation rules are defined. I wanted to avoid mixing validation code with business logic and partially achieved this by utilizing AOP to call my validation framework. But I also wanted to avoid defining validation rules in code as this can be become cumbersome and create extraneous classes. To that end, I chose to utilize the Valang validation language, which is part of the Spring Modules library, a set of extension to Spring. Details on Valang can be found in the references below, but it allows us to write succinct validation rules as part of the Spring configuration. For the user class our Valang code looks like this:

    <bean id="userValidator" class="org.springmodules.validation.valang.ValangValidator">
        <property name="valang">
            <value>
                <![CDATA[
                    { firstName : ? is not blank : 'First name is blank' : 'first_name_empty' }
                    { firstName : length(?) < 30 : 'First name too long' : 'first_name_length' : 30}
                    { lastName  : ? is not blank : 'Last name is blank' : 'last_name_empty' }
                    { lastName  : length(?) < 50 : 'Last name too long' : 'last_name_length' : 50 }
                    { email     : ? is not blank : 'E-mail is blank' : 'email_empty' }
                    { email     : email(?) == false : 'E-mail is invalid' : 'email_invalid' }
                    { email     : ? is blank or length(?) > 3 : 'E-mail is too short' : 'email_to_short' }
                ]]>
            </value>
        </property>
    </bean>

By naming the validation bean “userValidator” the validation framework will automatically identify this bean as the validation bean for the User class. We can then apply whatever Valang rules are deemed necessary by our requirements to implement server-side validation. Any errors are then inserted into the Validateable object as a ValidateableErrors object that will be sent back to Flex.

References