A blog about software development and other software related matters

Blog Archive

Showing posts with label Flex. Show all posts
Showing posts with label Flex. Show all posts

Saturday, August 30, 2008

AMF serialization from Java to Flex and back

There are some scenarios in which you want to pass objects to and from a Flex application to a Java back end, if your using an Adobe framework (LCDS or BlazeDS) than you get this functionality out of the box however there are some cases that you wish to escape Adobe's grip and uses some third party technology.
Some solutions that may come to mind are JSon or XML, the problem with these solutions is that they may require a lot of bandwidth and even lots of computing power for complex objects graphs, AMF to the rescue.
AMF is a binary protocol which is used natively by the flash player, with the release of BlazeDS it was made accessible to any Java client that wishes to use it, in order to use AMF we need to serialize an object into bytes and pass it as the payload of any protocol that we choose, the easiest way to do so is to encode the resulting AMF bytes into BASE64 encoding (a format that transforms byte arrays into a readable string form) and append it to the existing payload.
Ill start with the Java side first:


import com.google.inject.Inject;
import flex.messaging.endpoints.BaseHTTPEndpoint;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
*
* @author ronen
*/
public class AmfSerializer {

@Inject
private SerializationContext context;

public <T> String toAmf(final T source) throws IOException {
final StringBuffer buffer = new StringBuffer();
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final Amf3Output amf3Output = new Amf3Output(context);
amf3Output.setOutputStream(bout);
amf3Output.writeObject(source);
amf3Output.flush();
amf3Output.close();
final BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bout.toByteArray());
}

public <T> T fromAmf(final String amf) throws ClassNotFoundException, IOException {
final BASE64Decoder decoder = new BASE64Decoder();
byte[] input = decoder.decodeBuffer(amf);
InputStream bIn = new ByteArrayInputStream(input);
Amf3Input amf3Input = new Amf3Input(context);
amf3Input.setInputStream(bIn);
return (T) amf3Input.readObject();
}
}


This code uses BlazeDS API (the messaging-core, messaging-common and messaging-remoting jars) in order to serialize an object of type T into AMF byte array the bytes are encoded to a Base64 string, encoding result of an instance of the following VO:


package com.jdftm.vo;

import java.util.Date;

public class CurrentDayVO {

private Date now;

public CurrentDayVO() {
}

public void setNow(Date now) {
this.now = now;
}

public Date getNow() {
return now;
}
}


might look something like ChMzY29tLmpkZnRtLnZvLkN1cnJlbnREYXlWTwdub3cIAUJrjUw54AAA.

Now lets turn to the Flex side:


package com.jdftm.stomp.interop {
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
import mx.utils.Base64Decoder;

public class AMFSerializer {
public function serializeToString(value:Object):String{
if(value==null){
throw new Error("null isn't a legal serialization candidate");
}
var bytes:ByteArray = new ByteArray();
bytes.writeObject(value);
bytes.position = 0;
var be:Base64Encoder = new Base64Encoder();
be.encodeBytes(bytes);
var res:String = be.toString();
be.reset();
return res;
}

public function readObjectFromStringBytes(value:String):Object{
var dec:Base64Decoder=new Base64Decoder();
dec.decode(value);
var result:ByteArray=dec.drain();
result.position=0;
return result.readObject();
}
}
}


The logic is quite similar to the Java side code however when using the AMFSerializer we must register the serialized classes prior to serializing them:


registerClassAlias("com.jdftm.vo.CurrentDayVO", CurrentDayVO);


Failing to so will cause the de-serialization process (on both sides) to fail since it uses the alias in order to create the resulting instance object, its also required that the serialized classes on both ends to be in the same package as implemented in the CurrentDayVO Flex class:


package com.jdftm.vo{
[Bindable]
[RemoteClass(alias="com.jdftm.vo.CurrentDayVO")]
public class CurrentDayVO{
private var _now:Date;

public function get now():Date{
return _now;
}

public function set now(value:Date):void{
_now=value;
}
}
}


As youv seen AMF isn't to hard to use and may prove to be a powerful contender in the crowded integration protocols market.

Updated 2/09/08
Here is the SerializationContext implementation which is used in the Java serialization class


import com.google.inject.Provider;
import flex.messaging.io.SerializationContext;

public class SerializationContextProvider implements Provider<SerializationContext> {

@Override
public SerializationContext get() {
SerializationContext serializationContext = SerializationContext.getSerializationContext();// Threadlocal SerializationContent
serializationContext.enableSmallMessages = true;
serializationContext.instantiateTypes = true;
serializationContext.supportRemoteClass = true;// use _remoteClass field
serializationContext.legacyCollection = false;// false Legacy Flex 1.5 behavior was to return a java.util.Collection for Array, New Flex 2+ behavior is to return Object[] for AS3 Array
serializationContext.legacyMap = false;// false Legacy flash.xml.XMLDocument Type
serializationContext.legacyXMLDocument = false;// true New E4X XML Type
serializationContext.legacyXMLNamespaces = false;// determines whether the constructed Document is name-space aware
serializationContext.legacyThrowable = false;
serializationContext.legacyBigNumbers = false;
serializationContext.restoreReferences = false;
serializationContext.logPropertyErrors = false;
serializationContext.ignorePropertyErrors = true;
return serializationContext;

/*
serializationContext.enableSmallMessages = serialization.getPropertyAsBoolean(ENABLE_SMALL_MESSAGES, true);
serializationContext.instantiateTypes = serialization.getPropertyAsBoolean(INSTANTIATE_TYPES, true);
serializationContext.supportRemoteClass = serialization.getPropertyAsBoolean(SUPPORT_REMOTE_CLASS, false);
serializationContext.legacyCollection = serialization.getPropertyAsBoolean(LEGACY_COLLECTION, false);
serializationContext.legacyMap = serialization.getPropertyAsBoolean(LEGACY_MAP, false);
serializationContext.legacyXMLDocument = serialization.getPropertyAsBoolean(LEGACY_XML, false);
serializationContext.legacyXMLNamespaces = serialization.getPropertyAsBoolean(LEGACY_XML_NAMESPACES, false);
serializationContext.legacyThrowable = serialization.getPropertyAsBoolean(LEGACY_THROWABLE, false);
serializationContext.legacyBigNumbers = serialization.getPropertyAsBoolean(LEGACY_BIG_NUMBERS, false);
boolean showStacktraces = serialization.getPropertyAsBoolean(SHOW_STACKTRACES, false);
if (showStacktraces && Log.isWarn())
log.warn("The " + SHOW_STACKTRACES + " configuration option is deprecated and non-functional. Please remove this from your configuration file.");
serializationContext.restoreReferences = serialization.getPropertyAsBoolean(RESTORE_REFERENCES, false);
serializationContext.logPropertyErrors = serialization.getPropertyAsBoolean(LOG_PROPERTY_ERRORS, false);
serializationContext.ignorePropertyErrors = serialization.getPropertyAsBoolean(IGNORE_PROPERTY_ERRORS, true);
*/
}
}



This is the guice provider which is used when creating such contexts.

Tuesday, May 20, 2008

From ugly to usefull

Iv encountered a troubling error in Flex remote services, those of you who are familiar with Flex remote Java services know that results of remote services are serialized into Action script objects by the Flex framework so that the RIA client may consume them.
The problem is that due to some weird reason Java Float values are not converted properly into Numeric objects, for example a float value of 1.51 on the server side will be converted into 1.5099999904632568 Numeric value on the client side.
This is actually the same value of new Float(1.51).doubleValue() in Java which leads me to believe that Flex takes float values and converts them into double values (a stupid floating point error).
The only solution that iv found is to return only double values from the server.

On a different note iv stumbled on this nifty called terminator, this tool enables the division of a single bash window into multiple ones (very useful for those multiple ssh sessions) it made me think where else such an approach could work nicely (Firefox?), anyway check it out!

Monday, April 21, 2008

Making FunFx Flex 2 compatible

Moving to the latest and greatest software version in the enterprise takes time, Flex 3 came out not long ago and so did FunFx which a really cool tool for Flex integration testing.
FunFx got compiled with Flex 3 SDK which means that it won't run with Flex 2 projects out of the box, the developer does states that its possible to compile it from source with Flex 2 SDK however the procedure isn't trivial and took me some trial and error that i hope to save for the rest of you out there.
In order to get a Flex 2 compatible FunFx will need to compile the FunFxAdapter which is a swc library that any testable RIA has to depended upon, go ahead and grab its source from here, create a swc project within Flex builder called FunFxAdapter and add the source.
Now open the project properties and add in the following dependencies to the compiler options (your paths may vary):

 
-include-libraries "/Applications/eclipse 3.2.2/Adobe Flex Builder 3 Plug-in/sdks/2.0.1/frameworks/libs/automation.swc" "/Applications/eclipse 3.2.2/Adobe Flex Builder 3 Plug-in/sdks/2.0.1/frameworks/libs/automation_agent.swc"

The compiler options should look like:



Unfortunately the FunFxAdapter project depends upon the automation.swc library which was not a part of the Flex 2 SDK (it was introduced in Flex 3 SDK but this version isn't binary compilable with Flex 2 SDK), if your project is a legacy Flex 2 project than its most likely that you have access to this swc.
Compile the project and grab the compiled swc from the bin folder of the project, when adding it to the test target application you'll need to add some more dependencies in order to make it work with the compiled FunFxAdapter swc:
 
-include-libraries "/Users/ronen/Documents/workspace/FunFXAdapter/bin/FunFXAdapter.swc" "/Applications/eclipse 3.2.2/Adobe Flex Builder 3 Plug-in/sdks/2.0.1/frameworks/libs/automation.swc" "/Applications/eclipse 3.2.2/Adobe Flex Builder 3 Plug-in/sdks/2.0.1/frameworks/libs/automation_agent.swc" "/Applications/eclipse 3.2.2/Adobe Flex Builder 3 Plug-in/sdks/2.0.1/frameworks/locale/ja_JP/automation_agent_rb.swc"

hopefully iv saved your valuable time.
After publish comment:
Iv forgot to mention that you should add the AutomationGenericEnv.xml file to the src directory of the main project module and to the application folder under tomcat (a standard FunFx requirements also in the Flex 3 version).

Sunday, March 23, 2008

Entering the Flex realm (with Spring & Cairnagorm)

In this post ill present Flex development combined with the Cairngorm micro architecture & Spring IOC, it should provide an easy stepping point to any Java developer who wishes to get acquainted with the above.
Ill follow along these action items:

  • Flex server side setup & Spring related configuration.
  • Client side setup including Caringorm, Caringen & FlexBuilder.
  • Simple demo application client side walk through.
  • Simple demo application server side walk through.

Server side setup

Flex applications may be deployed on any Java container that supports War deployment, in order to keep things simple will stick with Tomcat.
Flex enabled War contains not only the default folders and files but also Flex configuration files & Jars, an easy way of getting a working skeleton of such a War is by using the BlazeDS binary distribution (an OSS project which provides the connectivity between Java remote services and Flex RIAs).
All that we need to do is to place the packaged blazeds.war that weve just downloaded into the webapps directory and start tomcat up (bin/./catalina.sh run), tomcat will unpack the War into its exploded form which will use as our base War to work with.
Stop tomcat & take a look at the webapps/blazeds/WEB-INF directory, it contains all the usual files and folders that you might expect with the following exceptions:
  • The lib folder contains flex Jars.
  • A new flex folder was added it contains flex configuration files.
  • Flex servlet & session definitions were added to the web.xml file.

Delete the compressed war (we don't need it anymore), will move on to configure Spring by getting Spring Jar and placing it into the WEB-INF/lib folder & by adding the following lines to the web.xml file (these will tell tomcat to bootstrap the spring environment):
     
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Create the following applicationContext.xml file under WEB-INF:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Add your spring beans here -->
</beans>

Now its time to integrate Spring & Flex:
  • Download the following zip file & copy the bin/flex folder into the WEB-INF/classes folder, this folder contains a factory class that enables Flex RIAs to access remote Spring managed beans services.
  • Add the following lines to flex/services-config.xml file (making Flex aware to the Spring factory):
<services-config>
<!-- Rest unchanged -->
<factories>
<factory id="spring" class="flex.samples.factories.SpringFactory"/>
</factories>
</services-config>

Client side and Development environment setup


Will use FlexBuilder eclipse plugin in order to obtain Flex SDK and IDE support (you can use it freely for 60 days), first will create a Flex project with the presented settings:







Notice that in the last screen iv imported the Cairngorm.swc which is an external library (similar to a Jar), Cairngorm provides a structured architecture to use when developing Flex applications (basically conventions that tell what should go where), one of the best introductions to Cairngorm is available on David Tucker's blog.
In order to make things less tedious will use Cairngen in order to generate the basic Cairngorm folder & files structure (ala rails), Cairngen is ant based and only requires you to change a small number of properties in the project.properties to get going, for our project will use the following ones (remember to adjust the paths):
################################# PROJECT PROPERTIES ##################################
project.name =FlexMusicArchiver
root.dir =/Users/ronen/Documents/workspace/FlexMusicArchiver/src
com.dir =com
domain.dir =ronen
project.dir =MusicArchive
cairngorm.version =2.2.1

################################# CREATING SEQUENCES ##################################
sequence.name =GetAlbumList

################################### CREATING VOs ######################################
vo.name =Album

#################### ENABLE REGISTER REMOTE CLASS META-DATA IN VO #####################
vo.remoteClass =false

############################### READ / WRITE MANAGEMENT ###############################
overwrite.files =false
prompt.on.delete =true

################################## LOG MODIFICATIONS ##################################
log.output =true

################################ PROTECTED PROPERTIES #################################
namespace =${com.dir}.${domain.dir}.${project.dir}
project-uri =${root.dir}/${com.dir}/${domain.dir}/${project.dir}


Simple demo application client side walk through


Fire up ant under Caringen folder, the basic project structure will get generated:


The FlexMusicArchiver.mxml file serves as the main entry point to the application, paste in the following code lines into it:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:control="com.ronen.MusicArchive.control.*"
xmlns:business="com.ronen.MusicArchive.business.*"
layout="absolute" xmlns:view="com.ronen.MusicArchive.view.*">

<!-- The component that contains remote services declerations-->
<business:Services/>
<!-- The application contoler which stores events to commands mappings-->
<control:FlexMusicArchiverController/>
<!-- A simple view component-->
<view:AlbumsList/>

</mx:Application>


Now create a new Flex component named AlbumsList.mxml under the view folder and add in these code lines:
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%" >
<mx:Script>
<![CDATA[
import mx.controls.Image;
import com.ronen.MusicArchive.vo.Album;
import com.ronen.MusicArchive.events.AlbumsFetchEvent;
import mx.events.ListEvent;
import com.ronen.MusicArchive.model.ModelLocator;

private var model:ModelLocator=ModelLocator.getInstance();
private var currAlbumPath:String;


private function fetchAlbums(e:MouseEvent){
var fetchEvent:AlbumsFetchEvent=new AlbumsFetchEvent();
fetchEvent.dispatch();
}

private function albumSelected(event:Event){
if(event.target.selectedItem!=null){
this.currAlbumPath=Album(event.target.selectedItem).coverPath ;
this.albumCover.load("http://localhost:8080/blazeds/images/"+this.currAlbumPath);
}
}
]]>
</mx:Script>

<mx:Panel>
<mx:Grid width="100%" height="100%" borderStyle="solid">
<mx:GridRow>
<mx:GridItem>
<mx:Text id="title" text="A list of all albums:" fontSize="12"/>
</mx:GridItem>
</mx:GridRow>

<mx:GridRow>
<mx:GridItem>
<mx:DataGrid id="albums" dataProvider="{model.albums}" change="albumSelected(event)">
<mx:columns>
<mx:DataGridColumn dataField="artist" headerText="Artist"/>
<mx:DataGridColumn dataField="title" headerText="Album title"/>
</mx:columns>
</mx:DataGrid>
</mx:GridItem>

<mx:GridItem>
<mx:Image id="albumCover" width="200" height="200"/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow>
<mx:GridItem>
<mx:Button id="fetch" label="fetch albums" click="{fetchAlbums(event)}"/>
</mx:GridItem>
</mx:GridRow>
</mx:Grid>
</mx:Panel>
</mx:Canvas>

This component makes use of a Grid layout to setup its UI components which includes: a DataGrid which is binded to the model.albums list (The Carinagorm ModelLocator idiom is used in order to get a reference to this list), an Image (its source is taken from the albumCover variable) and a fetch albums button that triggers the dispatching of the fetchEvent (the dispatching of the event in the fetchAlbums method is another Cairngorm idiom).
Add in the albums ArrayCollection deceleration to the model/ModelLocator.as file:
package com.ronen.MusicArchive.model
{
import com.adobe.cairngorm.CairngormError;
import com.adobe.cairngorm.CairngormMessageCodes;
import com.adobe.cairngorm.model.IModelLocator;
import mx.collections.ArrayCollection;

[Bindable]
public final class ModelLocator implements IModelLocator{
public var albums:ArrayCollection;

/**
* Defines the Singleton instance of the Application ModelLocator
*/
private static var instance:ModelLocator;

public function ModelLocator(access:Private){
if (access == null){
throw new CairngormError(CairngormMessageCodes.SINGLETON_EXCEPTION, "ModelLocator" );
}
instance = this;
}

/**
* Returns the Singleton instance of the Application ModelLocator
*/
public static function getInstance() : ModelLocator{
if (instance == null){
instance = new ModelLocator( new Private() );
}
return instance;
}
}
}
/**
* Inner class which restricts constructor access to Private
*/
class Private {}

This class is a singleton which gives an easy access to model data as we've seen in the AlbumsView component.
Now will head on to and create the events/AlbumsFetchEvent.as class:
package com.ronen.MusicArchive.events
{
import com.adobe.cairngorm.control.CairngormEvent;

import flash.events.Event;

public class AlbumsFetchEvent extends CairngormEvent
{

public static const FETCH_ALBUMS:String = "FetchAlbums";

public function AlbumsFetchEvent(){
super(FETCH_ALBUMS);
}

override public function clone():Event{
return new AlbumsFetchEvent();
}
}
}

This class does nothing more than to define the event that will be fired upon the fetch button click in the view, notice that it defines a constant value that will be used in the controller to map the event to its command, lets add the mapping in the control/FlexMusicArchiverController class:
package com.ronen.MusicArchive.control
{
import com.adobe.cairngorm.control.FrontController;
import com.ronen.MusicArchive.commands.*;
import com.ronen.MusicArchive.events.*;

public final class FlexMusicArchiverController extends FrontController{
public function FlexMusicArchiverController(){
this.initialize();
}

private function initialize() : void{
this.addCommand(AlbumsFetchEvent.FETCH_ALBUMS,AlbumsFetchCommand);
}
}
}

As you can see weve added the mappings in the initialize method to a AlbumsFetchCommand class which we need also to implement, create the following commands/AlbumsFetchCommand.as class:
package com.ronen.MusicArchive.commands
{
import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;
import com.ronen.MusicArchive.business.AlbumsFetchDelegate;
import com.ronen.MusicArchive.events.AlbumsFetchEvent;
import com.ronen.MusicArchive.model.ModelLocator;

import mx.collections.ArrayCollection;
import mx.rpc.IResponder;

public class AlbumsFetchCommand implements ICommand, IResponder{
public function AlbumsFetchCommand(){
}

public function execute(event:CairngormEvent):void {
var fetchEvent:AlbumsFetchEvent = event as AlbumsFetchEvent;
var delegate:AlbumsFetchDelegate = new AlbumsFetchDelegate( this );
delegate.fetchAlbums();
}

public function result( event:Object ):void {
ModelLocator.getInstance().albums=ArrayCollection(event.result);
}

public function fault( event:Object ):void {
trace("CONNECTION ERROR");
}

}
}

This class implement two Cairngorm interfaces, the first ICommand requires the implementation of the execute method which calls for the AlbumsFetchDelegate fetchAlbums method (the delegate acts as a bridge between the Flex application and the remote services calls, this makes it easy to swap different services implementations without changing command execution logic).
The second one is the IResponder which requires the implementation of the result method, this method will be called upon by the delegate after the service result has been fetched (notice that a reference to the command object is passed to the delegate constructor), now will create the business/AlbumsFetchDelegate.as class:
package com.ronen.MusicArchive.business
{
import mx.rpc.IResponder;
import com.adobe.cairngorm.business.ServiceLocator;

public class AlbumsFetchDelegate{
private var responder:IResponder;
private var service:Object;

public function AlbumsFetchDelegate(responder:IResponder){
this.responder=responder;
this.service = ServiceLocator.getInstance().getRemoteObject("fetchAlbums");
}

public function fetchAlbums(){
var call:Object=this.service.fetchAlbums();
call.addResponder(responder);
trace('fetch called');
}
}
}

This class access the ServiceLocator singleton (registers remote services) in order to get a reference to the fetch albums service, add the following declaration to the business/Services.mxml file:
<?xml version="1.0" encoding="utf-8"?>
<cairngorm:ServiceLocator xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:cairngorm="com.adobe.cairngorm.business.*">

<mx:RemoteObject id="fetchAlbums" destination="albumsService"/>

</cairngorm:ServiceLocator>


One last class before we can call it off (on the client side) is the vo/Album.as:

package com.ronen.MusicArchive.vo{
//The com.ronen.musicarchive.AlbumVO tells Flex that Album.as maps to AlbumVO.java
[RemoteClass(alias="com.ronen.musicarchive.AlbumVO")]
public class Album{

public var artist:String;

public var title:String;

public var coverPath:String;

public function Album(){
}
}
}

This class gives us a single coherent class to work with inside the Flex view classes without depending on the format which the service returns back (the conversion takes place at the command result method).

Simple demo application server side walk through


Will need to expose & create this service at the server side, will start by adding the following to the WEB-INF/flex/remoting-config.xml file (the file which exposes services to Flex RIAs):
<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service"
class="flex.messaging.services.RemotingService">
<!--rest unchanged-->
<destination id="albumsService">
<properties>
<factory>spring</factory>
<!--This is the spring bean id which is declared in the applicationContext.xml file-->
<source>albumsDao</source>
</properties>
</destination>
</service>

The albumsDao is actually the Spring bean id that we are about to create:

package com.ronen.musicarchive;
import java.util.Collection;

public interface AlbumsDao {
Collection fetchAlbums();
}
Now the implementation:

package com.ronen.musicarchive;
import java.util.ArrayList;
import java.util.Collection;

public class HardCodedAlbumsDao implements AlbumsDao {
public Collection fetchAlbums() {
Collection result = new ArrayList();
result.add(new AlbumVO("the bends", "radio head", "Radiohead.bends.albumart.jpg"));
result.add(new AlbumVO("MGMT", "latest fav", "MGMT_oracular_spectacular.jpg"));
return result;
}
}

The returned VO has to be created:

package com.ronen.musicarchive;

public class AlbumVO {

private String title;

private String artist;

private String coverPath;

public AlbumVO(){

}

public AlbumVO(String title, String artist, String coverPath) {
this.title = title;
this.artist = artist;
this.coverPath = coverPath;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getArtist() {
return artist;
}

public void setArtist(String artist) {
this.artist = artist;
}

public String getCoverPath() {
return coverPath;
}

public void setCoverPath(String coverPath) {
this.coverPath = coverPath;
}
}

This simple hard coded DAO dosn't require too much elaboration, just copy the compiled interface and class into the WEB-INF/classes folder, don't forget also to declare the DAO inside the application context file:

<bean id="albumsDao" class="com.ronen.musicarchive.HardCodedAlbumsDao"/>

If you got this far, start tomcat up and launch the FlexMusicArchiver.mxml file (inside eclipse right click Run as->Flex Application), if all went well you should see the application up and running :)

Troubleshooting, make sure that:
  • Tomcat has loaded witout any exceptions.
  • The Flex SWF compiles without errors.

Wednesday, March 5, 2008

Getting ahead with the program

Well it's been a week since my last post (time moves fast isn't it?) and had the need to write about some new idea's/solutions/stuff that iv found, so without further ado:

In the gookup front iv made some progress with the packging scheme of the application, the problem is that Ruby/JRuby programs need to have at least a parser installed in order to work (well almost true since for Ruby you may use somthing like RubyScript2Exe), still i don't want to make my users have to install JRuby (the only requirement that im willing to live with is the need to have a working >1.5 JRE).
After goggling quite a bit iv found two main approaches, the first is to use a main Java class as an entry point to your JRuby main code and package the whole application in a Jar, the down side with this approach is that it doesn't seem to answer how to package ruby gems that your application requires in a clean manner (a possible answer might be to use something like JRubyGems ).
The second approach is to use jruby-complete.jar and create a working JRuby environment as a part of your install process with something like this:


java -Xmx512m -jar jruby-complete.jar --command gem install gem-name

This will create a gem library under .jruby (or any custom library with the -Djruby.home=/custom/path flag) onto required gems will be installed.
In order to run your JRuby main code all you need to do is to issue:

java -Xmx512m -jar jruby-complete.jar --command main.rb

Iv not decided which one of them ill eventually use (if any), the nice things about these kind of projects is how they evolve and grow.



Another two related tidbits:

  • Since this application will be command line base iv decided to look for a Ruby library that will save me the trouble of parsing commands from the user, cmdparse seems to meet my expectations, not only does it have an nice design but also a default help and version commands by default.

  • Another issue which bothered me along the development process was the lack of a debugger in my IDE, im used to the Intellij debbuger but it doesn't seem to support JRuby code yet (Netbeans does), ruby-debug seems to be have ported to JRuby (haven't tested it yet) and from this screen cast it looks pretty awesome!


In the Flex front iv been taking baby steps in trying to figure out how things are related to each other, iv noticed is that Adobe has a tendency to rename things quite a lot (marketing takes it tall i guess), so that Flex Data Services is now called LiveCycle Data services, LiveCycle consists of a couple of parts of functionality out of which im only interested (at the moment) in Flex remoting services and the way that they interact with Java backends, this small fraction of functionality is distributed in a OSS distribution named BlazeDS project.
One frustrating thing that iv noticed is that Flex 2 compiled SWF's aren't compilable with latest BlazeDS, iv learned this the hard way following this simplistic getting started guide, (My bad it seems as if i haven't passed mxmlc flags during compilation)
iv learned that Flex RIA has couple of remote call options, one of which is RPC-type services which basically enable Flex RIA's to call remote Pojo methods and cosume the return values that they produce, its also possible to call managed Spring beans methods by using a custom factory.


Im planing to develope some toy project that will incorperate Flex, Spring and Hibernate, ill share my experience here so stay tuned!

Wednesday, February 27, 2008

Yet another informational post (yaip)

After not writing for some time in this blog iv decided that i should post more regularly and share cool ideas/technologies that i encounter on daily/weekly bases, my agenda these days revolves around some of the following:


  • gookup - a Google services backup utility which takes your valuable online data and stores it localy on your hard drive for safe keeping.
    Iv been working on it for the past couple of months, the nice thing about it (besides its usefulness i hope) is the fact that its fully JRuby based & uses Buildr as its build tool.
    This matching allows some intresting combination like 'auto' Jar requiring in our JRuby code via the usage of the artifacts that we define in our build (ill elaborate on this on some other post).

  • Another subject that will keep me busy in the couple of following weeks is Flex, this nifty piece of technology will be a main part of projects that ill take part in the near future.
    My plan is to study the following subjects:Flex Basics, Flex & Java/Tomcat integration, Cairngorm.
    So far iv taken a look on Flex Builder (current idea support should get better on 7.0.3) and some online resources such as thirty-minute Flex test drive .
    Still the best way to study a new technology is by getting your hands dirty and actually building something with it (ill figure something up).

  • Last but not least is Adobe AIR and JavaFX, im considering using one of the two for gookup front end (AIR dosn't support linux yet), still i might just use swing and profligacy instead if the integration with JRuby will prove to be impossible.