December 27, 2010

Getting started with the Tabbed UI and List View in Android 2.1 SDK

We've officially started developing under Android development with Flex/AIR for mobile. In the meantime I've investigated into the native Android development using Java and the Android SDK.
In this post I would like to share with you my experience and show you how to create an Android application that makes use of the Tabbed UI and the ListView.

For this example I'm using the Android SDK 2.1 with a Motorola Droid 2 device for testing activities.

Let's see how to develop a simple tab menu.

Tabbed UI

To create a Tab menu it’s necessary to define a TabHost Object. This object is the root class for a tab menu and it uses a tabWidget object to show the navigation buttons, and a Framelayout Object to show the tabs content.

Now we are going to see how to create a simple TabView using separated Activities for the contents of the tabs.The Activity class is the base class of all Android’s applications and it's is used to perform actions.
We can have several Activities in our Apllications but the user can interact with them one at a time.

The first step is to define two Activities for the Tabs’ context; for example we can use the class below:



package com.comtaste.android;
import com.comtaste.android.components.PersonListAdapter;
import android.app.ListActivity;
import android.os.Bundle;
/***
*
* @author Luca Florido
*
* This Activity is an example to build a ListView in Android
*/
public class SelectView extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/***
* This method is called every time the activity
* is change is state (see the Android's guide for
* understand the lifecycle of an Activity )
*/
@Override
protected void onResume() {
super.onResume();
try{
if (getListAdapter() == null ){
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
setListAdapter(new
PersonListAdapter(getApplicationContext(),displayWidth));
}else{
PersonListAdapter p = (PersonListAdapter)getListAdapter();
p.refresh();
}
}catch(Exception e ){
e.printStackTrace();
}

}

}

package com.comtaste.android;

import com.comtaste.android.datamanage.EngineDB;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
/***
*
* @author Luca Florido
*
*/
public class InsertView extends Activity {
private EditText nameED;
private EditText surnameED;
private EngineDB db;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new EngineDB(getApplicationContext());
setContentView(R.layout.inserview);
db = new EngineDB(getApplicationContext());
nameED = (EditText)this.findViewById(R.id.insertName);
surnameED = (EditText)this.findViewById(R.id.insertSurname);
Button buttonIns = (Button)this.findViewById(R.id.buttoninsert);
buttonIns.setWidth(100);
resize();
buttonIns.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(!nameED.getText().toString().equals("") && !surnameED.getText().toString().equals("") ){
db.insert(nameED.getText().toString(), surnameED.getText().toString());
nameED.setText("");
surnameED.setText("");
nameED.requestFocus();
}


}
});
}
public void resize(){
int wd = getWindowManager().getDefaultDisplay().getWidth();
nameED.setWidth(wd-100);
surnameED.setWidth(wd-100);
}
}

The second step is to define the view objects in an xml file and put it in the layer directory of the Android project ( in my example I use a file called tabview.xml). Declare the following objects into the xml file: the tabWidget and the FrameLayout Objects within a LinerLayout with vertical orientation as show below.

<?xml version="1.0" encoding="utf-8"?>
<TabHost
  android:id="@android:id/tabhost"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout android:orientation="vertical"
	  android:layout_width="fill_parent"
	  android:layout_height="fill_parent"
	  >
	  <TabWidget android:id="@android:id/tabs"
	  	android:layout_width="fill_parent"
	  	android:layout_height="wrap_content">
	  </TabWidget>
	  <FrameLayout
	  	android:id="@android:id/tabcontent"
	  	android:layout_width="fill_parent"
	  	android:layout_height="wrap_content">
	  </FrameLayout>
	  <Button
		android:id="@+id/closebutton"
	  	android:layout_width="100px"
	  	android:layout_height="wrap_content"
	  	android:text="@string/close"
	  	android:drawableLeft="@drawable/closeicon">
	  </Button>
  </LinearLayout>
</TabHost>


Now create the Activity for the TabView. The Android’s SDK provides us a particular type of Activity for manage the tab View: the TabActivity class.We can extend the TabActivity class:

package com.comtaste.android;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.view.View.OnClickListener;
/***
 * 
 * @author Luca Florido
 *
 * In this Activity there are all the configurations of the TabHost Object
 */
public class MenuView extends TabActivity   {
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tabview);
		/***
		 * Resource 
		 */
		Resources res = getResources(); 
		/***
		 *  Create and Initialize a TabHost Object with two TabSpec 
		 */
		TabHost tab = getTabHost();		
		TabHost.TabSpec spec;
		/***
		 * Create an Intent for the Activity in the first tab
		 */
		Intent intent;
		intent = new Intent().setClass(this, SelectView.class);
		/***
		 * Creation of the first tab
		 */
		spec = tab.newTabSpec("List").setIndicator("List",res.getDrawable(R.drawable.cancelicon));
		spec.setContent(intent);
		/***
		 * Adding of the first tab to the TabHost Object 
		 */
		tab.addTab(spec);
		/***
		 * Container of the Activity in the second tab
		 */
		intent = new Intent().setClass(this, InsertView.class);
		/***
		 * Creation of the second tab
		 */
		spec = tab.newTabSpec("Insert").setIndicator("Insert",res.getDrawable(R.drawable.inserticon));
		spec.setContent(intent);
		/***
		 * Adding of the second tab to the TabHost Object 
		 */
		tab.addTab(spec);
		/***
		 * Add a Listener to the Close Button  
		 */
		Button closeB = (Button)findViewById(R.id.closebutton); 
		closeB.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
}

In the onCreate() method we have to create an instance of the TabHost class with the method getTabHost() of the TabActivity object.
.

Then, for each tab, a TabHost.TabSpec has to be created to define the tab properties such as title,icon and content.

With the newTabSpec(String) method we create a new TabHost.TabSpec identified by the given string tag and with the setIndicator(CharSequence, Drawable)method we can set the text and icon for the tabs. In order to add the View Activity to each tabs it’s necessary to use the setContent(Intent) method where the argument Intent is a particular object that help us to call the appropriate Activity for each tabs.

Now in the next step you'll add the tabs to our TabHost by calling the method addTab(TabHost.TabSpec).

Notice that the TabWidget object has never been istantiated. This is because a TabWidget must always be a child of a TabHost, which is what you use for almost all interaction with the tabs.

So when a tab is added to the TabHost, it's automatically added to the child TabWidget.

ListView

A ListView is a ViewGroup that creates a list of scrollable items. The list items are automatically added to the list using a ListAdapter.

In this example I'm going to show you how to create a ListView using a custom ListAdapter.

Suppose that we have to represent a particular type of Data inside our List. For example we can use a DTO like this:

package com.comtaste.android.dataVO;
/***
 * 
 * @author Luca Florido
 *
 */
public class Person {
	public Person(){
		
	}
	public Person(String nameValue,String surnameValue ){
		this.name = nameValue;
		this.surname = surnameValue;
	}
	public String name;
	public String surname;
}

Now we have to define a custom ListAdapter that is able to show the parameters of Person’s Objects inside a List Collection (for example an ArrayList).

We still need two elements to show data within a Person object
in a right way.

First we need a View Container (in our example PersonView) to draw a view where we can put the values, and a button for making operations in the Collection ( for example to delete the selected data from the listcollection).

Second, we need a custom ListAdapter to fill the listView with PersonView Objects filled with the items inside our Collection.

Define a Container for the Data view. The personView object is a simple LinearLayout class where we define the view’s objects (as you can see in its constructor ) and a Person object filled by the PersonListAdapter.

package com.comtaste.android.components;
import com.comtaste.android.R;
import com.comtaste.android.dataVO.Person;
import android.content.Context;
import android.content.res.Resources;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/***
 * 
 * @author Luca Florido
 *
 * View that contains objects to show in the list all the properties of a Person Object
 */
public class PersonView extends LinearLayout {
	public Button buttonDel;
	public Person person;
	/***
	 * 
	 * @param context Context of the application
	 * @param p Person object
	 * @param displayWidth Width of the screen
	 */
	public PersonView(Context context, Person p,int displayWidth){
		super(context);
		this.setOrientation(HORIZONTAL);
		person = p;
		TextView titleName = new TextView(context);
		TextView valueName = new TextView(context);
		TextView titleSurName = new TextView(context);
		TextView valueSurName = new TextView(context);
		titleName.setText("NAME:");
		titleName.setWidth(200);
		valueName.setText(p.name);
		titleSurName.setText("SURNAME");
		valueSurName.setText(p.surname);
		LinearLayout main = new LinearLayout(getContext());
		titleName.setWidth(displayWidth-100);
		main.setOrientation(VERTICAL);
		main.addView(titleName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(valueName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(titleSurName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		main.addView(valueSurName, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		addView(main, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		buttonDel  = new Button(context);
		buttonDel.setText("Delete");
		buttonDel.setWidth(100);
		Resources res = getResources();
		buttonDel.setBackgroundDrawable(res.getDrawable(R.drawable.cancelicon));
		addView(buttonDel,new LinearLayout.LayoutParams(100,LayoutParams.WRAP_CONTENT));
	}
	
}

Now create a ListAdapter. The PersonListAdapter is an extension of BaseAdapter class that contains all the methods required by theListActivity to draw a List of Object. Below you can see the code of the PersonListAdapter.

package com.comtaste.android.components;
import java.util.ArrayList;
import java.util.List;
import com.comtaste.android.dataVO.Person;
import com.comtaste.android.datamanage.EngineDB;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.view.View.OnClickListener;
/***
 * 
 * @author Luca Florido
 *	
 */
public class PersonListAdapter extends BaseAdapter {
	private Context myContext;
	public List personList;
	private Person person;
	private EngineDB db;
	private int dWidth;
	public PersonListAdapter (Context context,int displayWidth){
		myContext = context;
		dWidth = displayWidth;
		db = new EngineDB(myContext);
		personList = new ArrayList();
		personList = db.selectList();
	}
	public int getCount(){
		return personList.size();
	}
	public Object getItem(int position) {
        return position;
    }
	public long getItemId(int position) {
        return position;
    }
	/***
	 * Create the View Objects to show in the UI
	 */
	public View getView(int position,View convertView, ViewGroup parent){
		person = personList.get(position);
		//Create a new PersonView object 
		PersonView personView = new PersonView(myContext, person,dWidth);
		//Define a method to delete a Person object from the List Collection
		personView.buttonDel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EngineDB db = new EngineDB(myContext);
				PersonView per= (PersonView)v.getParent(); 
				db.delete(per.person);
				refresh();
			}
		});
		return personView;
	}
	public void refresh(){
		personList = new ArrayList();
		personList = db.selectList();
		notifyDataSetChanged();
	}
}
In the constructor of the class we call a method that is able to create a List of Persons from a SQLLite database. In the getView() method a PersonView Object is created and filled with an object of the Person Collection. For each position from 0 to the integer value of getCount() method ( the value of this method is the size of the Collection of Persons) the getView() method is called. Then define the ListActivity. Here is the ListActivity class that we configure as a tab of the TabHost of the section about the tabbed UI (see above) Note that in the onResume() method of that Activity I've put some operations to refresh the Person Objects Collection and the List. Doing that I can refresh my List every time a user clicks on the List Tab. That’s all. Regards


September 29, 2010

New video on Comtaste Homepage

Today we just released a brand new company video showcase on our site. The introduction of this video is the first step of a progressive whole site-redesign. We, in Comtaste, think it's a good habit keep our website up to date and in line with the direction we are aiming at.
Now it's time for you to have a look at this great video.
To enjoy the video properly, remeber to turn the sound up.
Keep in touch with us, other improvements will come very soon!

September 20, 2010

How to install the Android SDK on Eclipse 3.5

In this post you'll learn to get started with the Android SDK (version 2.1, installing it, and set up a development environment based on Eclipse 3.5 Galileo with the Android Development Tool Plugin.

First of all you have to check if your environments fits all the requirements.

Here is a link with all the software and hardware requirements for developing applications with the Android SDK:

http://developer.android.com/sdk/requirements.html

If it's all right in your computer , go ahead with instaling the Android SDK.

After downloading the Android SDK starter package from this link (make sure to download the right package for your computer), unpack it in a folder and take a note of the name and location of your SDK directory. It's important in order to complete the installation of the ADT Eclipse plugin.

It's a good idea to insert in the Path environment variables of your computer the tools directory of the SDK, in this way it's possible to run all the commands in that directory without referring to the full path.

Now it's time to install the ADT plugin for eclipse.

This plugin is the fastest way to get started with Android SDK because it has a lot of functionalities for make easier the startup and the manage of any Android projects.

For using this plugin within Eclipse (I'm using the 3.5 version, but you can use the 3.4 though. Instead for the 3.6 version the plugin doe not exist) follow these steps to download the ADT plugin:

1. Open Eclipse. From the Help menu choose “Install New Software”

2. In the Available Software dialog, click Add....

3. In the Add Site dialog enter a name for the remote site in the "Name" field, and in the "Location" field,

enter this URL:

https://dl-ssl.google.com/android/eclipse/ (if you have problem with https you can use http)

4. And Click OK.

5. Back in the Available Software view, you should now see "Developer Tools" item added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. Click Next.

6. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. Click Next to read and accept the license agreement and install any dependencies, then click Finish.

7. Restart Eclipse.

If the installation finish successfully,we can modify the ADT preferences in Eclipse to point to the Android SDK directory:

1- Select Window > Preferences... to open the Preferences panel.

2- Select Android from the left panel.

3- For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory.

4- Click Apply, then OK.

The SDK uses a modular structure that separates the major parts of the SDK — Android platform versions, add-ons, tools, samples, and the API documentation — into a set of separately installable components.

The SDK starter package, which you've already downloaded, includes only a single component: the latest version of the SDK Tools. To develop any Android application, you also need to download at least one Android platform into your environment, although downloading additional components is highly recommended.

Next time we will see how to install and update additional components and write our first "Hello World" application


August 3, 2010

Fixing the horizontal scroll for the Flex Text Highlighter Class

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 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.

Demo --- Source

July 12, 2010

Adobe Alchemy: a comparative example

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 "c" 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 BubbleSort, 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:

public function bubbleSort(array:Array):void
{
	var temp:int = 0;
	var alto:int = array.length;
	while(alto > 0)
	{
		for(var i:int = 0; i<alto; i++)
		{
			if(array[i] > array[i+1])
			{
				temp = array[i];
				array[i] = array[i+1];
				array[i+1] = temp;
			}
		}
		alto--;
	} 
}

and here I show you the C implementation

void BubbleSort(int *array, int array_size)
{
   
  int i, tmp;
  int bound = array_size; 
 
  while (bound > 1)
  {
	for (i=0; i<bound-1; i++)
    {
        if (array[i] > array[i+1]) 
        { 
			tmp = array[i]; 
            array[i] = array[i+1]; 
            array[i+1] = tmp;
        } 
    }
    bound--; 
  }
}

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:

#include <stdlib.h>
#include <stdio.h>
 
//Header file for AS3 interop APIs
//this is linked in by the compiler (when using flaccon)
#include "AS3.h"
 
//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, "AS3ValType", &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, "length");
	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, "pop");
	AS3_Val emptyParams = AS3_Array("");
 	
	//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 >= 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, "push");
 	
	//Storing the ordered integer values into a new actionscript array object
	int j;
	for( j = 0; j < array_size ; j++)
	{
		AS3_Val int_to_push = AS3_Array("IntType", 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( "orderArray: AS3ValType", orderArrayMethod );
 
	// Release
	AS3_Release( orderArrayMethod );
 
	// notify that we initialized -- THIS DOES NOT RETURN!
	AS3_LibInit( result );
 
	// should never get here!
	return 0;
}

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 post
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:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" creationComplete="init();">
	
	<mx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			
			import cmodule.bubblesort.CLibInit;			
			
			private var startDate:Date;
			private var stopDate:Date;
			
			private function init():void
			{
				
				this.addEventListener("actionscriptSortComplete",handler);
				this.addEventListener("cSortComplete",handler);
				var intArray:Array = new Array();
				var intArray2:Array = new Array();
				for(var i:int = 20000; i > 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 == "actionscriptOrderingButton" )
				{
					var source1:Array = (list.dataProvider as ArrayCollection).source;
					bubbleSort(source1);
					this.dispatchEvent(new Event("actionscriptSortComplete"));
				}
				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("cSortComplete"));
				}
				
				
			}
			
			public function handler(event:Event):void
			{
				stopDate = new Date();
				var diff:Number = stopDate.getTime() - startDate.getTime();
				if(event.type == "actionscriptSortComplete")
				{
					timeLabel.text = "time elapsed : "+diff/1000+" sec!";
					(list.dataProvider as ArrayCollection).refresh();
				}
				else
				{
					timeLabel2.text = "time elapsed :"+diff/1000+"sec!";
					(list2.dataProvider as ArrayCollection).refresh();
				}
				
			}
			
		]]>
	</mx:Script>
	
	<mx:List id="list" width="30%"  />
	<mx:VBox>
		<mx:Button id="actionscriptOrderingButton" label="Actionscript BubbleSort" click="orderArray(event);"  />
		<mx:Label id="timeLabel" text="..." />
	</mx:VBox>
	<mx:List id="list2" width="30%"/>
	<mx:VBox>
		<mx:Button id="cOrderingButton" label="C BubbleSort" click="orderArray(event);"  />
		<mx:Label id="timeLabel2" text="..." />
	</mx:VBox>
	<mx:Label id="lb2" text="" />
	
	
</mx:Application>

And here are some screenshots of the results obtained by the test application:
test-actionscriptbubblesort.PNG

test-cbubblesort.PNG

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.

July 8, 2010

Managing Java Http sessions in GAE applications

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.

What is Google App Engine

Citing the corresponding google page: "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.

How the http session is managed

Session handling must be explicitly enabled by adding to your app engine configuration file true and then you will be able to access the session from within RPC services with:
this.getThreadLocalRequest().getSession();

When you enable it, you will find serialized sessions among your datastore entities as _ah_SESSION, 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:

Service A

Person p = new Person();
p.setName("Jack");
session.setAttribute("person", p);

Service B

Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack"
p.setName("Andy");

Service A again

Person p = (Person) session.getAttribute("person");
System.out.println(p.getName()); // prints "Jack" in GAE, 
// prints "Andy" in a standard J2EE evironment

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.

Alternatives to the http session

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 Memcache service and/or the DataStore service. While the former has the problem of the data expiration strategy: http://code.google.com/appengine/docs/java/memcache/overview.html#How_Cached_Data_Expires, the latter will suffer of the same performance problems of the GAE session implementation.


July 3, 2010

Flex Webservice: how to list available parameters for each operation

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 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.

<mx:Script>
	<![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);
					} 
				}
			}
		}
	]]>
</mx:Script>

This small script, based on the code of the previous post, 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.

June 24, 2010

Security Data Trasfer - AS3 Encrypting Libraries and Http Monitor Softwares

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 address . 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 demo 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 address, 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 site.
HP SWFScan offers several other features to help developers, code auditor/reviewers, and pen-testers examine the contents of Flash applications, including:


  • Highlighting the line of source code that contains the vulnerability to help better understand the context of the issue.

  • Providing summaries, details, and remediation advice for each vulnerability in accordance with Adobe's recommendation for secure Flash development.

  • Generating a vulnerability report to share and solve the detected issues.

  • Exporting the decompiled source code for use with other external tools.

  • Revealing all the URLs and web services the Flash Application contacts.

  • Flagging class names, function names, or variable names that may be of interest such as
    loadedUserXml or crypt().

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 here . 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

June 11, 2010

UiBinder : a simple way to build Widget from XML markup

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 :

simplewidget.png

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 :


<!doctype html>

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<link type="text/css" rel="stylesheet" href="PostBlogUiBinder.css">

<title>Simple widget project</title>

<script type="text/javascript" language="javascript" src="postbloguibinder/postbloguibinder.nocache.js"></script>
</head>

<body>

<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>

<h1>Sample Widget</h1>

<h3 align="center">Fill the following fields</h3>

<div id="simpleWidget" align="center"></div>

</body>
</html>


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 :



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 onModuleLoad().
*/
public class SimpleWidgetEntrypoint implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
SimpleWidget simpleWidget = new SimpleWidget();
RootPanel.get("simpleWidget").add(simpleWidget);
}
}

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


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


- SimpleWidget.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 {
}

@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");
}

}

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.

June 7, 2010

Binding improvement

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.


BindingManager.debugBinding:
Using the static method provided by the manager you will enable the debug for the property passed as parameter for the method like this:

BindingManager.debugBinding( "myComponent.propertyToDebug" )

Now when you lunch your application in debug mode, you can see in the console something like this:
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

BindingManager.setEnabled:
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:

BindingManager.setEnabled( yourComponent, true );


Discover all bindinded properties of a component:
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":


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 ];
}

This can be accessible only if you specify the use namespace mx_internal.