Sunday, December 21, 2008

FlexB – XML mapping for Flex/ActionScript classes and web services

Flex has built it support for working with XML as well as built in support for mapping XML to ActionScript classes and back to XML again if you have an XSD file. What about mapping to and from XML if you don’t have an XSD file, and what about this XML web service stuff? FlexB is a Flex/ActionScript library for more easily working with XML and web services. It consists of a combination of classes that I originally made for my own personal use while teaching myself Flex a little over 2 years ago, which I have recently decided to renovate and make public.

Where can I get the code, library, and/or participate?

http://flexb.sourceforge.net

Why don’t you just use an XSD file and the built in XML mappings?

Because I am lazy and don’t want to use an XSD file. There are also equivalents to this idea in other languages such as with XStream and Java.

Why map XML to ActionScript classes with all of the direct component XML support?

Components such as the DataGrid allow you to directly reference XML in order to do useful things with your data.  The following example shows how to populate a DataGrid using XML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml">
    <mx:XML xmlns="" id="CompoundFoo">
        <CompoundFoo my_name="wii">
            <SimpleFoo><name>Moo Cow</name><foo>Bar</foo></SimpleFoo>
            <SimpleFoo><name>Meow Cat</name><foo>BarBar</foo></SimpleFoo>
        </CompoundFoo>
    </mx:XML>
    <mx:DataGrid dataProvider="{CompoundFoo.SimpleFoo}">
        <mx:columns>
            <mx:DataGridColumn headerText="Name" dataField="name" />
            <mx:DataGridColumn headerText="Foo" dataField="foo" />
        </mx:columns>
    </mx:DataGrid>
</mx:Application>

image

Using XML directly in a DataGrid is one of the fastest ways possible to display data in a Flex application, but what about maintainability? The XML in the DataGrid is a popular Flex example, but it is unrealistic. In a real world application that XML or data will most likely come from some external source, an external source which is subject to change. It is also likely that the data will be used in the application in more than once place, and its usage is likely to involve other customizations. It is also common for data to need to be converted to other types, such as with a String to a Date. Mapping XML to ActionScript classes and then using those classes makes change easier, especially if those mapped classes are used in several places throughout the application.

How is mapping XML to ActionScript better for change then mapping XML directly to several components like the DataGrid?

If you were to change any part of the XML from the first example, you would then have to change all of these references to it; the dataProvider, dataFields, and any other references. Use that XML in several places and you have several changes to make. These direct references to the XML are mapping, which can be spread out throughout components. If you use an ActionScript class to do the mappings, then all of your mappings are in the same place so it is easier to find and change. Since references are then to ActionScript classes you also gain the advantage of those references being type and name safe.

For example a reference to SimpleFoo.foo as XML would always compile whether it existed or not. If there were a class called SimpleFoo then access to the property foo would cause a compile error if it didn’t exist.

The following example shows the same DataGrid and XML, but this time the DataGrid is populated using an ActionScript class:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
    xmlns:valentino="valentino.*"
    xmlns:mx="
http://www.adobe.com/2006/mxml">
    <mx:XML xmlns="" id="xml">
        <CompoundFoo my_name="wii">
            <SimpleFoo><name>Moo Cow</name><foo>Bar</foo></SimpleFoo>
            <SimpleFoo><name>Meow Cat</name><foo>BarBar</foo></SimpleFoo>
        </CompoundFoo>
    </mx:XML>
   
<valentino:CompoundFoo id="compoundFoo" xml="{xml}" />
    <mx:DataGrid dataProvider="{compoundFoo.foos}">
        <mx:columns>
            <mx:DataGridColumn headerText="Name" dataField="{valentino.SimpleFoo.NAME}" />
            <mx:DataGridColumn headerText="Foo" dataField="{valentino.SimpleFoo.FOO}" />
        </mx:columns>
    </mx:DataGrid>
</mx:Application>

This example uses the ActionScript classes CompoundFoo and SimpleFoo to contain all the instructions for XML Mapping. In the event that the XML were to change the only places in the application that would have to change would be those mappings. All current references to that data throughout the application could remain the same.

The difference is where you do the mapping. FlexB places the mappings in the ActionScript classes so that those are the only places that have change.

How does the XML mapping work?

My preference would be to eventually have a factory class look at annotations of plain old ActionScript classes and do the mappings, but for right now I am providing a class to extend that gives this mapping functionality. Using inheritance also provides the ability to easily override all of the mapping behavior.

The following ActionScript class defines the node, attribute, and class mappings from a “CompoundFoo” XML document:

package valentino
{
    import net.sourceforge.flexb.core.IMap;
    import net.sourceforge.flexb.mapper.XmlMappedObject;

    [Bindable]
    public class CompoundFoo extends XmlMappedObject
    {
        public var myName:String;
        [ArrayElementType("valentino.SimpleFoo")]
        public var foos:Array = new Array();
        override protected function mapNodeToFunction(nodeToFunctionMap:IMap):void
        {
            nodeToFunctionMap.put("SimpleFoo", "foos");
        }
        override protected function mapAttributeNodeToFunction(attributeNodeToFunctionMap:IMap):void
        {
            attributeNodeToFunctionMap.put("my_name", "myName");
        }
        override protected function mapNodeToClass(nodeToClassMap:IMap):void
        {
            nodeToClassMap.put("SimpleFoo", SimpleFoo);
            nodeToClassMap.put("CompoundFoo", CompoundFoo);
        }
    }
}

The node to function mappings specify the name of each node and the set/get functions of the class to map to. For example when the node “SimpleFoo” is encountered during mapping its value is associated with the class property of “"foos.”

The node to attribute mappings specify the name of each attribute and the set/get functions of the class to map to. For example when the attribute “my_name” is encountered during the mapping its value is associated with the class property of “myName.”

The node to class mappings specify the name of each node and the associated ActionScript class. For example when the node “SimpleFoo” is encountered during the mapping its value is mapped as the “SimpleFoo” ActionScript class.

Behavior such as needed for the conversion of data can also be handled by using set/get functions instead of providing publically accessible class variables.

“SimpleFoo” is also a reference to another ActionScript class:

package valentino
{
    import net.sourceforge.flexb.core.IMap;
    import net.sourceforge.flexb.mapper.XmlMappedObject;

    public class SimpleFoo extends XmlMappedObject
    {
        public var name:String;
        public var foo:String;   
        public static const FOO:String = "foo";
        public static const NAME:String = "name";


        override protected function mapNodeToFunction(nodeToFunctionMap:IMap):void
        {
            nodeToFunctionMap.put(FOO, "foo");
            nodeToFunctionMap.put(NAME, "name");
        }
        override protected function mapNodeToClass(nodeToClassMap:IMap):void
        {
            nodeToClassMap.put("SimpleFoo", SimpleFoo);
        }
    }
}

What about web service mapping?

It is actually an HTTPService mapping, and it is just an easy way to get XML data from an external source and map it to an ActionScript class. In FlexB it is called XmlService.

There are 3 ways to use it:

1. Just like an HTTPService where you handle the ResultEvent and call the mapping functions.

<service:XmlService
        id="xmlServiceResultID"
        result="xmlServiceResult(event)"
        url="../testdata/CompoundFoo.xml" />

private function xmlServiceResult(event:ResultEvent):void
{

        var compoundFoo:CompoundFoo = new CompoundFoo();
        compoundFoo.map(XML(event.result));
}

2. Specify to handle an XmlResultEvent which does the mapping for you.

<service:XmlService
        id="xmlResultService"
        resultClass="{CompoundFoo}"
        xmlResult="onXmlResult(event)"
        url="../testdata/CompoundFoo.xml" />

private function onXmlResult(event:XmlResultEvent):void
{
        var compoundFoo:CompoundFoo = event.xmlMappedObject as CompoundFoo;
}

3. Specify a function to call with the mapped instance of the object.

<service:XmlService
        id="xmlFunctionService"
        resultClass="{CompoundFoo}"
        resultFunction="{xmlServiceXmlResult}"
        url="../testdata/CompoundFoo.xml" />

public function xmlServiceXmlResult(compoundFoo:CompoundFoo):void
{

}

Sunday, July 6, 2008

In Response to the Easiest Java XML Binding. What About XStream?

Originally I asked the following question in this posting:

I have an XML document and I want to use that document to populate a corresponding set of Java objects. This is a commonly encountered scenario when working with Java, so what is the easiest method for Java XML Binding that requires the least amount of code?

What do I want? The 5 requirements of Java XML laziness.

I then went on to explain past methods of XML binding in Java, and what it was that I was exactly looking for. To summarize that endeavor, I was unable to locate something that fit my exact needs:

  1. I don't want to have to manually iterate through XML documents and manually map values.
  2. I don't want to have to use XSD files.
  3. I don't want to have to use libraries for binding compilers to use external binding definitions to map to Java classes.
  4. I don't want to have to modify existing XML documents so that I can use them as beans.
  5. I want to be able to have class and class field names that are different then their corresponding XML node names.

What is available?

I was aware that something had to exist that did this; I just couldn't find it. I searched the usual places such as sourcefoge.net, google, java.sun.com and so on, but everywhere I went I was bombarded with results that didn't fit my exact needs. After posting regarding this conundrum and my solution to it, which was to contribute to the problem of too many Java XML bindings by creating my own, several recommendations were made to me. The following is a list of Java XML bindings that have used and that were recommended to me:

  • JAXB - Requires Java Web Services Developer Pack v1.1 or later and the use of XSD's to bind the corresponding XML to Java interfaces (http://java.sun.com/developer/technicalArticles/WebServices/jaxb/).
  • JiBX - Open source project that uses binding definition documents to describe how XML is mapped to Java objects at binding runtime, where enhanced class files generated by the binding compiler build objects from an XML input document and can be outputted as XML documents (http://jibx.sourceforge.net/).
  • SAX/DOM/JAXP/Xerces-J - These are all types of Java XML parsers that require the manual handling of XML documents, meaning that you have to [in general] manually map the values from an XML document to the corresponding Java object (http://www.cafeconleche.org/books/xmljava/chapters/ch05.html).
  • Spring Beans - Uses the Inversion of Control container from the Spring Framework in order to bind values from special "bean" xml documents to Java classes. This is not useful for reading a specific XML document, but it is the binding that is of interest ; the automatic mapping of XML value to Java object field. (http://jvalentino.blogspot.com/2007/10/introduction-to-spring-framework.html).
  • EJB Beans - Enterprise Java Beans are a subject unto themselves, far to broad for discussion here. What is important though as with the inversion of control container from the Spring Framework, is the ability to bind values from XML documents to Java object fields (http://java.sun.com/javaee/5/docs/tutorial/doc/bnblr.html).
  • Castor - Uses marshalling and unmarshalling to go from XML to POJO and POJO to XML. The documentation is unfinished, but from what I can gather in order to go from XML to POJO and POJO to XML the POJO needs to implement serializable, and if the XML node names do not match class field names a binding file has to be used (http://www.castor.org/xml-framework.html).
  • Codehaus XFire - Another method for going from XML to POJO and POJO to XML, and requires the use of XSD files to do so (http://xfire.codehaus.org/Aegis+Binding).
  • XStream - Another method for going from XML to POJO and POJO to XML, but instead of having to use XSD files and other forms of external mappings it allows the use of annotations for aliasing (http://xstream.codehaus.org/).

What about XStream?

As it turns out XStream was exactly was I was looking for; it meets my 5 requirements of Java XML laziness. So how does it work?

Consider an RSS 2.0 document and what it represents:

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Lift Off News</title>
    <link>http://liftoff.msfc.nasa.gov/</link>
    <description>Liftoff to Space Exploration.</description>
    <language>en-us</language>
    <pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
    <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <generator>Weblog Editor 2.0</generator>
    <managingEditor>editor@example.com</managingEditor>
    <webMaster>webmaster@example.com</webMaster>
    <ttl>5</ttl>
 
    <item>
      <title>Star City</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
      <description>How do Americans get ready to work with Russians aboard the
        International Space Station? They take a crash course in culture, language
        and protocol at Russia's Star City.</description>
      <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
    </item>
 
    <item>
      <title>Space Exploration</title>
      <link>http://liftoff.msfc.nasa.gov/</link>
      <description>Sky watchers in Europe, Asia, and parts of Alaska and Canada
        will experience a partial eclipse of the Sun on Saturday, May 31st.</description>
      <pubDate>Fri, 30 May 2003 11:06:42 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
    </item>
 
    <item>
      <title>The Engine That Does More</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
      <description>Before man travels to Mars, NASA hopes to design new engines
        that will let us fly through the Solar System more quickly.  The proposed
        VASIMR engine would do that.</description>
      <pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
    </item>
 
    <item>
      <title>Astronauts' Dirty Laundry</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
      <description>Compared to earlier spacecraft, the International Space
        Station has many luxuries, but laundry facilities are not one of them.
        Instead, astronauts have other options.</description>
      <pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
    </item>
  </channel>
</rss>

Document from http://en.wikipedia.org/wiki/RSS_(file_format)

An "rss" node has a "channel" node, a "channel" node has "item" nodes, and every node has their own properties and attributes. These relationships can then be represented in terms of objects using a class diagram (ignoring methods for getters and setters):

From this class diagram it is then possible to generate the corresponding Java classes, assuming that the class fields have the same names as their corresponding XML nodes. This can't always work though since class fields can be represented in XML as nodes or attributes of nodes, so it would be necessary to designate this in Java. You may also not want to have the Java class field names the same as the XML node names, so there would need to be a way to designate this as well. This is why there will always need to be some form of mapping, which is why XStream provides annotations and also methods for their service to specify aliasing at runtime.

Bad use of annotations?

With my previous posting where I used annotations in the same manner as XStream, there was discussion regarding whether this use of annotations was necessary. The answer is absolutely yes for two reasons:

  1. For when XML node names are not the same as class and class field names.
  2. In order to translate the representation of a class field as an XML node or XML node attribute.

Consider the following class and the following XML document:

public class Example {
 public String myValue;
 public String version;
}

<example ver="1.0">
 <my_value>value</my_value>
</example>

How would one map the XML to the class when the class name and the field names are different then the XML node names? While some XML documents may be able to have their class field names interfered based on similarities, types, and positions this would not work for all cases. This is one reason why annotations or other mechanisms are need to map between class fields and XML nodes.

Also consider when converting the class to XML, how would one determine whether a class field should be represented as an XML node or a node attribute? The following XML documents all could be used to represent the data in the Example class:

<example>
 <ver>1.0</ver>
 <my_value>value</my_value>
</example>

<example ver="1.0" my_value="value" />

<example my_value="value">
 <ver>1.0</ver>
</example>

How does XStream do what you need?

XStream allows the use of annotations or object aliasing methods to specify mappings and attributes. For example here is my previous RSS 2.0 POJP example marked up for XStream using annotations:

@XStreamAlias("rss")
public class Rss2 {
 @XStreamImplicit
 private List<Channel> channel;
 @XStreamAsAttribute
 private String version;
 
 //getters and setters go here...
}

@XStreamAlias("channel")
public class Channel {
 private String title;
 private String link;
 private String description;
 private String language;
 private String pubDate;
 private String lastBuildDate;
 private String docs;
 private String generator;
 private String managingEditor;
 private String webMaster;
 private int ttl;
 @XStreamImplicit
 private List<Item> item;
 
 //getters and setters go here...
}

@XStreamAlias("item")
public class Item {
 private String title;
 private String link;
 private String description;
 private String pubDate;
 private String guid;
 
 //getters and setters go here...
}

The following code can be used to populate an RSS object using XML:

XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(Rss2.class);

//Create an RSS object and populate it using an XML file
Rss2 rssA = new Rss2();
xstream.fromXML(new FileReader(new File("test/Rss2Test.xml")), rssA);

The following code can then be used to convert a POJO to XML:

String xml = xstream.toXML(rssA);

Why did you reinvent the wheel with your RE: JAXB project?

As I have said before I created a factory for binding XML to POJOs and back because I could not find anything at the time that suited my exact needs. To me it is really not that big of a deal, because it only took a single afternoon and only consisted of several hundred lines of code.

 

Monday, June 30, 2008

The Easiest Java XML Binding

I have an XML document and I want to use that document to populate a corresponding set of Java objects. This is a commonly encountered scenario when working with Java, so what is the easiest method for Java XML Binding that requires the least amount of code? You can't answer that question without first defining what "easy" is in relation to the bindings between Java and XML. To me "easy" is synonymous with "simple," so I am equating easiness to complexity. Complexity is of interest because things that are complex take longer to implement and are generally harder to maintain, based on my experiences with software in a variety of languages and platforms. Less code written means less code to maintain, and less code to write means less time is required to write that code.

So what are the methods for binding Java and XML?

  • JAXB - Requires Java Web Services Developer Pack v1.1 or later and the use of XSD's to bind the corresponding XML to Java interfaces (http://java.sun.com/developer/technicalArticles/WebServices/jaxb/).
  • JiBX - Open source project that uses binding definition documents to describe how XML is mapped to Java objects at binding runtime, where enhanced class files generated by the binding compiler build objects from an XML input document and can be outputted as XML documents (http://jibx.sourceforge.net/).
  • SAX/DOM/JAXP/Xerces-J - These are all types of Java XML parsers that require the manual handling of XML documents, meaning that you have to [in general] manually map the values from an XML document to the corresponding Java object (http://www.cafeconleche.org/books/xmljava/chapters/ch05.html).
  • Spring Beans - Uses the Inversion of Control container from the Spring Framework in order to bind values from special "bean" xml documents to Java classes. This is not useful for reading a specific XML document, but it is the binding that is of interest ; the automatic mapping of XML value to Java object field. (http://jvalentino.blogspot.com/2007/10/introduction-to-spring-framework.html).
  • EJB Beans - Enterprise Java Beans are a subject unto themselves, far to broad for discussion here. What is important though as with the inversion of control container from the Spring Framework, is the ability to bind values from XML documents to Java object fields (http://java.sun.com/javaee/5/docs/tutorial/doc/bnblr.html).

I have used all of these methods in depth before, but this isn't exactly what I want though:

  • I don't want to have to manually iterate through XML documents and manually map values.
  • I don't want to have to use XSD files.
  • I don't want to have to use libraries for binding compilers to use binding definitions to map to Java classes.
  • I don't want to have to modify existing XML documents so that I can use them as beans.

My usage of Adobe Flex (http://jvalentino.blogspot.com/2008/02/flex-tutorial-part-ii-language-concepts.html) over the last couple of years has spoiled my expectations for language and XML interaction; I want more with less.

I know exactly what I want: I want to have a series of Java objects that are representations of nodes within an XML document, and pass the XML document to the Java object representing the root XML node and have all of the corresponding Java objects populate using that XML. I then want to be able to go from Java back to XML, and I don't want to have to do anything other then say "XML, go to Java" and then "Java, go to XML."

Why should there need to be complex mappings and external definitions when Java and XML are being used to representing the same thing?

Consider an RSS 2.0 document and what it represents:

<?xml version="1.0"?>
<rss version="2.0">
  <channel>
    <title>Lift Off News</title>
    <link>http://liftoff.msfc.nasa.gov/</link>
    <description>Liftoff to Space Exploration.</description>
    <language>en-us</language>
    <pubDate>Tue, 10 Jun 2003 04:00:00 GMT</pubDate>
    <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <generator>Weblog Editor 2.0</generator>
    <managingEditor>editor@example.com</managingEditor>
    <webMaster>webmaster@example.com</webMaster>
    <ttl>5</ttl>
 
    <item>
      <title>Star City</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
      <description>How do Americans get ready to work with Russians aboard the
        International Space Station? They take a crash course in culture, language
        and protocol at Russia's Star City.</description>
      <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
    </item>
 
    <item>
      <title>Space Exploration</title>
      <link>http://liftoff.msfc.nasa.gov/</link>
      <description>Sky watchers in Europe, Asia, and parts of Alaska and Canada
        will experience a partial eclipse of the Sun on Saturday, May 31st.</description>
      <pubDate>Fri, 30 May 2003 11:06:42 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
    </item>
 
    <item>
      <title>The Engine That Does More</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
      <description>Before man travels to Mars, NASA hopes to design new engines
        that will let us fly through the Solar System more quickly.  The proposed
        VASIMR engine would do that.</description>
      <pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
    </item>
 
    <item>
      <title>Astronauts' Dirty Laundry</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
      <description>Compared to earlier spacecraft, the International Space
        Station has many luxuries, but laundry facilities are not one of them.
        Instead, astronauts have other options.</description>
      <pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
    </item>
  </channel>
</rss>

Document from http://en.wikipedia.org/wiki/RSS_(file_format)

An "rss" node has a "channel" node, a "channel" node has "item" nodes, and every node has their own properties and attributes. These relationships can then be represented in terms of objects using a class diagram (ignoring methods for getters and setters):

From this class diagram it is then possible to generate the corresponding Java classes, assuming that the class fields have the same names as their corresponding XML nodes. This can't always work though since class fields can be represented in XML as properties or attributes, so it would be necessary to designate this in Java. You may also not want to have the Java class field names the same as the XML node names, so there would need to be a way to designate this as well. One easy way to designate specific things about classes, fields, and methods is to use annotations, so consider the following 3 annotations:

  1. @ClassXmlNodeName - used on a Java class to specify its corresponding node name in an XML document. This is required in order to designate a class as being bound to an XML document.
  2. @XmlAttributeName - used on a Java field to specify its corresponding attribute name in an XML document. This is required in order to specify that a particular class field should be represented in XML as an attribute instead of a property.
  3. @XmlNodeName - used on a Java field to specify its corresponding node name in an XML document. This is only required when a Java class field name is different than its corresponding XML node name.
@ClassXmlNodeName("rss")
public class Rss {
 private List<Channel> channels;
 @XmlAttributeName("version")
 private String version;
 
 //getters and settings go here...
}

@ClassXmlNodeName("channel")
public class Channel {
 private String title;
 private String link;
 private String description;
 private String language;
 private String pubDate;
 private String lastBuildDate;
 private String docs;
 private String generator;
 private String managingEditor;
 private String webMaster;
 private int ttl;
 private List<Item> items;

 //getters and settings go here...
}

@ClassXmlNodeName("item")
public class Item {
 private String title;
 private String link;
 private String description;
     private String pubDate;
     private String guid;
    
     //getters and settings go here... 
}

With the exception of the annotations, these Java classes are just like any other data transfer objects (DTOs) that would be used to represent a RSS XML document. These annotations act as the mappings between Java and XML when names and types do not provide enough information. With this information, the class representing the XML document root node, and the XML document it is possible to recursively map XML nodes to Java class fields and Java class fields back to XML nodes using Reflection. So using Reflection I wrote a library that can take any Plain Old Java Object (POJO) and an XML document, and use that XML document to populate that object and all of its child objects using one line of code. The same can then be done to convert a Java object back to its XML representation using a single line of code. All of this assuming that the Java classes correspond to the XML document.

Using this "XML Binder" library the following code takes the the given instance of an Rss object and populates it and its channels and items using the given XML document:

Rss rss = new Rss();
XmlBinderFactory.newInstance().bind(rss, new File("Rss2Test.xml"));

The following code can then be used to take that same Rss object once changes have been made to it and converts it back to XML:

String xml = XmlBinderFactory.newInstance().toXML(rss);

I assert that this can work with most XML documents that have appropriate corresponding Java classes, but I have only tested it out so far with RSS 1.0, RSS 2.0, and a general test XML document in no particular format. The question now is what do I do with this library; anyone interested?

Since there seems to be some interest I have started a sourceforge.net project called "Really Easy Java XML Binding" or "RE:JAXB" since this is sort of a reply to JAXB. Here is the link

I have included POJOs for RSS 1.0 and RSS 2.0 along with unit tests to verify that the mappings from XML and to XML are working correctly. What I am looking for are ways to improve the efficiency of the to and from binding code, as well as POJOs for other common XML formats.

Saturday, May 17, 2008

The Flexsite

Social networking websites such as MySpace and Facebook have many common themes regarding the reasons for their popularity. One common theme in particular is that each website gives the average user the ability to have a persistent, customizable, and maintainable online presence. These websites though typically are intended for individual users, meaning that there is not anything equivalent for businesses. If a business wants a website they have to either already have someone or hire someone to build and maintain the website. The more visually appealing and interactive that a websites needs to be the higher the cost and the more difficult it is to maintain. Flexsite solves this problem by providing a highly configurable, visually appealing, inexpensive, and easily maintainable website that operates like familiar social networking websites for small businesses with all of the setup included.

Flexsite uses numerous web technologies in order to provide services and interact with existing services:

• HTML
• XML
• Flash
• DTD
• Flex
• RSS
• WordPress
• PayPal
• PHP
• MySQL
• JavaScript
• CSS

The Flexsite application itself is divided into systems based on function, which incorporate one or more of the previously listed technologies and/or third party services. The visuals for Flexsite are done as an Adobe Flex application, which communicates with other services specified by the XML layout vocabulary. All communication with the Adobe Flex application is done through XML as well. Of all of the systems only the XML layout vocabulary is required, everything else is optional and Flexsite can run without them. The following is a diagram of all the involved systems:

Figure 1: Systems

The XML layout vocabulary is just an XML document used to specify website sizing, sections, menu items, content, Flash skins, and web services. There is also a corresponding DTD which is used to validate the layout XML. For web services that support PHP there are Flexsite Services that can be used to manipulate the XML using an Adobe Flex graphical user interface.

Figure 2: Layout Manager

Flexsite also incorporates the use of Flash Skins for the look and feel of the website. Flash skins are CSS files that refer to Flex components instead of HTML tags, compiled into SWF format. Through the layout manager users can specify the Flash skin to use for the website. Users can select from a variety of pre-made Flash skins or build and upload their own.

Figure 3: Some Example Flash Skins

There is also a Pay Per Download system that allows a web master to specify files that are available to download and how much they want to charge to download those files. This works by linking to PayPal through the Instant Payment Notification (IPN) API, which provides the user the file to download after successful payment. The user is then emailed a dynamic URL which can be used to download the file up to 24 hours after purchase.

Figure 4: Pay Per Download System

WordPress is a state-of-the-art publishing platform with a focus on aesthetics, web standards, and usability (WordPress.org). Flexsite has the ability to integrate WordPress, so that it can be used to manage the content that the site displays. WordPress supports multiple users with varying account permissions so that site content can be concurrently managed by multiple users. Another benefit of using WordPress is that is accessible to all levels of users since it operates like many familiar Word Processors, and it doesn’t require the download of installation of any software.

Figure 5: WordPress HTML Editor

Flexsite is also used to host its own website, and particular to this installation there is another PayPal integration that allows users to pay for Flexsite hosting services through the website. A graphical user interface is provided which displays all of the service pricing, and allows the user to select a domain name as well as a starting Flash skin for their new website.

Figure 6: Buying Hosting Services

The result is visually appealing and easily maintainable website that doesn’t require the installation of any software, and doesn’t require computer knowledge beyond that of operating a Word Processor. This technology is also accessible to everyone since it cost about the same as regular hosting, but includes the setup, domain name registration, website setup, WordPress setup, and customization.

www.theflexsite.com and www.theflexsite.net

 

Saturday, February 9, 2008

The Flex Tutorial: Part II - Language Concepts and Basics

The two languages of Flex

The Flex language consists of two flavors: ActionScript 3 and XML. ActionScript is a scripting language based on ECMAScript (JavaScript), used primarily for the development of websites and software using the Adobe Flash Player platform (http://en.wikipedia.org/wiki/ActionScript). The Extensible Markup Language (XML) is a general-purpose markup language, which is classified as an extensible language because it allows its users to define their own elements (http://en.wikipedia.org/wiki/XML). In Flex ActionScript files have the extension ".as" while the XML files have the extension ".mxml."

XML is used in Flex to represent static objects such as a button on a graphical user interface or an HTTP Service. For graphical user interface this provides a fast and efficient way of laying out components. For example consider an application that consists or a single panel and a single button:

Using MXML this would require the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
 <mx:Panel width="250" height="200" layout="vertical" horizontalAlign="center" 
 verticalAlign="middle" title="This is a panel">
  <mx:Button label="This is a button"/>
 </mx:Panel>
</mx:Application>

In this Flex (MXML) code you are essentially creating an Application with a vertical layout that contains a Panel with some size, layout, and text attributes. The panel then contains a Button with some text. This is easy to conceptualize since the in the code the application contains the panel, which then contains the button.

Using Java this same equivalent application would require the following code:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.BorderFactory;
import java.awt.Color;

public class Application extends JFrame {
    
    public static void main(String[] args) {
        JFrame frame = new Application();
        frame.setSize(400,400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public Application() {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(Color.black), 
            "This is a panel"));
        JButton button = new JButton("This is a button");
        panel.add(button);
        setContentPane(panel);
    }
}

In the Java code the concept remains the same, that an Application contains a Panel that contains a Button, but the code is not as easy to read (even when ignoring the extra stuff that was thrown in there to close the frame and set the border).

This just serves an example of how much less coding and complexity there is with constructing graphical user interface in MXML than with other object oriented languages. Less complexity means that the application will be easier to maintain, which is extremely important considering that the vast majority of time in the software lifecycle is spent in maintenance. Complexity is not only reduced with Flex and the layout out of graphical user interface components, Flex has numerous other features that do the same across the entire framework.

Though Flex is less complex that doesn't mean that it loses any capability. The genius of Flex is its ability to represent the same conceptual models as in other object oriented languages, only with less code and complexity. Consider the class diagrams of the example Flex and Java applications:

The same relationships are maintained: an application has a panel that has a button. Flex can be used to represent almost any object oriented design exactly. I use the term "almost" because ActionScript 3 currently doesn't support abstract classes.

Flex also has the ability to represent objects using ActionScript, which can be used in place of or in conjunction with MXML. For example you could create a "Person" ActionScript class and use it to represent data in an MXML component. The actual instantiation and value assignments of the "Person" class could then be done in either MXML or ActionScript.

The following is an ActionScript representation of a "Person" class:

package example.data
{
 public class Person
 {
  public var firstName:String;
  public var lastName:String;
  public var favoriteFood:String;
 }
}

Inside XML this class could be instantiated (assuming the class was included as "ex") like so:

<ex:Person id="person" firstName="John" lastName="Valentino" favoriteFood="Steak"/>

Inside of ActionScript this class could be instantiated like the following:

var person:Person = new Person();
person.firstName = "John";
person.lastName = "Valentino";
person.favoriteFood = "Steak";

 

What the heck are you doing? Where are the getters and setters?

Getters and setters are something that I feel have gotten a bit out of hand in object-oriented programming. The purpose of using getters and setters is to decouple objects and to provide hidden functionality when assigning values to attributes of objects. For example if the "Person" class contained an instance of "Person" called "child" you probably wouldn't want to make it (and all of its attributes) publicly accessible to prevent coupling. An example of hidden functionality would be if you wanted to check modify special characters in the first and last names when setting their values.

No matter how you or I feel about getters and setters and their under usage or over usage, Flex provides its own special functions for getters and setters. This allows classes to define methods to handle the getting and setting of attributes within classes, but those functions can be called (by lazy programmers like myself) as if they were publicly accessible attributes.

Consider the "Person" class redone to use the special get and set functions:

package example.data
{
 public class PersonII
 {
  private var _firstName:String, _lastName:String, 
        _favoriteFood:String;
  
  public function get firstName():String
  {
   return _firstName;
  }
  
  public function get lastName():String
  {
   return _lastName;
  }
  
  public function get favoriteFood():String
  {
   return _favoriteFood;
  }
  
  public function set firstName(value:String):void
  {
   _firstName = value;
  }
  
  public function set lastName(value:String):void
  {
   _lastName = value;
  }
  
  public function set favoriteFood(value:String):void
  {
   _favoriteFood = value;
  } 
 }
}

These special get and set functions are what allow these functions to be called as if they were attributes. Using this new person classes the example instantiations in MXML and ActionScript to not need to be changed; they work the same as before.

Inside XML this class could be instantiated (assuming the class was included as "ex") like so:

<ex:PersonII id="person" firstName="John" lastName="Valentino" favoriteFood="Steak"/>

Inside of ActionScript this class could be instantiated like the following:

var person:PersonII = new PersonII();
person.firstName = "John";
person.lastName = "Valentino";
person.favoriteFood = "Steak";

 

Bringing MXML and ActionScript together

One of the most important concepts in Flex is that every object has 2 aspects: the XML and the ActionScript. In a constant effort to eliminate complexity I have found that XML is preferable to ActionScript in most situations. A good rule of thumb to know when to use what is to ask yourself the question "Can I do this in MXML?" If the answer is no than you can go with ActionScript, otherwise stick with MXML to cut down on code size and complexity. You must exercise common sense though; if you find yourself having to do something that seems unintuitive in MXML than you should probably use ActionScript.

Typically in graphical user interface components ActionScript is used within MXML components. This allows graphical user interfaces to be statically laid out in MXML, and then use ActionScript to handle complex logic. For example consider the original example application that has been modified to use ActionScript to display a message when a button is pressed:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

 <mx:Script>
  <![CDATA[
  import mx.controls.Alert;

  private function buttonPressed():void
  {
   Alert.show("The button was pressed");
  }
  ]]>
 </mx:Script>

 <mx:Panel width="250" height="200" layout="vertical" horizontalAlign="center" 
  verticalAlign="middle" title="This is a panel">
  <mx:Button label="This is a button" click="buttonPressed()"/>
 </mx:Panel>
</mx:Application>

Now when the button is pressed the following message is displayed:

 

Binding

One of the most important features of Flex is the ability to bind objects to components. This is basically instant model-view-controller without having to use listeners or worry about observers and observables. A common need in programming graphical user interfaces is the ability to display some type of information to the user through some sort of component, that is then updated through some event. For example consider a series of text fields that display information about a person:

The following code shows how the data is bound to different fields within the graphical user interface:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" 
 title="Person Panel" horizontalAlign="center">

 <mx:Script>
  <![CDATA[

  [Bindable]
  private var firstName:String = new String();
  [Bindable]
  private var lastName:String = new String();
  [Bindable]
  private var favoriteFood:String = new String();

  private function john():void
  {
   firstName = "John";
   lastName = "Valentino II";
   favoriteFood = "Steak";
  }

  private function sarah():void
  {
   firstName = "Sarah";
   lastName = "Valentino";
   favoriteFood = "Pizza";
  }

  ]]>
 </mx:Script>
 <mx:Form width="100%">
  <mx:FormItem label="First Name:">
   <mx:TextInput text="{firstName}"/>
  </mx:FormItem>
  <mx:FormItem label="Last Name:">
   <mx:TextInput text="{lastName}"/>
  </mx:FormItem>
  <mx:FormItem label="Favorite Food:">
   <mx:TextInput text="{favoriteFood}"/>
  </mx:FormItem>
 </mx:Form>
 <mx:HBox>
  <mx:Button label="John" click="john()"/>
  <mx:Button label="Sarah" click="sarah()"/>
 </mx:HBox>

</mx:Panel>

The variables firstName, lastName, and favoriteFood, are made "Bindable" so that when ever they are changed anything that is referencing them is also changed. This means that since those variables are referenced by the TextInputs, when those variables are changed what is displayed in those TextInputs will also change.

For example the following is displayed when the "John" button is pressed:

The following is displayed when the "Sarah" button is pressed:

It should also be noted that if you declare instances in MXML that are automatically bindable, so the following example retains the same functionality:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" 
 title="Person Panel" horizontalAlign="center">
 
 <mx:String id="firstName"/>
 <mx:String id="lastName"/>
 <mx:String id="favoriteFood"/>

 <mx:Script>
  <![CDATA[

  private function john():void
  {
   firstName = "John";
   lastName = "Valentino II";
   favoriteFood = "Steak";
  }

  private function sarah():void
  {
   firstName = "Sarah";
   lastName = "Valentino";
   favoriteFood = "Pizza";
  }

  ]]>
 </mx:Script>
 <mx:Form width="100%">
  <mx:FormItem label="First Name:">
   <mx:TextInput text="{firstName}"/>
  </mx:FormItem>
  <mx:FormItem label="Last Name:">
   <mx:TextInput text="{lastName}"/>
  </mx:FormItem>
  <mx:FormItem label="Favorite Food:">
   <mx:TextInput text="{favoriteFood}"/>
  </mx:FormItem>
 </mx:Form>
 <mx:HBox>
  <mx:Button label="John" click="john()"/>
  <mx:Button label="Sarah" click="sarah()"/>
 </mx:HBox>

</mx:Panel>

If you want to use binding with a custom class however, such as with the Person class, you have to declare the class itself or its individual attributes as bindable. This allowing the class to be bound, but the instance still has to be declared as bindable. For example consider the bindable Person class:

package example.data
{
 [Bindable]
 public class Person
 {
  public var firstName:String;
  public var lastName:String;
  public var favoriteFood:String;
 }
}

To use the bindable Person class in the application example the Person instance has to be marked as "Bindable." The following is the application redone to use the Person class:

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" 
 title="Person Panel" horizontalAlign="center">

 <mx:Script>
  <![CDATA[
  import example.data.Person;
  
  [Bindable]
  private var person:Person = new Person();

  private function john():void
  {
   person.firstName = "John";
   person.lastName = "Valentino II";
   person.favoriteFood = "Steak";
  }

  private function sarah():void
  {
   person.firstName = "Sarah";
   person.lastName = "Valentino";
   person.favoriteFood = "Pizza";
  }

  ]]>
 </mx:Script>
 <mx:Form width="100%">
  <mx:FormItem label="First Name:">
   <mx:TextInput text="{person.firstName}"/>
  </mx:FormItem>
  <mx:FormItem label="Last Name:">
   <mx:TextInput text="{person.lastName}"/>
  </mx:FormItem>
  <mx:FormItem label="Favorite Food:">
   <mx:TextInput text="{person.favoriteFood}"/>
  </mx:FormItem>
 </mx:Form>
 <mx:HBox>
  <mx:Button label="John" click="john()"/>
  <mx:Button label="Sarah" click="sarah()"/>
 </mx:HBox>

</mx:Panel>

 

Wednesday, January 9, 2008

The Flex Tutorial: Part I - Setup and Organization

What is this tutorial?

"Flex development" refers to the use of the Adobe Flex to develop web applications that are deployed in the Adobe Flash runtime. The term "Enterprise" in the context of software development is usually used to indicate that something is large-scale, supports a large user base, and consists of many different systems or services. So I use the term "Flex Enterprise Development" to refer to large-scale flex web applications with emphasis on taking advantage of Flex features such as Data Binding and Web Services, and the use of architectures such as SOA, Three-Tier, and MVC. In particular Data Binding can be used to easily implement a MVC framework in an application with little to no extra code, and on a larger scale a combination of  Three-Tier and SOA can be used to organize components and make a system easily scalable. This tutorial intends to explain how to setup a development environment, show the important features of the Flex language, and show how to organize and implement small to large-scale systems.

Setting up a Flex Development Environment

In terms of treating web systems as three-tier architectures, meaning that on a high level they can be divided into presentation, service, and data tiers, Flex applications reside in the presentation tier. This means that for servicing it is required that server side scripting languages are used. Flex is not dependent on a single server side scripting language though, since Flex provides the ability to work with data formats such as WSDL, SOAP, Remote Objects, and HTTP Services. I tend to prefer using HTTP Services since is is just plain XML that you can define yourself without headers or envelopes, and is not specific to scripting language remote object technologies.

Adobe provides a free SDK for Flex, but the Flex Builder development environment (http://www.adobe.com/products/flex/flexbuilder/) is a huge time saver since it allows you to rapidly develop GUIs by dragging and dropping pre-made components and editing them accordingly. The first step for setting up a development environment is therefore to download and install Flex Builder.

The next step is to install and configure some sort of web service so that you can develop web services using a server side scripting language. You should also be aware that this choice will also affect which database you can use if you choose to use one. You should take into account that if you intend to deploy your system on someone else's hardware, meaning a web hosting service, you want to setup a similar environment. You should also be aware that most hosting services such as GoDaddy.com provide two options: a Windows (IIS) hosting plan that includes ASP/.NET with MS SQL and MS Access, and a Linux (Apache) hosting plan that includes PHP with MySQL. If you want to use something else like J2EE or ColdFusion you will need use a less traditional web hosting service or use your own hardware.

Personally I run IIS on port 80, Apache on port 8000, and JAS (Java Application Server for J2EE) on port 8080 on my Windows XP MCE laptop. I would like to point out though that setting up IIS on Windows XP MCE was difficult because of a lot of missing components and other issues that can be found with a quick web search. Apache is both free and easy to install, and I actually pointed its PHP services to the same one that I use for IIS, but there is really no need to have more than one web service and server side scripting language unless you are using more than one.

If you want to use IIS you have to be running Windows XP Pro or MCE, and can get it by putting in the Windows Installation CD and choosing to add IIS as an additional component. If you want to use Apache you can download it from the Apache website at http://httpd.apache.org/. IIS comes .NET and ASP ready which cannot used at all on Apache, but both Apache and IIS can be configured to use PHP. PHP can be downloaded for both Windows and Linux at http://www.php.net/downloads.php, along with instructions for how to configure on both IIS and Apache. If you want to use Java you can ether download JAS from http://java.sun.com/ along with the NetBeans IDE, or you can download Tomcat from http://tomcat.apache.org/.

For PHP, Java, and JSP though I prefer to use the Eclipse IDE. The Eclipse IDE can be downloaded from http://www.eclipse.org/downloads/, and comes with the ability to do Java. If you want to do PHP you can download a free plug-in from http://www.zend.com/en/community/pdt, and if you want to do JSP I recommend paying for the MyEclipse plug-ins at http://www.myeclipseide.com/.

Once you have decided on web services and language you will end up with with two IDEs: FlexBuilder and one dedicated to your server side scripting language of choice.

Setting up a Project

You want to create a project directory (through FlexBuilder) in your web root directory. Your web root directory is the directory setup to run web services you your computer. If you are running IIS the default web root directory is C:\inetpub\wwwroot, on Apache Windows the default directory is C:\Program Files\Apache Software Foundation\Apache2.2\htdocs, and on Apache Linux the default directory is /var/www/html/. All of these locations correspond to http://localhost/ using the web service that you are running.

You want to layout your project directory as follows:

- <Project Directory>: HTML page and scripts that execute your Flash SWF.
 - src: Flex source code, MXML and AS
 - html-template: templates for generating the HTML page used to run the Flash
 - service: service side scripting used to represent web services
 - data: data structure representations used by the server side scripting
 - settings: miscellaneous files for static content, for example CSS, a web services list...

It should also be noted that for larger projects the web servicing (the server side scripting in the service and data directories) may be located on another machine. In order for your Flex application to access content in an external location on the web, the root web directory of the server

This can be initiated in Flex Builder by specifying your root web directory as the workspace and creating a new project there. Then in the "New Flex Project" window specify the main source folder as "src" and the output folder as blank.

Once the project is created you also have to make sure that the runtime settings point to the HTTP location of the SWF file instead of the File location. This is done by changing the "URL or path to launch" in the Run Dialog for the project.

Laying Out the GUI

Once the project is created there is a single MXML file in your "src" directory, which is the root of the application. From this point it is best to divide up your application into packages based on sub-systems, presentation tier components, and classes used to represents data. It should also be noted that for larger applications you may want to separately group classes related to HTTP and other web services. For example if you had an application with several detailed panels, you may want to break each detailed panel into a separate class. The following is an example directory structure a flex application that divides it components by the following groups: Core Components (core), User Management Components (user), and Example (example)

- src: This is the source code directory
 - core: custom components used by all packages
  * MyFancyButton.mxml
 - user: components related for managing user accounts
  - data: data structures related to user components
   * UserRecord.as
  - interfaces: interfaces used for communicating with the user components
   * LoginInterface.as
   * ManageAccountInterface.as
  * LoginPanel.mxml
  * ManageAccountPanel.mxml
 - example: general components used for demonstrating Flex abilities
  - data: data structures used for the example components
   * CDRecord.as
  * WelcomePanel.mxml
 * MyProject.mxml

For example consider layout our a basic application that will display only the welcome screen as a custom component. First you would layout the entire GUI minus the welcome panel, which may look something like the following:

Next make a simple component named "WelcomePanel.mxml" in the "example" directory that inherits from "Panel."

Using State Transitions

Now that the application is laid out and there is a custom component that can be used, a state transition can be used to add the custom component to the application. In the "MyProject.mxml" component there is a "States" box that has a single state listed, which is the base state.

If you right-click on the base state and select the option to create a "New State," you can create a state called "WelcomeState" which can be used to display the welcome panel.

With the "WelcomeState" selected you can then drag and drop the "WelcomePanel" onto the "MyProject" component:

If you then reselect the base state the welcome panel will disappear, because the application goes back to its original state. If in the base state you select the welcome button from the menu panel and specify the "click" attribute to be "currentState='WelcomeState", when the welcome button is pressed the application will move from the base state to the "WelcomeState."

 

Contributors