Posts tagged "Mosaic"

Mosaic 9.5 Content Authorization

Mosaic 9.5 has allows control of content based on authorization rules stored in a policy file.  This means we can control access to an application, catalog, tile or other resource by setting permissions in the policy file.  We can also combine the permissions in different ways to control the user experience.

This is a very powerful feature that allows the developer or administrator to control resource access at a very fine grained level.  It also can be an incredibly maddening feature when it is not configured properly.  In this post I’ll try to demystify some of the magic behind authorization.  Hopefully this will make your configuration a bit less stressful.

The rules for the authorization of Mosaic content is stored in a policy file which is deployed to Mosaic as you would other resources.  The application and catalog descriptors will have a Policy Reference  that indicates what policy file(s) contain the rules for the resource.  The policy reference is optional, and if it is absent it means that there are no specific rules for that resource. There may be more than one policy file deployed to your server.

The policy file uses the OASIS eXtensible Access Control Markup Language (XACML) notation to define the authorization rules for each resource.  This allows you to set up some incredibly complex rules for authorization, but it also allows you to get a little too creative with the rules.  Its like juggling chainsaws.  Its really cool when it works, but if something goes wrong there will be a big mess to clean up.

The rules of authorization:

These are some general rules of thumb that will help you keep the authorization functionality from driving you crazy:

  1. Mosaic evaluates the authorization at runtime.
    When a user accesses an application, Mosaic reads the application descriptor and assembles the application before sending it to the client.  While this allows you to update rules with out recompiling code, it also means that large, complex policy files can cause performance issues.
  2. The evaluation of permissions for each resource is independent of that for other resources.
    When Mosaic determines that a resource is needed, it checks the policy file to see if the user has access (assuming there is a policy reference).  Then the next resource is similarly checked.  Mosaic  does not maintain state information between the calls, so  each resource  request is judged on its own merits.  For example, say a tile is used by two different applications. The tile  rules are evaluated separately from the evaluation of the applications.  In other words; If you can read a tile, you can read that tile regardless of what application it is in.
  3. If a resource is inside of another resource, you need access to the parent resource as well.
    Although each resource is evaluated on its own, for practical purposes, there is a evaluation order.  You can consider the evaluation order as application, catalog, view template, panel template and tile (or other catalog resource) and that these can be treated as an AND operation.
    What that means is that if you have access to the tiles and not access to the app, you won’t see anything.  Although the tile rules may say you have read access, the tiles have no container into which they can be put.
    For example; to see a tile the user must have access to the application AND the catalog AND the tile (1&1&1=1).  If any of these are denied, you will not see the tile.

In addition, there are two corollaries to the rules:

  1. What happens if there is no policy?
    This can happen if the resource (application, catalog, tile, etc.) has no policy file reference.  Since there is no rule, Mosaic assumes access is granted.
  2. What happens if there is a policy, but no rule applies?
    This can happen if there is no specific rule in the policy that applies to the resource for that user.  According to the XACML standard, this results in an indeterminate result.  In this case Mosaic falls back to the overall Mosaic authorization setting (also known as the base setting). This is set in the mosaic-context.xml file using the denyWhenIndeterminate property.  If the value is set to true then any indeterminate requests will be denied.
    One thing to watch for is an error in your XACML policy file.  If there is a mistake or typo that is still legal XACML, an indeterminate state can be returned.  For example, if you make a mistake in an attribute entry then the rule may not execute and an indeterminate result will be returned.  If the denyWhenIndeterminate property is set then no user will be able to access the resource.
    For these reasons I recommend adding a “catch all” rule that will apply when no others do.  It will make debugging your policy file much easier.

An Example

Lets take a look at a simple sample to see how this works.  The source for this example can be downloaded here.

The test consists of the following:

· Two user roles were added to Mosaic. Each role has one unique user:

o <security:user name=”r1″ password=”password” authorities=”ROLE_MOSAIC_R1″/>

o <security:user name=”r2″ password=”password” authorities=”ROLE_MOSAIC_R2″/>

· Two applications – App1 and App2

· One catalog – AppCatalog

· Two tiles – Tile1 and Tile2

· AppCatalog has entries for Tile1 and Tile2

· App1 uses Tile1 and Tile2 from the AppCatalog

· App2 uses Tile1 and Tile2 from the AppCatalog

· There is one policy file – ControlPolicy

· App1 and App2 contain a reference to ControlPolicy

· AppCatalog contains a reference to ControlPolicy at its root

· The Tile1 and Tile2 entries in the AppCatalog each contain a reference to ControlPolicy

When the applications are accessed using the owner’s account (a super user with all access granted) they look like the following:

App1 with no authorization rules:

image

 

App2 with no authorization rules:

image

 

Policy Rules:

Rules for R1:

· Read access for App1

· Read access for AppCatalog

· Read access for Tile1

Rules for R2:

· Read access for App2

· Read access for AppCatalog

· Read access for Tile2

Rules for resource owner:

· All actions to all resources

In addition there is a “catch all” rule to catch anything that does not apply to the above. This rule is set to deny.

Results

The following are the results when the two users attempt to access the two applications with the above listed rules:

For user R1:

· When accessing App1, user R1 sees the app and Tile1. He does not see Tile2

o The user has access to the app, the catalog and Tile1 (1&1&1=1) so he sees Tile1

o The user has no access to Tile2 (1&1&0=0) so he does not see Tile2

image

· When accessing App2, user R1 is denied access.

o The user has no access to the app, but does have access to the catalog and Tile1. Since he can’t see the app, access to the catalog and tile are not relevant (0&1&0=0)

image

For user R2:

· When accessing App1, user R1 is denied access

image

· When accessing App2, user R2 sees only Tile2. He does not see Tile1

image

 

Compound Rules

What happens if you want to do more complex rules on combinations of resources?  As I said earlier, Mosaic requests authorization on individual resources and does not pass the state information during the request.  If you want a combo – say only show Tile 2 if Tile 1 is present – can you do it?  You can, but you need to be a bit creative.

You need to find a way to combine the two tiles into a single resource on which Mosaic can check the authorization.  Fortunately, this can be easily done using view and panel templates.   In the catalog you can combine the tiles you need into a single view/panel.  The application will reference the view/panel template and not the tiles individually.  The policy file will include a resource entry for the view/panel as well as the tiles, catalog and application.

Of course the rules must be setup so the user has access to the tiles as well as the view/panel.

View Master

LiveCycle Mosaic ES2.5 has some very useful features for allowing users to customize their environment.  Some of the most useful revolve around the view object and its related view context.  With a bit of creative programming we can take advantage of the view object and allow users to create their own, customized design.

In this post I’ll look at a fairly common request for a customizable Mosaic app and see how it can be done while using many of the view features.

The source code used in this post can be found here.

Scenario

I’ll start with a short description of what we want from the app:

  1. An IT Request application with four tiles to begin (more may be added later):
    • Request List – has a list of currently active requests
    • Request Details – contains details about a single request
    • Customer Details – contains details about the customer to which the request applies
    • Customer History – contains information about a customer’s previous requests
  2. When a user selects an item from the request list the other tiles will update with relevant request/customer information
  3. User’s can customize their app to include any or all of the tiles.
  4. User’s can open multiple copies of the work space to work on different requests. 
  5. User’s can save their customized work space
  6. If a user has a customized work space, then it should come up when they login.
  7. If a user does not have a customized work space then a default will be presented.  The default will include the Request List and the Request Details.
  8. When a user’s customized work space is opened then the last request they were working on should be selected

Okay, that should do for now.

The Tiles

First we need to build the four tiles that make up the bulk of the application.  I won’t go too much into the general tile development, but instead I’ll concentrate on the “special” things I need to do to make the other requirements work.

Basically these are small Flex apps that happen to use the Mosaic API.  In my case I built them as ModuleTile files since they are all built on the same version of the Flex SDK.   Since this is a sample, I’m just going to read the data from a couple of local XML files using an HTTP Service.  No need to get too fancy here.

  • The Request List (RequestList.mxml) will be a simple data grid that shows the list of requests from the XML file. 
  • The Request Details (RequestDetails.mxml) is a screen that shows details about a single request.  Its pretty much a form.
  • The Customer Details (CustomerDetails.mxml) is a simple display screen that shows information about a single customer.
  • The Customer History (CustomerHistory.mxml) is a list of a single customer’s previous requests.

The construction of these tiles is pretty strait forward MXML development.

Inter-tile Communication

Requirement: When a user selects an item from the request list the other tiles will update with relevant request/customer information.

Mosaic has several methods to exchange data between tiles (see video for more), but there are a few requirements that lend themselves to using the view context for inter-tile communication:

  • User’s can open multiple copies of the work space to work on different requests.  –  This means that tiles in the same work space need to share data, but they shouldn’t interfere with tiles in another work space.  We can equate a work space with a Mosaic view. Then we can read that as the data needs to be exchanged between tiles in the same view and not tiles in another view.  Coincidentally, this is exactly how view attribute data works.
  • When a user’s customized work space is opened then the last request they were working on should be selected. – This means that the data the user is looking at needs to be saved and reloaded when the view is opened.  Fortunately the view context data is saved when the view is saved.  The tile just needs to be built to make use of that data. The one restriction is that the view data must be a primitive type – complex data types cannot be saved.

Let’s look at how the use of the view context data attributes are coded to meet these requirements.

Sending Data

The Request List tile will be broadcasting data to the other tiles.  When a user clicks on an item from the data grid (id=”grid”) two data attributes will be set – the caseNumber and the customerName.  These will be picked up by the other tiles. 

To send view data to the other tiles in the current view you would use the parentView.context.setAttribute method.  The first parameter is the attribute name, the second is its value.  Here is the code from the Request List tile:

private function selectRecord():void{
    var caseNumber:String = grid.selectedItem.caseNumber;
    var customerName:String = grid.selectedItem.customer;
    parentView.context.setAttribute(“caseNumber”,caseNumber);
    parentView.context.setAttribute(“customerName”,customerName);               
}

Receiving Data

The other three tiles need to receive the data and then do something with it.  In this case they will get related XML data and put it on the screen.

To meet the requirements the tile must check for the data when it loads (thus meeting the requirement to open the last request).  It must also watch for changes to the data so the tile is updated when the user selects a different request.

To get the value of a view data attribute I will use the parentView.context.getAttribute method.  The only parameter is the attribute name and the result is the contents of the data.

Mosaic also has a listener that can watch for changes in a view context attribute. The  parentView.context.addAttributeWatcher function works using the standard Flex event model in that it will fire a function when the attribute data changes.  You can then use the getAttribute function to get the data.

The following code is from the Request Details tile, but the other two tiles use similar techniques for getting the view context data.  The init function is called on the creationComplete event of the tile:

import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.events.PropertyChangeEvent;
           
[Bindable] private var currentRequest:XML;           
[Bindable] private var caseNum:String;
           

private function init():void{   
    parentView.context.addAttributeWatcher(“caseNumber”,onChange);  //watch for changes to the data
    onChange();                                                     //check for data on load
}
           
private function onChange(event:PropertyChangeEvent=null):void{
    caseNum = parentView.context.getAttribute(“caseNumber”);   //get the data
    if (caseNum != null)                                       //if there is data, then do something with it
         HttpService.send();
}      

Adding Tiles to a View

Requirements: User’s can customize their app to include any or all of the tiles
                             User’s can open multiple copies of the work space to work on different requests.

This requirement implies that the application needs a way to allow the user to create a new view and to add available tile to that view as they want.  Creating a new view is easy, as Mosaic has a built in button on the view skin to add a new view (the “+” button in the default skin). 

Adding tiles to the view takes a bit more effort.  Mosaic 9.5 doesn’t have an out of the box way to do this, but it does provide the APIs so it can be coded.  I need somewhere to put this code and the user controls.  It doesn’t make much sense to put it in any of the four tiles, as the user may not have add that tile to their view.  For this example I’ll add another tile called Header (Header.mxml).

I’ll need something to hold a list of the available tiles.  To be more flexible, I will also add the catalog name to that list as well.  That will allow me to add tiles from other catalogs into the view later on.    I created a simple class TileInfo to hold the tile and catalog name for each tile.  Then I created an array collection of the TileInfo objects and I populate that array collection when the Header tile is initialized (creation complete):

private function init():void{               
    //set the list of tiles (and their catalogs) that a user can add
    tileCollection.addItem(new TileInfo(“RequestList”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Request List”);
               
    tileCollection.addItem(new TileInfo(“RequestDetails”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Request Details” );
               
    tileCollection.addItem(new TileInfo(“CustomerDetails”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Customer Details”);
               
    tileCollection.addItem(new TileInfo( “CustomerHistory”,”ViewDemo_Catalog”));
    tileMenuCollection.addItem(“Customer History”)

}   

One of Header’s jobs will be to have a control that a user can use to add tiles.  I used a simple drop down (bound to the array collection) with the tile names and a button for the user to add the selected tile.

headerControls

When the user clicks on the Add Tile button a function executes that will add the tile.  When the function fires the code must first do the following:

  1. Locate the proper catalog
  2. Locate the proper tile in the catalog
  3. Find the view and panel that the user is looking at
  4. Add the tile to the view

As part of step 3 we should make sure that there is both a view and panel into which we can put the tile.  If either of these are missing, we can pull a pre-configured one out of the catalog.  By creating a pre-configured view and panel template, the layout can be defined ahead of time.  This will save a bit of coding.  In this case I created a view template called addView and a panel template called addPanel in the catalog.

The button handler in the Header tile looks like:

protected function addTile_clickHandler(event:MouseEvent):void            {
                if (tileDropDown.selectedIndex != -1){
                    var tileInfo:TileInfo = tileCollection.getItemAt(tileDropDown.selectedIndex) as TileInfo ;
                   
                    //get the tile
                    var cat:ICatalog = mosaicApp.getCatalog(tileInfo.catalogNm);
                    var tileToAdd:ITile = cat.getTile(tileInfo.tileNm);
                   
                    var view:IView = this.currentView();
                    var panel:IPanel = this.currentPanel(view);                       
                   
                    panel.addTile(tileToAdd);
                }
            }

This calls two functions to find (or add) the current view (currentView) and panel (currentPanel).  To determine if a view or panel is the one that the user is using, I check each view/panel for the displayed flag (true means that it is the current one).

The following is the function for determining the current view.  The panel function is similar (you can see it in the source code).

                   /**
             * find the current view.  If not found, then load one from the catalog
             **/
            protected function currentView():IView{               
                var currentView:IView;
               
                //find the current view by looking at the displayed flag in each view
                var viewArray:Array = mosaicApp.views;
                for each (var searchView:IView in viewArray){
                    if (searchView.displayed){
                        //found view
                        currentView = searchView;
                        break;
                    }
                }   
               
                //not found, so go into the catalog and get a default view
                if (currentView == null){
                    var catalog:ICatalog = mosaicApp.getCatalog(“ViewDemo_Catalog”);
                    currentView = catalog.getView(“addView”);
                    mosaicApp.addView(currentView);
                    currentView.display();
                }
               
                return currentView;
            }
           
           

Saving and Loading Views

Requirements:   User’s can save their customized work space
                                  If a user has a customized work space, then it should come up when they login. 
                                  If a user does not have a customized work space then a default will be presented.  The default will include the Request List and the Request Details.

The view skin has a control that allows users to save a view at any time:  clip_image002. Views can also be saved using the IView.save API.  Views are saved on the server and are tagged to the user’s account.  In this case I’ll let the user save the view using the built in controls.

Views can be loaded into an application either by using the organizer (added to the application’s xml file using the organizer element), or by using the API.  The organizer is an element added to the application’s xml definition.  It shows a list of the user’s saved Views and allows a user to add the view to the application at any time.

The requirement, however, state that the app should load the user’s view and if that does not exist, load the default view.   This will require loading the correct view using the API.  To add a view using the API you first have to find the view in the mosaicApp.userViews array, then add it to the application using the mosaicApp.addView method.   I could put the default view, with its panels and tiles, directly into the application’s XML file.  The problem with that is the default view will always load because Mosaic loads the application contents when the user accesses the app.    There will be no way to intercept it and show the user’s saved view.  In this case its better to open the view (default or saved) using the API. 

This means that the application’s XML file will not have any of the four tiles.  It will have the Header tile, which will contain the API calls to load the proper view. 

The application xml file looks like:

<?xml version=”1.0″ encoding=”UTF-8″?>
<app:Application name=”ITRequests” label=”IT Requests”
xmlns:view=”http://ns.adobe.com/Mosaic/View/1.0/”
xmlns:catalog=”http://ns.adobe.com/Mosaic/Catalog/1.0/”
xmlns:tile=”http://ns.adobe.com/Mosaic/Tile/1.0/”
xmlns:crx=”http://ns.adobe.com/Mosaic/CRXTypes/1.0/”
xmlns:app=”http://ns.adobe.com/Mosaic/Application/1.0/”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://ns.adobe.com/Mosaic/Application/1.0/ file:///C:/Adobe/Mosaic/Mosaic%209.5.0.1/docs/schemas/application.xsd”>

    <crx:Metadata>
        <crx:Description>ITRequests</crx:Description>
    </crx:Metadata>
    <app:Shell name=”ITRequests” label=”IT Requests”>
        <catalog:CatalogReference name=”cat” uri=”ViewDemo_Catalog”/>
        <view:Organizer visible=”false”/>
        <tile:TileReference catalog=”cat” name=”Header” label=”Header” width=”100%” height=”80″/>
        <view:ViewManager width=”100%” height=”100%”>
        </view:ViewManager>
    </app:Shell>
</app:Application>

Notice that I did add a ViewManager, this is necessary because Mosaic needs something to control the views that I will add later.

Now I need to add some code to the Header tile so it can load the proper view.  I’ll need to check to see if there are any saved views for the user.  If there are, then I add them to the application.  If not; then I’ll call another function to load the default view.  

           /**
             * check to see if the user has any saved views.  If so
             * bring them up.  If not, bring up the default
             */
            protected function getUserViews():void{               
                var userViews:Array = mosaicApp.userViews;
                for each (var view:IView in userViews ){
                    mosaicApp.addView(view);   
                    showDefaultBtn.visible = true;
                }
                if (userViews.length == 0){
                    showDefaultView();
                }
            }
            /**
             *  show the default view
             */
            protected function showDefaultView():void{
                var catalog:ICatalog = mosaicApp.getCatalog(“ViewDemo_Catalog”);
                var defaultView:IView = catalog.getView(“defaultView”);   //load a view template called defaultView from the catalog
                mosaicApp.addView(defaultView);
                showDefaultBtn.visible = false;
            }

To make sure this happens when the app first gets loaded, I’ll add a call to the getUserViews(); function to the Header’s init function.

I could have easily done this in one function, but I wanted user’s that have a saved view to “reload” the default one.  To do that I added a button (showDefaultBtn) that will fire the showDefaultView function.  If the default view is there, I want the button to be invisible.

Conclusion

By taking advantage of the Mosaic view features – inter-tile communication, view layout saving, view data saving and view related APIs – you can build a highly customizable application.  This will allow your users to have the freedom to set the system up the way they want.

The source code used in this post can be found here.

Mosaic and LiveCycle Data Services

Adobe’s two RIA products – LiveCycle Mosaic and LiveCycle Data Services (LCDS) – go together like peanut butter and jelly.  One provides a framework for intuitive, user focused applications, the other provides efficient access to real time back end data.  Between the two of them they can provide up-to-date data in an engaging user experience.

There are a couple of different ways to combine the two products, however.  What one you will choose will depend on your particular setup and how your back end data is organized.  So, do you prefer your jelly on top, or on the bottom?

In this post I’ll present both methods of Mosaic/LCDS integration using an overly simple example.  Hopefully this will give you some ideas for your projects.

In the end I built a simple Mosaic application that demonstrated both methods.

image

A Simple Service

For this example, I’m going to create a very simple LCDS RPC service that accesses a Java object.  This is based on the Adobe documentation that can be found at: http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=lcoverview_4.html

First I created a trivially simple POJO that echoes back a single String:

package remoting;
public class EchoService
{
    public String echo(String text) {
        return "Server says: I received '" + text + "' from you";
    }
}

Once that was compiled I moved the class file to the  WEB-INF/classes/remoting directory.  Then I added the following entry into the WEB-INF/flex/remoting-config.xml file:

<destination id="echoServiceDestination" channels="my-amf">
    <properties>
        <source>remoting.EchoService</source>
    </properties>
</destination>

The source entry points to my Java class and it uses the existing my-amf channel.

The last thing that I needed to do was to add a crossdomain.xml file to my LCDS server.  This is because my Mosaic server is running on a different box.

Jelly on top; Calling LCDS directly from a tile

The first method I’ll show is also the most direct.  This involves making a direct call from the Mosaic tile to the LCDS service. This is a useful method when there is a direct relationship between the tile’s visual elements and the data. What it has in simplicity, it lacks in power.  This method does not lend itself to decoupling the data from the tile.

<?xml version=”1.0″ encoding=”utf-8″?>
<mc:Tile xmlns:fx=”
http://ns.adobe.com/mxml/2009″

xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:mc=”com.adobe.mosaic.core.*”
layout=”absolute” width=”100%” height=”100%”
creationComplete=”init()”>

<fx:Declarations>
<mx:RemoteObject id=”remoteObject”
destination=”echoServiceDestination”
result=”resultHandler(event);”
fault=”faultHandler(event);”/>
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.messaging.Channel;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.messaging.config.ConfigMap;
import mx.messaging.events.*;
import mx.messaging.messages.*;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ObjectProxy;


private function init():void{
register();
var cs:ChannelSet = new ChannelSet();
var customChannel:Channel = new AMFChannel("my-amf","
http://myserver/lcds/messagebroker/amf");
cs.addChannel(customChannel);
remoteObject.channelSet = cs;
}

private function register():void{
registerClassAlias("flex.messaging.messages.CommandMessage",CommandMessage);
registerClassAlias("flex.messaging.messages.RemotingMessage",RemotingMessage);
registerClassAlias("flex.messaging.messages.AcknowledgeMessage", AcknowledgeMessage);
registerClassAlias("flex.messaging.messages.ErrorMessage",ErrorMessage);
registerClassAlias("DSC", CommandMessageExt);
registerClassAlias("DSK", AcknowledgeMessageExt);
registerClassAlias("flex.messaging.io.ArrayList", ArrayList);
registerClassAlias("flex.messaging.config.ConfigMap",ConfigMap);
registerClassAlias("flex.messaging.io.ArrayCollection",ArrayCollection);
registerClassAlias("flex.messaging.io.ObjectProxy",ObjectProxy);
registerClassAlias("flex.messaging.messages.HTTPMessage",HTTPRequestMessage);
registerClassAlias("flex.messaging.messages.SOAPMessage",SOAPMessage);
registerClassAlias("flex.messaging.messages.AsyncMessage",AsyncMessage);
registerClassAlias("DSA", AsyncMessageExt);
registerClassAlias("flex.messaging.messages.MessagePerformanceInfo", MessagePerformanceInfo);
}

// Send the message in response to a Button click.
private function echo():void {
var text:String = ti.text;
remoteObject.echo(text);
}

// Handle the recevied message.
private function resultHandler(event:ResultEvent):void {
ta.text += "Server responded: "+ event.result + "\n";
}

// Handle a message fault.
private function faultHandler(event:FaultEvent):void {
ta.text += "Received fault: " + event.fault + "\n";
}
]]>
</fx:Script>

<s:Label x=”11″ y=”5″ text=”Direct LCDS Call”/>
<s:TextInput x=”11″ y=”24″ id=”ti” text=”Hello World!”/>
<s:Button x=”147″ y=”25″ label=”Send” click=”echo();”/>
<s:TextArea id=”ta” width=”100%” height=”628″ y=”68″/>
</mc:Tile>

Again this is based on the LCDS documentation.  There are some concessions to the Mosaic framework however.  First, an AMF channel needs to be setup, also several classes need to be registered.  I know I’ve registered more than I need, but I will probably expand this tile later on.

As you can see, when the user clicks on the Send button, a function is called that makes use of the remote object.  The remote object then uses the AMF channel to make a LCDS call to the POJO.  The results are then shown on the screen.

Jelly on bottom; Using a Mosaic service to make the LCDS call

Another way to make an LCDS call from a Mosaic tile would be to use a Mosaic service as an intermediary.  In this case the tile wouldn’t be aware of the LCDS service at all, any interactions would be made through the Mosaic service.  This is very useful if multiple tiles need to access the same LCDS service as it only needs to be accessed once.  It also allows easy decoupling of the tiles and the data as the Mosaic service can be changed without affecting the inner workings of the tiles.  The draw back is that it does require a bit more coding and more for thought when planning out the Mosaic service.  For more info on creating Mosaic services, see my earlier blog entry

The interface

Let’s look at the code to do something similar to the simple example.  First the Interface object:

package com.adobe.etech{

public interface IHelloWorld    {
function setEcho(msg:String):void;
function getEcho():String;
function echoReady():Boolean;
function setLoaderURL(url:String):void;
}
}

Since the LCDS call is asynchronous, I needed a getter and setter function to make the request and get the response. I also need a method to determine when the asynchronous call is complete (so I can go get the data). The echoReady function is a bit of a cheat to allow this.  As I mentioned in an earlier post, there is no easy way to send a message from the Mosaic service to the tile because the service is not context aware.  You can push the context into the service, but for this example it would be overkill.  So I built a cheap and cheesy Boolean function that I can ping from the tile.

The final function setLoaderURL is very important to the application and requires a bit of explanation.  When I was working on this project, I set everything up as I did with the direct LCDS call.    I kept getting an error that the URL was null.  I knew I had set the URI for the amf channel, so what was the URL it needed?  After discussing it with several of my colleagues I was able to narrow it down to  the fact that the LoaderConfig.mx_internal::_url  object needs to have a URL to a MXML element.  Passing the tile’s loaderInfo.url value to the Mosaic service seems to do the trick.

The Mosaic Service

The service implementation is below:

package com.adobe.etech.impl
{
import com.adobe.etech.IHelloWorld;

import flash.display.Sprite;
import flash.net.registerClassAlias;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.core.mx_internal;
import mx.logging.targets.TraceTarget;
import mx.messaging.Channel;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.messaging.config.ConfigMap;
import mx.messaging.config.LoaderConfig;
import mx.messaging.events.*;
import mx.messaging.messages.*;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.RemoteObject;
import mx.utils.ObjectProxy;


public class HelloWorldLCDSService implements IHelloWorld
{

private var remoteObject:RemoteObject;
private var _echoMsg:String = “”;
private var _echoComplete:Boolean = false;

public function HelloWorldLCDSService()    {
register();

var amfChannel:AMFChannel  = new AMFChannel(“my-amf”,http://server/lcds/messagebroker/amf);
amfChannel.requestTimeout = 3;
amfChannel.connectTimeout = 3;
var channelSet:ChannelSet = new ChannelSet();
channelSet.addChannel( amfChannel );

amfChannel.addEventListener(ChannelFaultEvent.FAULT, handleChannelFault);
amfChannel.addEventListener(ChannelEvent.CONNECT, handleChannelConnect);
amfChannel.addEventListener(ChannelEvent.DISCONNECT, handleChannelDisconnect);

remoteObject = new RemoteObject();
remoteObject.destination =”echoServiceDestination”;
remoteObject.channelSet = channelSet;

remoteObject.addEventListener(ResultEvent.RESULT,resultHandler);
remoteObject.addEventListener(FaultEvent.FAULT,faultHandler);
}

private function handleChannelFault(e:ChannelFaultEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Fault” + “\n”
trace(“Channel Fault”);
trace(e);
}

private function handleChannelConnect(e:ChannelEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Connect” + “\n”
trace(“Channel Connect”);
trace(e);
}

private function handleChannelDisconnect(e:ChannelEvent):void {
_echoComplete = true;
_echoMsg +=”Channel Disconnect” + “\n”
trace(“Channel Disconnect”);
trace(e);
}


public function setEcho(msg:String):void    {
_echoComplete = false;
remoteObject.echo(msg);
}

public function getEcho():String{
return _echoMsg;
}

public function echoReady():Boolean{
return _echoComplete;
}

private function register():void{
registerClassAlias(“flex.messaging.messages.CommandMessage”,CommandMessage);
registerClassAlias(“flex.messaging.messages.RemotingMessage”,RemotingMessage);
registerClassAlias(“flex.messaging.messages.AcknowledgeMessage”, AcknowledgeMessage);
registerClassAlias(“flex.messaging.messages.ErrorMessage”,ErrorMessage);
registerClassAlias(“DSC”, CommandMessageExt);
registerClassAlias(“DSK”, AcknowledgeMessageExt);
registerClassAlias(“flex.messaging.io.ArrayList”, ArrayList);
registerClassAlias(“flex.messaging.config.ConfigMap”,ConfigMap);
registerClassAlias(“flex.messaging.io.ArrayCollection”,ArrayCollection);
registerClassAlias(“flex.messaging.io.ObjectProxy”,ObjectProxy);
registerClassAlias(“flex.messaging.messages.HTTPMessage”,HTTPRequestMessage);
registerClassAlias(“flex.messaging.messages.SOAPMessage”,SOAPMessage);
registerClassAlias(“flex.messaging.messages.AsyncMessage”,AsyncMessage);
registerClassAlias(“DSA”, AsyncMessageExt);
registerClassAlias(“flex.messaging.messages.MessagePerformanceInfo”, MessagePerformanceInfo);

}

public function setLoaderURL(url:String):void{
LoaderConfig.mx_internal::_url = url;

}

// Handle the recevied message.
private function resultHandler(event:ResultEvent):void {
_echoComplete = true;
_echoMsg += “Server responded: “+ event.result + “\n”;
}

// Handle a message fault.
private function faultHandler(event:FaultEvent):void {
_echoComplete = true;
_echoMsg += “Received fault: ” + event.fault + “\n”;
}
}
}

This is very similar to the direct LCDS call, except it has getters/setters so the calling tile can go and get the resulting data.   The amf channel listeners are there as a result of me trying to debug the setLoaderURL issue mentioned above.

The Tile

The tile that uses the service is quite simple. It uses the IHelloWorld interface to make the call and relies on Mosaic to inject the service instance at runtime (see my previous entry for more on how this works):

<?xml version=”1.0″ encoding=”utf-8″?>
<mc:Tile xmlns:fx=”
http://ns.adobe.com/mxml/2009″

xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:mc=”com.adobe.mosaic.core.*”
layout=”absolute” width=”100%” height=”100%”>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<fx:Script>
<![CDATA[
import com.adobe.etech.IHelloWorld;

[Bindable] public var helloService:IHelloWorld;
private var myTimer:Timer = new Timer(1000,1);  //1 second
private var timeoutID:uint;

// Send the message in response to a Button click.
private function echo():void {
var text:String = ti.text;
//remoteObject.echo(text);
helloService.setLoaderURL(this.loaderInfo.url);
helloService.setEcho(text);
if (helloService.echoReady()){
this.getEcho();
}else{
myTimer.addEventListener(TimerEvent.TIMER,checkEcho);
myTimer.start();
}
}

private function checkEcho(event:TimerEvent):void{
if (helloService.echoReady()){
myTimer.stop();
myTimer.removeEventListener(TimerEvent.TIMER,checkEcho);
this.getEcho();
} else{
//try again
myTimer.reset();
myTimer.start();
}
}

private function getEcho():void{
ta.text = helloService.getEcho();
}

]]>
</fx:Script>

<s:Label x=”11″ y=”5″ text=”LCDS Using Service” width=”195″/>
<s:TextInput x=”11″ y=”24″ id=”ti” text=”Hello World!”/>
<s:Button x=”147″ y=”25″ label=”Send” click=”echo();”/>
<s:TextArea id=”ta” width=”100%” height=”628″ y=”68″/>
</mc:Tile>

You may notice that I have a timer that checks to see if the data is returned.  This is because the service has no built in way of sending a message to the tile. The timer was a bit of a cheat and I wouldn’t recommend using this method in production code. Instead I would recommend passing the tile context to the service so it can send a proper Mosaic message (see this post for more info)

Conclusion

As you can see from this simple example, there are a couple of different options for combining LCDS and Mosaic.  Each has its advantages and weaknesses and it will depend on your situation as to which one to use:

Direct LCDS Call:

Pros:

  • Simple to code
  • Direct tie from data to visual elements

Cons:

  • visual elements not decoupled from tile
  • each tile makes its own connection – no connection sharing

Mosaic Service LCDS Call:

Pros:

  • LCDS call abstracted from tile
  • multiple tiles use same call

Cons:

  • more complex code
  • need to implement your own checker for returned data, or pass the tile context to the service

Special thanks to Leo Schuman and Marcel Boucher for their assistance and patience with LCDS. If you are interested, the source code can be found here.

Service Interruptus

While working on a recent LiveCycle Mosaic demo, I discovered some interesting consequences of using Mosaic services with large amounts of data and memory heavy tiles.  Since the cause of the issues was not immediately apparent, and the solution is quite simple, I thought I’d share my findings.

The Conditions

The demo I was constructing consists of quite a few Mosaic tiles that rely on common data.  Basically each tile shows a different aspect of the data, so the user gets a graphical breakdown of a current situation.  Since much of the data is shared across several tiles, I figured it would be a good use of a common Mosaic service.  Then each tile can access the same service and the data only needs to be loaded once.  The service will read an XML file from the Mosaic catalog, process it and will have functions that will present aspects of the data to the Tiles.

arch2

In the service implementation class, I have a standard Flex HTTPService object that I use to load the data into an XML object.  After the data is loaded into the service there are several functions that can be called by the tiles.

The Symptoms

For early testing I created a simple XML file and a couple of quickie tiles. By watching the Flash Builder 4 console, I could see that the service was loading, then the tiles.  The tiles could access the data via the service with no problems. As I continued adding more complex tiles, and increasing the size of the XML file, strange things started happening.

Every once in a while a tile would give a null pointer error.  Upon further inspection, this happened only in tiles that called the service functions on creation complete.  It looked as if the service had not loaded the data, but when I put break points in my code I could see that the data was loaded.  To aggravate the issue, it wasn’t consistent as to when the problem would happen.  I could load the application a dozen times and it would work fine, then it would fail once or twice and then be fine again.

WTF???

Somebody tell Schrodinger his cat is dead

If all else fails, procrastinate. I ignored the problem and continued working on the rest of the demo – hey it worked most of the time.  As I continued to add additional tiles and functionality to the service things steadily got worse.  Eventually it got to a point where it would fail more often than it would not.  To be fair to myself (and who else will), it really was a good thing to delay looking for the root of the problem.  At least now I could take a serious look at what was going wrong and have a reasonable chance of looking at a failed case.

I’ll save you the tribulation of my debugging efforts, needless to say I learned a lot about working with a non-linear multi-faceted environment such as Mosaic.  Not the least of which was – just observe, don’t participate.  Trying to find intermittent problems with multiple tiles, services, asynchronous events and a black box framework takes a level of patience for which I am not well equipped.  I tried to be Zen about it but The Norse part of my genetics just wanted to smash it with a big axe and go burn a village (ah, simpler times…)

After stepping through the code multiple times, and adding more trace statements than I’d like to admit, I was able to figure out that there were actually two separate problems.  One was fairly obvious, the other not so much.

Problems and Solutions

The first problem was in the service itself.   The tiles depended on the data provided by the service.  The service implementation uses an HTTPService to read the data from an XML file.  Since the HTTPService load operation is asynchronous (waits for a ResultEvent), a tile may try to access the service before the data is loaded.  When the tile makes the call to the service, the XML data is empty and an exception is thrown when the service tries to perform an operation on the data object.  When there wasn’t much data it loaded quickly enough not to present a problem.  As the test data became larger it took more time to load and the problem started to show itself.

If this was a “normal” Flex app, I’d just have the service dispatch an event when the data was loaded.  Flex components that depended on that service would have event listeners that would wait for the service to say it is ready.  This won’t work in the Mosaic framework however, because of the decoupled nature of services and tiles.  The tile does not have direct knowledge of the service context and therefore cannot pickup events thrown by the service.  The solution is to have the service send a message to the Mosaic framework, and have the tiles listen to the framework for a message.  Unfortunately, Mosaic service implementations don’t directly inherit the Mosaic context.  Yes, I can import the IContext class, but there is no way to initialize it directly with the Mosaic framework’s information.

The solution was a bit of a cheat.  I can get the Mosaic context information from a tile, it’s a property of the inherited mosaicApp object.  So what I did was to add an IContext variable to the service, with a setter function.  Then I had one of the tiles pass its context to the service using the setter.  Now when the service decides that both the data and context are set, it can set a Mosaic attribute saying that its ready.  Tiles will check the attribute before attempting to access the service.  As a bonus, tiles can watch for the attribute to change which will tell them the data has been updated.

I implemented the fix, and tested it out.  Everything worked fine … for a while.

Every once and a while the tile that passed its context to the service would throw an exception.  The exception stated that the service itself was null.  From what I understood about the way Mosaic handled the services, this should not be possible.  Mosaic is supposed to load the services before the tiles, guaranteeing that they would exist. Another round of step through and trace statements ensued.  From what I was able to deduce, Mosaic was indeed loading the service before the tiles, however the tiles could be created before the reference to the service was injected.  In other words, because I was setting the context on the tile’s creationComplete event, the service implementation’s reference may not be fully realized – resulting in a null pointer error.

The solution to this problem was less pleasant.  The only way I could figure to make sure the service reference was complete was to put a timer into the tile that set the service context.  Basically I check to see if the service object is null.  If it is then I set a timer’s event listener and start the timer.  The event listener checks again to see if the service is null.  If it is then it resets the timer.  If it is not then I set the context object and we move on.

I’m not a fan of these kind of timed wait loops. However; without being able to get an event from the service, I can’t see any other way of doing it.  The problem is that I can’t get an event without the context being set and I can’t set the context until I know the service is not null.

I also added a check in the other tiles to not only look for the service’s data loaded attribute, but they also check to see that the service object is not null.  Belt and suspenders programming at its best.

Conclusion

Here is the short version of what happened:

Issue 1

  1. Services that perform asynchronous operations need to tell their dependent tiles when these operations are complete
  2. Service have no direct way of notifying tiles as they don’t have access to the Mosaic context
  3. A tile can pass that context to the service if the service exposes a context object setter function

Issue 2

  1. Service load before tiles, however tiles can reach creation complete before the service injection has happened.  This means that the tile’s service object may be null.
  2. The only thing to do is to have the tile wait (using a timer loop) for the injection to be complete.

Creating an Organized Mosaic Project Structure

Lately, I’ve been working a lot with people that are new to LiveCycle ES2 Mosaic.  One thing always seems to come up is the question of the best way to organize Mosaic projects.    There aren’t any hard and fast rules (with the exception of the Catalog folder layout), but I’ve seen enough similarities in unrelated projects to suggest that there are some unofficial conventions that are forming.  I won’t go as far as to call the following “best practices”, rather consider them suggestions based on experience.  When combined with standard Flex best practices, these suggestions may make developing your Mosaic applications a bit easier.

Folder Structure

Organization will set you free – Alton Brown

Mosaic applications consist of quite a few moving parts.  There are the application descriptors, tile code, services and interfaces, authentication policies, shell skins, etc.  Keeping these sorted out will definitely make your life easier, especially when it comes to deploying and debugging.  Whenever possible, I prefer to keep all of the files/folders for a single Mosaic undertaking under a single folder.  That may mean having more than one application in the same folder, but at least the related code will be close by.

Under that parent folder I usually create one folder for each major Mosaic component.  The folder names are in lower case to differentiate them from the Catalog’s folders (more on that later).  For example:  I have a project called the Sales Dashboard, which will contain an application, catalog, several tiles, a service, a custom style sheet, etc.  To keep from going insane, I created the following folder structure:

topLevel

  • applications – this folder contains the application descriptor xml file(s)
  • catalogs – this folder contains the deployable contents for the project’s catalog.  If I was to have multiple catalogs, then they would each go in a separate subfolder.  A catalog’s structure is one of the few things that must have a specific structure.  This is because the catalog folder gets zipped and then deployed to the Mosaic server.  For more on the catalog folder’s structure, see the section below.
  • interfaces – this project uses a Mosaic Service component that is used by several tiles.  Each service component consists of two parts – the interface library and the service class.  This folder contains sub folders for each of the interface library projects.  Those subfolders contain a Flex Builder project that includes the source code for the interface.  In this example I have a single interface library called the “SalesDashboardInterfaceLibrary”, so the interface folder has a single subfolder with that name.  In the subfolder is a Flex Builder project for the interface:
    interfaces
  • policies – if you are using the Mosaic fine grained authorization, then this folder contains the XACML files that provide authorization information for the elements.
  • services – this folder is related to the interfaces folder.  It contains subfolders for each of the service class files.  Inside those subfolders is a Flex Builder project used to develop the service code.  For example, this application includes a “SalesDashboardService”. That subfolder contains a Flex Builder project for that service library:
    service
  • stylesheets – this project contains a custom skin for the Mosaic application.  The Flex Builder project for this skin is in a subfolder under the stylesheets folder.  If I had more than one skin, then each would get its own subfolder.  For example, my skin project is called “GlobalCorpSkins”:
    stylesheet
  • tiles – this folder contains sub folders for each of the Flex Builder tile projects.  Usually I try to keep related tiles in the same Flex Builder project (it makes debugging a bit easier), so a single sub folder may contain many tiles.  There are some cases, however, where a particular tile needs  its own project.  For example, if it uses a different Flex SDK or comes from a legacy application.  How fine grained you want to make the tile projects is really up to you, but keeping them all under this one tiles folder will make them easier to find.  In this example I have two tile projects – Flex 4 tiles (which contains several tiles) and Map (which contains a single, very complex tile):
    tiles

Catalog Structure

As I said earlier, the catalog structure is the one thing that must be in a specific format.  The catalog contains the deploy objects (compiled code, resources, etc.) and it will be zipped, then sent to the Mosaic server.  The server is expecting specific things to be in specific folders.  And yes, those folders are case sensitive.

catalog

  • descriptor.xml – this is the catalog’s definition file.  It must be named descriptor.xml and it must be at the root of the catalog zip file
  • Interfaces – contains the compiled swf for the interface libraries.
  • Resources – this is where the miscellaneous stuff needed for tiles and services is stored.  Things like images, XML files, videos, etc. are put here.
  • Services – contains the compiled swf for the service classes
  • Stylesheets – contains the skin classes complied into a swf
  • Tiles – contains subfolders for each of the tiles in the catalog.  The subfolder names is the same name as the tile, and they contain the tile swf files.

Flex Builder Linked Resources

Since tiles, services and skin projects rely on the Mosaic SDK, you’ll need to include the appropriate SDK swc in each of your projects.  Rather than hard coding the path, it is a good idea to create a pointer to the SDK folder and let Flash Builder sort out the location.  This makes your code more portable, if you give it to someone else, they don’t have to have the SDK in exactly the same location as you do.

To set up a linked resource to the Mosaic SDK:

  • Open Flex Builder
  • Choose Window –> Preferences
  • Choose General –> Workspace –> Linked Resources
  • Click the New button
  • Give it a name of MOSAIC_SDK
  • Click the Folder button and browse to your Mosaic SDK folder.  Don’t go any lower than the “sdk” folder.
  • Click OK to close the dialogs

When you create a new Mosaic project you can use the linked resource in your Flex Build Path.  Then if someone else opens your project and has the SDK in a different location, Flash Builder will sort out the reference (assuming they have a MOSAIC_SDK resource).

ANT Scripts

It may seem that I’ve gone a little berserk with the organization of the project.  I mean, how anal retentive can you get?  Why not just lump everything together in one or two folders and be done with it?

The answer lies in the application deployment through ANT scripts.  Having a highly organized structure like this allow you to build the deployment code as a few, small ANT files.  These can be combined together to quickly deploy code changes in an efficient manner.  There are few things more annoying than testing against the wrong code.

For example; At the root of the project I have an ANT script that deploys the catalog, application and policies.  Before that section executes, it calls ANT scripts in the sub folders that re-compile the interface, service, style sheet and tile classes, and move them to the appropriate location in the catalog structure.  Using this, I can make changes to a tile, run the root ANT script and ensure that everything is the current version.

True, it takes a bit more effort to set up, but the time and frustration savings are well worth it.  Here’s what my final folder structure looks like:

folderStructure

Request for Comments

For what its worth, most of the above is my opinion based on my own experiences.  If you have any additional suggestions, I’d love to hear them.

Debugging in Mosaic

Adobe’s Rich Internet Application (RIA) framework product, LiveCycle Mosaic, allows developers to create applications that are made up of smaller micro-apps called Tiles. Tiles can be either Flex applications or HTML pages and there are very mature tools for development and testing of individual Tiles.  Since one of Mosaic’s biggest features is that Tiles can communicate with each other on the client side (not requiring round trips to the server) its very useful to test Tiles running in the framework.     In this post I’m going to describe a few tools and tips to make this a bit easier.

Mosaic Debug WAR

There is a special debug version of the Mosaic WAR file that is built specifically for developers.  When you install/unzip Mosaic you fill find the debug version in the deploy/war/{logversion}/debug folder (logversion refers to either the log4j-logging or jdk-logging folder).  This version of Mosaic is the same as the production version, except it includes hooks for QTP and the Mosaic plugin for Flash Builder (see below).   If you want to create a debug environment, simply deploy this debug version to your application server.

Debug WAR in Standalone

Mosaic comes with a handy-dandy standalone version for development.  It comes bundled with its own Tomcat so you can start building things without worrying about setting up a more complex production environment.  As of the time of this post, the standalone version comes with the production version of Mosaic.  The first thing I always do is to replace it with the debug version.  Here’s how:

  • Stop the standalone Tomcat if its running
  • Go to the {mosaic home}/standalone/webapps folder
  • Delete the existing mosaic.war (don’t panic, you still have a copy in the deploy folder)
  • Delete the mosaic folder and everything in it – This will delete any deployed Mosaic apps
  • Copy the debug version from {mosaic home}/deploy/war/log4j-logging/debug/mosaic.war into the {mosaic home}/standalone/webapps folder
  • Start the standalone Tomcat and redeploy any apps

Debug Tools

Flash Player Debugger

If you are doing any Flash or Flex development you owe it to your self to get the Flash Player debug version (find it here).  Get the ActiveX one if you are using IE and the Netscape one if you are using Firefox.  This will allow you to connect to the Flash Builder tool and see exactly what’s going on in your apps.

Mosaic Flash Builder Plugin

The Mosaic team has put together a really useful plugin for the Flex Builder 4 IDE.  The LiveCycle Mosaic ES2 Plugin for Flash Builder 4 (FB4) plugin helps with tile creation as well as debugging.  Used in combination with the debug version of the mosaic.war file and the FlashPlayer debug version, you can do all of the standard debugging things that you could with FB4, but inside of the Mosaic framework.  This includes breakpoints, expression watchers, step through, etc.

The tool will even build a temporary Catalog and Application file so you can test Tiles in the framework strait away.  Having said that, however, I usually like to test with my own layouts and catalog setups.  Fortunately I can do this by deploying my Catalog and Application descriptors as per normal (using an ANT script), then I change the Debug Configuration in FB4 to use my setup.  By setting the Host Application and Catalog settings to point to my descriptors I can test the tiles as they would appear to the end user.  For example, in the shot below I have an Application called SalesDashboard and a Catalog called SalesDashboardCatalog.  This setup will launch the debugger using those descriptors:

image

You have 45 seconds to comply

If you are using Firefox as your web browser then you may have noticed that the Flash Player will crash after a short idle time.

image

This is especially annoying when you are debugging because the thing times out and crashes when you are in the middle of looking at variable properties.  This is because of a “feature” in Firefox that crashes the Flash Player after 45 seconds of inactivity.  Fortunately its fairly easy to override this by disabling the hang protection:

  • In Firefox type the following into the address bar (aka the “Location bar”) and hit enter:  about:config
  • Click the “I’ll be careful…” button
  • In the resulting Filter box type: dom.ipc.plugins.timeoutSecs
  • In the resluting dialog box enter -1 and click OK

Now the Flash Player won’t time out while you are trying to debug your application.

Lip Service – Using Mosaic 9.5 Services

LiveCycle Mosaic 9.5 has the concept of a service component.  This is a data store that defines objects that are used by multiple tiles. This allows the exchange of custom data objects between tiles as well as pre-configuring data before a tile is loaded.

In this post, I walk through a simple service example to explain how to put one together.  The source code for this project is located here

Why Services Matter

Why would you go through the effort of putting together a service? What does it give you that you can’t do with “normal” tiles? One good reason is that you need to exchange custom objects between tiles.

If you have multiple tiles that use the same custom object. If you were to compile each of those tiles with the object inside it and then deploy it, you would run into a problem due to the way Mosaic isolates tiles.

For example:

Say you have a complex object called Dog. A dog has several fields: name, color, breed and a Boolean called hungry. Now say you have two tiles that make use of the dog object – AddDog and ShowDogs. The AddDog tile creates a message that sends out a Dog object. The ShowDogs tile watches for a message with the Dog message in it.

When you package your tiles, each one will contain a copy of the Dog object.

clip_image002[4]

Since the Mosaic framework doesn’t know what a Dog object is and there are really two different Dog objects (one for each tile) you are going to get errors.

You could send each individual as a message (or an array of messages), but that gets cumbersome quickly. Also, if your custom object contains complex objects it becomes a problem.

Now let’s look at doing the same thing using Mosaic Services. This time you create an interface and service for the Dog object. The two tiles don’t include the Dog themselves, but they do refer to it.

clip_image002[6]

Now the framework is aware of what a Dog object is. When the AddDog tile sends a message with a Dog in it, the ShowDogs tile will be able to receive the message.

Using Mosaic Services

To create and use Mosaic services you need to do the following:

  • Create an ActionScript interface library. This allows you to separate the definition of the custom object from its implementation.
  • Create the ActionScript service, an implementation of the interface class.
  • Use the services in your tiles. You will be accessing the custom objects using the interface.
  • Add the services, interfaces and tiles to the catalog
  • Add the service reference to the application
  • Deploy the catalog and application to your Mosaic server.

When the user logs in, Mosaic will use the designated service implementation for the custom object based on the references in the application and catalog information. For those of you that are familiar with the Java Spring framework this is similar to Spring’s dependency injection.

Now let’s look at how to build the above mentioned example using services.

The Interface Library

Using FlashBuilder create a new Flex Library Project to hold the interface file(s). Ensure that you are using Flex 3.4 or greater. The interface spells out the fields and functions that must be in the service implementation.

In this case I only have one interface, IDogData. It defines the name, color, breed and hungry fields as well as a toString function that is useful for debugging.

package com.adobe.etech

{

public interface IDogData

{

function get name():String;

function set name(nm:String):void;

function get color():String;

function set color(clr:String):void;

function get breed():String;

function set breed(brd:String):void;

function get hungry():Boolean;

function set hungry(hngy:Boolean):void;

function toString():String;

}

}

The interface library needs to be compiled into a SWF file so it can be deployed to Mosaic. The easiest way to do this is to modify the sample ant scripts that are shipped as part of the stockDataService that comes with Mosaic.

The Service Implementation Library

Now that we have defined what the custom object will do, we need to actually do it. Create another Flex Library Project to hold the service classes. You will need to add a reference to the interface library you just created as well as a reference to the Mosaic tile API swc.

Next create ActionScript implementation classes that implement your interface library classes. The service class will need to have corresponding functions for each of the ones mentioned in the interface. This is where you put the code that carries out the operations that you named in the interface.

In this example, I have only one service class (DogData) that implements the IDogData interface. The service class fleshes out each of the functions from the interface. I have also added a constructor function that allows me to initialize the service at start up. I’ll talk more on that when I discuss the catalog descriptor.

package com.adobe.etech.impl

{

import com.adobe.etech.IDogData;

public class DogData implements IDogData{

private var _name:String;

private var _color:String;

private var _breed:String;

private var _hungry:Boolean;

public function DogData(nm:String=“not set”, clr:String=“not set”, brd:String=“not set”, hngry:Boolean=false){

_name = nm;

_color = clr;

_breed = brd;

_hungry = hngry;

trace (“*********** Dog: “ + this.toString());

}

public function toString():String{

return (_name + “, “ + _color + “, “ + _breed + “, “ + _hungry.toString());

}

public function get hungry():Boolean{

return _hungry;

}

public function set hungry(value:Boolean):void{

_hungry = value;

}

public function get breed():String{

return _breed;

}

public function set breed(value:String):void{

_breed = value;

}

public function get color():String{

return _color;

}

public function set color(value:String):void{

_color = value;

}

public function get name():String{

return _name;

}

public function set name(value:String):void{

_name = value;

}

}

}

Much like the interface library, the service library must be compiled into a SWF. Again, the stockDataService includes an ANT script that serves as a good starting point for how to do this.

Services in Tiles

Now that you have an interface library and a service implementation of that interface; its time to look at how the service is used in your tiles.

Start by creating a new Flex project to hold your tile source code. This project will be like any other Mosaic tile project except that you will include a reference to the service implementation library that you created earlier. I won’t get into creating general Mosaic tiles here, as you can find that information in other Adobe documents.

In your tile code, you will refer to the interfaces and not the service implementations. This is because we want Mosaic to select the correct services to ensure that we are using ones common to all tiles. We don’t want a copy of the service embedded in our tile code.

For example: I have a very simple tile called AddDogs. I want it to share the dog object, specified in the IDogData interface, that is loaded into the application. This will allow me to send IDogData objects as part of Mosaic messages. My Tile code looks like this:

<?xml version=”1.0″ encoding=”utf-8″?>

<mc:Tile xmlns:fx=”http://ns.adobe.com/mxml/2009

xmlns:s=”library://ns.adobe.com/flex/spark

xmlns:mx=”library://ns.adobe.com/flex/mx

xmlns:mc=”com.adobe.mosaic.core.*

layout=”absolute” width=”100%” height=”100%

>

<fx:Script>

<![CDATA[

import com.adobe.etech.IDogData;

import mx.controls.Alert;

[Bindable] public var dogData:IDogData;

protected function addBtn_clickHandler(event:MouseEvent):void{

dogData.name = dname.text;

dogData.color = dcolor.text;

dogData.breed = dbreed.text;

dogData.hungry = hungry.selected;

this.parentView.context.setAttribute(“changedDog”,dogData);

}

]]>

</fx:Script>

<fx:Declarations>

<s:RadioButtonGroup id=”hungryGroup/>

</fx:Declarations>

<mx:Form>

<mx:FormHeading label=”Add a new dog/>

<mx:FormItem label=”Dog’s Name>

<mx:TextInput id=”dname/>

</mx:FormItem>

<mx:FormItem label=”Color>

<mx:TextInput id=”dcolor/>

</mx:FormItem>

<mx:FormItem label=”Breed>

<mx:TextInput id=”dbreed/>

</mx:FormItem>

<mx:FormItem label=”Hungry” id=”dhungry>

<s:RadioButton x=”76” y=”20” id=”hungry” label=”Yes” value=”true” groupName=”hungryGroup/>

<s:RadioButton x=”76” y=”46” id=”nothungry” label=”No” value=”false” groupName=”hungryGroup/>

</mx:FormItem>

<mx:FormItem>

<mx:Button id=”addBtn

label=”Add

click=”addBtn_clickHandler(event)”/>

</mx:FormItem>

</mx:Form>

</mc:Tile>

I have another tile that also uses the IDogData object – ShowDogs. In this case the tile is listening for a message with the dog object and will show it in fields:

<?xml version=”1.0″ encoding=”utf-8″?>

<mc:Tile xmlns:fx=”http://ns.adobe.com/mxml/2009

xmlns:s=”library://ns.adobe.com/flex/spark

xmlns:mx=”library://ns.adobe.com/flex/mx

xmlns:mc=”com.adobe.mosaic.core.*

layout=”absolute” width=”100%” height=”100%

creationComplete=”init()”>

<fx:Declarations>

<!– Place non-visual elements (e.g., services, value objects) here –>

</fx:Declarations>

<fx:Script>

<![CDATA[

import com.adobe.etech.IDogData;

import mx.events.FlexEvent;

import mx.events.PropertyChangeEvent;

import mx.controls.Alert;

[Bindable] public var dogData:IDogData;

private function init():void{

getDogData();

this.parentView.context.addAttributeWatcher(“changedDog”,onDogChange);

}

private function onDogChange(e:PropertyChangeEvent):void{

getDogData();

}

private function getDogData():void{

dogname.text = dogData.name;

dogcolor.text = dogData.color;

dogbreed.text = dogData.breed;

doghungry.text = dogData.hungry.toString();

//Alert.show(dogData.toString(),”Change in Dog”);

}

]]>

</fx:Script>

<s:Label x=”51” y=”48” text=”Name/>

<s:Label x=”51” y=”68” text=”Color/>

<s:Label x=”50” y=”88” text=”Breed/>

<s:Label x=”50” y=”108” text=”Hungry/>

<s:Label x=”115” y=”49” id=”dogname/>

<s:Label x=”115” y=”69” id=”dogcolor/>

<s:Label x=”114” y=”89” id=”dogbreed/>

<s:Label x=”114” y=”109” id=”doghungry/>

</mc:Tile>

Adding Services to the Catalog

I mentioned earlier that the two tiles use the object interface and not any particular implementation of that interface. This is because we only want one implementation loaded, and that should not be in any particular tile. When the tile code runs, however; it will need an instantiated version of the object on which to work.

The Mosaic catalog is used to resolve this issue. In the catalog we will add the service implementation. In the tile descriptions we will create a reference to that service implementation. Mosaic will resolve the references so the running code has access to the instantiated object.

On the file system, in the catalogs folder, we need to add an Interfaces directory and Service directory. Into these we put the compiled interface and service SWF files (or you can have the ANT script do that for you).

image

The Interface Library Entry

In the catalog’s descriptor.xml file, there needs to be an entry for the interface library. The library has a name that will serve as a reference to other entries.

My advice is that you name the library the same as the interface library’s Flex project and SWF file name. There will be a lot of references in the catalog after we’re done and keeping the names strait will be messy enough.

For example, my IDogData interface is in a Flex project called MyDataInterfaceLibrary, so the interface library entry in the catalog looks like this:

<tile:InterfaceLibraryList>

<tile:InterfaceLibrary name=”MyDataInterfaceLibrary“>

<crx:Metadata>

<crx:Description>Dog Data Interfaces</crx:Description>

</crx:Metadata>

<tile:InterfaceList>

<tile:Interface interfaceName=”com.adobe.etech.IDogData“/>

</tile:InterfaceList>

</tile:InterfaceLibrary>

</tile:InterfaceLibraryList>

The Service Library Entry

The service implementation class needs an entry in the catalog as well. The service entry refers to the Interface Library Entry.

It also allows us to set some data when the service instance is first created. When I created the DogData class, I added a constructor that took four parameters. In the Service Library entry in the catalog, I use the ConstructorArgs tag to load some initial data into the instantiated object. That way I’ll have some dog data when the tiles first go to use the object.

<tile:ServiceLibrary name=”MyDataService“>

<crx:Metadata>

<crx:Description>Dog Data service</crx:Description>

</crx:Metadata>

<tile:ServiceClassList>

<tile:ServiceClass className=”com.adobe.etech.impl.DogData name=”SampleDogData scope=”singleton“>

<tile:Implements>

<tile:Interface library=”MyDataInterfaceLibrary interfaceName=”com.adobe.etech.IDogData“/>

</tile:Implements>

<tile:ConstructorArgs>

<tile:Argument value=”Rover“/>

<tile:Argument value=”Brown“/>

<tile:Argument value=”Doberman“/>

<tile:Argument value=”true“/>

</tile:ConstructorArgs>

</tile:ServiceClass>

</tile:ServiceClassList>

One other important thing to note is the scope attribute. By setting its value to singleton, I’m telling Mosaic to create only one instance of that object. All tiles will share that one instance. If anything changes it, it will be changed for ALL tiles.

The Tile Entries

The tile class entries need to be modified to tell Mosaic how to map the interface library types to variables in the tile. This is done by adding a Depends and Property element to the TileClass element.

<tile:TileClass name=”AddDogs label=”AddDogs catalog=”SimpleServiceCatalog initialWidth=”400 initialHeight=”400“>

<crx:Metadata>

<crx:Description><![CDATA[This tile has a description. It can me plain text or contain HTML.]]></crx:Description>

<crx:Category>Dogs</crx:Category>

</crx:Metadata>

<tile:Depends>

<tile:Interface library=”MyDataInterfaceLibrary interfaceName=”com.adobe.etech.IDogData“/>

</tile:Depends>

<tile:Properties>

<tile:Property type=”com.adobe.etech.IDogData name=”dogData“/>

</tile:Properties>

<tile:Content uri=”/mosaic/catalogs/SimpleServiceCatalog/tiles/AddDogs/content contentType=”application/x-shockwave-flash loadAs=”default“/>

</tile:TileClass>

The Depends clause tells us that this tile uses interfaces from the specified interface library. The Property element tells us that the interface maps to a specific variable in the tile. If you look at the tile’s MXML code you will see a variable that corresponds to the name attribute. In this case there is the line:
[Bindable] public var dogData:IDogData;

So this maps the interface library to the content of the tile, note that it does not mention the service library. This is done in the application’s descriptor.

Putting it all Together with the Application Descriptor

The final step is to use the application descriptor to identify the exact service that will carry out the work of the interface. A properties element will be added to each tile reference that uses the service. This will map the service to the property. When combined with the catalog entry for the tile, this will inject the service into the tile’s variable.

For example:

<tile:TileReference name=”AddDogs label=”Add Dogs catalog=”SimpleServiceCatalog“>

<tile:Properties>

<tile:Property name=”dogData“>

<tile:ServiceReference catalog=”SimpleServiceCatalog library=”MyDataService name=”SampleDogData“/>

</tile:Property>

</tile:Properties>

</tile:TileReference>

This entry tells Mosaic to map the SampleDogData service to the dogData property in the AddDogs tile. If you look at the catalog entry for that tile you can see that the dogData parameter is an IDogData object. You can also see that the SampleDogData service is a DogData class with some pre-named values supplied to the constructor.

What’s it look like

Assuming all of the code, packaging and mapping was done right; the application should be deployable now. Once that’s done you should be able to run it by going to the application’s URL. In the example the application is called SimpleService. It should look like the following:

image

You can see that there are two tiles: the AddDog on the left and the ShowDogs on the right. One thing to note is that the ShowDogs tile has data to start. This is because the initial data was listed in the catalog along with the service entry.

If I make changes to the dog’s data using the AddDog tile and hit the Add button then the data in the ShowDogs tile will change as well.

image

This is because the Add button click handler sets a Mosaic attribute that includes the IDogData object. The ShowDogs tile on the other hand is watching for a message that includes an IDogData object. If I loaded a new tile that used the same service I would see the new data, this is because service was marked as a singleton.