<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
   <title>Comtaste Consulting | Enterprise RIA consulting and development</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/" />
   <link rel="self" type="application/atom+xml" href="http://blog.comtaste.com/atom.xml" />
   <id>tag:blog.comtaste.com,2010://1</id>
   <updated>2010-08-03T16:24:02Z</updated>
   <subtitle>Enterprise RIA development and consulting with Adobe Flex 3, LiveCycle Data Services, Flex Data Services, Actionscript 3, Java and J2EE</subtitle>
   <generator uri="http://www.sixapart.com/movabletype/">Movable Type 3.33</generator>

<entry>
   <title>Fixing the horizontal scroll for the Flex Text Highlighter Class</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/08/fixing_the_horizontal_scroll_f.html" />
   <id>tag:blog.comtaste.com,2010://1.125</id>
   
   <published>2010-08-03T15:45:47Z</published>
   <updated>2010-08-03T16:24:02Z</updated>
   
   <summary>Recently I happened to have to implement a textarea to highlight the research done inside a textarea. For this I found an excellent library that was just in my case: Flex Text Highlighter Class. But if you turn wordwrap on...</summary>
   <author>
      <name>Liviu Stoica</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Recently I happened to have to implement a textarea to highlight the research done inside a textarea. For this I found an excellent library that was just in my case: <a href="http://tom-lee.blogspot.com/2007/01/update-flex-text-highlighter-class.html">Flex Text Highlighter Class</a>.
But if you turn wordwrap on the textarea and horizontal scroll appears that the library was unable to move to different results.
Then download this example you will find the library clean by this bug.

<a href="http://www.comtaste.com/demo/blog/HighlighterDemo/HighlighterDemo.html">Demo</a> --- <a href="http://www.comtaste.com/demo/blog/HighlighterDemo/srcview/index.html">Source</a>]]>
      
   </content>
</entry>
<entry>
   <title>Adobe Alchemy: a comparative example</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/adobe_alchemy_a_comparative_ex.html" />
   <id>tag:blog.comtaste.com,2010://1.124</id>
   
   <published>2010-07-12T15:36:04Z</published>
   <updated>2010-08-27T09:37:09Z</updated>
   
   <summary><![CDATA[In my last post I introduced the Alchemy Project and I explained how to install/set up the Alchemy environment on a Window machine to compile a very simple &quot;c&quot; file in a swc. Today I'll go deeper and talk about...]]></summary>
   <author>
      <name>Luca Galati</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="226" label="c" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="227" label="c++" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="1" label="test" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my last <a href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html">post</a> I introduced the Alchemy Project and I explained how to install/set up the Alchemy environment on a Window machine to compile a very simple &quot;c&quot; file in a swc. 
Today  I'll go deeper and talk about Alchemy through a comparative example:  Alchemy aimes to allow users to take advantage of efficient C/C++ (existing or not) designed to accomplish very cpu-intensive tasks. The performance improvements of flex applications can be very significant e I'll try to give you a sample, with a simple test: I've implemented an inefficient and decidedly didactic ordering algorithm, the <a href="http://en.wikipedia.org/wiki/Bubble_sort">BubbleSort</a>, either in Actionscript and in C/Alchemy. Then I've tested both implementation to order an actionscript reverse ordered array of integers with 20,000 elements(the worst case for the bubblesort algorithms). 

Here is the Actionscript implementation:

<pre class="brush: as3">
public function bubbleSort(array:Array):void
{
	var temp:int = 0;
	var alto:int = array.length;
	while(alto &gt; 0)
	{
		for(var i:int = 0; i&lt;alto; i++)
		{
			if(array[i] &gt; array[i+1])
			{
				temp = array[i];
				array[i] = array[i+1];
				array[i+1] = temp;
			}
		}
		alto--;
	} 
}
</pre>

and here I show you the C implementation

<pre class="brush:cpp">
void BubbleSort(int *array, int array_size)
{
   
  int i, tmp;
  int bound = array_size; 
 
  while (bound &gt; 1)
  {
	for (i=0; i&lt;bound-1; i++)
    {
        if (array[i] &gt; array[i+1]) 
        { 
			tmp = array[i]; 
            array[i] = array[i+1]; 
            array[i+1] = tmp;
        } 
    }
    bound--; 
  }
}
</pre>

Unfortunately I couldn't use the C implementation as it is. I needed to write some more code using Alchemy actionscript/C Api to realize the translation of the Actionscript array to the C integer array data structure:

<pre class="brush:cpp">
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include &quot;AS3.h&quot;
 
//INSERT HERE THE C IMPLEMENTATION OF THE BUBBLESORT ALGORITHM
 
static AS3_Val orderArray(void* self, AS3_Val args)
{
	//Creating a C representation of the Actionscript Array object
	AS3_Val actionscript_array = NULL;
	AS3_ArrayValue( args, &quot;AS3ValType&quot;, &amp;actionscript_array );
	 
	/*
	 *         Translation process from Actionscript to C in 4 steps:
	 */
	//STEP 1 : calculating the dimension of the Actionscript array
	AS3_Val actionscript_array_size =  AS3_GetS(actionscript_array, &quot;length&quot;);
	int array_size = AS3_IntValue(actionscript_array_size);
 	
	//STEP 2: declaring the C array to use with BubbleSort
	int array_c[array_size];
 	
	//STEP 3 : ActionScript function pop() of Array Class
	AS3_Val pop_function = AS3_GetS(actionscript_array, &quot;pop&quot;);
	AS3_Val emptyParams = AS3_Array(&quot;&quot;);
 	
	//STEP 4(iterative): Extracting the actionscript integer values from the actionscript array
	//and storing them into the c array
	int i = 0;
	for(i = array_size-1; i &gt;= 0 ; i--)
	{
		AS3_Val temp_actionscript_Int = AS3_Call(pop_function, actionscript_array, emptyParams);
		int tmp = AS3_IntValue(temp_actionscript_Int);
		array_c[i] = tmp;
		AS3_Release(temp_actionscript_Int);
	}
	AS3_Release(pop_function);
	/*
	 *   END of Translation process from actionscript to C
	 */
 	
	/*
	 *      Ordering operations: invoking the Bubble Sort on the c array of integers
	 */
	BubbleSort(array_c, array_size);
 	
	/*
	 *         Translation process from C to actionscript:
	 */
 	 
	//ActionScript function push() of Array Class
	AS3_Val push_function = AS3_GetS(actionscript_array, &quot;push&quot;);
 	
	//Storing the ordered integer values into a new actionscript array object
	int j;
	for( j = 0; j &lt; array_size ; j++)
	{
		AS3_Val int_to_push = AS3_Array(&quot;IntType&quot;, array_c[j]);
		AS3_Call(push_function, actionscript_array, int_to_push );
		AS3_Release(int_to_push);
	}
	AS3_Release(push_function);
 	
	return actionscript_array;
	/*
	 *   END of Translation process from C  to actionscript
	 */
}
 
//entry point for code
int main()
{
	//define the methods exposed to ActionScript
	//typed as an ActionScript Function instance
	AS3_Val orderArrayMethod = AS3_Function( NULL, orderArray );
 
	// construct an object that holds references to the functions
	AS3_Val result = AS3_Object( &quot;orderArray: AS3ValType&quot;, orderArrayMethod );
 
	// Release
	AS3_Release( orderArrayMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}
</pre>

As a consequence, when analyzing the test results, we have to consider the extra work the C/Alchemy implementation of the algorithm did to realize the ordering task.

To compile the previous code follow the instruction I showed in this <a href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html">post</a>
to obtain a file .swc you can use in a flex test application as I did in may test example.

Here the code of my flex test application:

<pre class="brush: as3">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;horizontal&quot; creationComplete=&quot;init();&quot;&gt;
	
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import mx.collections.ArrayCollection;
			
			import cmodule.bubblesort.CLibInit;			
			
			private var startDate:Date;
			private var stopDate:Date;
			
			private function init():void
			{
				
				this.addEventListener(&quot;actionscriptSortComplete&quot;,handler);
				this.addEventListener(&quot;cSortComplete&quot;,handler);
				var intArray:Array = new Array();
				var intArray2:Array = new Array();
				for(var i:int = 20000; i &gt; 0; i--)
				{
					intArray.push(i);
					intArray2.push(i);
				}
				list.dataProvider = intArray;
				list2.dataProvider = intArray2;
			}
			
			
			//INSERT HERE THE CODE OF THE ACTIONSCRIPT IMPLEMENTATION OF BUBBLESORT ALGORTHM
			
			public function orderArray(event:Event):void
			{
				startDate = new Date;
				
				if(event.target.id == &quot;actionscriptOrderingButton&quot; )
				{
					var source1:Array = (list.dataProvider as ArrayCollection).source;
					bubbleSort(source1);
					this.dispatchEvent(new Event(&quot;actionscriptSortComplete&quot;));
				}
				else
				{
					var loader:CLibInit = new CLibInit();
					var lib:Object = loader.init();
					var source2:Array = (list2.dataProvider as ArrayCollection).source;
					list2.dataProvider = lib.orderArray(source2);
					this.dispatchEvent(new Event(&quot;cSortComplete&quot;));
				}
				
				
			}
			
			public function handler(event:Event):void
			{
				stopDate = new Date();
				var diff:Number = stopDate.getTime() - startDate.getTime();
				if(event.type == &quot;actionscriptSortComplete&quot;)
				{
					timeLabel.text = &quot;time elapsed : &quot;+diff/1000+&quot; sec!&quot;;
					(list.dataProvider as ArrayCollection).refresh();
				}
				else
				{
					timeLabel2.text = &quot;time elapsed :&quot;+diff/1000+&quot;sec!&quot;;
					(list2.dataProvider as ArrayCollection).refresh();
				}
				
			}
			
		]]&gt;
	&lt;/mx:Script&gt;
	
	&lt;mx:List id=&quot;list&quot; width=&quot;30%&quot;  /&gt;
	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;actionscriptOrderingButton&quot; label=&quot;Actionscript BubbleSort&quot; click=&quot;orderArray(event);&quot;  /&gt;
		&lt;mx:Label id=&quot;timeLabel&quot; text=&quot;...&quot; /&gt;
	&lt;/mx:VBox&gt;
	&lt;mx:List id=&quot;list2&quot; width=&quot;30%&quot;/&gt;
	&lt;mx:VBox&gt;
		&lt;mx:Button id=&quot;cOrderingButton&quot; label=&quot;C BubbleSort&quot; click=&quot;orderArray(event);&quot;  /&gt;
		&lt;mx:Label id=&quot;timeLabel2&quot; text=&quot;...&quot; /&gt;
	&lt;/mx:VBox&gt;
	&lt;mx:Label id=&quot;lb2&quot; text=&quot;&quot; /&gt;
	
	
&lt;/mx:Application&gt;
</pre>

And here are some screenshots of the results obtained by the test application:
<img alt="test-actionscriptbubblesort.PNG" src="http://blog.comtaste.com/test-actionscriptbubblesort.PNG" width="553" height="202" />

<img alt="test-cbubblesort.PNG" src="http://blog.comtaste.com/test-cbubblesort.PNG" width="505" height="203" />

To order an array of 20,000 integers in the worst case:
- the actionscript algorithm spent : 32.031 sec
- the Alchemy/C algorithm spent : 7 sec
Using the Alchemy/C implementation of bubblesort I got an improvement in speed of about 75%.
This is certainly an encouraging result and an evidence that Alchemy can be exploited by developers to improve performance of the most intensive task executed by their flex application.
]]>
      
   </content>
</entry>
<entry>
   <title>Managing Java Http sessions in GAE applications</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/managing_session_data_in_gae_a.html" />
   <id>tag:blog.comtaste.com,2010://1.121</id>
   
   <published>2010-07-08T09:27:34Z</published>
   <updated>2010-07-08T23:51:02Z</updated>
   
   <summary>When a J2EE developer starts the design of a Google App Engine application he has to face some problems and adapts some of the well-established design patterns in web application development. Let&apos;s start with a bit of introduction to explain...</summary>
   <author>
      <name>Emanuele Tatti</name>
      <uri>http://www.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[When a J2EE developer starts the design of a Google App Engine application he has to face some problems and adapts some of the well-established design patterns in web application development. Let's start with a bit of introduction to explain what is a Google App Engine application. 

<h3>What is Google App Engine</h3>

Citing the corresponding google <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html">page</a>: "Google App Engine lets you run your web applications on Google's infrastructure. App Engine applications are easy to build, easy to maintain, and easy to scale as your traffic and data storage needs grow. With App Engine, there are no servers to maintain: You just upload your application, and it's ready to serve your users."
Basically Google App Engine is a service that lets you put your application "in the cloud", a cloud completely managed by Google, so you don't have to worry about the scalability or reliability of your application. Every request made to a page of your application will be managed by one of the server in this infrastructure, but no one can guarantee that the next request will be assigned to that machine as well.

<h3>How the http session is managed</h3>
Session handling must be explicitly enabled by adding to your app engine configuration file <em><sessions-enabled>true</sessions-enabled></em> and then you will be able to access the session from within RPC services with:

<pre class="brush:java">
this.getThreadLocalRequest().getSession();
</pre>

When you enable it, you will find serialized sessions among your datastore entities as <em>_ah_SESSION</em>, this is due to the fact that "the cloud" will read and write sessions from and to the datastore, and not from and to memory as the J2EE specification states (excluding an application deployed on a cluster).
Every time the HttpSession setAttribute method is invoked, the related datastore entity is updated and every subsequent invocation to the related getAttribute method will return the same object, as you would expect from a standard web application. The problem is when your services manipulate objects stored in the session, in that case your changes will be lost when another service will get the object from the session. A very simple sample:

<strong>Service A</strong>

<pre class="brush:java">
Person p = new Person();
p.setName("Jack");
session.setAttribute("person", p);
</pre>

<strong>Service B</strong>

<pre class="brush:java">
Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack"
p.setName("Andy");
</pre>

<strong>Service A again</strong>

<pre class="brush:java">
Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack" in GAE, 
// prints "Andy" in a standard J2EE evironment
</pre>

If you want a consistent behaviour you need to invoke setAttribute again after having modified the Person object in the session. This workaround will solve all the inconsistencies but has a pretty important trade-off, every setAttribute will trigger a new serialization and write to the datastore; ok, you are in the Google cloud, but the free resources are limited.  

<h3>Alternatives to the http session</h3>

There are a lot of alternative implementantion of session utilities if you use Python:  http://wiki.github.com/dound/gae-sessions/ (it also has a comparison table with other libraries). For Java developers the only alternative is to use the <a href="http://code.google.com/appengine/docs/java/memcache/overview.html">Memcache</a> service and/or the <a href="http://code.google.com/appengine/docs/java/datastore/overview.html">DataStore</a> service. While the former has the problem of the data expiration strategy: <a href="http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires">http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires</a>, the latter will suffer of the same performance problems of the GAE session implementation.


]]>
      
   </content>
</entry>
<entry>
   <title>Flex Webservice: how to list available parameters for each operation</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/07/flex_webservice_how_to_list_av_1.html" />
   <id>tag:blog.comtaste.com,2010://1.123</id>
   
   <published>2010-07-03T16:14:35Z</published>
   <updated>2010-07-03T16:22:29Z</updated>
   
   <summary>In a previous post I explained how to list available operations provided by a WebService, parsing the WSDL document using some undocumented classes of the Flex 3 and 4 SDKs. This time I want to give you some suggestions about...</summary>
   <author>
      <name>Francesco Rapanà</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Web 2.0 Applications" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="210" label="webservice" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="223" label="wsdl" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In a <a href="http://blog.comtaste.com/2010/03/flex_webservice_how_to_list_av.html" target="_blank">previous post</a> I explained how to list available operations provided by a WebService, parsing the WSDL document using some undocumented classes of the Flex 3 and 4 SDKs.
This time I want to give you some suggestions about the next step: listing parameters of every operation.
NB: most of the classes in the package mx.rpc.wsdl have the tag [ExcludeClass] so they could change with an SDK update or they can be not stable. Flex Builder intellisense will not work for these classes, so you have to import them manually.
Note that I'm testing this code using a WSDL from a Axis2 WebService, it may not work on WSDL with a different structure or it may need some tweaks.

<pre class="brush: as3">
&lt;mx:Script&gt;
	&lt;![CDATA[
		import mx.rpc.soap.LoadEvent;
		import mx.rpc.wsdl.WSDLMessagePart;
		import mx.rpc.wsdl.WSDLOperation;
		import mx.rpc.xml.Schema;
		protected function loadHandler(event:LoadEvent):void
		{
			if(event.wsdl) {
				for each(var op:WSDLOperation in event.wsdl.getPort().binding.portType.operations()) {
					var param:WSDLMessagePart = op.inputMessage.getPart("parameters");
					if(param) {
						var schema:Schema = event.wsdl.schemaManager.getResourcesForURI(param.element.uri)[0] as Schema;
						var element:Object = schema.getNamedDefinition(new QName(schema.schemaConstants.xsdURI,param.element.localName),schema.schemaConstants.elementTypeQName);
						trace(element.definition, element.schema);
					} 
				}
			}
		}
	]]&gt;
&lt;/mx:Script&gt;</pre>

This small script, based on the code of the <a href="http://blog.comtaste.com/2010/03/flex_webservice_how_to_list_av.html" target="_blank">previous post</a>, analyze the inputMessage of the WSDLOperation. If there is a WSDLMessagePart with name "parameters", it looks for the related Schema and then it searches the definition of the element of the WSDLMessagePart. This definition is just the XML of the complexType of the parameter, then you have to write your custom logic to use it. Some WSDL may non have the "part" node, instead there is the name of the element, you have to slightly modify the code above.

This is just a sketch and not a ready-to-use solution but it can point you in the right direction.]]>
      
   </content>
</entry>
<entry>
   <title>Security Data Trasfer - AS3 Encrypting Libraries and Http Monitor Softwares </title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/security_data_trasfer_as3_encr_1.html" />
   <id>tag:blog.comtaste.com,2010://1.122</id>
   
   <published>2010-06-24T13:36:10Z</published>
   <updated>2010-06-24T14:41:34Z</updated>
   
   <summary>One of the most important problem in Application development is the Security of Data Transfer from\to Client to\from Server. The Flash Player environment has a lot of security rules and controls to safeguard data in the Web, but sometimes it&apos;s...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="252" label="ActionScript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="246" label="as3corelib" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="247" label="as3crypto" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="243" label="Charles" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="239" label="Encryption" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="249" label="MD5" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="245" label="SWFScan" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[One of the most important problem in Application development is the Security of Data Transfer from\to Client to\from Server. The Flash Player environment has a lot of security rules and controls to safeguard data in the Web, but sometimes it's not enough, so we have to integrate them with Encrypting Algorithms develops in our ActionScript Classes. Now we are going to see a little overview that allows us a knowledge of the most simple and useful AS library for encrypting data.

The first library is the as3crypto library. This is available in the Google Code at this <a href='http://code.google.com/p/as3crypto/'>address</a>  . As you can see on the documentation, the library provides a lot of  Hashing Algorithms, like MD5 and SHA-256, Public Key Encryption Algorithms , like RSA, and Secret Key Encryption Algorithms, and introduces a SSL engine. I suggest to see the <a href='http://crypto.hurlant.com/demo/ '>demo</a> with all the functionalities of the as3crypto library. Another Encrypting Library is as3corelib. Like the  as3crypto, the  as3corelib is published on Goggle Code at the <a href='http://code.google.com/p/as3corelib/'>address</a>, here is the source code of the library and the documentation, but there isn't a demo about it.  as3corelib also does not have Encryption Algorithms but only Hashing  Algorithms. 

Sometimes it is useful to measure the Security of our applications, so we can use these free products to see the data transfer between Client and Server : SWFScan by HP and Charles. SWFScan automatically find security vulnerabilities in applications built on the Flash Platform. It  decompiles applications built on the Flash Platform to extract the ActionScript code and statically analyzes it to identify security issues such as information disclosure; identifies and reports insecure programming and deployment practices; and suggests solutions. You can download it from this <a href='http://www.hp.com/go/swfscan '>site</a>. 
HP SWFScan offers several other features to help developers, code auditor/reviewers, and pen-testers examine the contents of Flash applications, including:
<ul>
<li>Highlighting the line of source code that contains the vulnerability to help better understand the context of the issue.</li>
<li>Providing summaries, details, and remediation advice for each vulnerability in accordance with Adobe's recommendation for secure Flash development.</li>
<li>Generating a vulnerability report to share and solve the detected issues.</li>
<li>Exporting the decompiled source code for use with other external tools.</li>
<li>Revealing all the URLs and web services the Flash Application contacts.</li>
<li>Flagging class names, function names, or variable names that may be of interest such as 
loadedUserXml or crypt().</li>
</ul>

Charles is an Http Proxy and an HTTP Monitor, it is enable to see all the data transfer in a browser web or between a client and a server, it is also ables to monitor the AMF protocol traffic. You can have more information <a href='http://www.charlesproxy.com'>here</a> . I think it's a very useful tool for the visualization of Data Trasfer between client and Server and it takes a great support for evidence the bugs in security in our SWF Applications. Next time i will deepen all the functionalities of this Software.

Regards
 ]]>
      
   </content>
</entry>
<entry>
   <title>UiBinder : a simple way to build Widget from XML markup</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/uibinder_a_simple_way_to_build.html" />
   <id>tag:blog.comtaste.com,2010://1.120</id>
   
   <published>2010-06-11T14:55:03Z</published>
   <updated>2010-06-11T15:30:26Z</updated>
   
   <summary>UiBinder helps developers to build GWT widgets in a few simple steps, exploiting the flexibility and maintainability of XML. This allows developer without a strong background in java to be competitive in the GWT code production. Thus we see UiBinder...</summary>
   <author>
      <name>Michele del Prete</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Google apps" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Java" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="234" label="GWT" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="235" label="Java" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="237" label="UiBinder" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[UiBinder helps developers to build GWT widgets in a few simple steps, exploiting the flexibility and maintainability of XML. This allows developer without a strong background in java to be competitive in the GWT code production.

Thus we see UiBinder in action : first of all we must create a web application that use Google Web Toolkit. To do this, I use the eclipse's plugin for GWT, so from the prompt do :
File --> New --> Other --> Google --> Web application project. Then fill the required fields, uncheck the "Use Google app engine" option and click "Finish".

Now we realize the following html page containing a simple widget :

<img alt="simplewidget.png" src="http://blog.comtaste.com/simplewidget.png" width="448" height="524" />

Initially we have to modify the home page, an HTML page, in which we create a "div" element that permit us to inject content from a Java class, the entryPoint :

<pre class="brush: xml">

&lt;!doctype html&gt;
 
&lt;html&gt;
  &lt;head&gt;
    &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
 
    &lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;PostBlogUiBinder.css&quot;&gt;
 
    &lt;title&gt;Simple widget project&lt;/title&gt;
    
    &lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot; src=&quot;postbloguibinder/postbloguibinder.nocache.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
 
  &lt;body&gt;
 
    &lt;!-- OPTIONAL: include this if you want history support --&gt;
    &lt;iframe src=&quot;javascript:''&quot; id=&quot;__gwt_historyFrame&quot; tabIndex='-1' style=&quot;position:absolute;width:0;height:0;border:0&quot;&gt;&lt;/iframe&gt;
    
    &lt;!-- RECOMMENDED if your web app will not function without JavaScript enabled --&gt;
    &lt;noscript&gt;
      &lt;div style=&quot;width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif&quot;&gt;
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      &lt;/div&gt;
    &lt;/noscript&gt;
 
    &lt;h1&gt;Sample Widget&lt;/h1&gt;
 
    &lt;h3 align=&quot;center&quot;&gt;Fill the following fields&lt;/h3&gt;
     
    &lt;div id=&quot;simpleWidget&quot; align=&quot;center&quot;&gt;&lt;/div&gt;
    
  &lt;/body&gt;
&lt;/html&gt;

</pre>


as you can see we have create a div element with id called "simpleWidget" that we refer from the entrypoint java class.

Now we have to inject into this page the widget that we want to create. We do this into the entrypoint class, called SimpleWidgetEntrypoint :


<pre class="brush: java">


import com.post.uibinder.ui.SimpleWidget;
import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.user.client.ui.RootPanel;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SimpleWidgetEntrypoint implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
SimpleWidget simpleWidget = new SimpleWidget();
RootPanel.get("simpleWidget").add(simpleWidget);
}
}

</pre>

Now we have to create our widget, we can do this with the wizard plugin doing the following actions :

from the eclipse's prompt do File --> New --> Other --> Google Web Toolkit --> UiBinder --> Next

then digit the name of the java class of the widget, in our case "SimpleWidget" and then click Finish.

We can see now that the wizard has created two files :

- SimpleWidget.java
- SimpleWidget.ui.xml

To obtain our result widget we have to modify both files :

- SimpleWidget.ui.xml


<pre class="brush: xml">

&lt;!DOCTYPE ui:UiBinder SYSTEM &quot;http://dl.google.com/gwt/DTD/xhtml.ent&quot;&gt;
&lt;ui:UiBinder xmlns:ui=&quot;urn:ui:com.google.gwt.uibinder&quot;
xmlns:g=&quot;urn:import:com.google.gwt.user.client.ui&quot;&gt;
&lt;ui:style&gt;
.important {
font-weight: bold;
}
&lt;/ui:style&gt;
&lt;g:HTMLPanel ui:field=&quot;mainPanel&quot;&gt;
&lt;g:VerticalPanel&gt;
&lt;g:Label ui:field=&quot;descriptionLabel&quot; ui:text=&quot;Put a description of yourself&quot;&gt;&lt;/g:Label&gt;
&lt;g:TextArea ui:field=&quot;textArea&quot; ui:text=&quot;Put here your description&quot;&gt;&lt;/g:TextArea&gt;
&lt;g:Label ui:field=&quot;banLabel&quot; ui:text=&quot;Select which band you prefer among these&quot;&gt;&lt;/g:Label&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;U2&quot; &gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Radiohead&quot;&gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Pearl Jam&quot;&gt;&lt;/g:RadioButton&gt;
&lt;g:RadioButton ui:name=&quot;band&quot; ui:text=&quot;Depeche mode&quot;&gt;&lt;/g:RadioButton&gt;
&lt;/g:VerticalPanel&gt;
&lt;g:Button styleName=&quot;{style.important}&quot; ui:field=&quot;button&quot; ui:text=&quot;Confirm&quot; /&gt;
&lt;/g:HTMLPanel&gt;
&lt;/ui:UiBinder&gt; 

</pre>


- SimpleWidget.java

<pre class="brush: java">

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class SimpleWidget extends Composite {

private static SimpleWidgetUiBinder uiBinder = GWT
.create(SimpleWidgetUiBinder.class);

interface SimpleWidgetUiBinder extends UiBinder<Widget, SimpleWidget> {
}

@UiField
Button button;
@UiField
TextArea textArea;

public SimpleWidget() {
initWidget(uiBinder.createAndBindUi(this));
textArea.setSize("300px", "200px");
}

@UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("OK");
}

}

</pre>

To build the widget we need the following GWT elements :

- VerticalPanel
- Label
- RadioButton
- Button
- TextArea

if we don't use the UiBinder utilities we have to write the entire widget only with java code, but this time into the SimpleWidget java class we have only specified the size of the text area, all the other elements with their values are specified into the XML file.
This is why UiBinder simplifies the construction of GWT widget and simplifies also the collaboration between UI designers, which are more confortable with markup languages, and developers.]]>
      
   </content>
</entry>
<entry>
   <title>Binding improvement</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/06/binding_improvement.html" />
   <id>tag:blog.comtaste.com,2010://1.119</id>
   
   <published>2010-06-07T15:39:09Z</published>
   <updated>2010-06-08T10:46:12Z</updated>
   
   <summary>Since Flex 2, the Adobe Flex sdk&apos;s contain a class named BindingManager, unfortunately it&apos;s not documented in the released ASDoc, but this class it&apos;s really helpful to us to manage and debug all kind of binding inside our applications. BindingManager.debugBinding:...</summary>
   <author>
      <name>Liviu Stoica</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="50" label="actionscript" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="183" label="binding" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Since Flex 2, the Adobe Flex sdk's contain a class named BindingManager, unfortunately it's not documented in the released ASDoc, but this class it's really helpful to us to manage and debug all kind of binding inside our applications.


<strong>BindingManager.debugBinding:</strong>
Using the static method provided by the manager you will enable the debug for the property passed as parameter for the method like this:
<pre class="brush: as3">BindingManager.debugBinding( "myComponent.propertyToDebug" )</pre>

Now when you lunch your application in debug mode, you can see in the console something like this:
<em>Binding: destString = myComponent.prpertyToDebug, srcFunc result = First value
Binding: destString = myComponent.prpertyToDebug, error = TypeError: Error #1009: Cannot access a property or method of a null object reference.
Binding: destString = myComponent.propertyToDebug, srcFunc result = Changed value
</em>

<strong>BindingManager.setEnabled:</strong>
Another very handy method can be the setEnabled. By using this static method you will enable or disable all bindings for a specified component or document:
<pre class="brush: as3">BindingManager.setEnabled( yourComponent, true );</pre>


<strong>Discover all bindinded properties of a component:</strong>
From Flex 2 all documents property of the displayObject components have a non-null public _bindingsByDestination variable, containing the binding instances currently executed for the specified component.
So if you iterate inside the document._bindingsByDestination by String you will access to the "myComponent.bindedProperty":
<pre class="brush: as3">
use namespace mx_internal;
 
for (var binding:String in myComponent.document._bindingsByDestination)
{
   trace( binding );
  
  //And to access the to the binding instance use this:
  var myBinding:Binding = myComponent.document._bindingsByDestination[ binding ];  
}</pre>

This can be accessible only if you specify the use namespace <strong>mx_internal</strong>.
]]>
      
   </content>
</entry>
<entry>
   <title>Swiz framework - Custom Metadata Processor</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/swiz_framework_custom_metadata.html" />
   <id>tag:blog.comtaste.com,2010://1.118</id>
   
   <published>2010-05-31T13:40:23Z</published>
   <updated>2010-06-22T15:06:24Z</updated>
   
   <summary>In my last post I briefly introduced Swiz framework and uncovered part of its great potential. This post will be about Swiz&apos;s custom metadata processor, a powerful tool available with the 1.0 release. The metadata processors were available in previous...</summary>
   <author>
      <name>Constantin Moldovanu</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="232" label="metadata" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="224" label="swiz" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my <a href="http://blog.comtaste.com/2010/04/swiz_framework_inversion_of_co.html">last post</a> I briefly introduced Swiz framework and uncovered part of its great potential. This post will be about Swiz's custom metadata processor, a powerful tool available with the 1.0 release. The metadata processors were available in previous versions also, but now their API is open and allows developers to create their own ActionScript metadata and handle them rather easily.

As an example shows on <a href="http://swizframework.org/2009/12/swiz-1-0-reflection-api-and-custom-metadata-processors/">their site</a>, one has to choose a new metadata name and extend <code>org.swizframework.processors.BaseMetadataProcessor</code> (this class was called MetadataProcessor in the alpha release). In the example, a <em>Random</em> metadata was created, that assigns a random numeric value to any variable it decorates:
<pre class="brush: as3">
	[Random]
	public var randomNumber:Number;
</pre>

Such custom metadata are is extremely easy to use: once the processor class is created, it can simply be added to Swiz's custom processors:
<pre class="brush: xml">
	&lt;swiz:customProcessors&gt;
		&lt;processors:RandomProcessor /&gt;
	&lt;/swiz:customProcessors&gt;
</pre>

Obviously one should remember to edit the compiler parameters in order to add support for the newly created metadata: <code>-keep-as3-metadata+=Random</code>.

Since it came out, many useful custom metadata processors have been developed and released. Some of them, in no particular order, are:
<ul>
<li><a href="http://www.riaspace.net/2009/12/logprocessor-custom-metadata-processor-for-swiz-1-0-0/">Log processor</a>: just add a <em>[Log]</em> decoration to an instance of ILogger, to enable fast access to Flex logging API.</li>
<li><a href="http://odoe.net/thelab/flex/geocodeprocessor/GeocodeProcessor.html">Geocode Processor</a>: automatizes parts of the ESRI geolocation features.</li>
<li><a href="http://soenkerohde.com/2010/03/swiz-yahoo-finance-metadata-processor/">Yahoo Finance</a>: proof of concept that uses live data from Yahoo to populate a list decorated with custom metadata.</li>
<li><a href="http://code.google.com/p/foomonger-swizframework/">Foomonger</a>: metadata processor that simplifies the use of Swiz with <a href="http://code.google.com/p/as3-signals/">AS3signals</a></li>
</ul>

ActionScript metadata are customizable by themselves, but using Swiz framework makes the task more easy and fun. Looking forward to see a <a href="http://code.google.com/p/gag/">[WrittenWhile]</a> metadata!
]]>
      
   </content>
</entry>
<entry>
   <title>Using an editable Combobox as itemrenderer</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/using_an_editable_combobox_as.html" />
   <id>tag:blog.comtaste.com,2010://1.117</id>
   
   <published>2010-05-23T17:27:51Z</published>
   <updated>2010-05-23T17:53:12Z</updated>
   
   <summary>Flex editable combobox can be really useful if you need to let the user select either one of the predefined values or a custom input. The same result can be achieved using a TextInput for custom text and a button...</summary>
   <author>
      <name>Francesco Rapanà</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="3" label="flex 3" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Flex editable combobox can be really useful if you need to let the user select either one of the predefined values or a custom input. The same result can be achieved using a TextInput for custom text and a button that shows a non editable Combobox, but this solution looks less user friendly.
In this post I will show how to use an editable Combobox as itemrenderer in a List. This approach can be not the best (for example you can use an itemEditor) but maybe you will find the same issues using alternative solutions.
Let’s start creating a simple List with an ArrayCollection of CustomObject as dataProvider and using a custom itemRenderer:

Application.mxml
<pre class="brush: as3">
&lt;mx:Script&gt;
	&lt;![CDATA[
		import mx.collections.ArrayCollection;
		
		private var optionsAC:ArrayCollection = new ArrayCollection([
			"option1","option2","option3"
			]);
		[Bindable]
		private var myAC:ArrayCollection = new ArrayCollection([
			new CustomObject(false,"",optionsAC),
			new CustomObject(true,"custom Test",optionsAC),
			new CustomObject(false,"",optionsAC,2),
			]);
	]]&gt;
&lt;/mx:Script&gt;
&lt;mx:List dataProvider="{myAC}" width="300"
		 itemRenderer="customItemRenderer" /&gt;
</pre>
CustomObject.as
<pre class="brush: as3">
package
{
	import mx.collections.ArrayCollection;
	
	public class CustomObject
	{
		public var custom:Boolean;
		public var customString:String;
		public var options:ArrayCollection;
		public var optionIndex:int;
		
		public function CustomObject(c:Boolean = false,s:String = "",o:ArrayCollection = null ,oInd:int = 0)
		{
			custom = c;
			customString = s;
			options = o;
			optionIndex = oInd;
		}
	}
}
</pre>
customItemRenderer.mxml
<pre class="brush: as3">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%"&gt;
		
	&lt;mx:Script&gt;
		&lt;![CDATA[
			
			import mx.events.FlexEvent;
			
			override public function set data(value:Object):void {
				super.data = value;
				if(!data)
					return;
				if(data.custom) {
					combo.selectedIndex = -1;
					combo.text = data.customString;
				}
				else
					combo.selectedIndex = data.optionIndex;
			}
			
			private function onComboChange():void {
				if(combo.selectedItem) {
					data.optionIndex = combo.selectedIndex;
					data.custom = false;
				} else {
					data.customString = combo.text;
					data.custom = true;
				}
			}
			
		]]&gt;
	&lt;/mx:Script&gt;
	&lt;mx:ComboBox width="100%" id="combo" editable="true" dataProvider="{data.options}"  change="onComboChange()" /&gt;
&lt;/mx:HBox&gt;
</pre>
The customItemRenderer sets the data in the Combobox checking if there is a custom string or a predefined option. onComboChange saves the modified data into the custom objects whenever the user type into the Combobox or select one option from the dropdown list.
This example is straightforward and it could be useful most of the time you need something similar. But what happens if your CustomObject class is bindable?
Let’s modify CustomObject.as adding the Bindable Meta Tag:
<pre class="brush: as3">
[Bindable]
public class CustomObject
{
</pre>
Now, when onComboChange modify one of the attribute of CustomObject, a change event is dispatched, that brings to an update of the itemRenderer with a call to the set data function. Here the Combobox calls its updateDisplayList that select all the text inside its TextInput. So, if the user is typing, after the first keystroke the text will be selected and a second keystroke will eventually delete the previous inserted text.

Here’s a solution, extend the Combobox component and override its updateDisplayList:
<pre class="brush: as3">
package
{
	import mx.controls.ComboBox;
	
	public class CustomCombobox extends ComboBox
	{
		public function CustomCombobox()
		{
			super();
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			if(editable) {
				var begin:int = textInput.selectionBeginIndex;
				var end:int = textInput.selectionEndIndex;
			}
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			
			if (editable)
			{
				textInput.setSelection(begin, end);
			}
		}
	}
}
</pre>

The idea is simple, just save the previous selection indexes, than after the Combobox updateDisplayList restore them.
Don’t forget to change the Combobox component used in the itemRenderer with the new custom component.
I think there are many alternative solutions to obtain such interaction but I hope this could be useful to someone to save some time trying to understand why its combobox continue to select its text

This example works in Flex 3.5.]]>
      
   </content>
</entry>
<entry>
   <title>Mate Framework - an example</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/05/mate_framework_a_little_exampl.html" />
   <id>tag:blog.comtaste.com,2010://1.116</id>
   
   <published>2010-05-11T17:00:10Z</published>
   <updated>2010-05-12T13:58:23Z</updated>
   
   <summary>In my last post I showed you how Mate framework works. Now I would like to deepen the study on this framework with a short example, and I&apos;d like to show one of best practice ways to use it. For...</summary>
   <author>
      <name>Luca Florido</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="51" label="framework" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="217" label="Mate" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="219" label="MVC" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In my last post I showed you how Mate framework works. Now I would like to deepen the study on this framework with a short example, and I'd like to show one of best practice ways to use it. For this project I used Flex 4 and Mate_08_9.swc library.  

In respect of the Model View Control Pattern I create a project with six packages:  business, component, controls,maps, model and view. 

<img alt="MateProject.JPG" src="http://blog.comtaste.com/MateProject.JPG" width="240" height="229" />

In the business package I create all the classes that can communicate with remote services (like http services or wsdl services ), in fact you can find there a ServiceLocator class as an MXML file, that extends the Object class, where I put an httpService tag, from which I would like to obtain an XML File.

<pre class="brush: xml">
 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;DataPerson&gt;
	&lt;Person&gt;
		&lt;name&gt;Name&lt;/name&gt;
		&lt;surname&gt;Surname&lt;/surname&gt;
		&lt;phone&gt;12345678&lt;/phone&gt;
	&lt;/Person&gt;
	&lt;Person&gt;
		&lt;name&gt;Name 1&lt;/name&gt;
		&lt;surname&gt;Surname 1&lt;/surname&gt;
		&lt;phone&gt;123456789&lt;/phone&gt;
	&lt;/Person&gt;
&lt;/DataPerson&gt;
</pre>

In the Component package I create the components of my application (in this example only MyDataGrid.mxml) that I use into my View. 
In the controls package I put my Event class, in the maps package My Mate EventMap, and in the model package I create a singleton call MateExampleModel where I manage all the data structure used by my view components that are in View package.

Hope that the project structure is easy to understand, I would like to analize the core of the project in particular how I follow the MVC Pattern with Mate Framework.

First of all we can see into the Application tag (view.MateExample.xml) all the View components present  in my project, and it's easy to see that there are only an event dispatcher, a data binding with a property of the model, and the build of the EventMap component (component.MyEntityMap).

<pre class="brush: xml">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:component="component.*" xmlns:maps="maps.*"&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import controls.XMLLoadMateEvent;
			import model.ModelMateExample;
 
			public var evt:XMLLoadMateEvent = new XMLLoadMateEvent(XMLLoadMateEvent.XML_LOAD);
		]]&gt;
	&lt;/mx:Script&gt;
 
	&lt;mx:HBox width="100%" height="100%"&gt;
		&lt;mx:VBox width="30%"&gt;
			&lt;s:Button label="Fill the Datagrid" click="{dispatchEvent(evt)}" /&gt;
			&lt;component:MyDataGrid width="100%" height="100%" dataProvider="{ModelMateExample.instance().gridDB}"/&gt;
		&lt;/mx:VBox&gt;
	&lt;/mx:HBox&gt;
	&lt;maps:MyEntityMap /&gt;	
&lt;/mx:Application&gt;
</pre>

The Control components are  the Event Class, dispatched by the view, and the HttpServiceManage Class that contains all the methods for manage the resultObject coming from the HttpService (result and fault methods).  

The Mate Entity Map is separated by the other Control classes, and it contains all the tags that we analized in my last post... but I think is a good idea to deepen how I used that tags. First we can see how I manage the httpService: on the bottom of the file MyEventMap.mxml I build an object from my ServiceLocator and I used it to generate an instance of  an httpService  into the HttpServiveInvoker tag, and, inside it, I manage the resultObject and the fault with the methods of an instance of the HttpServiceManage Class (view the code below).

<pre class="brush: xml;highlight: [11]">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;mate:EventMap xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:mate="http://mate.asfusion.com/" xmlns:business="business.*"&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import controls.HttpServiceManage;
			import controls.XMLLoadMateEvent;
		]]&gt;
	&lt;/mx:Script&gt;
  
	&lt;!-- enable debugger --&gt;
	&lt;mate:Debugger level="{Debugger.ALL}"/&gt;
  
	&lt;!-- handler of the XMLLoadMateEvent --&gt;
	&lt;mate:EventHandlers type="{XMLLoadMateEvent.XML_LOAD}" debug="true"&gt;
		&lt;!-- HTTP Service --&gt;
		&lt;mate:HTTPServiceInvoker instance="{service.httpService}" debug="true" &gt;
			&lt;!-- result handlers --&gt;
			&lt;mate:resultHandlers &gt;
				&lt;mate:MethodInvoker generator="{HttpServiceManage}" method="result" arguments="{resultObject}" &gt;
				&lt;/mate:MethodInvoker&gt;
			&lt;/mate:resultHandlers&gt;
 
			&lt;!-- fault handlers --&gt;
			&lt;mate:faultHandlers&gt;
				&lt;mate:MethodInvoker generator="{HttpServiceManage}" method="fault" arguments="{fault}" &gt;
				&lt;/mate:MethodInvoker&gt;
			&lt;/mate:faultHandlers&gt;
		&lt;/mate:HTTPServiceInvoker&gt;		
	&lt;/mate:EventHandlers&gt;
 
	&lt;!-- Service Locator --&gt;
	&lt;business:ServiceLocator id="service"/&gt;
&lt;/mate:EventMap&gt;
</pre>

It's very import to see that I manage the model of my application without the PropertyInjector tag . In fact, if you see the code of the HttpServiceManageClass, you can observe that I use the model's objects inside the result method of my httpService. 

<pre class="brush: as3">
package controls
{
	import model.ModelMateExample;	
	import mx.controls.Alert;
	import mx.rpc.Fault;
  
	public class HttpServiceManage
	{
		public function HttpServiceManage()
		{
		}
		public function result(obj:Object):void{
			ModelMateExample.instance().gridDB = obj.DataPerson.Person;
		}
		public function fault(faultObj:Fault):void{
			Alert.show("Error: "+faultObj.message);
		}
	}
}
</pre>

Generally I prefer to use this kind of solution because I think it could be clearer for whom want to analize my code to understand the funcionalities and the model's properties managed by the methods.
This approach is not the only one that you can use in your Mate Project, in fact it would like to be only an example of the flexibility of this framework.I think that Mate could be a very simple and power solution for create Flex Project with a solid structure that guarantees good quality for our projects.

<a href="http://blog.comtaste.com/MateExampleProject.zip">Download example source code</a>

Regards
]]>
      
   </content>
</entry>
<entry>
   <title>Alchemy: compiling C/C++ code into SWF or SWC</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/alchemy_compiling_cc_code_into_1.html" />
   <id>tag:blog.comtaste.com,2010://1.115</id>
   
   <published>2010-04-30T09:29:04Z</published>
   <updated>2010-05-31T12:07:55Z</updated>
   
   <summary>Alchemy is a research project that is intended to allow user to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2). With Alchemy, Web application developers can now reuse existing open...</summary>
   <author>
      <name>Luca Galati</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="20" label="actionscript 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="226" label="c" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="227" label="c++" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="31" label="Flex 3" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="228" label="reuse" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Alchemy is a research project that is intended to allow user to compile C and C++ code that is targeted to run on the open source ActionScript Virtual Machine (AVM2).

With Alchemy, Web application developers can now reuse existing open source C and C++ client or server-side code on the Flash Platform. Alchemy aims to bring the power of high performance C and C++ libraries to Web applications with minimal degradation on AVM2. The C/C++ code is compiled to ActionScript 3.0 as a SWF or SWC that runs on Adobe Flash Player 10 or Adobe AIR 1.5. Alchemy is primarily intended to be used with C/C++ libraries that have few OS dependencies. The generated content runs within the security constraints of the AVM2, and cannot bypass Flash Player security protections. 

In this post I'm going to explain how to setup up Alchemy on Windows and then I'm showing how to walk through the steps to get a simple C code file compiled into a SWC, and then how to use that SWC within a simple Flex example.

<strong>Requirements</strong>
On windows we will use Cygwin.
<ul>
<li>Alchemy Toolkit Package for your Windows OS</li>
<li><a href="http://www.cygwin.com/">Cygwin</a> with the following packages installed </li>
<ul>
<li>Perl </li>
<li>zip </li>
<li>gcc / g++ </li>
</ul>
<li><a href="http://java.sun.com/">Java</a> </li>
<li>Flex 3.2 SDK </li>
<li>Flex SDK setup to target compilation for Flash Player 10 </li>
</ul>
Download and install Cygwin with the packages suggested before.Download and install Java.  Make sure to restart the Cygwin terminal after installing Java.  Download and install the Flex SDK, and add the $FLEX_HOME/bin directory to your Cygwin environment's path (within ~/.bashrc).Download the Alchemy Package, unzip it and then  copy  the alchemy folder to your system. We will refer to this path as $ALCHEMY_HOME. Open a Cygwin terminal and change to the $ALCHEMY_HOME/ directory. Run the $ALCHEMY_HOME/config script using the following command:

<font face="courier">./config</font>

 Open alchemy_setup for editing and add the path to the ADL executable (included in the Flex SDK): 

<font face="courier">export ADL=/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin/adl.exe</font>

Make sure to uncomment this line, and that it contains the path to ADL.exe on your system (Substitute <font face="courier">PATH_TO_FLEX_SDK_HOME</font> with the path of the Flex Sdk installed on your system). Open your bash setup script to edit. This can usually be found in the ~/.bashrc file. Edit the the .bashrc script so that alchemy-setup is run when the script is run: 

<font face="courier">source /cygdrive/c/alchemy/alchemy-setup</font>

This should be added before your PATH is modified.  Add $ALCHEMY_HOME/achacks to your path. 

<font face="courier">PATH=$ALCHEMY_HOME/achacks:/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin:$PATH</font>

Your .bashrc file should look similar to:
 
<font face="courier">source /cygdrive/c/alchemy/alchemy-setup
PATH=$ALCHEMY_HOME/achacks:/cygdrive/c/PATH_TO_FLEX_SDK_HOME/bin:$PATH
export PATH</font>

Obviously the file may contain other commands specific to your system. Save the file, and restart your cygwin terminal. Change to the $ALCHEMY_HOME/bin directory, and run the following command: 

<font face="courier">ln -s llvm-stub llvm-stub.exe</font>

Note that this step wont be necessary in future builds. Now your environment is ready to compile C/C++ code into a SWF or a SWC.

I've devoleped a simple C function to sum two doubles. Here is the code:

<pre class="brush:cpp">
//File doublesum.c
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include &quot;AS3.h&quot;
 
//Method exposed to ActionScript
//Takes two doubles and return the sum
static AS3_Val sum(void* self, AS3_Val args)
{
	//initialize double parameters to 0.0
	double operand1 = 0.0;
	double operand2 = 0.0;
	
	//parse the arguments. Expect 2.
	//pass in operand1 to hold the first argument, which
	//should be a double. Does the same with the second argument
	AS3_ArrayValue( args, &quot;DoubleType, DoubleType&quot;, &amp;operand1, &amp;operand2 );
	
	//calculate the sum and return it
	double sum = operand1+operand2;
	return AS3_Number(sum);
}
 
//entry point for code
int main()
{
	//define the methods exposed to ActionScript
	//typed as an ActionScript Function instance
	AS3_Val sumMethod = AS3_Function( NULL, sum );
 
	// construct an object that holds references to the functions
	AS3_Val result = AS3_Object( &quot;sum: AS3ValType&quot;, sumMethod );
 
	// Release
	AS3_Release( sumMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}</pre>

To compile the file doublesum.c , into the cygwin shell change to the directory where you stored the file (or your  C file) and type the following command :
 
<font face="courier">alc-on; which gcc</font>

It should print out the path that points to the gcc contained with the $ALCHEMY_HOME/achacks/ directory. Then enter the following command: 

<font face="courier">gcc doublesum.c -O3 -Wall -swc -o doublesum.swc</font>

You should see output similar to: 
<font face="courier">
WARNING: While resolving call to function 'main' arguments were dropped!

4232.achacks.swf, 261018 bytes written
frame rate: 60
frame count: 1
69 : 4
72 : 260949
76 : 32
1 : 0
0 : 0
frame rate: 24
frame count: 1
69 : 4
77 : 506
64 : 31
63 : 16
65 : 4
9 : 3
41 : 26
82 : 471
1 : 0
0 : 0

  adding: catalog.xml (deflated 75%)
  adding: library.swf (deflated 70%)
</font>

Now in the same directory you will find the file doublesum.swc. To test it I have developed an mxml file named DoubleSumTest.mxml. This is the code:

<pre class="brush:as3; html-script: true">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;mx:Application xmlns:mx=&quot;http://www.adobe.com/2006/mxml&quot; layout=&quot;vertical&quot;&gt;
	&lt;mx:Script&gt;
		&lt;![CDATA[
			import cmodule.doublesum.CLibInit;
			
			private function c_doubleSumFunction(op1:Number, op2:Number):Number
			{
				var loader:CLibInit = new CLibInit();
				var lib:Object = loader.init();
				return lib.sum(op1,op2);
				
			}
			
			private function buttonHandler():void
			{
				var operand1:Number = Number(operand1Field.text);
				var operand2:Number = Number(operand2Field.text);
				var sum:Number = this.c_doubleSumFunction(operand1, operand2);
				resultField.text = String(sum);
			}
		]]&gt;
	&lt;/mx:Script&gt;
 
	&lt;mx:TextInput id=&quot;operand1Field&quot; /&gt;
	&lt;mx:Label text=&quot;+&quot; /&gt;
	&lt;mx:TextInput id=&quot;operand2Field&quot;/&gt;
	&lt;mx:Label text=&quot;=&quot; /&gt;
	&lt;mx:TextInput id=&quot;resultField&quot; /&gt;
	&lt;mx:Button id=&quot;sumButton&quot; label=&quot;sum&quot; click=&quot;buttonHandler()&quot;/&gt;
	
&lt;/mx:Application&gt; 
</pre>
Download this file,named DoubleSumTest.mxml (or write your own test file) and save it in the same directory of the doublesum.swc.
Into the cygwin shell, change to the directory where you stored the file and use the following command to compile the ActionScript/Flex code using MXMLC: 

<font face="courier">mxmlc.exe -library-path+=./doublesum.swc -target-player=10.0.0 DoubleSumTest.mxml </font>

This will generate a Flash Player 10 SWF. Executing this file in a browser  will show you 3 TextInput followed by a Button labeled sum.
Introducing 2 double numbers in the first and second TextInput and clicking on  the button will show their sum in the third TextInput calculated by the C function in doublesum.c . 

For more information about Alchemy visit: <a href="http://labs.adobe.com/technologies/alchemy/ ">http://labs.adobe.com/technologies/alchemy/ </a>.
]]>
      
   </content>
</entry>
<entry>
   <title>Create a google site with the Google sites Java API</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/create_a_google_site_with_the.html" />
   <id>tag:blog.comtaste.com,2010://1.114</id>
   
   <published>2010-04-22T16:06:08Z</published>
   <updated>2010-04-22T16:14:42Z</updated>
   
   <summary>With the google sites API we can build client application that can access, publish and modify content within a Google site In this post I show some functionalities of Google sites Java library that allow to : - Create a...</summary>
   <author>
      <name>Michele del Prete</name>
      <uri>http://www.comtaste.com</uri>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[With the google sites API we can build client application that can access, publish and modify content within a Google site

In this post I show some functionalities of Google sites Java library that allow to :

- Create a site
- Insert web pages into a site

All these action are done by an istance of SitesService :

<pre class="brush: java">
SitesService client = new SitesService("mySite");
</pre>

<u>Create a site</u>

This feature is only available to Google Apps domains. To create a site we must execute :

<pre class="brush: java">
    SiteEntry entry = new SiteEntry():
    entry.setTitile(new PlainTextContruct("title of the site"));
    entry.setSummary(new PlainTextConstruct("summary of the site"));
 
    Theme theme = new Theme();
    theme.setValue("theme of the site");
 
    entry.setTheme(theme);
 
    client.insert(new URL(getSiteFeedUrl(), entry));
</pre>

where the method "getSiteFeedUrl()" return the url's related of site feed of "domain", composed as follows: "http://sites.google.com/feeds/site/" + domain + "/"

where "domain" is the name of your domain. If the site is hosted on a Google account we have to put "site" instead of domain.

We can use a site feed to :

- list the Google sites that a user owns
- list the Google sites that a user has viewing permission for
- to modify the name of an existing site
- to create and/or copy an entire site

At page creation we can choose a large variety of themes, the same themes that we can select during the manual creation of a Google Site from the Url http://sites.google.com.

<u>Insert web pages</u>


Now we show how to insert web pages into the sites that we have created.

<pre class="brush: java">
WebPageEntry pageEntry = new WebPageEntry();
pageEntry.setTitle(new PlainTextConstruct("title of the page"));

XmlBlob blob = new XmlBlob();
blob.setBlob("HTML content of the page");

pageEntry.setContent(new XhtmlTextConstruct(blob));

client.insert(new URL(getContentSiteFeedUrl("siteName")), pageEntry);

</pre>

where the method "getContentSiteFeedUrl("siteName")" return the url's related of content feed of the webspace name of "siteName". With the content feed we can lists a Site's latest content. The url's feed is the follow: "http://sites.google.com/feeds/site/" + domain + "/" + siteName + "/". 

In this example I chose to create a "webpage", but there are other kinds of pages that I can create :

- FileCabinetPageEntry
- AnnouncementsPageEntry
- ListPageEntry

With Google Sites API you can create a web application that offers a service to create in a simple way a Google site, to the users of a given Google apps domain. You can find the references to the Google API to the following link : http://code.google.com/intl/it-IT/labs/.]]>
      
   </content>
</entry>
<entry>
   <title>Keeping Google App Engine alive</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/keeping_google_app_engine_aliv_1.html" />
   <id>tag:blog.comtaste.com,2010://1.113</id>
   
   <published>2010-04-16T16:02:37Z</published>
   <updated>2010-05-31T11:43:12Z</updated>
   
   <summary>Working with GAE is simply amazing, but their app cache system take a lot to respond for the first time request on a low volume app. App Engine Cache System The Python runtime environment caches imported modules between requests on...</summary>
   <author>
      <name>Liviu Stoica</name>
      <uri>http://blog.comtaste.com</uri>
   </author>
   
   <category term="231" label="google app engine" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="229" label="python" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Working with GAE is simply amazing, but their app cache system take a lot to respond  for the first time request on a low volume app.

<strong>App Engine Cache System</strong>
The Python runtime environment caches imported modules between requests on a single web server, similar to how a standalone Python application loads a module only once even if the module is imported by multiple files. If a handler script provides a main() routine, the runtime environment also caches the script. Otherwise, the handler script is loaded for every request.

<strong>The Problem</strong>
The cached script remain alive only a few seconds, so if your app has no request for 15 sec or more, the system throw away it.
So if your application dont have a a high traffic volume the handler script is loaded for every request.

<strong>Solution</strong>
First solution can be an external service that call your application every 10 sec or more. But this is not the best trick to do.

The App Engine Cron Service allows you to configure regularly scheduled tasks that operate at defined times or regular intervals. These tasks are commonly known as cron jobs. 

These cron jobs are automatically triggered by the App Engine Cron Service. For instance, you might use this to send out a report email on a daily basis, to update some cached data every 10 minutes, or to update some summary information once an hour.
A cron job will invoke a URL at a given time of day. A URL invoked by cron is subject to the same limits and quotas as a normal HTTP request, including the request time limit.

This sounds perfect for our situation, implement a cron that request a script every 10 seconds, and this will keep our application alive.
<pre class="brush: python">
### in queue.yaml
queue:
- name: hothandler
  rate: 20/m
  bucket_size: 1
</pre>

<pre class="brush: python">
### in cron.yaml
cron:
- description: ensure hot handler
  url: /_ah/queue/hothandler/start
  schedule: every 4 hours
</pre>

<pre class="brush: python">
### in app.yaml
handlers:
- url: /_ah/queue/hothandler/.*
  script: hothandler.py
  login: admin
</pre>

<pre class="brush: python">
### in hothandler.py
"""
Copyright (C)  2009  twitter.com/rcb
 
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
 
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
import random
from wsgiref.handlers import CGIHandler
from google.appengine.api.labs import taskqueue
from google.appengine.api import memcache
from google.appengine.api.capabilities import CapabilitySet
memcache_service = CapabilitySet('memcache', methods=['set','get'])
hot_handler_queue = taskqueue.Queue(name='hothandler')
HOT_HANDLER_PREFIX = '/_ah/queue/hothandler/'
def wsgi_app(env, res):
    """ visit '/_ah/queue/hothandler/start' as admin to start a task """
    token = env['PATH_INFO'].replace(HOT_HANDLER_PREFIX,'')
    cur_token = memcache.get(HOT_HANDLER_PREFIX)
    if cur_token is None:
        if not memcache_service.is_enabled():
            cur_token = token
    if token in [cur_token, 'start']:
        next_token = str(random.random())
        url = '%s%s'%(HOT_HANDLER_PREFIX, next_token)
        next_task = taskqueue.Task(countdown=10, url=url)
        hot_handler_queue.add(next_task)
        memcache.set(HOT_HANDLER_PREFIX, next_token)
    res('200 OK',[('Content-Type','text/plain')])
    return ['ok']
def main():
    CGIHandler().run(wsgi_app)
    
if __name__ == '__main__':
    main()
</pre>

### how to launch
1) visit "/_ah/queue/hothandler/start" in your browser
2) login as an admin which inserts the first task
3) view your logs

By the way this is on the production server, the dev server does not run the tasks automatically. 

Literally like clockwork, a task hits the app once every 10 seconds and keeps it hot.

6 req/minute * 60 minutes/hour * 24 hours/day = 8640 req/day

It is a very small price to pay for good response time with a low volume app. 

Memcache is used to ensure there is at most 1 active task, and cron is used to ensure there is at least 1 active task every 4 hours, so no maintenance.

CapabilitySet is used to test if memcache is available.

Apparently, if 1 handler remains warm, all other warm handlers remain warm too, so hothandler can exist in its own handler called hothandler.py, which is more modular. 

<strong>Reference</strong>
<a href="http://code.google.com/intl/it-IT/appengine/docs/python/config/cron.html">Scheduled Tasks With Cron for Python</a>
<a href="http://code.google.com/intl/it-IT/appengine/docs/python/runtime.html#App_Caching">GAE App Caching</a>
<a href="http://appengine-cookbook.appspot.com/recipe/hot-handler/">Hot Handler on Google Cookbook</a>
]]>
      
   </content>
</entry>
<entry>
   <title>Swiz Framework - Inversion of Control micro-architecture</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/swiz_framework_inversion_of_co.html" />
   <id>tag:blog.comtaste.com,2010://1.112</id>
   
   <published>2010-04-13T14:19:17Z</published>
   <updated>2010-04-14T12:50:23Z</updated>
   
   <summary>Swiz is a Flex framework that aims at simplicity in development of Rich Internet Applications by hiding most of the boilerplate code behind well-designed metadata that implement Inversion of Control and simply inject objects where they are required. Besides this,...</summary>
   <author>
      <name>Constantin Moldovanu</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Actionscript 3" scheme="http://www.sixapart.com/ns/types#category" />
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="51" label="framework" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="225" label="ioc" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="224" label="swiz" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[Swiz is a Flex framework that aims at simplicity in development of Rich Internet Applications by hiding most of the boilerplate code behind well-designed metadata that implement Inversion of Control and simply inject objects where they are required. Besides this, Swiz also introduces Custom Metadata Processors, with which developers can easily introduce their own, meaningful metadata and extend processors to grant them functionality.
In this post we will see how to configure and use the last available version of Swiz, 1.0.0 beta, that can be downloaded from their <a href="http://swizframework.org/">site</a> as a pre-compiled library or source code from their GIT repository. 
All of Swiz configuration is done within the main application file; for example, in MXML:
<pre class="brush: xml; highlight: [5]">
	&lt;fx:Declarations&gt;
		&lt;swiz:SwizConfig id=&quot;swizConfig&quot; strict=&quot;true&quot;
						 eventPackages=&quot;com.comtaste.rss.events&quot;
						 viewPackages=&quot;com.comtaste.rss.view&quot; /&gt;
		&lt;swiz:Swiz id=&quot;swiz&quot; config=&quot;{swizConfig}&quot;&gt;
			&lt;swiz:beanProviders&gt;
				&lt;swiz:BeanProvider&gt;
					&lt;control:RSSController /&gt;
					&lt;model:RSSModel /&gt;
					&lt;swiz:Bean name=&quot;serviceLocator&quot;&gt;
						&lt;model:ServiceLocator /&gt;
					&lt;/swiz:Bean&gt;
				&lt;/swiz:BeanProvider&gt;
			&lt;/swiz:beanProviders&gt;
		&lt;/swiz:Swiz&gt;
	&lt;/fx:Declarations&gt;
</pre>

<strong>SwizConfig</strong> defines the global configuration:
<ul>
<li>eventPackages - name of the package(s) where custom events are defined. These events will be automatically associated with custom controllers that perform logical or remote operations.</li>
<li>viewPackages - name of the package(s) where views of the application are defined. Swiz listens for custom events launched by these views and triggers the mapped controller(s).</li>
</ul>
These two properties ensure that launched events are captured and mapped to their actions, automatically in the background. It is possible to use Swiz injection without automatic event mapping, simply by not setting these properties.

<strong>Swiz</strong> uses the previously defined SwizConfig to define which objects are to be injected: each instance of this class has its own set of beans, that can be defined in two ways:
<ul>
<li>by class type, inserting each type in the bean provider list</li>
<li>by name, inserting a Bean object with a name and a type in the bean provider list</li>
</ul>

In this example I have chosen to create three beans: controller, model and service locator. I used the service locator in reference to Cairngorm's one, as a repository of remote services, but in this case it's just a simple Object. One can make many other choices, such as placing the remote services within delegates, controllers, or define them as additional beans. 

A powerful feature of this new version of Swiz is that it can define multiple bean contexts, each with its set of beans, simply by defining Swiz instances.

The last set of classes we need are the controllers, that may or may not extend Swiz's <strong>AbstractController</strong>. Extending this class provides methods such as <em>executeServiceCall</em> or <em>executeURLRequest</em>, which allow to call a remote service and assign handler methods:
<pre class="brush: as3; highlight: [3]">
	[Mediate(event="RSSEvent.GET_RSS_FEED")]
	public function getFeed():void {
		super.executeServiceCall(serviceLocator.rssService.send(), onFeedResult, onFault);
	}
</pre>

Another powerful feature of Swiz comes with the <strong>Mediate</strong> metadata, that allows a custom event that is defined in one of the packages configured through the <em>eventPackages</em> property to be automatically associated with a method. This handler method can also take parameters in input, as for example the event itself:
<pre class="brush: as3">
	[Mediate(event="RSSEvent.GET_RSS_FEED")]
	public function getFeed(event:RSSEvent):void {}
</pre>

More than this, if the event has properties, they can be defined within the metadata and their values are passed to the handler method. Suppose the event has two properties, url and date:
<pre class="brush: as3; highlight: [3]">
	[Mediate(event="RSSEvent.GET_RSS_FEED", properties="url,date")]
	public function getFeed(url:String, date:Date):void {}
</pre>

The properties of each metadata are carefully checked by the Swiz engine, at runtime, and errors are thrown when event names or properties are spelled wrong. These errors are descriptive and it's rather easy to understand which property of which metadata is wrong.

Bean injection is realized through the use of the <strong>Inject</strong> metadata. This metadata replaces the <em>Autowire</em> one, which got deprecated from the previous stable version:
<pre class="brush: as3">
	[Inject(bean="serviceLocator")]
	public var serviceLocator:ServiceLocator;
		
	[Inject]
	public var model:RSSModel;
</pre>

In this example, serviceLocator is injected through the name of its bean while model is injected through the type of its class, as defined in the bean providers above.

Swiz, with its dependency injection and custom metadata, is a powerful framework and offers a lot of interesting possibilities. In future posts we will see how to take full advantage of it and use custom metadata.

This working example and its source-code can be found <a href="http://blog.comtaste.com/upload/rssFeed/RSSReader.html">here</a>.
]]>
      
   </content>
</entry>
<entry>
   <title>Dynamic creation of messaging destinations in BlazeDS</title>
   <link rel="alternate" type="text/html" href="http://blog.comtaste.com/2010/04/dynamic_creation_of_messaging.html" />
   <id>tag:blog.comtaste.com,2010://1.111</id>
   
   <published>2010-04-02T10:46:57Z</published>
   <updated>2010-04-02T16:45:56Z</updated>
   
   <summary>In a former post on this blog I wrote about messaging from java to flex without using JMS. That can be a good starting point for the current post&apos;s topic: http://blog.comtaste.com/2009/03/messaging_from_java_to_flex_wi_1.html. In that case I was relying on a correct...</summary>
   <author>
      <name>Emanuele Tatti</name>
      <uri>http://www.comtaste.com</uri>
   </author>
         <category term="Flex" scheme="http://www.sixapart.com/ns/types#category" />
   
   <category term="93" label="blazeds" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="16" label="flex" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="104" label="messaging services" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://blog.comtaste.com/">
      <![CDATA[In a former post on this blog I wrote about messaging from java to flex without using JMS. That can be a good starting point for the current post's topic: <a href="http://blog.comtaste.com/2009/03/messaging_from_java_to_flex_wi_1.html">http://blog.comtaste.com/2009/03/messaging_from_java_to_flex_wi_1.html</a>.

In that case I was relying on a correct blazeds messaging configuration where a messaging destination called <em>actionscriptMessaging</em> was created. 
I can think about several use cases where the number and configuration of messaging destinations cannot be determined at implementation or deploy time: think about social or collaborative applications where users are organized in different groups depending on their interest or a common goal, or a much simpler example, a chat where a user can create a private chat room.

If you want to send messages only to some clients you can use the consumer selector property: <a href="http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=messaging_6.html">http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=messaging_6.html</a> or alternatively you can create multiple destinations.
Creating a destination from a J2EE backend (where BlazeDS is deployed) is as simple as writing these lines of code:

<pre name="code" class="brush:java">
        MessageBroker broker = MessageBroker.getMessageBroker(null);
        service = (MessageService) broker.getService("message-service");
        destination = (MessageDestination) service.createDestination("myDest");
 
        if (service.isStarted()) {
        	destination.start(); 
        }
</pre>

The service id must be the one specified in <em>messaging-config.xml</em>:

&lt;service id="<strong>message-service</strong>"  class="flex.messaging.services.MessageService"&gt;

The message broker is obtained in the same way as the former post, the <em>null</em> parameter is better explained in the class javadocs: http://help.adobe.com/en_US/livecycle/9.0/programLC/javadoc/flex/messaging/MessageBroker.html#getMessageBroker(java.lang.String) 

The destination <strong>must</strong> be started before any client tries to subscribe, otherwise you would get the "No destination configured" error. Here it is the client side subscription:

<pre name="code" class="brush:as3">
    var c:Consumer = new Consumer();
    c.destination = "myDest";
 
    var channelSet:ChannelSet = new ChannelSet();
    channelSet.addChannel(new AMFChannel("my-polling-amf", "http://localhost:8080/ContextRoot/messagebroker/amfpolling"));
 
    c.channelSet = channelSet;
    c.subscribe();
</pre>

Of course the destination must match the newly created server side messaging destination; the other peculiarity is the manual setting of the channel used: not having configured a channel server side we can specify the desired channel. That must be among the channels defined in <em>services-config.xml</em>

<pre name="code" class="brush:xml">
        &lt;channel-definition id="my-polling-amf" class="mx.messaging.channels.AMFChannel"&gt;
            &lt;endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling" class="flex.messaging.endpoints.AMFEndpoint"/&gt;
 
            &lt;properties&gt;
                &lt;polling-enabled&gt;true&lt;/polling-enabled&gt;
                &lt;polling-interval-seconds&gt;4&lt;/polling-interval-seconds&gt;
            &lt;/properties&gt;
        &lt;/channel-definition&gt;
</pre>

The message sending is the same as specified in the former blog post:

<pre name="code" class="brush:java">
        AsyncMessage msg = new AsyncMessage();
        msg.setClientId("Java dispatcher");
        msg.setTimestamp(new Date().getTime());
        // Unique ID
        msg.setMessageId(UUIDUtils.createUUID());
        msg.setDestination("myDest");
        msg.setBody("My message");
 
        //send message to destination
        MessageBroker.getMessageBroker(null).routeMessageToService(msg, null);
</pre>

Note that the message body (in this example a simple string) can be any object mapped in ActionScript with the <em>RemoteClass</em> tag.]]>
      
   </content>
</entry>

</feed>
