Flex Pasta » BlazeDS
It has been about a year now since Adobe announced it was open sourcing the Flex SDK, BlazeDS, and the Flex Compiler. Today on my way home, I started thinking about improvements to the Flex Open Source Adobe that I would like to see in the future.
5. Upgrade LCDS/BlazeDS to Java 5.
I am not sure the reasoning for having BlazeDS written in Java 1.4. Most projects using Flex are going to use Java 1.5 since they are most likely newer software. If for whatever reason, BlazeDS to Java 5 is not viable, at least create a separate Java 5 project that extends the BlazeDS code base. This project could use features of Java 5 to give developers more tools. In particular, annotations with remote objects would be a huge advantage for developers. Bean property configuration, service method security, better enum handling, code generator support, etc would all be great.
4. Bring the Flex Compiler Source Code out from the shadows
After attending MAX last month, I heard little about improvements to the Flex Compiler for Gumbo. I guess the compiler isn’t the sexy part of Flex so maybe that is why. But the compiler is just as important as the Flex SDK itself, so I would love to understand how it works. I think the community would benefit with more exposure to the compiler code base.
3. Make it easier to set up the Flex SDK, BlazeDS, and the Flex Compiler for local builds
The most looked at code base of the three components is probably the Flex SDK, just because we can hit F3 in eclipse and go look at the source code. However, how many people out there(other than Adobe employees) know how to check out the source code for the Flex SDK, BlazeDS, and the Flex Compiler and then be able to make changes to the code? I have been able to do it for the Flex SDK and BlazeDS, but it took some time(I also don’t think my config was ideal). I spent a couple of hours trying to figure out the Flex Compiler with no luck. I am hopefull for a little documentation for those of us out on an island trying to set it up.
2. Improve the ability to run different versions of the Flex SDK
If you go out and download Flex Eclipse plug-in site today, you will probably get Flex version 3.2. The rest of the development team might be using another version; say version 3.0 on the project. Figuring it might be a good idea to have the same version of Flex as your coworkers, you visit opensource.adobe.com to download version 3.0. The nice interface in FlexBuilder lets you have multiple Flex SDK’s installed and you can easily flip the compiler between different versions of the SDK. One problem: Charts. When you download the plugin, you get the charts bundled with the source code, but when you download releases from the open source page, charts are left off(I’m not sure the reason). This means a project using charts won’t compile for you without some hacking to get it to work.
1. Avoid using mx_internal/private in the Flex SDK
There are important instances where the private keyword is usefull(when I don’t want a subclass to override it or even be able to call it). However, and I admit to doing this as well, we tend to use the private keyword by default when we don’t want a method to be public. The protected keyword would be a much better option for the majority of methods in the Flex SDK. I have found it difficult at times to extend Flex components and even BlazeDS code because the methods are private or mx_internal. Maybe it was the intent of the authors to keep these methods private to avoid future upgrade hassles, but it can be problamtic to extend them. My latest example of one such problem involves creating a ColumnChart. I created the chart and had a ColumnSeries. The chart was simple and I set the properties labelAlign=”center” labelPosition=”outside”. I was wanting to center the labels at the top of the bars on the outside.
As you can see in the picture, the labels are left aligned. The as-doc states that labels on the outside can only be left aligned. I want to try and extend column series to get the labels in the middle. I find the method:
private function renderExternalLabels
I can’t extend it since it’s private. Ok, so I find where renderExternalLabels method is called.
mx_internal function updateLabels()
This goes on for four or five methods before there is one that can be extended. The point is that marking methods protected more aggressively can help everyone out who is trying to extend these components.
Those are my top five wishes for Flex Open Source. What are your wishes?
Like many Flex/Java applications, they are started from scratch and use java 1.5 or greater. I was surprised that there were no annotations for BlazeDS to make it easier to mark up remote objects and services. Being that BlazeDS is open source, I thought it would be valuable to use annotated classes for remote objects. I created a custom BeanProxy(a class that defines what properties go from Java to actionscript, and vice versa). Note: I have submitted the code to Adobe for acceptance into the BlazeDS code base. I plan on expanding the code further, and I hope others will contribute as well. The link to the enhancement request can be found here: Please vote for the issue! Inclusion into the BlazeDS code base will help make it maintainable in the long run.
Now for a step by step guide about the annotations, and how to use them. First, I will point out that somethings I have done in the code are not ideal but are necessary to be compatible will BlazeDS which is primarily a java 1.4 app.
- Download the Jar and source: BlazeDS Annotations Jar and Source Files
- Take one of your domain classes/remote objects and implement IAnnotatedProxy and mark the class with the @FlexClass Annotation. The IAnnotatedProxy is a marker interface and its existence is simply to tell BlazeDS it has annotatations and should use the AnnotatedBeanProxy instead of the normal BeanProxy.
- Add this one liner to the servlet init of your webapp:
PropertyProxyRegistry.getRegistry().register(IAnnotatedProxy.class, new AnnotatedBeanProxy()); - Begin adding @FlexField annotations to your “getter” methods on your remote objects. As I will explain in more detail, I have broken up what the @FlexField annotation does into two parts:
- Annotations that manipulate whether a field is included in BlazeDS AMF serialization.
- @FlexField( fieldType = FlexFieldType.ReadWrite) - Default option. Acts just like domain objects do today with BlazeDS, it reads a field if and only if both a matching getter and setter exist.
- @FlexField( fieldType = FlexFieldType.Exclude) - Does not include this field in AMF serialization even though a matching getter and setter may exist. Benefits are 1) Performance, 2) Security, and 3) Unnecessary Clutter. Keep in mind though, if you have a field populated with data going from Java to Flex, when it comes back from Flex to Java, the fields you excluded will be null.
- @FlexField( fieldType = FlexFieldType.Transient) - Include this field in serialization from Java to Flex if it has a “getter” method, but it does not require a matching “setter” method. The primary benefit here is I may have a field such as a calculation that doesn’t have a “setter” because it is a calculation. Yet I want the field to be translated over to the flex front end because I will use it for display only purposes to the end user.
- Annotations that manipulate data during serialization primarily for security purposes. Note, for use of the following annotations, remote objects on both the flex and Java side MUST extend mx.rpc.remoting.JavaObject. Before using the following annotations, make sure to fully understand what they are doing.
- @FlexField( fieldType = FlexFieldType.ReadOnly) - This field is included in serialization to and from Java and Flex. However, when data is coming from Flex into Java, encoded data in the JavaObject’s key determines the value of the field. Example: An account number field with the value of 999 is passed from Java to Flex. The account number is encoded in the JavaObject’s “key” field. Now the user goes to save their account settings, so data is sent back from Flex to Java. If the account number is anything other than “999″, a (runtime) ReadOnlyException is thrown. The primary benefit here is security. I want the user to be able and see, but not edit the account number on the Flex side. There may be other fields in the domain class they can edit, but this field is off limits.
- @FlexField( fieldType = FlexFieldType.CreateOnly) - This field is included in serialization to and from Java and Flex, and is almost identical to the ReadOnly Annotation. The difference here is that, if the field has no value(is null) when it goes from Java to Flex, the field can be created on the flex side and sent back. An example here is a foreign fey field. I have a customer creating an order. The order contains a customer id field. I want to let the customer create an order with their customer id for the first time, but after that, want to make sure that data is not tampered with later.
- Annotations that manipulate whether a field is included in BlazeDS AMF serialization.
Web 2.0 and Security
With Web 2.0, application security is a big concern. Data is much more exposed to the curious eyes of an end user (especially primary and foreign keys) than in a traditional web app. My post on BlazeDS and Security goes into more detail. One of the driving forces for these annotations is for object security.
Annotations: To be Continued….
The annotations here create a starting point for use in BlazeDS. I hope the community will build on these annotations. The next goal is to tackle securing remote service methods using annotations. Feel free to post ways you would like to see annotations used with BlazeDS in the future.
A common hurdle a developer may face is dealing with exceptions in BlazeDS. When an exception is thrown in Java, how do we handle this in flex? Here is a simple and flexible approach inspired by Scott Morgan.
1. Create a Java Class that extends RuntimeException.
package com.flexpasta.exception;
public class FlexException extends RuntimeException
{
public FlexException(String message)
{
super(message);
}
}
2. Create a matching flex class called FlexException, and put the usual RemoteObject tag in their so BlazeDS will know what to look for. Also remember in actionscript, each object must be instantiated at least once, so be sure to do that somewhere with FlexException.
3. In Java, whenever there is a known exception, or some error where the end user needs to be shown a message, throw a FlexException and pass in the message the user should see in the constructor. Let’s say the user just entered an invalid password. throw new FlexException(”Wrong Password Entered, Please Try Again.”);
4. Flex receives the Exception in the form of a fault. In the fault handler, you call this method:
/**
* Parse the incoming fault for an FlexException class. If the exception class is found and it has a matching actionscript class,
* show an alert to the user with the correspoding messages. If we don't recognize the Exception type, show a generic error.
*
* @param fault
*
*/
public static function handleException(fault:Fault): void
{
var msg : String = fault.faultString;
var clazz : Class = getExceptionClass(fault);
var instance : Error = null;
if (clazz != null)
{
Alert.show(msg,'Error');
}
else
{
Alert.show('Error! Please try again. If this issue persists, contact the system administrator');
}
}
/**
*
* Return the Class corresponding to the exception by parsing the fault string. If a corresponding actionscript error class is found,
* return it. Otherwise, return null.
*
* @return
*
*/
public static function getExceptionClass(fault:Fault) : Class
{
var clazz:Class = null;
var index:int = myFault.faultString.indexOf("FlexException");
if (index != -1)
{
var cname:String = myFault.faultString.substr(0,index-1);
try
{
clazz = getDefinitionByName("com.flexpasta.FlexException") as Class;
}
catch (e:ReferenceError)
{}
}
return clazz;
}
When we see a Flex Exception, we show the message to the end user. If for some reason we have an unplanned error in Java, like NullPointerException, a message is displayed to the end user: ‘Error! Please try again. If this issue persists, contact the system administrator’. A generic message to handle all unplanned errors.
5. What if the app needs to DO something special with certain Java Exceptions? Say the user has just entered 3 password attempts, and I want to be able to handle locking their account through an exception.
Conclusion
It is pretty simple with BlazeDS to create a base exception handling system. Depending on project needs, this approach can easily be modified or enhanced. In flex, it is important to setup a strong exception handling that accounts for both planned and unplanned exceptions.
As first discussed in a previous post, “The Pros and Cons of Cairngorm“, I noted the need for a more lightweight framework for developing in Flex and Air. I am releasing version 1.0 of The Penne Framework, a simplified Flex and Air framework, as a second option to the popular Cairngorm Framework. This page has the Penne base code, and a java/flex example application using Penne(called the Italian Store) with remote objects. I have created a diagram which summarizes how Penne differs from Cairngorm.
About the Diagram
Let’s discuss the command class in Cairngorm, because this is the meat of the difference between Cairngorm and Penne. In Cairngorm, I will have one command class for a type of event. For example, I might have a remote service that returns a list of customers. This would have one command class. Then I could have another command class for getting all of the customer orders. In Penne, there is one request and result class for both of these remote calls. The request would have 2 methods in this case:
1: getAllCustomers(),
2: getAllCustomerOrders().
The result class would have
1: getAllCustomers(custList:ArrayCollection),
2: getAllCustomerOrders(orderList:ArrayCollection).
In a large project, the number of classes to create in Cairngorm would be drastically higher than Penne. There is a ton of overhead work to create in even a simple remote call in Cairngorm. With Penne, it is easy to grow your project without as much busy work.
Penne still keeps a strong structure for code layout. It is easier for a developer to see what is happening. Instead of looking at an event that is mapped to a command, which is mapped to a delegate, which calls an external service, in Penne I just call the method directly from a view class. It is very clear the remote service I am calling and from where. If I use BlazeDS and remote objects, my java remote methods can directly matchup to my flex request/response classes. There is a huge reduction in steps to figure out a path to a bug with Penne.
Hang on a Minute, How can Penne just delete all those event classes?? How will Penne ever have code reuse??
Penne is not getting rid of event classes. They are just not part of the framework. I am no longer required to create one for every type of remote service call. If creating a component such as a date chooser, or datagrid, then standard events are used to allow parent components to interact with them. Depending on the task, this kind of flexibility in a component is usually NOT needed. With Penne, call the request method directly from within a view component, and the result will cause bindings to fire changes back to the view components. Only use events for remote service calls when it is required for code reuse or the parent component needs to be aware, not for any other reason. I don’t create events because I have to anymore, I create them because they are NEEDED for something more than just kicking off a remote service call.
What about the model? Certainly Penne can’t get rid of that too?!?!
The model isn’t gone in Penne. Model variables still exist in the application. ModelLocators still exist just like in Cairngorm. Penne, however, offers a secondary option for remote services. Penne allows the developer to place “model” variables inside the response classes if desired. By placing the result directly in a variable in the same class, tt becomes much easier to see what binded variable goes with which remote service call. In my view layer I can just say PastaRemoteResult.getInstance.pastaTypes. In Cairngorm, if you opened up a model class and I said to someone, “Where does this model variable customerList get set?” They would probably start sweating and begin opening up all of the command classes trying to remember which one(s) it is. Then after it’s found a text search will be done to find the corresponding view where the CairngormEvent that goes with that command gets invoked. It is tough enough for the person who wrote the code to know where everything lives. Just wait until a new hire comes to code on the application has no idea what is going where. With Penne it is simple and structured. Everything is easy to find. If for some reason I need to control things like viewstacks and state management, I can still create a separate “model” class just for this, but all remote service calls’ model variables live in the response class.
Conclusion
The Penne Framework improves upon Cairngorm by simplifying it without sacrificing separation of duties. Penne drastically reduces the number of classes created in a large enterprise project. This reduces code complexity and readability. As an added benefit, Penne will reduce my pesky Flex Builder compile times!
Take a look at Penne, I welcome feedback and suggestions. The Design approach to flex can be improved. I hope Penne can start to accomplish this goal!
The Code
Here are the three zip files to download. One is the Penne.zip which includes the Penne source and Penne.swc. The other two are the Italian store. There are 3 projects in all which can be imported right into eclipse. I am using flex 3, java 1.5, with eclipse europa. The example Italian Store application is extremely simple. It shows how Penne can be used and offers comments as to how Penne works.
You’ve just set up your flex-java project using BlazeDS AMF. You’ve got some classes in java which have matching actionscript classes that have the magic “RemoteClass” tag to tell the bean proxy where to find your class. Everything is working well and then you have a thought, how in the world can I make this flex app secure? With remote classes in actionscript, your application is more wide open then any jsp application. Someone with the right knowledge can decompile your swf and see the classes, giving out a blue print to your application’s architecture.
BlazeDS and Security
BlazeDS uses the PropertyDescriptor class when going from java to actionscript. Basically, this means for each getter and setter you have in java, BlazeDS is going to pick this up via reflection and serialize the data to AMF output to the client. If you have a getter, but no setter in java, it won’t be read by BlazeDS. Keep in mind that regardless of what is in your actionscript class, all data returned from your java service will be sent back over the wire to the client flex app.
Where do I start?
Let’s assume you have a java class called Customer. Customer.java has 3 getters and setters for id(the primary key), username, and password. You have a simple flex app that allows you to change your password. When the customer changes their password, you send off a remote call to your java service updateCustomer(). Without getting into whether you are using hibernate or some other database access method, we’ll assume that in the end your updateCustomer() method executes this following query: update customer set username=’admin’, password=’password1′ where id=1. Excellent right? Everything works. You have to assume however, that any flex app, can send any request it wants, regardless of what safeguards you have in place in actionscript. Pretend now that hacker Joe comes along and starts snooping your remote classes. He notices your actionscript class “Customer” being sent over the wire calling the updatePassword() method. Joe then modifies the customer.id to 2 and the username and password of his choice. The update query runs and now hacker Joe is able to login to another user’s account using his own username and password! UH OH!!!!! In a JSP/HTML app you might already have the customer stored in a session, so you would never be passing the customer.id over the wire and would not have to worry about this type of tampering. With actionscript and remote objects, it is all there in the open. How do you tackle securing the flex app?
1. Secure the primary keys
- Store at least the primary key in Session on the way out from java to flex. When you get the request from flex to java, check to make sure the user has access to the primary key they are trying to change.
2. Secure the foreign keys
-Other classes will probably have your customer.id as a foreign key in their class. Make sure these are secure from tampering as well.
3. Secure your remote methods that flex will be calling
-Use remoting-config.xml to exclude methods that the user should not have access to. One way to this:
<destination id=”customerService”>
<properties>
<source>customerService</source>
</properties>
<exclude-methods>
<method name=”updateCustomer” security-constraint=”admin-users”/>
</exclude-methods>
</destination>
You can read more about this in the BlazeDS dev guide.
4. Secure any other fields that are sensistive and should not be able to be changed by the end user.
Conclusion
BlazeDS does contain some features to help secure your flex app. It still lacks a strong security model for securing bean classes. Most of the work for security will need to be done by an app by app basis. Think about security during your design in the beginning. Flex is more open than many realize and it only takes one bad hacker Joe to poke a hole in your app. Have someone dedicated to specifically laying out a security design and have checkpoints to ensure standards are met.

