<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>My Experiments with Technology</title>
	<atom:link href="http://technicalmumbojumbo.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://technicalmumbojumbo.wordpress.com</link>
	<description></description>
	<lastBuildDate>Mon, 30 Jan 2012 09:30:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='technicalmumbojumbo.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>My Experiments with Technology</title>
		<link>http://technicalmumbojumbo.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://technicalmumbojumbo.wordpress.com/osd.xml" title="My Experiments with Technology" />
	<atom:link rel='hub' href='http://technicalmumbojumbo.wordpress.com/?pushpress=hub'/>
		<item>
		<title>The Android Tutorial Series Part 4 &#8211; RESTful Web Services and Google Maps integration with Android Application</title>
		<link>http://technicalmumbojumbo.wordpress.com/2012/01/19/android-tutorial-restful-webservices-google-maps-integration/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2012/01/19/android-tutorial-restful-webservices-google-maps-integration/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 08:02:52 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[google maps]]></category>
		<category><![CDATA[RESTful WebServices]]></category>
		<category><![CDATA[restful]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=657</guid>
		<description><![CDATA[Short Link: http://wp.me/p5Jvc-aB My previous three blogs have focused on the following areas in the Android platform: A Hello World Application A Basic Calculator Application A Sneak Peek at Layouts This blog post is going to focus on Andriod application &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2012/01/19/android-tutorial-restful-webservices-google-maps-integration/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=657&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Short Link:</strong> http://wp.me/p5Jvc-aB</p>
<p>My previous three blogs have focused on the following areas in the Android platform:</p>
<ul>
<li><a href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/" title="The Android Tutorial Series Part 1 – Hello&nbsp;World" target="_blank">A Hello World Application</a></li>
<li><a href="http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/" title="The Android Tutorial Series Part 2 – Calculator&nbsp;App" target="_blank">A Basic Calculator Application</a></li>
<li><a href="http://technicalmumbojumbo.wordpress.com/2011/12/08/android-tutorial-series-layout/" title="The Android Tutorial Series Part 3 –&nbsp;Layout" target="_blank">A Sneak Peek at Layouts</a></li>
</ul>
<p>This blog post is going to focus on Andriod application integration with the outside world using RESTful web services. Also it is going to look at how the wonderful Google Maps product can be integrated within Android App. My technology configuration as stated in the <a href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/" title="The Android Tutorial Series Part 1 – Hello&nbsp;World" target="_blank">first blog post</a> remains unchanged.</p>
<p><span id="more-657"></span></p>
<p>Today&#8217;s tutorial is going to do two things. One, it is going to communicate with a public RESTful web service API, supply a postal code and getting details of possible matches for the code. The possible matches will be listed for the user&#8217;s convenience. On selecting one of the matches, the Google Map within the page will zoom in on the location.</p>
<p>To implement this I need to create two activities. The first activity PostalCodeSearchActivity will prompt the end user to supply the postal code/zip code to search. On receiving the postal code, the PostalCodeSearchActivity activates the second Activity RESTfulWebServicesActivity. As a part of RESTfulWebServicesActivity&#8217;s creation process, it starts an asynchronous task which interrogates the public RESTful Web Service API and retrieves possible matches. These are displayed in the RESTfulWebServicesActivity. On selection of a location, the location is displayed in the Google Maps view of the application. Enough of theory, let&#8217;s first look at the PostalCodeSearchActivity code.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.rest;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class PostalCodeSearchActivity extends Activity {
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 
        		LayoutParams.FILL_PARENT);
        layout.setLayoutParams(params);
        
		TextView label = new TextView(this);
		label.setText(&quot;Enter the zip code&quot;);
		label.setMaxHeight(100);
		label.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
		label.setGravity(Gravity.CENTER);
		label.setTextColor(this.getResources().getColor(R.color.white));

		final EditText searchField = new EditText(this);
		searchField.setInputType(InputType.TYPE_NUMBER_VARIATION_NORMAL);
		searchField.setMaxHeight(100);
		searchField.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
		searchField.setGravity(Gravity.LEFT);
		searchField.setTextColor(this.getResources().getColor(R.color.white));
		searchField.requestFocus();

		Button searchButton = new Button(this);
		searchButton.setText(&quot;Search&quot;);
		searchButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(PostalCodeSearchActivity.this, RESTfulWebServicesActivity.class);
				i.putExtra(PostalCodeSearchActivity.this.getString(R.string.zip), searchField.getText().toString());
				startActivity(i);
			}
		});
		
		layout.addView(label);
		layout.addView(searchField);
		layout.addView(searchButton);
		
		this.setContentView(layout);         
    }
}
</pre></p>
<p>In the PostalCodeSearchActivity&#8217;s onCreate method, a content View for postal code / zip code search is created. It consists of a EditText control to accept user input and a search button to trigger the postal code search. Refer lines 47 to 55 for implementation of the search button&#8217;s onClickListener. The onclickListener requires implementation of onClick method. As per our design, we need to pass on the user provided zip code information to RESTfulWebServicesActivity. In Android, this is implemented via the Intent class. We create an intent using two parameters, the first is the Context which is PostalCodeSearchActivity instance and second is the Activity class to instantiate RESTfulWebServicesActivity; refer line 51. Using putExtra method of the Intent we pass on the user inputted postal code information. The RESTfulWebServicesActivity activity is initiated by invoking the startActivity method with the Intent instance as its argument. Note the layout information dynamically defined in the PostalCodeSearchActivity class could have been easily defined in a xml. I did it out of habit but the best practice is to use a xml to define the PostalCodeSearchActivity layout.</p>
<p>Now let&#8217;s look at RESTfulWebServicesActivity&#8217;s source code. Here I have adhered to the best practice with the page content layout been defined in xml. Refer the main.xml located within res/layout folder of the Andriod project.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/main&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; &gt;

    &lt;com.google.android.maps.MapView
        android:id=&quot;@+id/map&quot;
        android:layout_width=&quot;300dp&quot; 
        android:layout_height=&quot;250dp&quot;
        android:layout_gravity=&quot;center&quot;
        android:enabled=&quot;true&quot;
        android:clickable=&quot;true&quot;
        android:apiKey=&quot;AABBCCXX&quot;
     /&gt;
    &lt;ListView
        android:id=&quot;@+id/list&quot;
        android:layout_width=&quot;wrap_content&quot; 
        android:layout_height=&quot;wrap_content&quot;
     /&gt;
    
    &lt;Button 
    	android:id=&quot;@+id/backButton&quot;
    	android:text=&quot;Go back to Search Page&quot;
    	android:layout_gravity=&quot;center&quot;
    	android:layout_width=&quot;wrap_content&quot;
    	android:layout_height=&quot;wrap_content&quot;
    /&gt;
&lt;/LinearLayout&gt;
</pre></p>
<p>In the main.xml, we have defined the following elements an instance of MapView named map, a ListView named list and Button named backButton.</p>
<p>The MapView is a ready-to-use component for Google Maps. This component will display the location for given zip code/postal code. The MapView will only work once the developer obtains a free license. Google provides key string which is stored in the apiKey attribute of MapView. Details for obtaining the key are provided <a href="http://code.google.com/android/add-ons/google-apis/mapkey.html" title="Google API Key" target="_blank">here</a>. The ListView will display all possible matches for a given zip code and the back button will navigate back to the PostalCodeSearchActivity in case the user intends to revisit the zip code value. Next let&#8217;s look at the RESTfulWebServicesActivity source code.</p>
<p><pre class="brush: java;">
package com.android.rest;

import com.android.async.GeoNamesAsyncTask;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class RESTfulWebServicesActivity extends MapActivity {
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        
        //Reset MapView
        MapView map = (MapView)this.findViewById(R.id.map);
        MapController control = map.getController();
        control.setZoom(2);
        
        //Add dynamic behaviour to Back button
        Button backButton = (Button)this.findViewById(R.id.backButton);
        backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        
        //Retrieve matching locations
        GeoNamesAsyncTask task = new GeoNamesAsyncTask(this);
        Intent i = this.getIntent();
        String zipCode = i.getStringExtra(this.getString(R.string.zip));
        
        if (zipCode == null) {
        	zipCode = &quot;24501&quot;;
        }
        
        task.execute(zipCode);
                
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
</pre></p>
<p>Note that the Activity extends MapActivity. This is extremely important. This allows MapView to be used in the context of RESTfulWebServicesActivity class. In the onCreate method of the Activity, the content view is set to main.xml. The MapView is reset via lines 23 to 25. This is necessary or the MapView tends to retain the last selected result. Once a user has selected a zip code, the appropriate location is highlighted in the MapView; even if user navigates back to the PostalCodeSearchActivity and returns to the RESTfulWebServicesActivity, the previously selected location is displayed. Therefore we find the MapView component via the findViewById method, gain access to the view&#8217;s MapController and zoom out to move out of focus of the location. Next we implement a OnClickListener to the backButton. The onClick method implementation simply invokes finish method of the Activity. This causes the control to return back to PostalCodeSearchActivity.</p>
<p>As discussed earlier, the PostalCodeSearchActivity has supplied user input zip code to RESTfulWebServicesActivity. We create a asynchronous task named GeoNamesAsyncTask. Here&#8217;s the source code of GeoNamesAsyncTask.</p>
<p><pre class="brush: java;">
package com.android.async;

import java.util.List;

import com.android.rest.R;
import com.android.rest.adapter.PostalCodeAdapter;
import com.android.rest.vo.GeoName;
import com.google.android.maps.MapActivity;

import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.LinearLayout.LayoutParams;

public class GeoNamesAsyncTask extends AsyncTask&lt;String, Void, List&lt;GeoName&gt;&gt; {

	private Context ctx = null;
	
	public GeoNamesAsyncTask(Context ctx) {
		this.ctx = ctx;
	}
	
	@Override
	protected List&lt;GeoName&gt; doInBackground(String... arg0) {
		return new GeoNamesService().searchPostalCode(arg0[0]);
	}

	@Override
	protected void onPostExecute(List&lt;GeoName&gt; result) {
		this.populateActivity(result);
	}
	
	void populateActivity(List&lt;GeoName&gt; locations) {
		
		//Associate Adapter to ListView for matching locations
		MapActivity mapAct = (MapActivity)ctx;
		ListView list = (ListView) mapAct.findViewById(R.id.list);

		PostalCodeAdapter adapter = new PostalCodeAdapter(this.ctx, locations);
		list.setAdapter(adapter);
				
	}
}	
</pre></p>
<p>The asynchronous behavior is induced in GeoNamesAsyncTask by making AsyncTask as its parent class. The AsyncTask accepts three parameters as its formal type parameters. The first parameter defines the type of argument it will accept in its execute and doInBackground methods. The third parameter defines the type for the onPostExecute method. The asynchronous task is triggered in RESTfulWebServicesActivity by invoking the execute method, refer line 46.</p>
<p>The GeoNamesAsyncTask constructor accepts a Context as argument. This is to retain reference to the triggering Activity. Within the task we need to implement two methods doInBackground and onPostExecute method.</p>
<p>The doInBackground method is activated on execution of the execute method. The GeoNamesAsyncTask in turn uses the services of GeoNamesService class to invoke relevant RESTful web service APIs and get matching location information. Details of GeoNamesService will be covered later.</p>
<p>Once the information is retrieved, the task&#8217;s onPostExecute method is invoked. Here we invoke custom populateActivity method which populates the ListView of RESTfulWebServicesActivity with matching location information.</p>
<p>Why does the RESTful Web Services processing needs to be asynchoronous? In case you try to do it in the context of the parent thread, the following exception is thrown:</p>
<p><pre class="brush: plain;">
12-21 17:38:38.058: E/AndroidRuntime(638): Caused by: android.os.NetworkOnMainThreadException
</pre></p>
<p>Now let&#8217;s look GeoNamesService source code.</p>
<p><pre class="brush: java;">
package com.android.async;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.android.rest.vo.GeoName;
import com.google.gson.Gson;

public class GeoNamesService {

	private static final String GEONAME_RESTURL 
		= &quot;http://api.geonames.org/postalCodeSearchJSON?maxRows=4&amp;username=demo&amp;postalcode=&quot;;
	
	GeoNamesService() {
		
	}
	
	public List&lt;GeoName&gt; searchPostalCode (String code) {
		
		String url = GEONAME_RESTURL + code ;
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			
			if(entity != null) {
				InputStream stream = entity.getContent();
				String responseString = convertStreamToString(stream);
				
				DataWrapper wrap = new DataWrapper();
				wrap = wrap.fromJson(responseString);
				return wrap.postalCodes;
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + &quot;\n&quot;);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
	}
	
	public class DataWrapper {
		public List&lt;GeoName&gt; postalCodes = null;
		
		public DataWrapper fromJson(String jsonString) {
			return new Gson().fromJson(jsonString, DataWrapper.class);
		}
	}		
}
</pre></p>
<p>The RESTful Web Service API I am invoking belongs to <a href="http://www.geonames.org/" title="Geo Names" target="_blank">geonames.org</a>. The site provides free geographical database services. The registration is free and useful as the demo user has quota limits which routinely gets exceeded. I am using an API which provides me JSON payload. To convert JSON to Java Object I am using the Gson project. In case you need a framework for XML binding have a look at <a href="http://simple.sourceforge.net/" title="Simple XML Binding Framework" target="_blank">Simple</a>. </p>
<p>The implementation of searchPostalCode method uses Apache Commons HTTPClient project to establish a HTTP connection with the Web Service. The Json response string is unmarshalled into Java object using Gson. Here&#8217;s the JSON string for postal code 80907:</p>
<p><pre class="brush: plain;">
{&quot;postalCodes&quot;:[{&quot;adminName2&quot;:&quot;El Paso&quot;,&quot;adminCode2&quot;:&quot;041&quot;,&quot;adminCode1&quot;:&quot;CO&quot;,&quot;postalCode&quot;:&quot;80907&quot;,&quot;countryCode&quot;:&quot;US&quot;,&quot;lng&quot;:-104.817034,&quot;placeName&quot;:&quot;Colorado Springs&quot;,&quot;lat&quot;:38.876001,&quot;adminName1&quot;:&quot;Colorado&quot;}]}
</pre></p>
<p>Here&#8217;s the structure of the GeoName class. The DataWrapper is part of GeoNamesService. The top level element in the JSON string is postalCodes which matches the attribute name in the DataWrapper class. The rest of the data maps to the List.</p>
<p><pre class="brush: java;">
package com.android.rest.vo;

public class GeoName {
	
	public int postalCode = 0;
	public String placeName = null;
	public String countryCode = null;
	public float lat = 0.0f;
	public float lng = 0.0f;
}
</pre></p>
<p>The GeoName class defines only the relevant attributes from the JSON response. The attribute name within the JSON string and the GeoName class attributes are an exact match.</p>
<p>The final piece of the puzzle is the populateActivity method of GeoNamesAsyncTask. The method associates the List to the ListView using the PostalCodeAdapter. Here&#8217;s the source code of PostalCodeAdapter.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.rest.adapter;

import java.util.ArrayList;
import java.util.List;

import com.android.rest.OverlayItems;
import com.android.rest.R;
import com.android.rest.vo.GeoName;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class PostalCodeAdapter extends BaseAdapter {

	private Context ctx = null;
	
	private List&lt;GeoName&gt; names = new ArrayList&lt;GeoName&gt;();

	public PostalCodeAdapter(Context ctx, List&lt;GeoName&gt; locations) {
		this.ctx = ctx;
		this.names = locations;
	}
	
	
	@Override
	public int getCount() {		
		return names.size();
	}

	@Override
	public Object getItem(int arg0) {
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {

		LinearLayout layout = new LinearLayout(ctx);
		AbsListView.LayoutParams params = new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, 
				LayoutParams.FILL_PARENT);
		layout.setLayoutParams(params);
		
		layout.setOrientation(LinearLayout.HORIZONTAL);
		
		GeoName location = this.names.get(arg0);
				
		TextView value = new TextView(this.ctx);
		value.setText(location.placeName);
		value.setMaxHeight(100);
		value.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
		value.setGravity(Gravity.CENTER);
		value.setTextColor(this.ctx.getResources().getColor(R.color.white));
		value.setOnClickListener(new CityClickListener(location));
		
		layout.addView(value);
		
		return layout;
	}
	
	class CityClickListener implements OnClickListener {

		private GeoName geoName = null;
		
		CityClickListener(GeoName name) {
			this.geoName = name;
		}
		
		@Override
		public void onClick(View v) {
		
			AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
			builder.setView(createView());
			builder.setTitle(&quot;Details of &quot; + geoName.placeName);
		    builder.setCancelable(true);

			builder.setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel();
		           }
			});
			
			AlertDialog alert = builder.create();
			alert.show();
			
			updateMap(); 
			
		}
		
		private void updateMap() {
			
			MapActivity mapAct = (MapActivity)ctx;
			MapView map = (MapView)mapAct.findViewById(R.id.map);
			map.setScrollBarStyle(MapView.SCROLLBARS_INSIDE_INSET);
			map.setBuiltInZoomControls(Boolean.TRUE);
			map.displayZoomControls(Boolean.TRUE);
			
			GeoPoint point = new GeoPoint((int)(geoName.lat * 1E6), (int)(geoName.lng * 1E6));
			MapController mc = map.getController();
			mc.setZoom(17);
			mc.setCenter(point);
			mc.animateTo(point);
			
			List&lt;Overlay&gt; overlays = map.getOverlays();
			overlays.clear();

			OverlayItems items = new OverlayItems(ctx.getResources().getDrawable(R.drawable.marker));
			OverlayItem item = new OverlayItem(point, geoName.placeName, &quot;&quot; + geoName.postalCode);
			
			items.addOverlay(item);
			overlays.add(items);
			
						
		}
		
		
		private View createView() {
			
			LinearLayout l = new LinearLayout(ctx);
			l.setOrientation(LinearLayout.VERTICAL);
			LinearLayout.LayoutParams params = new LayoutParams(100, 300);
			l.setLayoutParams(params);
			
			TextView city = new TextView(ctx);
			city.setText(&quot;City, Country : &quot; + geoName.placeName + &quot;, &quot; + geoName.countryCode);
			city.setMaxHeight(100);
			city.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
			city.setGravity(Gravity.CENTER);
			city.setTextColor(ctx.getResources().getColor(R.color.white));

			TextView orientation = new TextView(ctx);
			orientation.setText(&quot;Orientation : &quot; + geoName.lat + &quot; || &quot; + geoName.lng);
			orientation.setMaxHeight(100);
			orientation.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
			orientation.setGravity(Gravity.CENTER);
			orientation.setTextColor(ctx.getResources().getColor(R.color.white));
						
			l.addView(city);
			l.addView(orientation);
			
			return l;
		}	
	}
}
</pre></p>
<p>Refer the getView method on line number 61. Note the use of AbsListView.LayoutParams instead of LinearLayout.LayoutParams. If LinearLayout.LayoutParams is used the following exception is thrown:</p>
<p><pre class="brush: plain;">
java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
</pre></p>
<p>For clarification of why this occurs refer <a href="http://stackoverflow.com/questions/7278101/change-custom-button-size-for-layouts-and-containers" title="Change Custom Button Size for Layout &amp; Containers" target="_blank">here</a>.</p>
<p>The CityClickListener displays a dialog window with city, country and latitude and longitude details. The method createView creates the dialog window contents. The updateMap method updates the map with selected location&#8217;s lat/lng details. This is done by instantiating a GeoPoint. The GeoPoint accepts integer values for latitude and longitude in microdegrees; therefore the lat/lng values of GeoName has to multipled by 1E6 to get value in microdegrees. Next we set the zoom value of the MapView&#8217;s MapController and use the center and animateTo method to assign the GeoPoint. </p>
<p>To get the pointer effect of Google Maps, we add an OverLay to the Map, refer line number 125 to 132.</p>
<p>Here&#8217;s the output of our effort.</p>
<p><img src="http://technicalmumbojumbo.files.wordpress.com/2012/01/mapview.png?w=500" alt="MapView" align="center" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/657/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/657/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/657/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=657&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2012/01/19/android-tutorial-restful-webservices-google-maps-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2012/01/mapview.png" medium="image">
			<media:title type="html">MapView</media:title>
		</media:content>
	</item>
		<item>
		<title>Interview Question: During XML modeling, do you model a data member as XML Element or XML Attribute?</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/12/30/interview-question-xml-modeling-xml-element-vs-attribute/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/12/30/interview-question-xml-modeling-xml-element-vs-attribute/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 07:49:07 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[xml]]></category>
		<category><![CDATA[xml element attribute]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=646</guid>
		<description><![CDATA[Short Link: http://wp.me/p5Jvc-aq In case your resume showcases experience in using XML, the interviewer would normally probe you regarding what selection criteria do you apply in modeling a data member as a XML element or attribute. The following are some &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/12/30/interview-question-xml-modeling-xml-element-vs-attribute/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=646&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Short Link:</strong> http://wp.me/p5Jvc-aq</p>
<p>In case your resume showcases experience in using XML, the interviewer would normally probe you regarding what selection criteria do you apply in modeling a data member as a XML element or attribute.</p>
<p><span id="more-646"></span></p>
<p>The following are some of the selection criteria which I could think of or gather from internet:</p>
<p><strong>Readability</strong></p>
<p>At the end of the day, XML is human readable, hence some effort must be expended in keeping format easy to read. For example consider the following two XMLs PersonElements and PersonElements_Attributes.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!-- PersonElements.xml --&gt;
&lt;Person&gt;
	&lt;FirstName&gt;Steve&lt;/FirstName&gt;
	&lt;MiddleName&gt;M&lt;/MiddleName&gt;
	&lt;LastName&gt;Richardson&lt;/LastName&gt;
	&lt;DateOfBirth&gt;10-March-1988&lt;/DateOfBirth&gt;
	&lt;Gender&gt;Male&lt;/Gender&gt;
	&lt;UniqueIdentifierNumber&gt;123-45-6789&lt;/UniqueIdentifierNumber&gt;
&lt;/Person&gt;
</pre></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!-- PersonElements_Attributes.xml --&gt;
&lt;Person uniqueIdentifierNumber=&quot;123-45-6789&quot; gender=&quot;male&quot;&gt;
	&lt;FirstName&gt;Steve&lt;/FirstName&gt;
	&lt;MiddleName&gt;M&lt;/MiddleName&gt;
	&lt;LastName&gt;Richardson&lt;/LastName&gt;
	&lt;DateOfBirth&gt;10-March-1988&lt;/DateOfBirth&gt;
&lt;/Person&gt;
</pre></p>
<p>In PersonElements.xml, all data members have been modeled as elements; in PersonElements_Attributes.xml, some data members namely uniqueIdentifierNumber and gender have been modeled as attributes. Both XMLs represent the same data but in different formats. For a human readability standpoint PersonElements is easier to read vis-a-vis PersonElements_Attributes.</p>
<p><strong>Data or meta-data</strong></p>
<p>The second criteria I would apply is to verify if the data member represents data with respect to the parent element or metadata. Consider the following XML metadata.xml.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Person id=&quot;1AEFHG234&quot;&gt;
	&lt;FirstName&gt;Steve&lt;/FirstName&gt;
	&lt;MiddleName&gt;M&lt;/MiddleName&gt;
	&lt;LastName&gt;Richardson&lt;/LastName&gt;
	&lt;DateOfBirth&gt;10-March-1988&lt;/DateOfBirth&gt;
	&lt;Gender tc=&quot;1&quot;&gt;Male&lt;/Gender&gt;
	&lt;UniqueIdentifierNumber tc=&quot;0&quot;&gt;123-45-6789&lt;/UniqueIdentifierNumber&gt;
	&lt;AnnualIncome currency=&quot;USD&quot; currencycode=&quot;1&quot;&gt;120000&lt;/AnnualIncome&gt;
&lt;/Person&gt;
</pre></p>
<p>The XML format has become a data communication format of choice for electronic communication e.g. web services. Therefore information pertinent for system processing needs to be incorporated within the XML message payload. This additional information may not have a strong relationship or belongingness with the containing element, however is important from a system processing standpoint. Such information can be modeled as an attribute. In our example, the id attribute uniquely identifies the Person element. The id attribute by itself does not have any business context significance with the Person element but purely present from B2B processing standpoint. </p>
<p>Secondly we have introduced the attribute tc for two elements namely Gender and UniqueIdentifierNumber. From a human readability perspective, the actual values of these elements are sufficient, but from system processing point of view, getting codes instead of description is preferred, hence we have the tc or typecode attribute which points to code value 1. In the second case &#8216;UniqueIdentifierNumber&#8217; from the formatting a human may decipher that the unique number is US Social Security Number but for the convenience of system processing we use tc=&#8221;1&#8243; attribute to identify that this is a social security number. This technique is commonly used in ACORD(An insurance domain specific XML standard) XML modeling. </p>
<p>The third and the final example is that of AnnualIncome element. Here we need to model two aspects, measurement unit and value. Containing them together in one element is achieved by keeping the currency code or description as attribute and measurement value &#8217;120000&#8242; as the element value. alternative methods for modeling would have been as follows:</p>
<p><pre class="brush: xml;">
&lt;!-- Option 1 --&gt;
&lt;Person&gt;
.
.
.
	&lt;AnnualIncomeCurrencyCode&gt;USD&lt;/AnnualIncomeCurrencyCode&gt;
	&lt;AnnualIncome&gt;120000&lt;/AnnualIncome&gt;
.
.
&lt;/Person&gt;
</pre></p>
<p><pre class="brush: xml;">
&lt;!-- Option 2 --&gt;
&lt;Person&gt;
.
.
.
	&lt;CurrencyCode&gt;USD&lt;/CurrencyCode&gt;
	&lt;AnnualIncome&gt;120000&lt;/AnnualIncome&gt;
.
.
&lt;/Person&gt;
</pre></p>
<p><pre class="brush: xml;">
&lt;!-- Option 3 --&gt;
&lt;Person&gt;
.
.
.
	&lt;AnnualIncome&gt;
		&lt;CurrencyCode&gt;USD&lt;/CurrencyCode&gt;
		&lt;Value&gt;120000&lt;/Value&gt;
	&lt;/AnnualIncome&gt;
.
.
&lt;/Person&gt;
</pre></p>
<p>Consider an XML containing a lot of measures and measure types; it would become difficult to comprehend if any of the three above mentioned approaches are used.</p>
<p><strong>Extensibility</strong></p>
<p>XML used for electronic communication needs to be flexible for accepting change. Inevitably business requirements change, data structures evolve; a data member modeled as an attribute cannot be extended further. For example, consider the  XML Extension-1.xml. It does not provide any room for the publisher attribute to evolve. </p>
<p><pre class="brush: xml;">
&lt;!-- Extension-1.xml --&gt;
&lt;Books&gt;
	&lt;Book id=&quot;12345&quot; publisher=&quot;McGraw Hill&quot;&gt;
		&lt;Title&gt;XML Modeling - An approach&lt;/Title&gt;
		&lt;Author&gt;Ray Johnson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-March-2001&lt;/BookReleaseDate&gt;
	&lt;/Book&gt;
	&lt;Book id=&quot;22345&quot; publisher=&quot;Apress&quot;&gt;
		&lt;Title&gt;XML XSLT Guide&lt;/Title&gt;
		&lt;Author&gt;Tim Gibson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-May-2010&lt;/BookReleaseDate&gt;
	&lt;/Book&gt;	
&lt;/Books&gt;
</pre></p>
<p>In case the publisher was modeled as a XML element, it could further on easily evolve into Extension-2.xml or Extension-3.xml.</p>
<p><pre class="brush: xml;">
&lt;!-- Extension-2.xml --&gt;
&lt;Books&gt;
	&lt;Book id=&quot;12345&quot;&gt;
		&lt;Title&gt;XML Modeling - An approach&lt;/Title&gt;
		&lt;Author&gt;Ray Johnson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-March-2001&lt;/BookReleaseDate&gt;
		&lt;Publisher&gt;
			&lt;Name&gt;McGraw Hill&lt;/Name&gt;
			&lt;Location&gt;Seattle&lt;/Location&gt;
		&lt;/Publisher&gt;		
	&lt;/Book&gt;
	&lt;Book id=&quot;22345&quot;&gt;
		&lt;Title&gt;XML XSLT Guide&lt;/Title&gt;
		&lt;Author&gt;Tim Gibson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-May-2010&lt;/BookReleaseDate&gt;
		&lt;Publisher&gt;
			&lt;Name&gt;Apress&lt;/Name&gt;
			&lt;Location&gt;Florida&lt;/Location&gt;
		&lt;/Publisher&gt;	
	&lt;/Book&gt;	
&lt;/Books&gt;
</pre></p>
<p><pre class="brush: xml;">
&lt;!-- Extension-3.xml --&gt;
&lt;Books&gt;
	&lt;Book id=&quot;12345&quot; publisherid=&quot;12&quot;&gt;
		&lt;Title&gt;XML Modeling - An approach&lt;/Title&gt;
		&lt;Author&gt;Ray Johnson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-March-2001&lt;/BookReleaseDate&gt;
	&lt;/Book&gt;
		&lt;Book id=&quot;22345&quot; publisherid=&quot;13&quot;&gt;
		&lt;Title&gt;XML XSLT Guide&lt;/Title&gt;
		&lt;Author&gt;Tim Gibson&lt;/Author&gt;
		&lt;BookReleaseDate&gt;20-May-2010&lt;/BookReleaseDate&gt;
	&lt;/Book&gt;	
	&lt;Publisher id=&quot;12&quot;&gt;
		&lt;Name&gt;McGraw Hill&lt;/Name&gt;
		&lt;Location&gt;Seattle&lt;/Location&gt;
	&lt;/Publisher&gt;
		&lt;Publisher id=&quot;13&quot;&gt;
		&lt;Name&gt;Apress&lt;/Name&gt;
		&lt;Location&gt;Florida&lt;/Location&gt;
	&lt;/Publisher&gt;
&lt;/Books&gt;
</pre></p>
<p><strong>Relationship with parent element</strong></p>
<p>Any data member which shares a one-to-one relationship with the parent element can be modeled as an attribute, provided the containment relationship between the parent element is weak. A Person and FirstName have a strong containment relationship, a Book and Publisher do not necessarily share a strong containment relationship. If the relationship is one-to-many, that element necessairly needs to be modeled as a XML element. While modeling a person who is an insurance agent, his/her agent number can be modeled as an attribute, however the states in which he/she are licensed to sell insurance can be more than one. Hence the states need to be modeled as XML element.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Persons&gt;
	&lt;Person agentNbr=&quot;23456&quot;&gt;
		&lt;FirstName&gt;Harry&lt;/FirstName&gt;
		&lt;LastName&gt;Maxwell&lt;/LastName&gt;
		&lt;LicenseState&gt;VA&lt;/LicenseState&gt;
		&lt;LicenseState&gt;GA&lt;/LicenseState&gt;
		&lt;LicenseState&gt;FL&lt;/LicenseState&gt;
	&lt;/Person&gt;
&lt;/Persons&gt;
</pre></p>
<p><strong>Modeling Relationships</strong></p>
<p>While explaining the extensibility point I used two sample XMLs Extension-2.xml and Extension-3.xml. In Extension-2.xml the Publisher element was made a child element of Book. In Extension-3.xml, the Publisher element was retained as a separate data structure within the root element and its id was modeled as an attribute in Book element. Extension-3.xml provides a flexible structure where I can reuse the same publisher element across multiple Books. Therefore when relationships are not modeled as container relationships(e.g. Extension-2.xml) and a reference is provided at one end of the relationship, the reference can be modeled as a attribute.</p>
<p><strong>Who&#8217;s the information consumer?</strong></p>
<p>One key criteria to consider is who is the potential consumer of the information? Is it a human or is it a machine? If it is a machine, the data member can be modeled as an attribute, while a human being would find element preferable due to readability. Machines usually consume meta-data, while humans consume data.<br />
 This point might have some overlap with the data or metadata point. I just wanted to highlight it.</p>
<p><strong>Is member order/sequence important?</strong></p>
<p>In some cases maintaining data in specific order is important. Elements support maintenance of ordered sequence, attributes do not.</p>
<p><strong>Some Useful references:</strong></p>
<p><a href="http://xml.coverpages.org/elementsAndAttrs.html" title="XML Elements And Attributes" target="_blank">http://xml.coverpages.org/elementsAndAttrs.html</a><br />
<a href="http://xml.coverpages.org/elementAttr9804.html" title="XML Elements and Attributes Discussion" target="_blank">http://xml.coverpages.org/elementAttr9804.html</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/646/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/646/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/646/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=646&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/12/30/interview-question-xml-modeling-xml-element-vs-attribute/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>The Android Tutorial Series Part 3 – Layout</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/12/08/android-tutorial-series-layout/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/12/08/android-tutorial-series-layout/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 08:16:50 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[framelayout]]></category>
		<category><![CDATA[gridview]]></category>
		<category><![CDATA[layout]]></category>
		<category><![CDATA[linearlayout]]></category>
		<category><![CDATA[listview]]></category>
		<category><![CDATA[relativelayout]]></category>
		<category><![CDATA[tablayout]]></category>
		<category><![CDATA[tablelayout]]></category>
		<category><![CDATA[tabslayout]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=595</guid>
		<description><![CDATA[Short Link: http://wp.me/p5Jvc-9B My first two tutorials in this series covered a simple HelloWorld and provided an insight into development of a simple android based mobile application (mobile app). In this blog post I intended to skim below the surface &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/12/08/android-tutorial-series-layout/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=595&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Short Link:</strong> http://wp.me/p5Jvc-9B</p>
<p>My first two tutorials in this series covered a simple <a href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/" title="The Android Tutorial Series Part 1 – Hello World" target="_blank">HelloWorld</a> and provided an insight into development of a <a href="http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/" title="The Android Tutorial Series Part 2 – Calculator App" target="_blank">simple android based mobile application</a> (mobile app). In this blog post I intended to skim below the surface and take a look at the various layout formats supported by the Android 4.0 platform. My development platform as discussed in <a href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/" title="The Android Tutorial Series Part 1 – Hello World" target="_blank">Part 1 HelloWorld blog post</a> remains unchanged.</p>
<p><span id="more-595"></span></p>
<p>Android allows definition of its UI in two ways, defining UI elements, their layout declaratively in a XML or programmatically adding UI elements with layout information using Java programming language. I intend to cover both the methods of UI creation. The Android 4.0 platform supports the following layout formats:</p>
<ul>
<li>FrameLayout</li>
<li>LinearLayout</li>
<li>ListView</li>
<li>GridView</li>
<li>TableLayout</li>
<li>RelativeLayout</li>
<li>TabLayout</li>
</ul>
<p>In the subsequent paragraphs, I will be explaining each layout, its configuration settings and wherever possible detail out how to implement the layout declaratively and programmatically. Before starting, let me describe the common resources for the subsequent discussion. They are colors.xml and strings.xml located within the /res/values folder.</p>
<p>colors.xml<br />
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
        &lt;color name=&quot;white&quot;&gt;#ffffffff&lt;/color&gt;
        &lt;color name=&quot;red&quot;&gt;#ffff0000&lt;/color&gt;
        &lt;color name=&quot;black&quot;&gt;#ff000000&lt;/color&gt;
        &lt;color name=&quot;blue&quot;&gt;#ff0000ff&lt;/color&gt;
        &lt;color name=&quot;green&quot;&gt;#ff00ff00&lt;/color&gt;
        &lt;color name=&quot;cyan&quot;&gt;#ff00ffff&lt;/color&gt;
        &lt;color name=&quot;dkgray&quot;&gt;#ff444444&lt;/color&gt;
        &lt;color name=&quot;gray&quot;&gt;#ff888888&lt;/color&gt; 
&lt;/resources&gt;
</pre></p>
<p>strings.xml<br />
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    &lt;string name=&quot;hello&quot;&gt;Hello World, LayoutDemoActivity!&lt;/string&gt;
    &lt;string name=&quot;app_name&quot;&gt;Layout Demonstrator&lt;/string&gt;
    &lt;string name=&quot;usernamelbl&quot;&gt;UserNameLabel&lt;/string&gt;
    &lt;string name=&quot;usernamefld&quot;&gt;usernamefld&lt;/string&gt;
    &lt;string name=&quot;passwordfld&quot;&gt;passwordfld&lt;/string&gt;
    &lt;string name=&quot;passwordlbl&quot;&gt;passwordlbl&lt;/string&gt;

    &lt;!-- FrameLayout starts --&gt;    
    &lt;string name=&quot;firstview&quot;&gt;My First View&lt;/string&gt;
    &lt;string name=&quot;secondview&quot;&gt;My Second View&lt;/string&gt;    
    &lt;!-- FrameLayout ends --&gt;    
    
    &lt;!-- LinearLayout starts --&gt;    
    &lt;string name=&quot;one&quot;&gt;One&lt;/string&gt;
    &lt;string name=&quot;two&quot;&gt;Two&lt;/string&gt;
    &lt;string name=&quot;three&quot;&gt;Three&lt;/string&gt;    
    &lt;!-- LinearLayout ends --&gt;   
    
    &lt;!-- TableLayout starts --&gt;    
    &lt;string name=&quot;calchint&quot;&gt;Enter your input&lt;/string&gt;
    &lt;string name=&quot;onefigure&quot;&gt;1&lt;/string&gt;
    &lt;string name=&quot;twofigure&quot;&gt;2&lt;/string&gt;
    &lt;string name=&quot;threefigure&quot;&gt;3&lt;/string&gt;
    &lt;string name=&quot;eqfigure&quot;&gt;=&lt;/string&gt;
    &lt;!-- TableLayout ends --&gt;   
     
    &lt;!-- RelativeLayout starts --&gt;
    &lt;string name=&quot;username&quot;&gt;User name:&lt;/string&gt;
    &lt;string name=&quot;password&quot;&gt;Password:&lt;/string&gt;
    &lt;string name=&quot;login&quot;&gt;Log In&lt;/string&gt;
    &lt;!-- RelativeLayout ends --&gt;
&lt;/resources&gt;
</pre></p>
<p>I will explain the significance and application of the two XMLs individual entries during the walk thru of individual layout. Let&#8217;s look at the first layout, FrameLayout.</p>
<p><strong>FrameLayout</strong></p>
<p>The FrameLayout is the simplest of all layouts. It is designed to contain and display only one UI element. Addition of multiple UI elements will just cause the subsequent elements to overlay above the previous element(s). Following is the source of framelayout.xml which is FrameLayout&#8217;s declarative implementation:</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;&gt;

    &lt;TextView
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/firstview&quot; /&gt;

    &lt;TextView
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/secondview&quot; /&gt;
    
&lt;/FrameLayout&gt;
</pre></p>
<p>The root element FrameLayout defines that UI window will be presented using the FrameLayout format. The attributes layout_width and layout_height prescribe the width and height for the layout container. In the XML we have defined the value of two attributes as &#8216;fill_parent&#8217; which means that the layout container is expected to cover the available screen real estate. Alternatively the developer is free to define specific dimensions in the following units: px(pixels), dp(density-independent pixels) and sp(scaled pixels based on preferred font size), in(inches) and mm (millimeters). An elaborate explanation on the various units is available <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Dimension" title="Android Application Resources - Dimensions" target="_blank">here</a>. </p>
<p>Next I have defined a TextView UI element. The layout_height attribute is defined as &#8216;wrap_content&#8217; which means that the height of the TextView component depends on the length of the component&#8217;s text message. The text message is defined by the value of android:text attribute. The value can be the text message string or a pointer to the name attribute of string defined in strings.xml. In our case, it is a pointer to the string named &#8216;firstview&#8217;, the syntax format is @string/{name}. In addition to the firstview TextView component we have defined another TextView component named secondview. The code associated with the second TextView is commented out. This is specifically done to showcase the impact of adding more than one UI components in FrameLayout. Run the code leaving secondview element definition commented. So how do we run code? My Android project name is LayoutDemo. During Android project creation, eclipse creates a Activity class named LayoutDemoActivity. Please find below the source code of LayoutDemoActivity class.</p>
<p><pre class="brush: java; highlight: [11];">
package com.android.layout;

import android.app.Activity;
import android.os.Bundle;

public class LayoutDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
</pre></p>
<p>Change line number 11 to the following:</p>
<p><pre class="brush: java;">
setContentView(R.layout.framelayout);
</pre></p>
<p>To understand intricacies of the generated class R refer to Satya Komatineni&#8217;s blog post <a href="http://knowledgefolders.com/akc/display?url=displaynoteimpurl&amp;ownerUserId=satya&amp;reportId=2883" target="_blank">&#8216;Understanding R.java&#8217;</a>. </p>
<p>The changed source code causes LayoutDemoActivity class to use the framelayout.xml as its content. To run the LayoutDemoActivity class do the following. Within the project, search and open the AndroidManifest.xml. Check if the manifest file has the following entry, if not add it.</p>
<p><pre class="brush: xml;">
        &lt;activity
            android:label=&quot;@string/app_name&quot;
            android:name=&quot;.LayoutDemoActivity&quot; &gt;
            &lt;intent-filter &gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
</pre></p>
<p>Please note one thing. The top element of the manifest file is defined as follows:</p>
<p><pre class="brush: xml;">
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    package=&quot;com.android.layout&quot;
    android:versionCode=&quot;1&quot;
    android:versionName=&quot;1.0&quot; &gt;
</pre></p>
<p>Refer the package attribute value. The complete class name is derived by concatenating package attribute value of manifest element and value of android:name attribute of activity element; therefore we have &#8216;com.android.layout&#8217; + &#8216;.LayoutDemoActivity&#8217; which becomes com.android.layout.LayoutDemoActivity. Hence the activity name attribute always begin with a &#8216;.&#8217;. Do keep this in mind in case you intend to modularize based on package name and keep Activity classes under different packages. </p>
<p>In the Eclipse menu select Run &#8211;&gt; Run Configurations. In the left pane within Android application select &#8216;LayoutDemo&#8217;(this can be any name you may have provided). In the right pane under the &#8216;Android&#8217; tab in Launch Action select the Launch radio button. Within the drop-down choices select &#8216;com.android.layout.LayoutDemoActivity&#8217;. The application should open in the AVD. The text message &#8216;My First View&#8217; should be displayed. There&#8217;s the output.</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/framelayout.png?w=500" alt="Frame Layout Example" align="middle" /></div>
<p></p>
<p>Uncomment the secondview TextView and run the application again. The text message will appear garbled as the two TextView contents will overlap. Now that we have covered the declarative  programming part, let&#8217;s look at the programmatic option.</p>
<p>Here&#8217;s the source code of FrameLayoutActivity class.</p>
<p><pre class="brush: java; highlight: [15];">
package com.android.layout;

import android.app.Activity;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.TextView;

public class FrameLayoutActivity extends Activity {
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        TextView view1 = new TextView(this);
        view1.setText(R.string.firstview);

        TextView view2 = new TextView(this);
        view2.setText(R.string.secondview);
        
        FrameLayout frame = new FrameLayout(this);
        frame.addView(view1);
        //frame.addView(view2);
        
        setContentView(frame);
    }
}
</pre></p>
<p>In Java world environment, the generated R.class is used to reference application resources.<br />
Note that there is android.R class which holds platform specific resource values. The R.class you need will be part of your custom package which in my case is com.android.layout package. The R class reference format is R.{resourceType}.{resourceName}, hence we have R.string.firstview at line number 15 in source code. </p>
<p>Add the entry for FrameLayoutActivity in Android manifest file. </p>
<p><pre class="brush: xml;">
        &lt;activity 
            android:label=&quot;@string/app_name&quot;
            android:name=&quot;.FrameLayoutActivity&quot;&gt;
            &lt;intent-filter &gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
</pre></p>
<p>Run the FrameLayoutActivity class using the same method as mentioned for running LayoutDemoActivity. Instead of selecting LayoutDemoActivity as the launch class select FrameLayoutActivity. In the source code note line number 22 which comments out view2. Uncomment the line and run the application to understand the impact of having more than one UI components in FrameLayout.</p>
<p><strong>LinearLayout</strong></p>
<p>The next layout we look at is LinearLayout. This layout container lays out its children aligned to a particular orientation either horizontal or vertical. The developer needs to define the orientation and the children components are laid out horizontally one besides the other or vertically one below the other. </p>
<p>Here&#8217;s how you define LinearLayout declaratively. Refer linearlayout.xml</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot;&gt;

    &lt;TextView
        android:layout_width=&quot;100dp&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/one&quot; 
        android:background=&quot;@color/red&quot;
        android:textColor=&quot;@color/cyan&quot;
        android:gravity=&quot;left&quot;
        android:textStyle=&quot;bold&quot;
        android:layout_gravity=&quot;left&quot; 
        android:layout_weight=&quot;0&quot;
        android:layout_marginLeft=&quot;5dp&quot;
        android:layout_marginTop=&quot;5dp&quot;
        android:layout_marginBottom=&quot;5dp&quot; /&gt;
       
    &lt;TextView
        android:layout_width=&quot;100dp&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/two&quot; 
        android:background=&quot;@color/green&quot;
        android:textColor=&quot;#ff000000&quot;
        android:gravity=&quot;center&quot;
        android:typeface=&quot;sans&quot;
        android:textStyle=&quot;bold|italic&quot;
        android:layout_gravity=&quot;center&quot; 
        android:layout_weight=&quot;0&quot;
        android:layout_marginLeft=&quot;5dp&quot;
        android:layout_marginTop=&quot;5dp&quot;
        android:layout_marginBottom=&quot;5dp&quot;
        android:layout_marginRight=&quot;5dp&quot;/&gt;
        
    &lt;TextView
        android:layout_width=&quot;100dp&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/three&quot; 
        android:background=&quot;@color/blue&quot;
        android:textColor=&quot;@color/white&quot;
        android:gravity=&quot;right&quot;
        android:typeface=&quot;serif&quot;
        android:textStyle=&quot;italic&quot;
        android:layout_gravity=&quot;right&quot; 
        android:layout_weight=&quot;0&quot;
        android:layout_marginLeft=&quot;5dp&quot;
        android:layout_marginTop=&quot;5dp&quot;
        android:layout_marginBottom=&quot;5dp&quot;
        android:layout_marginRight=&quot;5dp&quot;/&gt;
&lt;/LinearLayout&gt;
</pre></p>
<ul>
<li><b>android:orientation</b> &#8211; The orientation of the LinearLayout is determined by the value specified for this attribute. The valid options are vertical and horizontal. For our example we are using vertical orientation.</li>
<li><b>android:layout_width</b> &#8211; This attribute defines the width of the TextView. The TextView also defines another attribute named android:width. Apparently both attributes achieve the <a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android%3awidth" title="Android width Attribute" target="_blank">same thing</a>, defining width dimension of the TextView.</li>
<li><b>android:layout_height</b> &#8211; The layout_height defines the height of the TextView component, presently it is defined as &#8216;wrap_content&#8217;, so as to size it to the text contents of the TextView component.
</li>
<li><b>android:text</b> &#8211; already explained earlier.</li>
<li><b>android:background</b> &#8211; This attribute assigns the background color to the TextView. We can assign a color from the application resources colors.xml. The resource reference format is @color/{name}. Alternatively color can be directly assigned as done for textColor of the second TextView, refer line number 26. The color value is a hexadecimal value in the Alpha-Red-Green-Blue (#AARRGGBB) format.
</li>
<li><b>android:textColor</b> &#8211; This attribute assigns color to the text content of TextView. Value assignment is similar to the background attribute.
</li>
<li><b>android:gravity</b> &#8211; This attribute defines the orientation of text message vis-a-vis the TextView layout. For our example we have provided left aligned orientation.
</li>
<li><b>android:typeface</b> &#8211; This attribute defines the font used by the text content of TextView. The valid options are normal, sans, serif, monospace.</li>
<li><b>android:textStyle</b> &#8211; This attribute defines the text styling such as bold, italic etc. In case you want to apply two styles together, use the | and assign both values to textStyle attribute. Refer line number 29 for ready reference.</li>
<li><b>android:layout_gravity</b> &#8211; This attribute defines the orientation of the TextView component. Note the layout_gravity takes care of the TextView component orientation, while the gravity attribute takes care of TextView&#8217;s text content&#8217;s orientation, a vital difference. To understand further details refer <a href="http://sandipchitale.blogspot.com/2010/05/linearlayout-gravity-and-layoutgravity.html" title="Sandeep Chitale:android:layout_gravity and android:gravity Difference" target="_blank">Sandip Chitale&#8217;s blog post</a>.</li>
<li><b>android:layout_weight</b> &#8211; This attribute determines how the space leftover after laying out all components is distributed amongst the components. The attribute accepts a numeric value. To get a better insight refer <a href="http://stackoverflow.com/questions/3736663/problems-understanding-android-xml-layout-weight" title="Problems understanding android XML layout_weight" target="_blank">Mayra&#8217;s excellent answer in stackoverflow.com</a>.</li>
<li><b>android:layout_marginLeft</b>, <b>bandroid:layout_marginRight</b>,<br />
<b>android:layout_marginTop</b>, <b>android:layout_marginBottom</b> &#8211; These attributes determine the left, right, top and bottom margin settings for the TextView component. The units are same as the ones defined for width or height.</li>
</ul>
<p>In the example, I have created three TextViews with varying attribute settings to showcase the various configurations. Play around with layout_weight values to understand the impact of this attribute. Here&#8217;s the output of the linearlayout.xml:</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/linearlayout.png?w=500" alt="Linear Layout Example" /></div>
<p></p>
<p>For programmatic implementation refer to the LinearLayoutActivity class below:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LinearLayoutActivity extends Activity {
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        TextView view1 = new TextView(this);
        view1.setText(R.string.one);
        view1.setBackgroundResource(R.color.red);
        view1.setTextColor(Color.CYAN);
        view1.setGravity(Gravity.LEFT);
        view1.setTypeface(Typeface.DEFAULT_BOLD);
        
        TextView view2 = new TextView(this);
        view2.setText(R.string.two);
        view2.setBackgroundResource(R.color.green);
        //view2.setBackgroundColor(0xffff0000);
        view2.setTextColor(0xff000000);
        view2.setGravity(Gravity.CENTER);
        view2.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);

        TextView view3 = new TextView(this);
        view3.setText(R.string.three);
        view3.setBackgroundResource(R.color.blue);
        view3.setTextColor(getResources().getColor(R.color.white));
        view3.setGravity(Gravity.RIGHT);
        view3.setTypeface(Typeface.SERIF, Typeface.ITALIC);
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        		LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        layout.setLayoutParams(params);
        
        LinearLayout.LayoutParams params1  = new LinearLayout.LayoutParams(100, 
                ViewGroup.LayoutParams.WRAP_CONTENT,0);
        params1.gravity = Gravity.LEFT;
        params1.weight = 0;
        params1.leftMargin = 5;
        params1.topMargin = 5;
        params1.bottomMargin = 5;
        
        LinearLayout.LayoutParams params2  = new LinearLayout.LayoutParams(100, 
                ViewGroup.LayoutParams.WRAP_CONTENT,0);
        params2.gravity = Gravity.CENTER;
        params2.weight = 0;
        params2.leftMargin = 5;
        params2.topMargin = 5;
        params2.bottomMargin = 5;
        params2.rightMargin = 5;
        
        LinearLayout.LayoutParams params3  = new LinearLayout.LayoutParams(100, 
                ViewGroup.LayoutParams.WRAP_CONTENT,0);
        params3.gravity = Gravity.RIGHT;
        params3.weight = 0;
        params3.leftMargin = 5;
        params3.topMargin = 5;
        params3.bottomMargin = 5;
        params3.rightMargin = 5;
        
        layout.addView(view1, params1);
        layout.addView(view2, params2);
        layout.addView(view3, params3);
        
        setContentView(layout);
    }
}
</pre></p>
<p>The following list summarizes relationship between the XML attributes and UI component Class&#8217;s methods.</p>
<p>For LinearLayout:</p>
<ul>
<li><b>android:layout_weight</b>, <b>android:layout_height</b> &#8211; The width and height are constructor arguments of inner class LayoutParams of LinearLayout. Refer code between line number 43 and 45.
</li>
<li><b>android:orientation</b> &#8211; This XML attribute maps to instance method setOrientation on LinearLayout class. Refer line number 41</li>
</ul>
<p>For TextView:</p>
<ul>
<li><b>android:text</b> &#8211; This attribute maps to instance method setText on TextView. Refer line number 26. The setText method is overloaded and allows two arguments one is an actual text string and the other is reference to application string resource.
</li>
<li><b>android:background</b> &#8211; This attribute maps to two methods of the TextView namely setBackgroundColor and setBackgroundResource. The first method allows setting of color directly, refer commented line number 28 and second allows pointing to application color resource refer line number 35.
</li>
<li><b>android:textColor</b> &#8211; This attribute maps to setTextColor method of TextView. The method accepts the actual color value(line number 21, 29) or the application resource color reference (line number 36). Sadly there is no setTextColorResource method available, hence the convoluted way of setting text color using a resource.
</li>
<li><b>android:gravity</b> &#8211; This attribute maps to setGravity method of TextView. It accepts int argument. Use android.view.Gravity class&#8217;s static final int values (line number 22, 30, 37).
</li>
<li><b>android:typeface</b>, <b>android:textStyle</b> &#8211; This attribute maps to TextView&#8217;s setTypeface method. The setTypeface method is overloaded to accept only typeface or a combination of typeface and text style (line number 23, 31, 38).
</li>
</ul>
<p>We have so far covered attributes directly mapping to the TextView class. There are some other XML attributes which do not directly map to the TextView class. For these, an instance of LinearLayout.LayoutParams needs to be created and its appropriate properties need to be set.</p>
<ul>
<li><b>android:layout_width</b>, <b>android:layout_height</b>, <b>android:layout_weight</b> &#8211; These attributes are constructor arguments of the LinearLayout.LayoutParams(line number 43-44). The layout_weight attribute also maps to weight property of LayoutParams class(line number 50).
</li>
<li><b>android:layout_gravity</b> &#8211; This attribute maps to the gravity attribute of LayoutParams(line number 49, 57). Note this is the gravity orientation for the TextView component within the LinearLayout container.
</li>
<li><b>android:layout_margin*</b> &#8211; These attributes map to the *Margin properties of LayoutParams class(line number 59 to line number 62).</li>
</ul>
<p>The association of an instance of LinearLayout.LayoutParams with its component is achieved via the layout&#8217;s addView method which accepts the UI component and LayoutParams as its input arguments(line number 73 to 75).</p>
<p><b>An important note</b>: The dimensional setter methods such as setHeight, setWidth accept int input parameters. The input parameter accept pixel values. The dimension in xml definition were defined in dp. Hence a conversion is necessary. Android provides a ready utility class TypedValue to achieve the conversion. Refer its method <a href="http://developer.android.com/reference/android/util/TypedValue.html#applyDimension%28int,%20float,%20android.util.DisplayMetrics%29" title="Apply Dimension" target="_blank">applyDimension</a>; here&#8217;s a <a href="http://androidactivity.wordpress.com/2011/10/04/use-dip-sp-metrics-programmatically/" title="Use DIP SP Metrics Programmatically" target="_blank">sample</a> for reference. I have purposely chosen to avoid this implementation for code legibility, however in practice it is expected that the developer takes care of this to ensure UI consistency across devices.</p>
<p><strong>ListView</strong></p>
<p>ListView displays a list of scrollable items which the user can select. Typically the selection is used to trigger some subsequent processs or activity. The following example uses a combination of declarative and programming elements to implement Android ListView.</p>
<p>Refer to the listlayout.xml.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;ListView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:id=&quot;@+id/list&quot;&gt;
&lt;/ListView&gt;
</pre></p>
<p>The ListView is defined in the listlayout.xml. The next step is to provide data to the view. This is achieved by implementing an adapter. Android provides a ready-to-use ArrayAdapter for simple strings etc. Alternatively the developer can subclass BaseAdapter and implement a custom Adapter. My aim is to create a list which displays images and their corresponding names. Find below source code of my custom Adapter CustomImageListAdapter.</p>
<p><pre class="brush: java;">
package com.android.adapter;

import com.android.layout.R;

import android.content.Context;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomImageListAdapter extends BaseAdapter {

	private int[] images = {R.drawable.autumnwalk, R.drawable.bridge, R.drawable.butterfly,
			R.drawable.cheetah, R.drawable.cloud, R.drawable.highway, R.drawable.martini,
			R.drawable.rocksculpture, R.drawable.skyatsunset, R.drawable.slicedorange,
			R.drawable.smoke, R.drawable.tulips};
	
	private String[] imageDesc = { &quot;Autumn Walk&quot;, &quot;Bridge&quot;,
			&quot;Butterfly&quot;, &quot;Cheetah&quot;, &quot;Cloud&quot;, &quot;Highway&quot;, &quot;Martini&quot;, 
			&quot;Rock Sculpture&quot;, &quot;Sky at Sunset&quot;, &quot;Sliced Orange&quot;, &quot;Smoke&quot;,
			&quot;Tulips&quot;};
	
	private Context ctx = null;
	
	public CustomImageListAdapter(Context context) {
		this.ctx = context;
	}
	
	@Override
	public int getCount() {
		return images.length;
	}

	@Override
	public Object getItem(int arg0) {
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		
		ImageView imgView = new ImageView(this.ctx);
		imgView.setScaleType(ScaleType.FIT_CENTER);
		imgView.setPadding(8, 8, 8, 8);
		imgView.setImageResource(images[arg0]);
		imgView.setAdjustViewBounds(Boolean.TRUE);
		imgView.setContentDescription(imageDesc[arg0]);
		imgView.setMaxHeight(200);
		imgView.setMaxWidth(200);

		TextView tv = new TextView(this.ctx);
		tv.setText(imageDesc[arg0]);
		tv.setMaxHeight(100);
		tv.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
		tv.setGravity(Gravity.CENTER);
		tv.setTextColor(this.ctx.getResources().getColor(R.color.white));
		
		LinearLayout layoutView = new LinearLayout(this.ctx);
		layoutView.setOrientation(LinearLayout.HORIZONTAL);
		LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(150, 150);
		layoutView.addView(imgView, params1);
		LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		layoutView.addView(tv, params2);
		
		return layoutView;
	}

}
</pre></p>
<p>The images array holds image references for our application. All images are courtesy <a href="http://www.stockvault.net/" title="stockvault" target="_blank">stockvault</a>. The actual images are stored in the res/drawable folder. The image descriptions are held in the imageDesc string array. The CustomImageListAdapter&#8217;s constructor accepts Context as input argument.<br />
The overridden getView method is the most crucial implementation of the Adapter.The getView method is responsible for creating the individual row of the ListView.</p>
<p>The getView implementation creates a LinearLayout of horizontal orientation containing two UI components ImageView and TextView. To understand the finer details of ImageView setScaleType method refer this <a href="http://etcodehome.blogspot.com/2011/05/android-imageview-scaletype-samples.html" title="Android ImageView ScaleType Samples" target="_blank">blog post</a>. ImageView&#8217;s setImageResource associates image application resource reference to view. The setContentDescription is used to set its description. The rest of the code is self-explanatory or has already been covered in the earlier sections.	</p>
<p>For displaying use the following ListViewSupplementActivity class.</p>
<p><pre class="brush: java;">
package com.android.layout.dynamic;

import com.android.adapter.CustomImageListAdapter;
import com.android.layout.R;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class ListViewSupplementActivity extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.listlayout);
		ListView view = (ListView) findViewById(R.id.list);
		view.setAdapter(new CustomImageListAdapter(this));
		
	}

}
</pre></p>
<p>The setContentView method sets the listlayout.xml as the content view. The method findViewById is used to retrieve the ListView component and the view&#8217;s setAdapter is invoked to associate the CustomImageListAdapter to the view.</p>
<p>To run select ListViewSupplementActivity in Eclipse &#8211;&gt; Run Configurations&#8217;s launch option. Ensure that the android manifest file has the following entry:</p>
<p><pre class="brush: xml;">
        &lt;activity 
            android:label=&quot;@string/app_name&quot;
            android:name=&quot;.ListViewLayoutActivity&quot;&gt;
            &lt;intent-filter &gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
</pre></p>
<p>The generated output is</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/listview.png?w=500" alt="ListView Example" /></div>
<p></p>
<p><strong>GridView</strong></p>
<p>The ListView displays a scrollable single column list. GridView on the other hand displays a scrollable grid of m columns and n rows. ListView is one dimensional, GridView are two dimensional. Like the ListView, the declarative portion of GridView is minimal. Refer the gridlayout.xml.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;GridView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/grid&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:numColumns=&quot;2&quot;
    android:verticalSpacing=&quot;10dp&quot;
    android:horizontalSpacing=&quot;10dp&quot;
    android:scrollbarStyle=&quot;outsideOverlay&quot;
    android:verticalScrollbarPosition=&quot;right&quot;
    android:scrollbars=&quot;vertical&quot;&gt;
&lt;/GridView&gt;
</pre></p>
<p>The layout_width and layout_height XML attributes are familiar. The andriod:numColumns defines the number of columns of the grid. For our example we are looking for a two column grid, therefore the value for numColumns is 2. The android:verticalSpacing and android:horizontalSpacing attributes define the vertical and horizontal spacing of the GridView container. The rest of the attributes i.e. <a href="http://developer.android.com/reference/android/view/View.html#attr_android:scrollbarStyle" title="Android Scrollbar Style" target="_blank">scrollbarStyle</a>, verticalScrollbarPosition and scrollbars are associated with styling, position and display of the grid scrollbar.</p>
<p>To run the GridView create the GridViewSupplementActivity class.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout.dynamic;

import com.android.adapter.CustomImageAdapter;
import com.android.layout.R;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewSupplementActivity extends Activity {

	private float positionX = 0f;
	private float positionY = 0f;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.gridlayout);
		
		GridView grid = (GridView)findViewById(R.id.grid);
		grid.setAdapter(new CustomImageAdapter(this));
		
		grid.setOnTouchListener(new OnTouchListener() {
			
			public boolean onTouch(View v, MotionEvent event) {
				
				GridViewSupplementActivity.this.positionX = event.getX();
				GridViewSupplementActivity.this.positionY = event.getY();
				return false;
			}
		});
		
		grid.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView&lt;?&gt; parent, View v, int position, long id) {
	    		
	        	DisplayMetrics dm = new DisplayMetrics();
	        	GridViewSupplementActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);

	        	int yOffset = dm.heightPixels - parent.getMeasuredHeight();
	        	
	        	GridViewSupplementActivity.this.positionY = GridViewSupplementActivity.this.positionY - 2*yOffset; //position X remains unchanged.
	    			        	
	            Toast t = Toast.makeText(GridViewSupplementActivity.this, v.getContentDescription(), Toast.LENGTH_SHORT);
	            t.setGravity(Gravity.LEFT, (int)GridViewSupplementActivity.this.positionX, 
	            		(int)GridViewSupplementActivity.this.positionY);
	            
	            t.show();
	        }
		});
		
		
	}

}
</pre></p>
<p>Line number 26 in GridViewSupplementActivity assigns gridlayout.xml as the Activity&#8217;s content. The grid is populated using an Adapter CustomImageAdapter. Refer the adapter&#8217;s source code.</p>
<p><pre class="brush: java;">
package com.android.adapter;

import com.android.layout.R;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class CustomImageAdapter extends BaseAdapter {

	private int[] images = {R.drawable.autumnwalk, R.drawable.bridge, R.drawable.butterfly,
			R.drawable.cheetah, R.drawable.cloud, R.drawable.highway, R.drawable.martini,
			R.drawable.rocksculpture, R.drawable.skyatsunset, R.drawable.slicedorange,
			R.drawable.smoke, R.drawable.tulips};
	
	private String[] imageDesc = { &quot;Autumn Walk&quot;, &quot;Bridge&quot;,
			&quot;Butterfly&quot;, &quot;Cheetah&quot;, &quot;Cloud&quot;, &quot;Highway&quot;, &quot;Martini&quot;, 
			&quot;Rock Sculpture&quot;, &quot;Sky at Sunset&quot;, &quot;Sliced Orange&quot;, &quot;Smoke&quot;,
			&quot;Tulips&quot;};
	
	private Context ctx = null;
	
	public CustomImageAdapter(Context context) {
		this.ctx = context;
	}
	
	@Override
	public int getCount() {
		return images.length;
	}

	@Override
	public Object getItem(int arg0) {
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		ImageView imgView = new ImageView(this.ctx);
		imgView.setScaleType(ScaleType.FIT_END);
		imgView.setPadding(8, 8, 8, 8);
		imgView.setImageResource(images[arg0]);
		imgView.setAdjustViewBounds(Boolean.TRUE);
		imgView.setContentDescription(imageDesc[arg0]);
		imgView.setMaxHeight(100);
		imgView.setMaxWidth(100);
		
		return imgView;
	}

}
</pre></p>
<p>The implementation is similar to the earlier CustomImageListAdapter. Instead of having a LinearLayout with ImageView and TextView as its constituents, this adapter only creates an ImageView.</p>
<p>So far the layouts used as examples did not have any dynamic behavior. In grid view I intend to add some dynamic behavior, here on clicking an image, the description of the image will be displayed for a short period of time. To implement this functionality, we have implemented two listeners one is onTouchListener and the other is OnItemClickListener. The OnTouchListener is responsible for gathering X and Y co-ordinate position of the touch. The OnItemClickListener is responsible for creating a Toast which is display the image description at the specified co-ordinates. Note that the onTouch method returns false; this ensures that the event continues to be propogated and the OnItemClickListener can be triggered. The X co-ordinate position is not a problem however I was unable to fix up the Y co-ordinate position. I am sure the computation I have used for Y co-ordinate is screen specific but could not find any screen independent solution. Here are two references I used : <a href="http://stackoverflow.com/questions/6576728/obtaining-click-coordinates-in-android-listview-onitemclicklistener" title="Obtaining Click Coordinates in ListView" target="_blank">1</a> and <a href="http://stackoverflow.com/questions/2638342/incorrect-coordinates-from-getlocationonscreen-getlocationinwindow" title="Incorrect coordinates from getLocationOnScreen" target="_blank">2</a>. </p>
<p>To run the GridViewSupplementActivity class go to Eclipse Menu &#8211;&gt; Run Configurations. Select &#8216;GridViewSupplementActivity&#8217; in the launch drop down. Note for the class to run the following entry should be present in the android manifest file(AndroidManifest.xml).</p>
<p><pre class="brush: xml;">
        &lt;activity 
            android:label=&quot;@string/app_name&quot;
            android:name=&quot;.dynamic.GridViewSupplementActivity&quot;&gt;
            &lt;intent-filter &gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;    
</pre></p>
<p>Note the android:name attribute value. If you refer our earlier discussion of the package attribute of the root element manifest, the class name is created appending the package name to the activity attribute name. GridViewSupplementActivity&#8217;s complete name is com.android.layout.dynamic.GridViewSupplementActivity. The manifest element&#8217;s package attribute value is com.android.layout. Therefore to ensure the validity of the class name the activity attribute name is .dynamic.GridViewSupplementActivity. The same logic applies to ListViewSupplementActivity too.</p>
<p>The output generated is</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/gridview.png?w=500" alt="GridView Example" align="middle" /></div>
<p><strong>TableLayout</strong></p>
<p>The TableLayout lays out its consituents into rows and columns. The layout consists of number of TableRow components, each containing one or more Android UI components.<br />
First let&#8217;s implement the TableLayout declaratively. Refer the source code of tablelayout.xml</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TableLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:stretchColumns=&quot;*&quot;&gt;
    
    &lt;TableRow&gt;
        
        &lt;TextView
        	android:hint=&quot;@string/calchint&quot; 
        	android:gravity=&quot;bottom&quot;
        	android:textSize=&quot;20dp&quot;
        	android:paddingLeft=&quot;5dp&quot;
        	android:paddingTop=&quot;0dp&quot;
        	android:paddingRight=&quot;0dp&quot;
        	android:paddingBottom=&quot;2dp&quot;
        	android:background=&quot;@color/white&quot;
        	android:textColorHint=&quot;@color/blue&quot;
        	android:textStyle=&quot;bold&quot;
        	android:height=&quot;40dp&quot;
        	android:layout_marginLeft=&quot;5dp&quot;
        	android:layout_marginRight=&quot;5dp&quot;
        	android:layout_marginTop=&quot;5dp&quot;
        	android:layout_marginBottom=&quot;5dp&quot;
        	android:layout_span=&quot;3&quot;
        	android:layout_width=&quot;fill_parent&quot;/&gt;
        
    &lt;/TableRow&gt;
    &lt;TableRow&gt;
        
        &lt;TextView
        	android:text=&quot;@string/onefigure&quot;
        	android:textSize=&quot;24dp&quot; 
        	android:textStyle=&quot;bold&quot;
        	android:background=&quot;@color/dkgray&quot;
        	android:textColor=&quot;@color/white&quot;
        	android:gravity=&quot;center_horizontal&quot;
        	android:layout_marginLeft=&quot;5dp&quot;
        	android:layout_marginRight=&quot;5dp&quot;/&gt;
        
        &lt;TextView
        	android:text=&quot;@string/twofigure&quot;
        	android:textSize=&quot;24dp&quot; 
        	android:textStyle=&quot;bold&quot;
        	android:background=&quot;@color/dkgray&quot;
        	android:textColor=&quot;@color/white&quot;
        	android:gravity=&quot;center_horizontal&quot;
        	android:layout_marginRight=&quot;5dp&quot;/&gt;
        
        &lt;TextView
        	android:text=&quot;@string/threefigure&quot;
        	android:textSize=&quot;24dp&quot; 
        	android:textStyle=&quot;bold&quot;
        	android:background=&quot;@color/dkgray&quot;
        	android:textColor=&quot;@color/white&quot;
        	android:gravity=&quot;center_horizontal&quot;
        	android:layout_marginRight=&quot;5dp&quot;/&gt;
        
    &lt;/TableRow&gt;
    &lt;TableRow&gt;
        
        &lt;TextView
        	android:text=&quot;@string/eqfigure&quot;
        	android:textSize=&quot;32dp&quot; 
        	android:textStyle=&quot;bold&quot;
        	android:background=&quot;@color/gray&quot;
        	android:textColor=&quot;@color/white&quot;
        	android:gravity=&quot;center_horizontal&quot;
        	android:layout_marginTop=&quot;5dp&quot;
        	android:layout_marginRight=&quot;5dp&quot;
        	android:layout_column=&quot;1&quot; 
        	android:layout_span=&quot;2&quot; /&gt;
       
    &lt;/TableRow&gt;
        
&lt;/TableLayout&gt;
</pre></p>
<p>In our example we are defining a table with 3 rows and 3 columns. The root element TableLayout has one layout specific attribute stretchColumns. This defines the specific columns which will stretch over the available space in the row. By specifying &#8216;*&#8217;, we have designated all columns to equally use the available space. Alternatively one can specify one or more columns to this attribute. In case of multiple columns use the comma(,) delimiter to specify the columns. In our case &#8216;*&#8217; can be changed to &#8217;0,1,2&#8242;. Note the column number are zero index based.</p>
<p>Next we have defined the first table row containing one TextView. Most of the TextView XML attributes have already been explained in the previous sections, I will focus on those which are new.</p>
<ul>
<li><b>android:hint</b> &#8211; The text which appears when the TextView is loaded. Usually acts as a suggestion to the application end user.</li>
<li><b>android:textColorHint</b> &#8211; Defines the color of the hint text.</li>
<li><b>android:layout_span</b> &#8211; In some cases content spans multiple columns. In HTML world we have the colspan which determines the number of columns a cell can span. The layout_span attribute implements the same thing. We have defined layout_span as 3 meaning the TextView will span all the three columns in the table.</li>
</ul>
<p>The following XML attributes are defined in the 3rd TableRow TextView UI component.</p>
<ul>
<li><b>android:layout_column</b> &#8211; Allows developer to specify a specific column number within which the UI component will be laid out. In our example, the value provided is 1 meaning the TextView of eqfigure will be laid out in the second column as the span is set to 2, it will cover the second and third columns.</li>
</ul>
<p>To run the tablelayout.xml do the following change in line number 11 of LayoutDemoActivity class and then run the class.</p>
<p><pre class="brush: java;">
setContentView(R.layout.tablelayout);
</pre></p>
<p>Like stretchColumns TableLayout provides shrinkColumns. The shrinkColumns ensures that columns cover reasonable screen real estate. To get more information about TableLayout and also shrinkColumns refer <a href="http://android-pro.blogspot.com/2010/02/table-layout.html" title="Table Layout" target="_blank">here</a>.</p>
<p>Now that we have covered the declarative aspect of TableLayout, let&#8217;s understand how the same can be implemented programmatically.</p>
<p><pre class="brush: java;">
package com.android.layout;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TableLayoutActivity extends Activity {
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		TableLayout table = new TableLayout(this);
		TableLayout.LayoutParams params = new TableLayout.LayoutParams();
		params.width = TableLayout.LayoutParams.FILL_PARENT;
		params.height = TableLayout.LayoutParams.FILL_PARENT;
		table.setLayoutParams(params);
		table.setStretchAllColumns(Boolean.TRUE);
		
		TableRow displayRow = new TableRow(this);
		
		TextView calculatorDisplay = new TextView(this);
		calculatorDisplay.setHint(R.string.calchint);
		calculatorDisplay.setGravity(Gravity.BOTTOM);
		calculatorDisplay.setTextSize(20);
		calculatorDisplay.setPadding(5, 0, 0, 2);
		calculatorDisplay.setBackgroundResource(R.color.white);
		calculatorDisplay.setHintTextColor(getResources().getColor(R.color.blue));
		calculatorDisplay.setTypeface(null,Typeface.BOLD);
		calculatorDisplay.setHeight(40);
		
		TableRow.LayoutParams rowParams = new TableRow.LayoutParams();
		rowParams.span = 3;
		rowParams.leftMargin = 5;
		rowParams.rightMargin = 5;
		rowParams.topMargin = 5;
		rowParams.bottomMargin = 5;
		
		displayRow.addView(calculatorDisplay, rowParams);
		
		table.addView(displayRow);
		
		TableRow.LayoutParams leftViewParams = new TableRow.LayoutParams();
		leftViewParams.leftMargin = 5;
		leftViewParams.rightMargin = 5;

		TableRow.LayoutParams viewParams = new TableRow.LayoutParams();
		viewParams.rightMargin = 5;

		
		TableRow row1 = new TableRow(this);
		TextView view1 = new TextView(this);
		view1.setText(R.string.onefigure);
		view1.setTextSize(24);
		view1.setTypeface(null,Typeface.BOLD);
		view1.setBackgroundColor(Color.DKGRAY);
		view1.setTextColor(getResources().getColor(R.color.white));
		view1.setGravity(Gravity.CENTER_HORIZONTAL);
		row1.addView(view1, leftViewParams);

		TextView view2 = new TextView(this);
		view2.setText(R.string.twofigure);
		view2.setTextSize(24);
		view2.setTypeface(null,Typeface.BOLD);
		view2.setBackgroundColor(Color.DKGRAY);
		view2.setTextColor(getResources().getColor(R.color.white));
		view2.setGravity(Gravity.CENTER_HORIZONTAL);
		row1.addView(view2, viewParams);
		
		TextView view3 = new TextView(this);
		view3.setText(R.string.threefigure);
		view3.setTextSize(24);
		view3.setTypeface(null,Typeface.BOLD);
		view3.setBackgroundColor(Color.DKGRAY);
		view3.setTextColor(getResources().getColor(R.color.white));
		view3.setGravity(Gravity.CENTER_HORIZONTAL);
		row1.addView(view3, viewParams);

		
		table.addView(row1);
		
		TableRow row2 = new TableRow(this);
		TextView view4 = new TextView(this);
		view4.setText(&quot;=&quot;);
		view4.setTextSize(32);
		view4.setTypeface(null,Typeface.BOLD);
		view4.setBackgroundColor(Color.GRAY);
		view4.setTextColor(getResources().getColor(R.color.white));
		view4.setGravity(Gravity.CENTER_HORIZONTAL);

		TableRow.LayoutParams calcParams = new TableRow.LayoutParams();
		calcParams.topMargin = 5;
		calcParams.rightMargin = 5;
		calcParams.column = 1;
		calcParams.span = 2;
		
		row2.addView(view4, calcParams);
		
		table.addView(row2);
		
		this.setContentView(table);
	}

}
</pre></p>
<p>I will just focus on the specific areas not explained in the previous sections. To implement android:stretchColumns functionality, the TableLayout class provides two methods, one is setStretchAllColumns and the other is setColumnStretchable. Since we needed all columns to be stretchable, we used the first method; refer line number 23 in the source. In case we want specific columns to be made stretchable, we can use the second method, it accepts column number and boolean as input arguments.</p>
<p>TableLayout creation and initialization of its LayoutParams is covered in source code line number 18 to 23. TableRow creation, addition of its constiuents components and their LayoutParams is covered from line number 37-42, 48-53 and 96-100.<br />
The remaining code is self-explanatory. Each TableRow alongwith its LayoutParams is added to the TableLayout via the addView method. TableRow.LayoutParams properties column and span map to XML attributes layout_column and layout_span.</p>
<p>Ensure that TableLayoutActivity is added in the Android Manifest file. Run the class via selecting it in the Launch option to view the results. The output is below</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/tablelayout.png?w=500" alt="Table Layout Example" align="middle" /></div>
<p><strong>RelativeLayout</strong></p>
<p>The RelativeLayout arranges its child components based on component&#8217;s layout positioning definition relative to one another. Each component can be laid out above, below, to the left or right of another component. A combination of positional rules such as right of X component and below Y component can also be applied. To gain an understanding let&#8217;s look at the declarative implementation of the layout in relativelayout.xml</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;300dp&quot;
    android:layout_height=&quot;600dp&quot;&gt;

    &lt;TextView
        android:text=&quot;@string/username&quot; 
        android:gravity=&quot;right&quot;
        android:id=&quot;@string/usernamelbl&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:height=&quot;40dp&quot;
        android:layout_marginLeft=&quot;10dp&quot;
        android:layout_marginTop=&quot;10dp&quot;
        android:layout_marginRight=&quot;10dp&quot;
        android:layout_marginBottom=&quot;10dp&quot; /&gt;

   	&lt;EditText
        android:id=&quot;@string/usernamefld&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:height=&quot;40dp&quot;
        android:width=&quot;200dp&quot;
        android:layout_marginLeft=&quot;10dp&quot;
        android:layout_marginTop=&quot;10dp&quot;
        android:layout_marginRight=&quot;10dp&quot;
        android:layout_marginBottom=&quot;10dp&quot;
        android:layout_toRightOf=&quot;@string/usernamelbl&quot; /&gt;
    
    &lt;TextView
        android:id=&quot;@string/passwordlbl&quot;
        android:text=&quot;@string/password&quot; 
        android:gravity=&quot;right&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_below=&quot;@string/usernamelbl&quot;
        android:height=&quot;40dp&quot;
        android:layout_marginLeft=&quot;10dp&quot;
        android:layout_marginTop=&quot;10dp&quot;
        android:layout_marginRight=&quot;10dp&quot;
        android:layout_marginBottom=&quot;10dp&quot; /&gt;
   		
   	&lt;EditText
        android:id=&quot;@string/passwordfld&quot;
        android:inputType=&quot;textPassword&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:height=&quot;40dp&quot;
        android:width=&quot;200dp&quot;
        android:layout_marginLeft=&quot;10dp&quot;
        android:layout_marginTop=&quot;10dp&quot;
        android:layout_marginRight=&quot;10dp&quot;
        android:layout_marginBottom=&quot;10dp&quot;
        android:layout_toRightOf=&quot;@string/passwordlbl&quot; 
        android:layout_below=&quot;@string/usernamefld&quot;/&gt;
    
   	&lt;Button
   	    android:text=&quot;@string/login&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
		android:layout_below=&quot;@string/passwordfld&quot;
		android:layout_centerHorizontal=&quot;true&quot;   	    
   	    /&gt;
    	
&lt;/RelativeLayout&gt;
</pre></p>
<p>Lets&#8217;s understand some newly added XML attributes in the relativelayout.xml. We are trying to develop a simple login page with username, password and submit button.</p>
<p>The first TextView a label field for &#8216;User Name&#8217; text is defined with attributes which we are aware of. Next EditText to capture the actual value of user input is defined. A positional constraint of the EditText is defined via the android:layout_toRightOf attribute. The value is the application string resource reference for the username TextView. Next we define password label which should be positioned below username label. This is achieved by the android:layout_below attribute. The value assigned is the application string resource reference for the username TextView. The EditText component to accept password input is positioned to the right of password TextView and below username EditText component by using two attributes android:layout_toRightOf and android:layout_below. The last component to be covered in the submit button which is purely positioned as center horizontal to be placed below TextViews and EditTexts. I was a bit surprised that RelativeLayout has a special android:layout_centerHorizontal; my thinking was that android:layout_gravity should have sufficed.</p>
<p>To run the application change line number 11 in LayoutDemoActivity class to the following and launch LayoutDemoActivity in Eclipse Run Configurations:</p>
<p><pre class="brush: java;">
setContentView(R.layout.relativelayout);
</pre></p>
<p>Now let&#8217;s look at how this can be implemented programmatically. Have a look at the source code of RelativeLayoutActivity.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class RelativeLayoutActivity extends Activity {

	private static int HEIGHT = 40;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		RelativeLayout relLayout = new RelativeLayout(this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(300, 600);
		relLayout.setLayoutParams(params);
		TextView userNameLabel = new TextView(this);
		userNameLabel.setText(R.string.username);
		userNameLabel.setGravity(Gravity.RIGHT);
		userNameLabel.setId(R.string.usernamelbl);
		RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
				LayoutParams.WRAP_CONTENT);
		params1.height = HEIGHT;
		params1.setMargins(10, 10, 10, 10);
		relLayout.addView(userNameLabel, params1);
		
		EditText userNameField = new EditText(this);
		userNameField.setId(R.string.usernamefld);
		RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
				LayoutParams.WRAP_CONTENT);
		params2.height = HEIGHT;
		params2.width = 200;
		params2.setMargins(10, 10, 10, 10);
		params2.addRule(RelativeLayout.RIGHT_OF, R.string.usernamelbl);
		relLayout.addView(userNameField, params2);
		
		TextView passwordLabel = new TextView(this);
		passwordLabel.setId(R.string.passwordlbl);
		passwordLabel.setText(R.string.password);
		passwordLabel.setGravity(Gravity.RIGHT);
		RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
				LayoutParams.WRAP_CONTENT);
		params3.addRule(RelativeLayout.BELOW, R.string.usernamelbl);
		params3.height = HEIGHT;
		params3.setMargins(10, 10, 10, 10);
		
		relLayout.addView(passwordLabel, params3);

		EditText pwdField = new EditText(this);
		pwdField.setId(R.string.passwordfld);
		pwdField.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
		RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
				LayoutParams.WRAP_CONTENT);
		params4.height = HEIGHT;
		params4.width = 200;
		params4.setMargins(10, 10, 10, 10);
		params4.addRule(RelativeLayout.RIGHT_OF, R.string.passwordlbl);
		params4.addRule(RelativeLayout.BELOW, R.string.usernamefld);
		
		relLayout.addView(pwdField, params4);

		Button submit = new Button(this);
		submit.setText(R.string.login);
		RelativeLayout.LayoutParams params5 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
				LayoutParams.WRAP_CONTENT);
		params5.addRule(RelativeLayout.BELOW, R.string.passwordfld);
		params5.addRule(RelativeLayout.CENTER_HORIZONTAL);
		relLayout.addView(submit, params5);
		
		this.setContentView(relLayout);
		
		
	}
	
}
</pre></p>
<p>The layout positioning constraints are defined in RelativeLayout.LayoutParams class&#8217;s addRule method. The method accepts position and applicable component reference as its input arguments. Refer the line numbers 41, 50, 64-65, 73-74.</p>
<p>Run the programmatic or declarative option. The output is</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/relativelayout.png?w=500" alt="Relative Layout Example" align="middle" /></div>
<p><strong>TabLayout</strong></p>
<p>There are applications which need the tabs. Individual tab page logically groups together data. Android implements this using the TabActivity. However do note that the class TabActivity has been deprecated in the favor of Fragments. I tried to understand how Fragments work but could not figure it out. I did find this <a href="http://android.codeandmagic.org/2011/07/android-tabs-with-fragments/" title="Android Tabs With Fragments" target="_blank">blog post</a> by Evelina Vrabie. I am still digesting the approach which appears a stretch compared to TabActivity. I need to develop the example using TabActivity and explore Fragments later.</p>
<p>The Tab implementation example is done programmatically. Refer the source code of TabsLayoutActivity class.</p>
<p><pre class="brush: java;">
package com.android.layout;

import com.android.layout.tab.CoffeeShopListActivity;
import com.android.layout.tab.FoodChainListActivity;
import com.android.layout.tab.RestaurantListActivity;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;

public class TabsLayoutActivity extends TabActivity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		TabHost tabHost = getTabHost();
		Intent intent = null;
		
		intent = new Intent().setClass(this, RestaurantListActivity.class);
		TabHost.TabSpec spec = tabHost.newTabSpec(&quot;restaurants&quot;);
		spec.setIndicator(&quot;Restaurant&quot;);
		spec.setContent(intent);
		tabHost.addTab(spec);
		
		intent = new Intent().setClass(this, FoodChainListActivity.class);
		spec = tabHost.newTabSpec(&quot;chains&quot;);
		spec.setIndicator(&quot;Food Chain&quot;);
		spec.setContent(intent);
		tabHost.addTab(spec);
		
		intent = new Intent().setClass(this, CoffeeShopListActivity.class);
		spec = tabHost.newTabSpec(&quot;shops&quot;);
		spec.setIndicator(&quot;Coffee Shop&quot;);
		spec.setContent(intent);
		tabHost.addTab(spec);
		
		tabHost.setCurrentTab(1);
		
	}
	
}
</pre></p>
<p>Note line number 13 where TabsLayoutActivity extends TabActivity. Access to the underlying TabHost instance which provides the tab functionality is obtained via TabActivity&#8217;s getTabHost method. I am planning to develop a tabbed application which displays three tab data. The individual tab categories are restaurant, food chain and coffee shop. Each of the tab can be implemented as a View or Activity. To achieve modular design it is recommended that individual Activity per tab are created. Accordingly I have created three Activity classes RestaurantListActivity, FoodChainListActivity and CoffeeShopListActivity. The source code is below:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout.tab;

import android.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class RestaurantListActivity extends ListActivity {

	private static final String[] restaurants = new String[] {
		&quot;Golden Punjab&quot;, &quot;Shikara&quot;, &quot;The Bowl House&quot;, 
		&quot;Copper Chimney&quot;, &quot;Gajalee&quot;};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ListView view = getListView();
		view.setAdapter(new ArrayAdapter&lt;String&gt;(getBaseContext(), R.layout.simple_list_item_1, restaurants));
		
	}
	
}
</pre></p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout.tab;

import android.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FoodChainListActivity extends ListActivity {

	private static final String[] chains = new String[] {
		&quot;Pizza Hut&quot;, &quot;Dominos&quot;, &quot;Kailas Parbat&quot;, &quot;Malgudi's&quot;, 
		&quot;Only Parathas&quot;, &quot;KFC&quot;};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ListView view = getListView();
		view.setAdapter(new ArrayAdapter&lt;String&gt;(getBaseContext(), R.layout.simple_list_item_1, chains));
		
	}	
}
</pre></p>
<p><pre class="brush: java; wrap-lines: false;">
package com.android.layout.tab;

import android.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CoffeeShopListActivity extends ListActivity {

	private static final String[] coffeeShops = new String[] {
		&quot;Barista&quot;, &quot;Cafe Coffee Day&quot;};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ListView view = getListView();
		view.setAdapter(new ArrayAdapter&lt;String&gt;(getBaseContext(), R.layout.simple_list_item_1, coffeeShops));
		
	}
	
}
</pre></p>
<p>Each of the Activity classes consist of a simple ListView with the some instances of the applicable category.</p>
<p>Refer the following lines in TabsLayoutActivity</p>
<p><pre class="brush: java;">
		intent = new Intent().setClass(this, RestaurantListActivity.class);
		TabHost.TabSpec spec = tabHost.newTabSpec(&quot;restaurants&quot;);
		spec.setIndicator(&quot;Restaurant&quot;);
		spec.setContent(intent);
		tabHost.addTab(spec);
</pre></p>
<p>Until now in all our examples we have created a single Activity instance and interacted with it. In this example, we will have to switch between TabActivity and the three Activity instances. This is achieved in Android using an Intent class. The class is responsible for transitioning from one Activity to another. In line number 1 we create an Intent for RestaurantListActivity. Later we create a TabSpec. The indicator attribute holds the text label of the tab. The content holds the presentation data and content. By setting the content to intent, we are assigning RestaurantListActivity class to that tab. The same exercise is done with the other two *ListActivity classes.</p>
<p>Edit the Android Manifest file and key in the following entries.</p>
<p><pre class="brush: xml;">
        &lt;activity 
            android:label=&quot;@string/app_name&quot;
            android:name=&quot;.TabsLayoutActivity&quot;&gt;
            &lt;intent-filter &gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;

                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;


        &lt;activity android:name=&quot;.tab.RestaurantListActivity&quot; /&gt;
        &lt;activity android:name=&quot;.tab.FoodChainListActivity&quot; /&gt;
        &lt;activity android:name=&quot;.tab.CoffeeShopListActivity&quot; /&gt;   
</pre></p>
<p>Run the TabsLayoutActivity class using Eclipse&#8217;s Run Configurations.</p>
<p>The output is:</p>
<div align="center"><img src="http://technicalmumbojumbo.files.wordpress.com/2011/12/tablayout.png?w=500" alt="Tabs Layout Example" align="middle" /></div>
<p>Phew! This has been one long post. This is me signing off.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/595/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/595/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/595/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=595&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/12/08/android-tutorial-series-layout/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/framelayout.png" medium="image">
			<media:title type="html">Frame Layout Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/linearlayout.png" medium="image">
			<media:title type="html">Linear Layout Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/listview.png" medium="image">
			<media:title type="html">ListView Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/gridview.png" medium="image">
			<media:title type="html">GridView Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/tablelayout.png" medium="image">
			<media:title type="html">Table Layout Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/relativelayout.png" medium="image">
			<media:title type="html">Relative Layout Example</media:title>
		</media:content>

		<media:content url="http://technicalmumbojumbo.files.wordpress.com/2011/12/tablayout.png" medium="image">
			<media:title type="html">Tabs Layout Example</media:title>
		</media:content>
	</item>
		<item>
		<title>The Android Tutorial Series Part 2 &#8211; Calculator App</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 08:57:11 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[edittext]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[spinner]]></category>
		<category><![CDATA[textview]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=572</guid>
		<description><![CDATA[My previous blog post provided an introduction to the Android platform with a characteristic Hello World example. This post intends to continue our exploration further by creating a simple calculator application using the Android platform. A calculator application is already &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=572&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My previous <a title="The Android Tutorial Series Part 1 – Hello World" href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/">blog post</a> provided an introduction to the Android platform with a characteristic Hello World example. This post intends to continue our exploration further by creating a simple calculator application using the Android platform. A calculator application is already present in the emulator environment but I thought it would be a good starting point to gain an improved understanding into the platform. </p>
<p><span id="more-572"></span></p>
<p>My development environment remains unchanged to the one mentioned in <a title="The Android Tutorial Series Part 1 – Hello World" href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/">Part 1</a> of the Android tutorial series.</p>
<p>Let&#8217;s begin by creating a new Android application named Calculator1.0. To create the application, in the eclipse menu select File -&gt; New -&gt; Other -&gt; Android Project. In the project creation wizard enter the following values:</p>
<ul>
<li>Project Name: Calculator1.0</li>
<li>Build Target: Android 4.0</li>
<li>Application Name: Retain the project name. The developer is free to choose a different name.</li>
<li>Package Name: com.calculator</li>
<li>Minimum SDK: 14</li>
</ul>
<p>The Calculator1.0 project has been created. In the eclipse package explorer, verify if the following folders are created. There should be a src folder which contains com.calculator.CalculatorActivity class. The res folder should have two sub-folders in it namely layout and values. The layout folder will have main.xml file and values folder will have strings.xml.</p>
<p>If the assertions made above are true, the project has been successfully created. Next, let&#8217;s proceed to adding the calculator specific functionality to the project. My aim is to create a simple application which accepts two input values and the mathematical operation to be applied on the two values.</p>
<p>Let&#8217;s begin by first creating the user interface. To facilitate user interface aspect separation, Android implements user interface using three components, the static definition of user interface in res/layout/main.xml, labeling and aligned aspects in res/values/strings.xml and the dynamic user interface aspects using the com.calculator.CalculatorActivity class.</p>
<p>First let&#8217;s begin with res/values/strings.xml. Here&#8217;s the source code of strings.xml</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    &lt;string name=&quot;app_name&quot;&gt;Calculator 1.0&lt;/string&gt;
    &lt;string name=&quot;operation&quot;&gt;Select Operation&lt;/string&gt;
    &lt;string name=&quot;FirstInput&quot;&gt;Input 1&lt;/string&gt;
    &lt;string name=&quot;SecondInput&quot;&gt;Input 2&lt;/string&gt;
    &lt;string name=&quot;welcomeMessage&quot;&gt;Welcome to Calculator&lt;/string&gt;
    &lt;string name=&quot;spacer&quot;&gt;----------------------&lt;/string&gt;
    &lt;string name=&quot;calculate&quot;&gt;Calculate&lt;/string&gt;
    &lt;string name=&quot;opPrompt&quot;&gt;Select Operation&lt;/string&gt;
    &lt;string-array name=&quot;operations&quot;&gt;
        &lt;item &gt;Multiply&lt;/item&gt;
        &lt;item &gt;Divide&lt;/item&gt;
        &lt;item &gt;Add&lt;/item&gt;
        &lt;item &gt;Subtract&lt;/item&gt;
    &lt;/string-array&gt;
    &lt;string name=&quot;answer&quot;&gt;Answer:&lt;/string&gt;
	&lt;string name=&quot;textSize&quot;&gt;16sp&lt;/string&gt;
&lt;/resources&gt;
</pre></p>
<p>The strings.xml acts as a repository which provides text strings for your application. The app_name resource is created by default; other resources are added as a part of the Calculator application customization. The utilization of the resources defined in the strings.xml will be elaborated upon as a part of the main.xml explanation. Two resources to keep an eye on in strings.xml are operations and textSize. The string array &#8216;operations&#8217; defines the drop-down string values for the &#8216;operation&#8217; field of the calculator. The textSize resource was planned to be used for standardizing the text size definition of Android widgets. Unfortunately this did not work. As per research the appropriate method to implement this is using a dimens.xml in values folder. Details are provided <a href="http://developer.android.com/guide/topics/resources/more-resources.html#Dimension" title="Application Resources - Dimension" target="_blank">here</a>. Will look into that in a subsequent post. </p>
<p>Let&#8217;s move on to res/layout/main.xml file.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    android:orientation=&quot;vertical&quot; 
    android:paddingLeft=&quot;6px&quot; 
    android:textSize=&quot;10sp&quot;&gt;

    &lt;TextView
        android:id=&quot;@+id/textViewWelcomeMsg&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/welcomeMessage&quot;
        android:textAppearance=&quot;?android:attr/textAppearanceLarge&quot; 
        android:paddingBottom=&quot;10px&quot;/&gt;

    &lt;!-- &lt;TextView
        android:id=&quot;@+id/textViewSpacer&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/spacer&quot;
        android:textAppearance=&quot;?android:attr/textAppearanceLarge&quot; /&gt;
	--&gt;

    &lt;TextView
        android:id=&quot;@+id/textViewInput1&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/FirstInput&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/editTextInput1&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:inputType=&quot;numberDecimal&quot; 
        android:textSize=&quot;16sp&quot; 
        android:hint=&quot;Enter first input&quot;&gt;
        &lt;requestFocus /&gt;
    &lt;/EditText&gt;

    &lt;TextView
        android:id=&quot;@+id/textViewInput2&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/SecondInput&quot; /&gt;

    &lt;EditText
        android:id=&quot;@+id/editTextInput2&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:inputType=&quot;numberDecimal&quot;  
        android:textSize=&quot;16sp&quot; 
        android:hint=&quot;Enter second input&quot;
        /&gt;
		
    &lt;Spinner
        android:id=&quot;@+id/spinnerOperation&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:prompt=&quot;@string/opPrompt&quot;  
        android:textSize=&quot;14sp&quot;
        android:entries=&quot;@array/operations&quot;
        android:drawSelectorOnTop=&quot;true&quot;
        android:spinnerMode=&quot;dropdown&quot;
        android:dropDownWidth=&quot;wrap_content&quot;
       
	/&gt;
    &lt;!-- spinnerMode=dropdown|dialog --&gt;
		
    &lt;Button
        android:id=&quot;@+id/buttonCalculate&quot;
        android:layout_width=&quot;175px&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/calculate&quot;
        android:onClick=&quot;onCalculateClick&quot; 
        android:textSize=&quot;16sp&quot;
        android:layout_gravity=&quot;center_horizontal&quot; 
        /&gt;

    &lt;TextView
        android:id=&quot;@+id/textViewAns&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/answer&quot; 
        android:textSize=&quot;20sp&quot; 
        android:paddingTop=&quot;20px&quot;
        android:textColor=&quot;#FFFFFF&quot;/&gt;
&lt;/LinearLayout&gt;
</pre></p>
<p>The root level element is LinearLayout. The LinearLayout format is one of the many layout formats provided by Android. For details on other formats refer <a href="http://developer.android.com/guide/topics/ui/layout-objects.html" title="Android Layouts" target="_blank">here</a>. The LinearLayout component aligns its constituent components in a single direction i.e. vertically or horizontally. The alignment is dependent on the definition of LinearLayout&#8217;s orientation attribute. In our example we have used the vertical alignment. The rest of LinearLayout&#8217;s attributes are self-explanatory. In our example we have used four types of Android widgets. The first is the TextView, second is EditText, third Spinner and fourth is Button.</p>
<p>The TextView component displays text to the user. Let&#8217;s have a look at the first TextView component defined in the main.xml and its attribute values. </p>
<p><pre class="brush: xml;">
    &lt;TextView
        android:id=&quot;@+id/textViewWelcomeMsg&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/welcomeMessage&quot;
        android:textAppearance=&quot;?android:attr/textAppearanceLarge&quot; 
        android:paddingBottom=&quot;10px&quot;/&gt;
</pre></p>
<p>The id attribute establishes the unique name of the component. This value is extremely useful in dynamically searching for a specific component. The values associated with layout_width or layout_height are standard and are explained <a href="http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html" title="Layout Params" target="_blank">here</a>. The &#8216;wrap_content&#8217; means that the component will sized just large enough to encapsulate its contents.The value associated to the text attribute is the textual content which is displayed in the user interface. To associate the text attribute&#8217;s value with resource defined in the strings.xml we use the special notation of @string/. The value following the / character map to the resource name defined in the strings.xml; in the present case we have @string/welcomeMessage. One more point to notice is the value defined for textAppearance attribute is ?android:attr/textAppearanceLarge. This means we will be using the Android device specific value for textAppearance. There are a number of device specific values available. Details are documented <a href="http://developer.android.com/reference/android/R.attr.html" title="R.attr" target="_blank">here</a>.</p>
<p>The next component/widget to look at is EditText. Let&#8217;s use the EditText component with id editTextInput1 from the main.xml.</p>
<p><pre class="brush: xml;">
    &lt;EditText
        android:id=&quot;@+id/editTextInput1&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:inputType=&quot;numberDecimal&quot; 
        android:textSize=&quot;16sp&quot; 
        android:hint=&quot;Enter first input&quot;&gt;
        &lt;requestFocus /&gt;
    &lt;/EditText&gt;
</pre></p>
<p>EditText enhances the TextView widget by providing the ability to be editable. The next attribute to look at is inputType. We have used inputType value as numberDecimal. This means that the EditText will only accept numeric characters or a decimal character. The inputType supports the following <a href="http://developer.android.com/reference/android/R.styleable.html#TextView_inputType" title="InputType options" target="_blank">different values</a>. The hint attribute holds the text that is displayed to user before he/she submits any input to the field.</p>
<p>Next let&#8217;s look at the third component Spinner. </p>
<p><pre class="brush: xml;">
    &lt;Spinner
        android:id=&quot;@+id/spinnerOperation&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:prompt=&quot;@string/opPrompt&quot;  
        android:textSize=&quot;14sp&quot;
        android:entries=&quot;@array/operations&quot;
        android:drawSelectorOnTop=&quot;true&quot;
        android:spinnerMode=&quot;dropdown&quot;
        android:dropDownWidth=&quot;wrap_content&quot;     
	/&gt;
</pre></p>
<p>The Spinner widget basically provides a control that can display a drop-down list. The prompt attribute contains the text that is displayed on the Spinner. The entries points to an array resource holding all the drop-down values. In our example it refers to the operations string array. The spinnerMode attribute accepts two values drop-down or dialog. Run the application with both modes to understand the difference. The prompt text appears in the drop down in the &#8216;dialog&#8217; mode and does not appear in the &#8216;dropdown&#8217; mode. I have not been able to figure out why my drop-down does not appear like a traditional drop-down with a down arrow button, instead there appears a small triangle at the right hand bottom corner of the spinner widget.</p>
<p>The final component is the button. </p>
<p><pre class="brush: xml;">
    &lt;Button
        android:id=&quot;@+id/buttonCalculate&quot;
        android:layout_width=&quot;175px&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/calculate&quot;
        android:onClick=&quot;onCalculateClick&quot; 
        android:textSize=&quot;16sp&quot;
        android:layout_gravity=&quot;center_horizontal&quot; 
        /&gt;
</pre></p>
<p>The user is expected to key in the two input values, select the mathematical operation and click the button to trigger the computation process. The Button provides an attribute layout_gravity to decide the placement of the Button in the UI screen. The possible values for layout_gravity are provided <a href="http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#attr_android:layout_gravity" title="Layout Gravity" target="_blank">here</a>. To trigger the computation process the Button widget is provided with an attribute onClick which maps to the button click event. The string associated to the onClick method consists of a method implemented on the Activity instance holding the Button widget. The expected method name and signature is </p>
<p><pre class="brush: java;">
public void onCalculateClick(View view) {
}
</pre></p>
<p>To complete the final piece of the Calculator Application, below is the source code of the CalculatorActivity class.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
//import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CalculatorActivity extends Activity {
	
	private static final String MULTIPLY = &quot;Multiply&quot;;
	private static final String DIVIDE   = &quot;Divide&quot;;
	private static final String ADD      = &quot;Add&quot;;
	private static final String SUBTRACT = &quot;Subtract&quot;;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        /*Spinner spinner = (Spinner) findViewById(R.id.spinnerOperation);
        ArrayAdapter&lt;CharSequence&gt; adapter = ArrayAdapter.createFromResource(this, R.array.operations,
                android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);*/
    }
    
    public void onCalculateClick(View view) {
    	switch (view.getId()) {
    	
	    	case R.id.buttonCalculate:
	    		EditText text1 = (EditText)findViewById(R.id.editTextInput1);
	    		String text1Val = text1.getText().toString();
	    		EditText text2 = (EditText)findViewById(R.id.editTextInput2);
	    		String text2Val = text2.getText().toString();
	    		Spinner spinner = (Spinner)findViewById(R.id.spinnerOperation);
	    		String value = (String)spinner.getSelectedItem();
	    		
	    		if (value == null || text1Val == null || text2Val == null) {
	    			Toast.makeText(view.getContext(), &quot;Please select input values.&quot;,   Toast.LENGTH_LONG).show();
	    		}
	    		
	    		float input1Val = Float.parseFloat(text1Val);
	    		float input2Val = Float.parseFloat(text2Val);
	    		
	    		
	    		String retVal = calc(input1Val, input2Val, value);
    		
	    		TextView tv = (TextView)findViewById(R.id.textViewAns);
	    		tv.setText(&quot;Answer: &quot; + retVal);
    	}
    }
    	
    private String calc(float input1, float input2, String operation) {
		
    	if (MULTIPLY.equals(operation)) {
			return Float.toString(input1 * input2);
		} else if (DIVIDE.equals(operation)) {
			if (input2 == 0) {
				return &quot;Not A Number&quot;;
			}
			return Float.toString(input1 / input2);
		} else if (ADD.equals(operation)) {
			return Float.toString(input1 + input2);
		} else if (SUBTRACT.equals(operation)) {
			return Float.toString(input1 - input2);
		}
		
		return &quot;Improper operation!&quot;;
	}   
}
</pre></p>
<p>The implementation code of the onCalculateClick and calc methods are self-explanatory. Please note the commented out code involving the ArrayAdapter. This is an alternative method for populating the drop-down dynamically.</p>
<p>Overall the structure of the Android application is similar to a Flex application. Probably also to Windows Presentation Foundation or Silverlight application; although I do not have any hands-on experience on those. The added advantage of Android is that one does not have to learn a new programming language unlike Flex where one needs to learn ActionScript.</p>
<p>Run the Android application in the eclipse environment. In case you are rerunning the application, ensure that you do not close the emulator, for details refer here. On trying to start application directly, I experienced a number of errors. Two errors are shown below:</p>
<p><pre class="brush: plain;">
[2011-11-11 23:27:33 - Calculator] Failed to install Calculator.apk on device 'emulator-5554!
[2011-11-11 23:27:33 - Calculator] (null)
[2011-11-11 23:27:33 - Calculator] Launch canceled!

[2011-11-11 23:33:13 - Calculator] Failed to install Calculator.apk on device 'emulator-5554': device not found
[2011-11-11 23:33:13 - Calculator] com.android.ddmlib.InstallException: device not found
[2011-11-11 23:33:13 - Calculator] Launch canceled!
</pre></p>
<p><pre class="brush: plain;">
[2011-11-14 11:41:05 - Calculator1.0] emulator-5554 disconnected! Cancelling 'com.calculator.CalculatorActivity activity launch'!
[2011-11-14 11:48:22 - Calculator1.0] Failed to install Calculator1.0.apk on device 'emulator-5554!
[2011-11-14 11:48:22 - Calculator1.0] (null)
[2011-11-14 11:48:22 - Calculator1.0] Failed to install Calculator1.0.apk on device 'emulator-5554': EOF
[2011-11-14 11:48:22 - Calculator1.0] com.android.ddmlib.InstallException: EOF
[2011-11-14 11:48:22 - Calculator1.0] Launch canceled!
</pre></p>
<p>These issues were fixed by trying to run the application again. However the behavior of the application continued to be erratic. </p>
<p>Finally I started using the following procedure. In case I did not have the emulator running; I started it by running the Hello World application of my <a title="The Android Tutorial Series Part 1 – Hello World" href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example" target="_blank">previous blog post</a>. After it was successfully running, I ran my new Calculator application in the already started emulator. It has consistently run fine. Here&#8217;s the expected console output:</p>
<p><pre class="brush: plain;">
[2011-11-16 18:21:40 - Calculator1.0] Android Launch!
[2011-11-16 18:21:40 - Calculator1.0] adb is running normally.
[2011-11-16 18:21:40 - Calculator1.0] Performing com.calculator.CalculatorActivity activity launch
[2011-11-16 18:21:45 - Calculator1.0] Uploading Calculator1.0.apk onto device 'emulator-5554'
[2011-11-16 18:21:45 - Calculator1.0] Installing Calculator1.0.apk...
[2011-11-16 18:21:52 - Calculator1.0] Success!
[2011-11-16 18:21:52 - Calculator1.0] Starting activity com.calculator.CalculatorActivity on device emulator-5554
[2011-11-16 18:21:53 - Calculator1.0] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.calculator/.CalculatorActivity }
</pre></p>
<p>This approach has been useful for debugging as well. I was trying to run the Calculator application independently and it was unable to run on the emulator. I had by oversight placed the onClick attribute in the Spinner instead of the Button. This was causing the application to fail. To add to my woes the LogCat was showing nothing giving me no idea as to the reason for the error. I used my new approach of having Hello World app to get my emulator up and running. Next I ran the Calculator application, the exception trace immediately appeared in LogCat allowing me to easily debug the problem. </p>
<p>That&#8217;s all for the moment. In the next blog post I will try to skim below the Android layout surface. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/572/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/572/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/572/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=572&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/11/18/android-tutorial-part-calculator-app-application-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>The Android Tutorial Series Part 1 &#8211; Hello World</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/#comments</comments>
		<pubDate>Thu, 17 Nov 2011 08:31:02 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[helloworld]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[avd]]></category>
		<category><![CDATA[edittext]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[spinner]]></category>
		<category><![CDATA[textview]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=561</guid>
		<description><![CDATA[The mobile world has gained a lot of mind share with the ongoing battle between Apple&#8217;s iOS and Google Android operating system. As the world wide use of smart phones or devices with smart phone like convergence capabilities increases, developer &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=561&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The mobile world has gained a lot of mind share with the ongoing battle between Apple&#8217;s iOS and Google Android operating system. As the world wide use of smart phones or devices with smart phone like convergence capabilities increases, developer interest and demand for application development on such devices will shoot up. I have decided to take the Android operating system for a test drive. This is going to be my maiden foray in the Android world. So here goes my Hello World example for Android.<br />
<span id="more-561"></span><br />
There are a number of Android &#8216;Hello World&#8217; examples. My intention is to consolidate all the installation and configuration information along with the typical start-up errors faced by the Android developer. First let&#8217;s go over the configuration details. My system configuration is as below:</p>
<ul>
<li>Operating System: Windows 7</li>
<li>Java Version: Java 1.6.0_24</li>
<li>Eclipse environment: Eclipse Java EE IDE for Web Developers &#8211; Indigo Service Release 1 (3.7.1)</li>
<li>Android SDK: Android 4.0</li>
<li>Eclipse Plugin: ADT (Android Development Tools) Eclipse Plugin 15.0.0</li>
</ul>
<p><strong>Installation and Configuration</strong></p>
<p>Java is presumed to be already installed. Install the Eclipse environment. <a title="Eclipse Downloads" href="http://www.eclipse.org/downloads/" target="_blank">Download</a> the eclipse installable. Eclipse &#8216;Classic&#8217; version is satisfactory, however I am using Jave EE IDE for Web Developers version. Any Eclipse version greater than 3.5 is suitable.</p>
<p>Next proceed to installing the Android SDK. <a title="Android SDK Index" href="http://developer.android.com/sdk/index.html" target="_blank">Download</a> the SDK starter package. Run the starter package. On completion of the installation of starter package, run the SDK Mananger executable. The wizard will prompt the user to select Android packages to install. Select the following under Android 4.0 (API14):</p>
<ul>
<li>Documentation</li>
<li>SDK Platform</li>
<li>Samples for SDK</li>
<li>ARM EABI v7a System Image (This is required for Android Virtual Device)</li>
<li>Google APIs (optional)</li>
</ul>
<p>In Tools select the following:</p>
<ul>
<li>Android SDK Tools</li>
<li>Android SDK Platform-Tools</li>
</ul>
<p>For more details on recommended Andriod platform components for installation refer <a title="Android Installation Prerequisites" href="http://developer.android.com/sdk/installing.html#which" target="_blank">here</a>.</p>
<p>Next, let&#8217;s install the Android Development Tools(ADT) eclipse plugin. I tried installing using the <a title="ADT Eclipse Plugin" href="https://dl-ssl.google.com/android/eclipse/" target="_blank">update site</a> (both HTTPs and HTTP) but was unsuccessful; so I used the <a title="ADT Eclipse Plugin - Direct Download" href="http://dl.google.com/android/ADT-15.0.0.zip" target="_blank">direct download</a> option. For configuring the ADT plugin, refer the instructions mentioned <a title="ADT Eclipse Plugin Configuration" href="http://developer.android.com/sdk/eclipse-adt.html#configuring" target="_blank">here</a>.</p>
<p>The official installation guide for Android can be found <a title="Android Eclipse Installation &amp; Configuration" href="http://developer.android.com/sdk/installing.html" target="_blank">here</a>.</p>
<p>This completes the installation and configuration of the Android platform and ADT plugin on Eclipse platform. Now let&#8217;s move on to our first working example Hello World.</p>
<p><strong>Hello World Application/App</strong></p>
<p>To create the Hello World Android project, start Eclipse, then select File -&gt; New -&gt; Other -&gt; Android Project. Enter project name as HelloWorld, select Android 4.0 as build target and com.android.hello as package name. Leave the default selections for Create Activity and Minimum SDK. The HelloWorld project will be created in the eclipse environment. In the created project&#8217;s folder structure note two folders namely src and res. The src will have the class com.android.hello.HelloWorldActivity. Open the class. The class extends Activity class. Activity class is responsible for creating the window in which the developer places his/her custom UI contents. Here&#8217;s the source code of the HelloWorldActivity class. Note the implementation of onCreate method has been customized. The default implementation will be different.</p>
<p><pre class="brush: java;">
package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloWorldActivity extends Activity {
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView view = new TextView(this);
        view.setText(&quot;This is my introduction to the world of Andriod.&quot;);
        setContentView(view);
    }
}
</pre></p>
<p>As the method name suggests the onCreate method is invoked during the creation of the Activity instance. Note the following three lines of the onCreate method implementation.</p>
<p><pre class="brush: java;">
        TextView view = new TextView(this);
        view.setText(&quot;This is my introduction to the world of Andriod.&quot;);
        setContentView(view);
</pre></p>
<p>The first line creates the Android UI widget TextView which is used for displaying textual content. The second line assigns the text content i.e. &#8216;This is my introduction to the world of Andriod.&#8217; and the third associates the TextView to the Activity instance.</p>
<p>In the eclipse package explorer examine the res folder. This folder will have two sub folders namely layout and values. The main.xml within layout folder&#8217;s use will be elaborated in Part 2 of this series. The strings.xml in values folder holds the message resources in a typical key value pair fashion. The application name is stored under the key app_name. Currently the value is defaulted to the Android project name; you are free to customize.  </p>
<p>Now let&#8217;s run the Hello World Android application. To run the application we need an Android device or something that emulates an Android device. The ADT plugin provides an Android Virtual Device(AVD) emulator. The AVD can be created by invoking AVD Manager.exe directly within the Android SDK or within the Eclipse environment using the menu  Window -&gt; AVD Manager. For instructions on creating AVD refer <a title="AVD Creation" href="http://developer.android.com/resources/tutorials/hello-world.html#avd" target="_blank">here</a>. While configuring the AVD, for skin select the built-in HVGA. This helps in reducing the start-up time, in turn improving the developer productivity.</p>
<p><strong>Errors &amp; their fixes while running the Hello World Application</strong></p>
<p>In case one has installed the SDK in the non-standard location like D: drive etc you might encounter the following error.</p>
<p><pre class="brush: plain;">
[2011-11-11 12:34:18 - Emulator] PANIC: Could not open: C:\Users\&lt;username&gt;\.android/avd/myAVD.ini 
</pre></p>
<p>One of the ways to fix this problem is to copy the contents on the .android folder to the C:\Users\ folder. The other is run the following command:</p>
<p><pre class="brush: plain;">
mklink /J &quot;C:\Users\&lt;username&gt;\.android&quot; &quot;D:\Users\&lt;username&gt;\.android&quot;
</pre></p>
<p>Note the mklink command only <a title="mklink Reference" href="http://code.google.com/p/android/issues/detail?id=18562" target="_blank">works in Vista and Windows 7 operating systems</a>.</p>
<p>The other problem experienced by developers is the following:</p>
<p><pre class="brush: plain;">
Unable to find a 'userdata.img' file for ABI armeabi to copy into the AVD folder.
</pre></p>
<p>This error is experienced if the package &#8216;ARM EABI v7a System Image&#8217; is not installed in the SDK. Install it and the <a href="http://stackoverflow.com/questions/7817044/how-to-create-a-avd-for-android-4-0" title="UserData Img Fix" target="_blank">error should go away</a>.</p>
<p>Now to run the app, right click on the HelloWorld project in the package explorer. Select Run As -&gt; Android Application. The Run configuration wizard is displayed. Retain the defaults and select the Automatic option for target. The eclipse console will show the following if the deployment is successful:</p>
<p><pre class="brush: plain; highlight: [8,9];">
[2011-11-15 14:29:01 - HelloWorld] ------------------------------
[2011-11-15 14:29:01 - HelloWorld] Android Launch!
[2011-11-15 14:29:01 - HelloWorld] adb is running normally.
[2011-11-15 14:29:01 - HelloWorld] Performing com.android.hello.HelloWorldActivity activity launch
[2011-11-15 14:29:01 - HelloWorld] Automatic Target Mode: launching new emulator with compatible AVD 'myAVD'
[2011-11-15 14:29:01 - HelloWorld] Launching a new emulator with Virtual Device 'myAVD'
[2011-11-15 14:29:24 - HelloWorld] New emulator found: emulator-5554
[2011-11-15 14:29:24 - HelloWorld] Waiting for HOME ('android.process.acore') to be launched...
[2011-11-15 14:30:42 - HelloWorld] HOME is up on device 'emulator-5554'
[2011-11-15 14:30:42 - HelloWorld] Uploading HelloWorld.apk onto device 'emulator-5554'
[2011-11-15 14:30:43 - HelloWorld] Installing HelloWorld.apk...
[2011-11-15 14:31:42 - HelloWorld] Success!
[2011-11-15 14:31:42 - HelloWorld] Starting activity com.android.hello.HelloWorldActivity on device emulator-5554
[2011-11-15 14:31:44 - HelloWorld] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.android.hello/.HelloWorldActivity }
</pre></p>
<p>Note the considerable time spent between the Waiting for HOME and HOME is up on device&#8230;. statements. This is primarily because the Android architecture is defined on a different CPU vis-a-vis the Intel or AMD processor architecture. Therefore the <a href="http://stackoverflow.com/questions/3425870/why-does-android-avd-take-so-long-to-start-up" title="AVD Startup Delay" target="_blank">emulator takes time</a> to compile code. </p>
<p>Note that once the AVD has been started it should not be shutdown, you can run the application on the started AVD instance. To achieve this in the Run configuration set the target selection in manual mode. The user will be prompted to select the target AVD. On being prompted select the newly started AVD. For details check <a href="http://stackoverflow.com/questions/3425870/why-does-android-avd-take-so-long-to-start-up" title="AVD Reuse" target="_blank">reference</a> and read answer from &#8216;spiffly&#8217;. </p>
<p>The AVD should open the application with the App name &#8216;HelloWorld&#8217; and the text as mentioned in the onCreate method prominently displayed on the emulator screen.</p>
<p>That&#8217;s all for android development desk. In my next blog post I will create a small working Android application.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/561/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=561&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/11/17/android-tutorial-part-1-helloworld-example/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>RESTEasy Client Framework (RESTful Web Services Client) &#8211; A Tutorial</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/09/08/resteasy-client-framework-restful-web-services-client-tutorial/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/09/08/resteasy-client-framework-restful-web-services-client-tutorial/#comments</comments>
		<pubDate>Thu, 08 Sep 2011 11:05:59 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[client]]></category>
		<category><![CDATA[RESTEasy]]></category>
		<category><![CDATA[RESTful WebServices]]></category>
		<category><![CDATA[Client]]></category>
		<category><![CDATA[JBoss RESTEasy]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=538</guid>
		<description><![CDATA[Around two years back I had posted a blog post on RESTful Web Services using JBoss RESTEasy framework. That blog post was focused on the server side of RESTful Web Services. It explained how to expose your business functionality as &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/09/08/resteasy-client-framework-restful-web-services-client-tutorial/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=538&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Around two years back I had posted a <a href="http://technicalmumbojumbo.wordpress.com/2009/10/13/restful-webservices-using-jboss-resteasy-tutorial/" title="Developing RESTful Web Services using JBoss RESTEasy" target="_blank">blog post</a> on RESTful Web Services using JBoss RESTEasy framework. That blog post was focused on the server side of RESTful Web Services. It explained how to expose your business functionality as RESTful Web Services to the consumer community, i.e. act as a Service Provider. This post intends to look at the other side of the RESTful Web Service contract, the client side. How does a service consumer utilize a RESTful Web Service interface? What facilities does the JBoss RESTEasy framework provide to support service consumers? I found the RESTEasy Client Framework documentation a little lacking so decided put a small tutorial together. The examples below are implemented using RESTEasy 2.2.2 GA version.</p>
<p><span id="more-538"></span></p>
<p>First, I need to setup a service provider which will serve me consumable RESTful Web Services. I selected RESTful Web Services API provided by <a href="http://www.geonames.org/" title="Geo Names" target="_blank">geonames.org</a>. The site provides detailed documentation(http://www.geonames.org/export/web-services.html) along with sample URLs for consumption. The sample URLs are:</p>
<p><a href="http://api.geonames.org/postalCodeSearch?postalcode=24501&amp;maxRows=10&amp;username=demo" title="Geo Names Postal Code in XML" target="_blank">http://api.geonames.org/postalCodeSearch?postalcode=24501&amp;maxRows=10&amp;username=demo</a><br />
<a href="http://api.geonames.org/postalCodeSearchJSON?postalcode=9011&amp;maxRows=10&amp;username=demo" title="Geo Names Postal Code in JSON" target="_blank">http://api.geonames.org/postalCodeSearchJSON?postalcode=9011&amp;maxRows=10&amp;username=demo</a></p>
<p>I have used the demo user. This user has a daily user limit. So I suggest you create your own user. GeoNames offers free services for a defined daily limit. It also provides it&#8217;s own client libraries; for the purpose of this tutorial I have chosen to ignore these libraries. The Geonames API supports message payload delivery in XML and JSON format. We will have a look at both types of payload. First let&#8217;s look at XML payload.</p>
<p>Here&#8217;s the sample URL for XML payload. I am searching for postal code 24501 with a limit of retrieving max. 10 results.</p>
<p><a href="http://api.geonames.org/postalCodeSearch?postalcode=24501&amp;maxRows=10&amp;username=demo" title="Geo Names Postal Code in XML">http://api.geonames.org/postalCodeSearch?postalcode=24501&amp;maxRows=10&amp;username=demo</a></p>
<p>The XML payload is as below:</p>
<p><pre class="brush: xml;">
&lt;geonames&gt;
	&lt;totalResultsCount&gt;4&lt;/totalResultsCount&gt;
	&lt;code&gt;
		&lt;postalcode&gt;24501&lt;/postalcode&gt;
		&lt;name&gt;Lynchburg&lt;/name&gt;
		&lt;countryCode&gt;US&lt;/countryCode&gt;
		&lt;lat&gt;37.38311&lt;/lat&gt;
		&lt;lng&gt;-79.17833&lt;/lng&gt;
		&lt;adminCode1&gt;VA&lt;/adminCode1&gt;
		&lt;adminName1&gt;Virginia&lt;/adminName1&gt;
		&lt;adminCode2&gt;680&lt;/adminCode2&gt;
		&lt;adminName2&gt;Lynchburg (city)&lt;/adminName2&gt;
		&lt;adminCode3/&gt;&lt;adminName3/&gt;
	&lt;/code&gt;
	&lt;code&gt;
		&lt;postalcode&gt;24501&lt;/postalcode&gt;
		&lt;name&gt;Rasoolabad&lt;/name&gt;
		&lt;countryCode&gt;PK&lt;/countryCode&gt;
		&lt;lat&gt;34.18583&lt;/lat&gt;
		&lt;lng&gt;71.76333&lt;/lng&gt;
		&lt;adminCode1/&gt;
		&lt;adminName1&gt;NWFP Peshawar&lt;/adminName1&gt;
		&lt;adminCode2/&gt;&lt;adminName2/&gt;
		&lt;adminCode3/&gt;&lt;adminName3/&gt;
	&lt;/code&gt;
	&lt;code&gt;
		&lt;postalcode&gt;24501&lt;/postalcode&gt;
		&lt;name&gt;Chitral Karoona&lt;/name&gt;
		&lt;countryCode&gt;PK&lt;/countryCode&gt;
		&lt;lat&gt;34.18583&lt;/lat&gt;
		&lt;lng&gt;71.76333&lt;/lng&gt;
		&lt;adminCode1/&gt;
		&lt;adminName1&gt;NWFP Peshawar&lt;/adminName1&gt;
		&lt;adminCode2/&gt;&lt;adminName2/&gt;
		&lt;adminCode3/&gt;&lt;adminName3/&gt;
	&lt;/code&gt;
	&lt;code&gt;
		&lt;postalcode&gt;24501&lt;/postalcode&gt;
		&lt;name&gt;Staffanstorp&lt;/name&gt;
		&lt;countryCode&gt;SE&lt;/countryCode&gt;
		&lt;lat&gt;55.64277&lt;/lat&gt;
		&lt;lng&gt;13.20638&lt;/lng&gt;
		&lt;adminCode1&gt;M&lt;/adminCode1&gt;
		&lt;adminName1&gt;Skåne&lt;/adminName1&gt;
		&lt;adminCode2&gt;1230&lt;/adminCode2&gt;
		&lt;adminName2&gt;Staffanstorp&lt;/adminName2&gt;
		&lt;adminCode3/&gt;
		&lt;adminName3/&gt;
	&lt;/code&gt;
&lt;/geonames&gt;
</pre></p>
<p>The RESTEasy framework is a Java based framework. Therefore, the developer will be interested in working with POJOs (Plain Old Java Object) and not raw XML. The RESTEasy framework facilitates this by using built-in JAXB (Java API for XML Binding) features. To match the XML payload structure I am creating two Java classes GeoNames and GeoCode. The source code of the two classes is shown below:</p>
<p><pre class="brush: java;">
package com.resteasy.model;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name=&quot;geonames&quot;)
public class GeoNames {
	
	private int resultsCount = 0;
	private ArrayList&lt;GeoCode&gt; codes = new ArrayList&lt;GeoCode&gt;();
	
	@XmlElement(name=&quot;totalResultsCount&quot;)
	public int getResultsCount() {
		return resultsCount;
	}
	public void setResultsCount(int resultsCount) {
		this.resultsCount = resultsCount;
	}
	
	@XmlElement(name=&quot;code&quot;)
	public ArrayList&lt;GeoCode&gt; getCodes() {
		return this.codes;
	}
	public void setCode(ArrayList&lt;GeoCode&gt; codes) {
		this.codes = codes;
	}
	
	@Override 
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;Names....&quot;);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Results Count: &quot;);
		sb.append(this.resultsCount);
		sb.append(&quot;\n&quot;);
		for (GeoCode code : this.codes) {
			sb.append(&quot;**********\n&quot;);
			sb.append(code);
			sb.append(&quot;**********\n&quot;);
		}
		
		return sb.toString();
	}	
}
</pre><br />
<pre class="brush: java;">
package com.resteasy.model;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonProperty;

@XmlRootElement (name=&quot;code&quot;)
public class GeoCode {
	
	private int postalCode = 0;
	private String name = null;
	private String countryCode = null;
	private BigDecimal latitude = null;
	private BigDecimal longitude = null;
	private String adminCode1 = null;
	private String adminName1 = null;
	private String adminCode2 = null;
	private String adminName2 = null;
	private String adminCode3 = null;
	private String adminName3 = null;

	@XmlElement (name=&quot;postalcode&quot;)
	public int getPostalCode() {
		return postalCode;
	}
	public void setPostalCode(int postalCode) {
		this.postalCode = postalCode;
	}
	
	@XmlElement (name=&quot;name&quot;)
	public String getName() {
		return name;
	}
	
	@JsonProperty(&quot;placeName&quot;)
	public void setName(String name) {
		this.name = name;
	}
	
	@XmlElement (name=&quot;countryCode&quot;)
	public String getCountryCode() {
		return countryCode;
	}
	public void setCountryCode(String countryCode) {
		this.countryCode = countryCode;
	}
	
	@XmlElement (name=&quot;lat&quot;)
	public BigDecimal getLatitude() {
		return latitude;
	}
	
	@JsonProperty(&quot;lat&quot;)
	public void setLatitude(BigDecimal latitude) {
		this.latitude = latitude;
	}
	
	@XmlElement (name=&quot;lng&quot;)
	public BigDecimal getLongitude() {
		return longitude;
	}
	@JsonProperty(&quot;lng&quot;)
	public void setLongitude(BigDecimal longitude) {
		this.longitude = longitude;
	}
	
	@XmlElement (name=&quot;adminCode1&quot;)
	public String getAdminCode1() {
		return adminCode1;
	}
	public void setAdminCode1(String adminCode1) {
		this.adminCode1 = adminCode1;
	}
	
	@XmlElement (name=&quot;adminName1&quot;)
	public String getAdminName1() {
		return adminName1;
	}
	public void setAdminName1(String adminName1) {
		this.adminName1 = adminName1;
	}
	
	@XmlElement (name=&quot;adminCode2&quot;)
	public String getAdminCode2() {
		return adminCode2;
	}
	public void setAdminCode2(String adminCode2) {
		this.adminCode2 = adminCode2;
	}
	
	@XmlElement (name=&quot;adminName2&quot;)
	public String getAdminName2() {
		return adminName2;
	}
	public void setAdminName2(String adminName2) {
		this.adminName2 = adminName2;
	}
	
	@XmlElement (name=&quot;adminCode3&quot;)
	public String getAdminCode3() {
		return adminCode3;
	}
	public void setAdminCode3(String adminCode3) {
		this.adminCode3 = adminCode3;
	}
	
	@XmlElement (name=&quot;adminName3&quot;)
	public String getAdminName3() {
		return adminName3;
	}
	public void setAdminName3(String adminName3) {
		this.adminName3 = adminName3;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;PostalCode: &quot;);
		sb.append(this.postalCode);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Name: &quot;);
		sb.append(this.name);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Country Code: &quot;);
		sb.append(this.countryCode);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Latitude: &quot;);
		sb.append(this.latitude);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Longitude: &quot;);
		sb.append(this.longitude);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Name 1: &quot;);
		sb.append(this.adminName1);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Code 1: &quot;);
		sb.append(this.adminCode1);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Name 2: &quot;);
		sb.append(this.adminName2);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Code 2: &quot;);
		sb.append(this.adminCode2);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Name 3: &quot;);
		sb.append(this.adminName3);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Admin Code 3: &quot;);
		sb.append(this.adminCode1);
		sb.append(&quot;\n&quot;);

		return sb.toString();
	}	
}
</pre></p>
<p>I have used annotations to achieve XML binding between the payload and Java classes. Detailed explanation of the JAXB annotation is outside the purview of this blog post. However the annotation names are self-explanatory. There are some JSON annotations in GeoCode, however our current focus is only on XML annotations i.e. annotations whose names are prefixed by &#8220;Xml&#8221;. In case there is a difference between the XML element and Class property use the name variable in the XMLElement annotation to map the XML element name to the class property. For e.g. refer the following annotation for latitude property in GeoCode class.</p>
<p><pre class="brush: java;">
	@XmlElement (name=&quot;lat&quot;)
	public BigDecimal getLatitude() {
		return latitude;
	}
</pre></p>
<p>The next step is to create an interface which will act as a Proxy for communicating with the Geonames API. Here&#8217;s the source code of the proxy GeoNamesService. RESTful Web Services specific annotations are used. For explanation refer to my previous <a href="http://technicalmumbojumbo.wordpress.com/2009/10/13/restful-webservices-using-jboss-resteasy-tutorial/" title="Developing RESTful Web Services using JBoss RESTEasy" target="_blank">blog post</a> of RESTful Web Services. </p>
<p><pre class="brush: java; wrap-lines: false;">
package com.resteasy.client;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.jboss.resteasy.client.ClientResponse;

import com.resteasy.model.GeoNames;
import com.resteasy.model.PostalCodesJSON;

@Path(&quot;&quot;)
public interface GeoNamesService {

	@GET
	@Produces(&quot;application/xml&quot;)
	ClientResponse&lt;GeoNames&gt; getPostalCodeInformation(@QueryParam(&quot;postalcode&quot;) int postalCode,
			@QueryParam(&quot;maxRows&quot;) int rows, @QueryParam(&quot;username&quot;) String userName);

	@GET
	@Produces(&quot;application/xml&quot;)
	ClientResponse&lt;GeoNames&gt; getPostalCodes();

	@GET
	@Produces(&quot;application/json&quot;)
	ClientResponse&lt;PostalCodesJSON&gt; getPostalCodesinJSON(@QueryParam(&quot;postalcode&quot;) int postalCode,
			@QueryParam(&quot;maxRows&quot;) int rows, @QueryParam(&quot;username&quot;) String userName);
	
}
</pre></p>
<p>I have defined three methods, a parameterized getPostalCodeInformation, getPostalCodes and getPostalCodesinJSON. The first two handle XML payload and the last one is for JSON. Let&#8217;s focus on the first two. The methods are expected to return the ClientResponse class with a type variable aligned to the XML payload. Therefore for the XML payload we have defined the type as GeoNames, a class whose structure has been aligned to the XML structure. The second method getPostalCodes does not accept any argument. </p>
<p><pre class="brush: java;">
	@GET
	@Produces(&quot;application/xml&quot;)
	ClientResponse&lt;GeoNames&gt; getPostalCodes();
</pre></p>
<p>Update(2nd Jan 2012):The following libraries have been included in the classpath for RESTfulWSClientJSON:</p>
<ul>
<li>commons-codec-1.2.jar</li>
<li>commons-httpclient-3.1.jar</li>
<li>commons-logging-1.0.4.jar</li>
<li>jackson-core-asl-1.6.3.jar</li>
<li>jackson-jaxrs-1.6.3.jar</li>
<li>jackson-mapper-asl-1.6.3.jar</li>
<li>resteasy-jackson-provider-2.2.2.GA.jar</li>
<li>resteasy-jaxrs-2.2.2.GA.jar</li>
<li>jaxrs-api-2.2.2.GA.jar</li>
</ul>
<p>The following libraries are needed for the other two test classes.</p>
<ul>
<li>commons-codec-1.2.jar</li>
<li>commons-httpclient-3.1.jar</li>
<li>commons-logging-1.0.4.jar</li>
<li>resteasy-jaxrs-2.2.2.GA.jar</li>
<li>jaxrs-api-2.2.2.GA.jar</li>
<li>jaxb-impl-2.2.4.jar</li>
<li>resteasy-jaxb-provider-2.2.2.GA.jar</li>
</ul>
<p>Please note that GeoCode is a shared class for all the clients. Therefore comment out the JsonProperty related code when using these two client classes. </p>
<p>End Update<br />
Now let&#8217;s take it for a test run. Here&#8217;s the source code of the test class RESTFulWSClientNoParam.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.resteasy.client;

import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.ProxyFactory;

import com.resteasy.model.GeoNames;

public class RESTFulWSClientNoParam {

	private static final String GEONAMES_URL = &quot;http://api.geonames.org/postalCodeSearch?&quot; +
			&quot;postalcode=24501&amp;maxRows=10&amp;username=demo&quot;;
		
	public static void main(String[] args) {
		
		GeoNamesService service = ProxyFactory.create(GeoNamesService.class, GEONAMES_URL);
		ClientResponse&lt;GeoNames&gt; response = service.getPostalCodes();
		
		if (response.getStatus() == 200 ) {
			GeoNames names = response.getEntity();
			System.out.println(names);
			
		} else {
			System.out.println(&quot;Request processing failed. HTTP Status: &quot; +        response.getStatus()
			+ &quot; &quot; + response.toString());
		}
		response.releaseConnection();

	}
}
</pre></p>
<p>The test class run output is</p>
<p><pre class="brush: plain;">
Names....
Results Count: 4
**********
PostalCode: 24501
Name: Lynchburg
Country Code: US
Latitude: 37.38311
Longitude: -79.17833
Admin Name 1: Virginia
Admin Code 1: VA
Admin Name 2: Lynchburg (city)
Admin Code 2: 680
Admin Name 3: 
Admin Code 3: VA
**********
**********
PostalCode: 24501
Name: Rasoolabad
Country Code: PK
Latitude: 34.18583
Longitude: 71.76333
Admin Name 1: NWFP Peshawar
Admin Code 1: 
Admin Name 2: 
Admin Code 2: 
Admin Name 3: 
Admin Code 3: 
**********
**********
PostalCode: 24501
Name: Chitral Karoona
Country Code: PK
Latitude: 34.18583
Longitude: 71.76333
Admin Name 1: NWFP Peshawar
Admin Code 1: 
Admin Name 2: 
Admin Code 2: 
Admin Name 3: 
Admin Code 3: 
**********
**********
PostalCode: 24501
Name: Staffanstorp
Country Code: SE
Latitude: 55.64277
Longitude: 13.20638
Admin Name 1: Skåne
Admin Code 1: M
Admin Name 2: Staffanstorp
Admin Code 2: 1230
Admin Name 3: 
Admin Code 3: M
**********
</pre></p>
<p>The RESTful Web Services client class ProxyFactory creates the GeoNamesService interface implementation proxy using the create method. The method takes two arguments, one is the Client Proxy class and second is the string URL of the RESTful Web Service. The ClientResponse class provides getStatus method which maps to HTTP status code. The rest of the code is self-explanatory.</p>
<p>As we are using the complete URL including the query parameter the Path annotation (line number 13) in the client proxy interface GeoNamesService is provided a value &#8220;&#8221; instead of the usual &#8220;/&#8221;.</p>
<p>Typically RESTful Web Services API accept arguments. To illustrate parameterized RESTful Web Service APIs look at the method getPostalCodeInformation in GeoNamesService interface. </p>
<p><pre class="brush: java; wrap-lines: false;">
	@GET
	@Produces(&quot;application/xml&quot;)
	ClientResponse&lt;GeoNames&gt; getPostalCodeInformation(@QueryParam(&quot;postalcode&quot;) int postalCode,
			@QueryParam(&quot;maxRows&quot;) int rows, @QueryParam(&quot;username&quot;) String userName);
</pre></p>
<p>The method getPostalCodeInformation accepts three arguments namely postal code, max. rows and user name. Here&#8217;s the test class RESTFulWSClient.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.resteasy.client;

import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.ProxyFactory;

import com.resteasy.model.GeoNames;

public class RESTFulWSClient {

	private static final String GEONAMES_URL = &quot;http://api.geonames.org/postalCodeSearch&quot;;
		
	public static void main(String[] args) {
		
		GeoNamesService service = ProxyFactory.create(GeoNamesService.class, GEONAMES_URL);
		ClientResponse&lt;GeoNames&gt; response = service.getPostalCodeInformation(24501, 10, &quot;demo&quot;);
		
		if (response.getStatus() == 200 ) {
			GeoNames names = response.getEntity();
			System.out.println(names);
		} else {
			System.out.println(&quot;Request processing failed. HTTP Status: &quot; + response.getStatus()
			+ &quot; &quot; + response.getLocation());
		}
		response.releaseConnection();

	}
}
</pre></p>
<p>The output of the test class is similar to the earlier output.</p>
<p>So far we have covered the XML payload RESTEasy Client processing. Let&#8217;s have a look at the JSON option.<br />
Here&#8217;s the JSON URL:</p>
<p><a href="http://api.geonames.org/postalCodeSearchJSON?postalcode=24501&amp;maxRows=10&amp;username=demo" title="Geo Names Postal Code in JSON" target="_blank">http://api.geonames.org/postalCodeSearchJSON?postalcode=24501&amp;maxRows=10&amp;username=demo</a></p>
<p>Here&#8217;s the JSON output:</p>
<p><pre class="brush: plain; wrap-lines: true;">
{&quot;postalCodes&quot;:[{&quot;adminName2&quot;:&quot;Lynchburg (city)&quot;,&quot;adminCode2&quot;:&quot;680&quot;,&quot;adminCode1&quot;:&quot;VA&quot;,&quot;postalCode&quot;:&quot;24501&quot;,&quot;countryCode&quot;:&quot;US&quot;,
&quot;lng&quot;:-79.178326,&quot;placeName&quot;:&quot;Lynchburg&quot;,&quot;lat&quot;:37.383112,&quot;adminName1&quot;:&quot;Virginia&quot;},{&quot;postalCode&quot;:&quot;24501&quot;,&quot;countryCode&quot;:&quot;PK&quot;,&quot;lng&quot;:71.7633333,&quot;placeName&quot;:&quot;Rasoolabad&quot;,&quot;lat&quot;:34.1858333,
&quot;adminName1&quot;:&quot;NWFP Peshawar&quot;},{&quot;postalCode&quot;:&quot;24501&quot;,&quot;countryCode&quot;:&quot;PK&quot;,&quot;lng&quot;:71.7633333,&quot;placeName&quot;:&quot;Chitral Karoona&quot;,&quot;lat&quot;:34.1858333,&quot;adminName1&quot;:&quot;NWFP Peshawar&quot;},{&quot;adminName2&quot;:&quot;Staffanstorp&quot;,&quot;adminCode2&quot;:&quot;1230&quot;,&quot;adminCode1&quot;:&quot;M&quot;,&quot;postalCode&quot;:&quot;24501&quot;,
&quot;countryCode&quot;:&quot;SE&quot;,&quot;lng&quot;:13.206381797790527,&quot;placeName&quot;:&quot;Staffanstorp&quot;,&quot;lat&quot;:55.642772521210716,
&quot;adminName1&quot;:&quot;Skåne&quot;}]}
</pre></p>
<p>The structure of the JSON payload is slightly different from the XML payload. Therefore I have defined a new Class PostalCodesJSON. This class continues to reuse GeoCode class.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.resteasy.client;

import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.ProxyFactory;

import com.resteasy.model.PostalCodesJSON;


public class RESTFulWSClientJSON {

	private static final String GEONAMES_URL = &quot;http://api.geonames.org/postalCodeSearchJSON&quot;;
		
	public static void main(String[] args) {
		
		GeoNamesService service = ProxyFactory.create(GeoNamesService.class, GEONAMES_URL);
		ClientResponse&lt;PostalCodesJSON&gt; response = service.getPostalCodesinJSON(24501, 10, &quot;demo&quot;);
		
		if (response.getStatus() == 200 ) {
			PostalCodesJSON codes = response.getEntity();
			System.out.println(codes);
		} else {
			System.out.println(&quot;Request processing failed. HTTP Status: &quot; + response.getStatus()
			+ &quot; &quot; + response.getLocation());
		}
		response.releaseConnection();

	}

}
</pre></p>
<p>Note that we have defined GeoCode as a List in the PostalCodesJSON class. They can also be defined as a GeoCode array. The rest of the code remains unchanged.</p>
<p>Refer to the third method defined in getPostalCodesinJSON. It accepts three arguments similar to the getPostalCodeInformation method.</p>
<p><pre class="brush: java; wrap-lines: false;">
	@GET
	@Produces(&quot;application/json&quot;)
	ClientResponse&lt;PostalCodesJSON&gt; getPostalCodesinJSON(@QueryParam(&quot;postalcode&quot;) int postalCode,
			@QueryParam(&quot;maxRows&quot;) int rows, @QueryParam(&quot;username&quot;) String userName);
</pre></p>
<p>In case there are differences in the JSON property name and corresponding Class property name, use the JsonProperty annotation to map the JSON property to class property. For example, refer latitude property in GeoCode class.</p>
<p><pre class="brush: java;">
	@JsonProperty(&quot;lat&quot;)
	public void setLatitude(BigDecimal latitude) {
		this.latitude = latitude;
	}
</pre></p>
<p>There is a reason why the JsonProperty annotation is defined on the setLatitude method. As a consuming application, we are deserializing from JSON format to POJO property. This process invokes the setter method. In case of serialization the JsonProperty would have to be defined in the getLatitude method.</p>
<p>Here&#8217;s the test class RESTFulWSClientJSON for JSON payload.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.resteasy.client;

import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.ProxyFactory;

import com.resteasy.model.PostalCodesJSON;


public class RESTFulWSClientJSON {

	private static final String GEONAMES_URL = &quot;http://api.geonames.org/postalCodeSearchJSON&quot;;
		
	public static void main(String[] args) {
		
		GeoNamesService service = ProxyFactory.create(GeoNamesService.class, GEONAMES_URL);
		ClientResponse&lt;PostalCodesJSON&gt; response = service.getPostalCodesinJSON(24501, 10, &quot;demo&quot;);
		
		if (response.getStatus() == 200 ) {
			PostalCodesJSON codes = response.getEntity();
			System.out.println(codes);
		} else {
			System.out.println(&quot;Request processing failed. HTTP Status: &quot; + response.getStatus()
			+ &quot; &quot; + response.getLocation());
		}
		response.releaseConnection();

	}
}
</pre></p>
<p>Here&#8217;s the test class run output:</p>
<p><pre class="brush: plain;">
Names....

**********
PostalCode: 24501
Name: Lynchburg
Country Code: US
Latitude: 37.383112
Longitude: -79.178326
Admin Name 1: Virginia
Admin Code 1: VA
Admin Name 2: Lynchburg (city)
Admin Code 2: 680
Admin Name 3: null
Admin Code 3: VA
**********
**********
PostalCode: 24501
Name: Rasoolabad
Country Code: PK
Latitude: 34.1858333
Longitude: 71.7633333
Admin Name 1: NWFP Peshawar
Admin Code 1: null
Admin Name 2: null
Admin Code 2: null
Admin Name 3: null
Admin Code 3: null
**********
**********
PostalCode: 24501
Name: Chitral Karoona
Country Code: PK
Latitude: 34.1858333
Longitude: 71.7633333
Admin Name 1: NWFP Peshawar
Admin Code 1: null
Admin Name 2: null
Admin Code 2: null
Admin Name 3: null
Admin Code 3: null
**********
**********
PostalCode: 24501
Name: Staffanstorp
Country Code: SE
Latitude: 55.642772521210716
Longitude: 13.206381797790527
Admin Name 1: Skåne
Admin Code 1: M
Admin Name 2: Staffanstorp
Admin Code 2: 1230
Admin Name 3: null
Admin Code 3: M
**********
</pre></p>
<p>That covers the RESTEasy Client Framework tutorial. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/538/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/538/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/538/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=538&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/09/08/resteasy-client-framework-restful-web-services-client-tutorial/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>Investigating Hibernate fetch strategies &#8211; A tutorial</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/08/24/investigating-hibernate-fetch-strategy-tutorial/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/08/24/investigating-hibernate-fetch-strategy-tutorial/#comments</comments>
		<pubDate>Wed, 24 Aug 2011 14:04:52 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[fetch-strategy]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[hibernate]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=518</guid>
		<description><![CDATA[It has been nearly 3 or more years since my last post on Object Relational Mapping (ORM) tool Hibernate. There is an inevitable performance overhead associated with ORM tools like Hibernate. The overhead gets further magnified by application of imprudent &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/08/24/investigating-hibernate-fetch-strategy-tutorial/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=518&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It has been nearly 3 or more years since my last post on Object Relational Mapping (ORM) tool Hibernate. There is an inevitable performance overhead associated with ORM tools like Hibernate. The overhead gets further magnified by application of imprudent querying or fetch strategy. Hibernate is a sophisticated ORM tool and a developer needs to understand the programming intricacies/flexibilities provided by Hibernate before applying it in application development. This blog post intends to cover the various data fetching strategies supported by Hibernate.</p>
<p><span id="more-518"></span></p>
<p>Before getting into the nitty gritties of hibernate fetch, a quick summary of the setup. I am using the following softwares:</p>
<ul>
<li>Hibernate 3.6.6</li>
<li>Oracle Express Edition 10.2.0.1.0</li>
<li>Eclipse 3.4.1</li>
<li>Windows 7 Operating System</li>
</ul>
<p>Now let&#8217;s move on to hibernate configuration. First the hibernate configuration xml i.e. hibernate.cfg.xml.</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;

    &lt;session-factory&gt;

        &lt;!-- Database connection settings --&gt;
        &lt;property name=&quot;connection.driver_class&quot;&gt;oracle.jdbc.driver.OracleDriver&lt;/property&gt;
        &lt;property name=&quot;connection.url&quot;&gt;jdbc:oracle:thin:@localhost:1521:xe&lt;/property&gt;
        &lt;property name=&quot;connection.username&quot;&gt;system&lt;/property&gt;
        &lt;property name=&quot;connection.password&quot;&gt;manager&lt;/property&gt;

        &lt;!-- JDBC connection pool (use the built-in) --&gt;
        &lt;property name=&quot;connection.pool_size&quot;&gt;10&lt;/property&gt;

        &lt;!-- SQL dialect --&gt;
        &lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.Oracle10gDialect&lt;/property&gt;

        &lt;!-- Enable Hibernate's automatic session context management --&gt;
        &lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;

        &lt;!-- Disable the second-level cache  --&gt;
        &lt;property name=&quot;cache.provider_class&quot;&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;

        &lt;!-- Echo all executed SQL to stdout --&gt;
        &lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
        &lt;!--&lt;property name=&quot;format_sql&quot;&gt;true&lt;/property&gt;--&gt;
		&lt;!--&lt;property name=&quot;use_sql_comments&quot;&gt;true&lt;/property&gt;--&gt;
        

        &lt;!-- Drop and re-create the database schema on startup --&gt;
        &lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;

    &lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;
</pre></p>
<p>I have defined the Oracle database details such as its driver class, connection URL, and credentials. Please customize these values to your environment specifics. Next we look at project dependencies. They are as follows:</p>
<ul>
<li>hibernate3.jar</li>
<li>antlr-2.7.6.jar</li>
<li>commons-collections-3.1.jar</li>
<li>dom4j-1.6.1.jar</li>
<li>hibernate-jpa-2.0-api-1.0.1.Final.jar</li>
<li>javassist-3.12.0.GA.jar</li>
<li>jta-1.1.jar</li>
<li>log4j-1.2.16.jar</li>
<li>ojdbc14.jar</li>
<li>slf4j-api-1.6.1.jar</li>
<li>slf4j-lo4j12-1.6.1.jar</li>
</ul>
<p>Since we are using lo4j for logging, here&#8217;s the log4j properties file. Note specific changes have been made in the logging levels to gain insights into the SQL statements executed by hibernate. Refer lines 22 to 28. This is an essential tool for SQL debugging.</p>
<p><pre class="brush: plain; highlight: [22,23,24,25,26,27,28]; wrap-lines: false;">
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:\hibernate.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'debug' to 'debug' ##

log4j.rootLogger=info, file
#log4j.logger.net.sf.hibernate=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trace

### log JDBC bind parameters ###
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug

### log prepared statement cache activity ###
log4j.logger.org.hibernate.ps=debug
</pre></p>
<p>Now let&#8217;s move on to the meatier stuff of hibernate. To understand Hibernate&#8217;s fetch strategy let&#8217;s consider a scenario consisting of two entities Person and Address. They share a one-to-many relationship; i.e. one person has more than one addresses. Both the entities need to be made persistent.</p>
<p>I am using annotations to make the classes persistent. Here are the classes with their annotations. </p>
<p><pre class="brush: java; wrap-lines: false;">
package com.tutorial.hibernate.fetch;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Generated;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
@Table(name=&quot;PERSON&quot;,
		schema=&quot;SYSTEM&quot;)
public class Person implements Serializable {

	private static final long serialVersionUID = 4333499410830154895L;

	private int id = 0;
	private String firstName = null;
	private String lastName = null;

	private List&lt;Address&gt; addresses = new ArrayList&lt;Address&gt;();
	
	@Id
	@Generated(value=&quot;assigned&quot;)
	@Column(name=&quot;ID&quot;)
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Column(name=&quot;FIRST_NAME&quot;)
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	@Column(name=&quot;LAST_NAME&quot;)
	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	@BatchSize(size=2)
	public List&lt;Address&gt; getAddresses() {
		return addresses;
	}

	public void setAddresses(List&lt;Address&gt; addresses) {
		this.addresses = addresses;
	}
	
	public void addAddress(Address address) {
		address.setPerson(this);
		this.addresses.add(address);
		
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;**** Person **** &quot;);
		sb.append(&quot;Id: &quot;);
		sb.append(this.id);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;First name: &quot;);
		sb.append(this.firstName);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Last name: &quot;);
		sb.append(this.lastName);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;**** Person **** &quot;);
		sb.append(&quot;\n&quot;);
		
		return sb.toString();
	}
	
}
</pre></p>
<p><pre class="brush: java; wrap-lines: false;">
package com.tutorial.hibernate.fetch;

import java.io.Serializable;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=&quot;ADDRESS&quot;,
		schema=&quot;SYSTEM&quot;)

public class Address implements Serializable {

	@Id
	@Generated(value=&quot;assigned&quot;)
	private int id = 0;
	
	@Column(name=&quot;FIRST_LINE&quot;)	
	private String firstLine  = null;
	@Column(name=&quot;SECOND_LINE&quot;)
	private String secondLine = null;
	@Column(name=&quot;CITY&quot;)
	private String city       = null;
	@Column(name=&quot;ZIP_CODE&quot;)
	private String zipCode    = null;
	@ManyToOne
	@JoinColumn(name=&quot;PERSON_ID&quot;)	
	private Person person     = null;
	
	@Column(name=&quot;PERSON_ID&quot;, insertable=false, updatable=false)
	private Integer personId = null;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

	public String getFirstLine() {
		return firstLine;
	}
	
	public void setFirstLine(String firstLine) {
		this.firstLine = firstLine;
	}
	
	public String getSecondLine() {
		return secondLine;
	}
	
	public void setSecondLine(String secondLine) {
		this.secondLine = secondLine;
	}
	
	public String getCity() {
		return city;
	}
	
	public void setCity(String city) {
		this.city = city;
	}
	
	public String getZipCode() {
		return zipCode;
	}
	
	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	public Person getPerson() {
		return person;
	}
	
	public void setPerson(Person person) {
		this.person = person;
	}
	
	public Integer getPersonId() {
		return personId;
	}
	public void setPersonId(Integer personId) {
		this.personId = personId;
	}
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;***** Address ******&quot;);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Id: &quot;);
		sb.append(this.id);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;First Line: &quot;);
		sb.append(this.firstLine);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Second Line: &quot;);
		sb.append(this.secondLine);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;City: &quot;);
		sb.append(this.city);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Zip Code: &quot;);
		sb.append(this.zipCode);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Person Id: &quot;);
		sb.append(this.personId);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;***** Address ******&quot;);
		sb.append(&quot;\n&quot;);
		
		return sb.toString();

	}
	
}
</pre></p>
<p>In the Person class refer the annotation defined for getAddresses method.</p>
<p><pre class="brush: java;">
	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	//@Fetch(FetchMode.SELECT)
	//@Fetch(FetchMode.SUBSELECT)
	//@BatchSize(size=2)
</pre></p>
<p>This annotation defines one-to-many relationship between Person and Address. Note the commented out lines for the Fetch and BatchSize annotation. This will be changed later as we progress.</p>
<p>Similarly a many-to-one relationship is defined in Address class for person attribute.</p>
<p><pre class="brush: java;">
	@ManyToOne
	@JoinColumn(name=&quot;PERSON_ID&quot;)	
	private Person person     = null;
</pre></p>
<p>Purely from a relationship definition standpoint, there is no need to define the personId attribute in Address. This has been specifically added to facilitate querying using HQL. More on that later.</p>
<p>Run the following SQL scripts to create tables PERSON and ADDRESS in database.</p>
<p><pre class="brush: sql; wrap-lines: false;">
CREATE TABLE person(id INTEGER, first_name VARCHAR2(20), last_name VARCHAR2(20), 
	PRIMARY KEY(id));
	
CREATE TABLE ADDRESS(id INTEGER, first_line VARCHAR2(20), second_line VARCHAR2(20), 
	city VARCHAR2(20), zip_code VARCHAR2(10), person_id INTEGER, 
	PRIMARY KEY(id), CONSTRAINT ADDRESS_FK1 FOREIGN KEY (person_id) REFERENCES person(id));
</pre></p>
<p>To query the database, we need to have data. The DataLoader class creates some records in PERSON and ADDRESS. On successful run of the code we will be creating two persons with four addresses each and one person with two addresses. Here&#8217;s the source code of DataLoader class.</p>
<p><pre class="brush: java;">
package com.tutorial.hibernate.fetch;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class DataLoader {

	public static void main(String[] args) {
		
		SessionFactory factory = HibernateUtil.getFactory();
		
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		Person p = new Person();
		p.setId(1);
		p.setFirstName(&quot;Bill&quot;);
		p.setLastName(&quot;Banks&quot;);
		
		Address a1 = new Address();
		a1.setFirstLine(&quot;Line 11&quot;);
		a1.setSecondLine(&quot;Line 12&quot;);
		a1.setZipCode(&quot;12345&quot;);
		a1.setId(1);
		a1.setPerson(p);
		p.addAddress(a1);
		
		Address a2 = new Address();
		a2.setFirstLine(&quot;Line 21&quot;);
		a2.setSecondLine(&quot;Line 22&quot;);
		a2.setZipCode(&quot;54321&quot;);
		a2.setId(2);
		a2.setPerson(p);
		p.addAddress(a2);

		Address a3 = new Address();
		a3.setFirstLine(&quot;Line 31&quot;);
		a3.setSecondLine(&quot;Line 32&quot;);
		a3.setZipCode(&quot;11221&quot;);
		a3.setId(3);
		a3.setPerson(p);
		p.addAddress(a3);

		Address a4 = new Address();
		a4.setFirstLine(&quot;Line 41&quot;);
		a4.setSecondLine(&quot;Line 42&quot;);
		a4.setZipCode(&quot;22331&quot;);
		a4.setId(4);
		a4.setPerson(p);
		p.addAddress(a4);

		Person p1 = new Person();
		p1.setId(2);
		p1.setFirstName(&quot;Steve&quot;);
		p1.setLastName(&quot;Jobs&quot;);
		
		Address a11 = new Address();
		a11.setFirstLine(&quot;Line 111&quot;);
		a11.setSecondLine(&quot;Line 112&quot;);
		a11.setZipCode(&quot;12345&quot;);
		a11.setId(5);
		a11.setPerson(p1);
		p1.addAddress(a11);
		
		Address a22 = new Address();
		a22.setFirstLine(&quot;Line 221&quot;);
		a22.setSecondLine(&quot;Line 222&quot;);
		a22.setZipCode(&quot;54321&quot;);
		a22.setId(6);
		a22.setPerson(p1);
		p1.addAddress(a22);

		Address a33 = new Address();
		a33.setFirstLine(&quot;Line 331&quot;);
		a33.setSecondLine(&quot;Line 332&quot;);
		a33.setZipCode(&quot;11221&quot;);
		a33.setId(7);
		a33.setPerson(p1);
		p1.addAddress(a33);

		Address a44 = new Address();
		a44.setFirstLine(&quot;Line 441&quot;);
		a44.setSecondLine(&quot;Line 442&quot;);
		a44.setZipCode(&quot;22331&quot;);
		a44.setId(8);
		a44.setPerson(p1);
		p1.addAddress(a44);

		Person p2 = new Person();
		p2.setId(3);
		p2.setFirstName(&quot;Clark&quot;);
		p2.setLastName(&quot;Jacob&quot;);
		
		Address a111 = new Address();
		a111.setFirstLine(&quot;Line 111&quot;);
		a111.setSecondLine(&quot;Line 112&quot;);
		a111.setZipCode(&quot;12345&quot;);
		a111.setId(9);
		a111.setPerson(p2);
		p2.addAddress(a111);
		
		Address a222 = new Address();
		a222.setFirstLine(&quot;Line 221&quot;);
		a222.setSecondLine(&quot;Line 222&quot;);
		a222.setZipCode(&quot;54321&quot;);
		a222.setId(10);
		a222.setPerson(p2);
		p2.addAddress(a222);
	
		session.save(p);
		session.save(p1);
		session.save(p2);
		
		tx.commit();
	}

}
</pre></p>
<p>On running the DataLoader class, the following SQL output is generated on the console:</p>
<p><pre class="brush: plain; wrap-lines: false;">
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: select address_.id, address_.CITY as CITY1_, address_.FIRST_LINE as FIRST3_1_, address_.PERSON_ID as PERSON4_1_, address_.SECOND_LINE as SECOND5_1_, address_.ZIP_CODE as ZIP6_1_ from SYSTEM.ADDRESS address_ where address_.id=?
Hibernate: insert into SYSTEM.PERSON (FIRST_NAME, LAST_NAME, ID) values (?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.PERSON (FIRST_NAME, LAST_NAME, ID) values (?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.PERSON (FIRST_NAME, LAST_NAME, ID) values (?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into SYSTEM.ADDRESS (CITY, FIRST_LINE, PERSON_ID, SECOND_LINE, ZIP_CODE, id) values (?, ?, ?, ?, ?, ?)
</pre></p>
<p>Hibernate provides 4 strategies for retrieving data:</p>
<ul>
<li>SELECT</li>
<li>JOIN</li>
<li>SUBSELECT</li>
<li>BATCH</li>
</ul>
<p><strong>Fetch Strategy : SELECT</strong></p>
<p>At the moment the persistent classes are configured at default settings. Here&#8217;s the DataSelectFetch class to retrieve Person and Address records.</p>
<p><pre class="brush: java;">
package com.tutorial.hibernate.fetch;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DataSelectFetch {

	public static void main(String[] args) {
		SessionFactory fact = HibernateUtil.getFactory();
		Session session = fact.openSession();
		
		Query q = session.createQuery(&quot; FROM Person p &quot;);
		
		System.out.println(&quot;Retrieving Data&quot;);
		List l = q.list();
		System.out.println(&quot;Data retrieved: &quot; + l.size());
		for (Object object : l) {
			Person p = (Person) object;
			System.out.println(p);
			System.out.println(&quot;Address retrieval initiated.&quot;);
			List&lt;Address&gt; addresses = p.getAddresses();
			System.out.println(&quot;Address retrieval complete.&quot;);
			int i=1;
			for (Address address : addresses) {
				System.out.println(&quot;#### individual address: &quot; + i);
				System.out.println(address);
				System.out.println(&quot;#### Address complete&quot;);
				i++;
			}
		}

	}
}
</pre></p>
<p>The console output generated is as below:</p>
<p><pre class="brush: plain;">
Retrieving Data
Hibernate: select person0_.ID as ID0_, person0_.FIRST_NAME as FIRST2_0_, person0_.LAST_NAME as LAST3_0_ from SYSTEM.PERSON person0_
Data retrieved: 3
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
#### individual address: 1
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

#### Address complete
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, 
addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
#### individual address: 1
***** Address ******
Id: 5
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 6
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 7
First Line: Line 331
Second Line: Line 332
City: null
Zip Code: 11221
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 8
First Line: Line 441
Second Line: Line 442
City: null
Zip Code: 22331
Person Id: 2
***** Address ******

#### Address complete
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, 
addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
#### individual address: 1
***** Address ******
Id: 9
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 3
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 10
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 3
***** Address ******

#### Address complete
</pre></p>
<p>There are four SQLs fired. This first one is fired for retrieving all the records in the PERSON table. The remaining three are fired for retrieving addresses records for each Person. This is basically the N+1 problem. The first query retrieves N records from database, in this case N Person records. For each Person a new query retrieves Addresses. Therefore for N persons, N queries retrieve information from ADDRESS table.</p>
<p>Change the annotation definition in the getAddresses method to the following:</p>
<p><pre class="brush: java;">
	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	@Fetch(FetchMode.SELECT)
	//@Fetch(FetchMode.SUBSELECT)
	//@BatchSize(size=2)
</pre></p>
<p>Basically uncomment the following line.</p>
<p><pre class="brush: java;">
	@Fetch(FetchMode.SELECT)
</pre></p>
<p>Running DataSelectFetch generates the same console output. This is the SELECT fetch mode. Let&#8217;s now move on to the next fetch strategy join.</p>
<p><strong>Fetch Strategy : JOIN</strong></p>
<p>Refer to the class DataOuterJoinFetch.</p>
<p><pre class="brush: java; highlight: [15]; wrap-lines: false;">
package com.tutorial.hibernate.fetch;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DataOuterJoinFetch {

	public static void main(String[] args) {
		SessionFactory fact = HibernateUtil.getFactory();
		Session session = fact.openSession();
		
		Query q = session.createQuery(&quot; SELECT p, a FROM Person as p left outer join p.addresses a where p.id = a.personId&quot;);
		
		System.out.println(&quot;Retrieving Data&quot;);
		List l = q.list();
		System.out.println(&quot;Result size: &quot; + l.size());
		System.out.println(&quot;Data retrieved&quot;);
		for (Object object : l) {
			if (object instanceof Object[]) {
				Object[] objArr = (Object[]) object;
				System.out.println(&quot;Person&quot;);
				System.out.println(objArr[0]);
				System.out.println(&quot;Address&quot;);
				System.out.println(objArr[1]);
			} else {
				throw new RuntimeException(&quot;Unable to process.&quot;);
			}
		}

	}
}
</pre></p>
<p>Refer to line 15 of the source code. We have established an outer join between Person and Address. Note the usage of the personId attribute here. That is the reason to maintain the attribute. Also note the special attributes added in its annotation definition.</p>
<p><pre class="brush: java;">
	@Column(name=&quot;PERSON_ID&quot;, insertable=false, updatable=false)
	private Integer personId = null;
</pre></p>
<p>The annotation definition ensures that many-to-one relationship maintains the PERSON_ID column value in the ADDRESS table. This attribute is purely for display purposes only.</p>
<p>The run output of DataOuterJoinFetch is as below:</p>
<p><pre class="brush: plain; wrap-lines: false;">
Retrieving Data
Hibernate: select person0_.ID as ID0_0_, addresses1_.id as id1_1_, person0_.FIRST_NAME as FIRST2_0_0_, person0_.LAST_NAME as LAST3_0_0_, addresses1_.CITY as CITY1_1_, addresses1_.FIRST_LINE as FIRST3_1_1_, addresses1_.PERSON_ID as PERSON4_1_1_, addresses1_.SECOND_LINE as SECOND5_1_1_, addresses1_.ZIP_CODE as ZIP6_1_1_ from SYSTEM.PERSON person0_ left outer join SYSTEM.ADDRESS addresses1_ on person0_.ID=addresses1_.PERSON_ID where person0_.ID=addresses1_.PERSON_ID
Result size: 10
Data retrieved
Person
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

Person
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

Person
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

Person
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

Person
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address
***** Address ******
Id: 5
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 2
***** Address ******

Person
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address
***** Address ******
Id: 6
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 2
***** Address ******

Person
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address
***** Address ******
Id: 7
First Line: Line 331
Second Line: Line 332
City: null
Zip Code: 11221
Person Id: 2
***** Address ******

Person
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address
***** Address ******
Id: 8
First Line: Line 441
Second Line: Line 442
City: null
Zip Code: 22331
Person Id: 2
***** Address ******

Person
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address
***** Address ******
Id: 9
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 3
***** Address ******

Person
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address
***** Address ******
Id: 10
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 3
***** Address ******
</pre></p>
<p>All the data is retrieved in a single SQL. The generated query is an outer join between the PERSON and ADDRESS tables. This is efficient except for the fact that the Person object is repeated for the number of addresses. Alternatively change the Fetch annotation on the getAddresses method to the following:</p>
<p><pre class="brush: java;">
	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	@Fetch(FetchMode.JOIN)
	//@Fetch(FetchMode.SUBSELECT)
	//@BatchSize(size=2)
	public List&lt;Address&gt; getAddresses() {
		return addresses;
	}
</pre></p>
<p>Run the DataSelectFetch class. Here&#8217;s the ouput:</p>
<p><pre class="brush: plain;">
Retrieving Data
Hibernate: select person0_.ID as ID0_, person0_.FIRST_NAME as FIRST2_0_, person0_.LAST_NAME as LAST3_0_ from SYSTEM.PERSON person0_
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, 
addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
Data retrieved: 3
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

#### Address complete
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 5
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 6
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 7
First Line: Line 331
Second Line: Line 332
City: null
Zip Code: 11221
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 8
First Line: Line 441
Second Line: Line 442
City: null
Zip Code: 22331
Person Id: 2
***** Address ******

#### Address complete
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 9
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 3
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 10
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 3
***** Address ******

#### Address complete
</pre></p>
<p>Four SQLs are fired. First to retrieve all Persons and the next three for retrieving associated addresses for that person. This seems similar to the SELECT fetch strategy except that fact that all database retrieval take place upfront in JOIN fetch unlike in SELECT where it happens on a need basis. This can become an important performance consideration.</p>
<p>Update 18th Nov 2011: This does not really look like a join query. I changed the querying class to the following class:</p>
<p><pre class="brush: java;">
package com.tutorial.hibernate.fetch;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class DataFetchJoin {

	public static void main(String[] args) {
		SessionFactory fact = HibernateUtil.getFactory();
		Session session = fact.openSession();
		
		Person p = (Person)session.get(Person.class, 1);
		
		System.out.println(&quot;Retrieving Data&quot;);
		System.out.println(p);
		System.out.println(&quot;Address retrieval initiated.&quot;);
		List&lt;Address&gt; addresses = p.getAddresses();
		System.out.println(&quot;Address retrieval complete.&quot;);
		int i=1;
		for (Address address : addresses) {
			System.out.println(&quot;#### individual address: &quot; + i);
			System.out.println(address);
			System.out.println(&quot;#### Address complete&quot;);
			i++;
		}
	}
}
</pre></p>
<p>On running the test class, the console output is as follows:</p>
<p><pre class="brush: plain;">
Hibernate: select person0_.ID as ID0_1_, person0_.FIRST_NAME as FIRST2_0_1_, person0_.LAST_NAME as LAST3_0_1_, addresses1_.PERSON_ID as PERSON4_0_3_, addresses1_.id as id3_, addresses1_.id as id1_0_, addresses1_.CITY as CITY1_0_, addresses1_.FIRST_LINE as FIRST3_1_0_, addresses1_.PERSON_ID as PERSON4_1_0_, addresses1_.SECOND_LINE as SECOND5_1_0_, addresses1_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.PERSON person0_ left outer join SYSTEM.ADDRESS addresses1_ on person0_.ID=addresses1_.PERSON_ID where person0_.ID=?
Retrieving Data
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

#### Address complete
</pre></p>
<p>This is more on expected lines for JOIN mode. The difference was that here I retrieved one Person only vis-a-vis the earlier queries retrieved N persons. Hibernate querying is complex and too flexible for my comfort.<br />
End Update:18th Nov 2011</p>
<p><strong>Fetch Strategy : SUBSELECT</strong></p>
<p>Let&#8217;s move on to the next fetch strategy SUBSELECT. Change the fetch mode in getAddresses annotation to the following:</p>
<p><pre class="brush: java;">
	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	@Fetch(FetchMode.SUBSELECT)
	//@BatchSize(size=2)
	public List&lt;Address&gt; getAddresses() {
		return addresses;
	}
</pre></p>
<p>Run the DataSelectFetch class. The output is as follows:</p>
<p><pre class="brush: plain;">
Retrieving Data
Hibernate: select person0_.ID as ID0_, person0_.FIRST_NAME as FIRST2_0_, person0_.LAST_NAME as LAST3_0_ from SYSTEM.PERSON person0_
Data retrieved: 3
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID in (select person0_.ID from SYSTEM.PERSON person0_)
#### individual address: 1
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

#### Address complete
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 5
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 6
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 7
First Line: Line 331
Second Line: Line 332
City: null
Zip Code: 11221
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 8
First Line: Line 441
Second Line: Line 442
City: null
Zip Code: 22331
Person Id: 2
***** Address ******

#### Address complete
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 9
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 3
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 10
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 3
***** Address ******

#### Address complete
</pre></p>
<p>Two SQLs are fired. One to retrieve all Persons and the second uses a SUBSELECT query in the WHERE clause to retrieve all addresses that has matching person ids.</p>
<p>Let&#8217;s change line number 15 in DataSelectFetch from</p>
<p><pre class="brush: java;">
		Query q = session.createQuery(&quot; FROM Person p &quot;);
</pre></p>
<p><pre class="brush: java;">
		Query q = session.createQuery(&quot; FROM Person p WHERE p.id = ? OR p.id = ?&quot;);
		q.setInteger(0, 1);
		q.setInteger(1, 2);
</pre></p>
<p>The two database queries are changed to the following:</p>
<p><pre class="brush: plain; wrap-lines: false;">
Hibernate: select person0_.ID as ID0_, person0_.FIRST_NAME as FIRST2_0_, person0_.LAST_NAME as LAST3_0_ from SYSTEM.PERSON person0_ where person0_.ID=? or person0_.ID=?
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID in (select person0_.ID from SYSTEM.PERSON person0_ where person0_.ID=? or person0_.ID=?)
</pre></p>
<p><strong>Fetch Strategy : BATCH</strong></p>
<p>Now let&#8217;s look at the last fetch strategy i.e. batch.</p>
<p>Change the getAddresses annotation to the following:</p>
<p><pre class="brush: java;">
	@OneToMany(mappedBy=&quot;person&quot;, cascade=CascadeType.ALL)
	@Column(name=&quot;id&quot;)
	@BatchSize(size=2)
	public List&lt;Address&gt; getAddresses() {
		return addresses;
	}
</pre></p>
<p>Run the DataSelectFetch class. This will be the older version of the class without the changes as suggested for Subselect option. The console output is:</p>
<p><pre class="brush: plain; wrap-lines: false;">
Retrieving Data
Hibernate: select person0_.ID as ID0_, person0_.FIRST_NAME as FIRST2_0_, person0_.LAST_NAME as LAST3_0_ from SYSTEM.PERSON person0_
Data retrieved: 3
**** Person **** Id: 1
First name: Bill
Last name: Banks
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID in (?, ?)
#### individual address: 1
***** Address ******
Id: 1
First Line: Line 11
Second Line: Line 12
City: null
Zip Code: 12345
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 2
First Line: Line 21
Second Line: Line 22
City: null
Zip Code: 54321
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 3
First Line: Line 31
Second Line: Line 32
City: null
Zip Code: 11221
Person Id: 1
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 4
First Line: Line 41
Second Line: Line 42
City: null
Zip Code: 22331
Person Id: 1
***** Address ******

#### Address complete
**** Person **** Id: 2
First name: Steve
Last name: Jobs
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
Hibernate: select addresses0_.PERSON_ID as PERSON4_0_1_, addresses0_.id as id1_, addresses0_.id as id1_0_, addresses0_.CITY as CITY1_0_, addresses0_.FIRST_LINE as FIRST3_1_0_, addresses0_.PERSON_ID as PERSON4_1_0_, addresses0_.SECOND_LINE as SECOND5_1_0_, addresses0_.ZIP_CODE as ZIP6_1_0_ from SYSTEM.ADDRESS addresses0_ where addresses0_.PERSON_ID=?
#### individual address: 1
***** Address ******
Id: 5
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 6
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 3
***** Address ******
Id: 7
First Line: Line 331
Second Line: Line 332
City: null
Zip Code: 11221
Person Id: 2
***** Address ******

#### Address complete
#### individual address: 4
***** Address ******
Id: 8
First Line: Line 441
Second Line: Line 442
City: null
Zip Code: 22331
Person Id: 2
***** Address ******

#### Address complete
**** Person **** Id: 3
First name: Clark
Last name: Jacob
**** Person **** 

Address retrieval initiated.
Address retrieval complete.
#### individual address: 1
***** Address ******
Id: 9
First Line: Line 111
Second Line: Line 112
City: null
Zip Code: 12345
Person Id: 3
***** Address ******

#### Address complete
#### individual address: 2
***** Address ******
Id: 10
First Line: Line 221
Second Line: Line 222
City: null
Zip Code: 54321
Person Id: 3
***** Address ******

#### Address complete
</pre></p>
<p>The batch size maps to the number of persons whose addresses are retrieved. In the present case the first batch is triggered for Person with id 1 and 3, the second batch is for Person with id is 2. I am not sure why hibernate deviates from the order in which the ids are retrieved. Need to figure that out.</p>
<p>To sum up we have four different methods/strategies hibernate provides to retrieve data. It is upto the developer to judiciously choose one of the four strategies which ensures optimum application and database performance.</p>
<p>That&#8217;s all at the moment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/518/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/518/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/518/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=518&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/08/24/investigating-hibernate-fetch-strategy-tutorial/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>java.util.concurrent: Executors, Thread Pools(Cache, Fixed, Scheduled), ExecutorCompletionService &#8211; A tutorial</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/05/16/java-util-concurrent-executors-thread-pools-cache-fixed-scheduled-executorcompletionservice-tutorial/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/05/16/java-util-concurrent-executors-thread-pools-cache-fixed-scheduled-executorcompletionservice-tutorial/#comments</comments>
		<pubDate>Mon, 16 May 2011 07:24:36 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[executorcompletionservice]]></category>
		<category><![CDATA[executors]]></category>
		<category><![CDATA[threadpool]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=504</guid>
		<description><![CDATA[I received a request from one of my blog readers Kunal inquiring if I was planning to post something on FutureTask and ExecutorCompletionService. Since he put the seed of a possible blog post in my mind, I decided to go &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/05/16/java-util-concurrent-executors-thread-pools-cache-fixed-scheduled-executorcompletionservice-tutorial/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=504&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I received a request from one of my blog readers <a title="java.concurrency CyclicBarrier and CountdownLatch: What’s the difference?" href="http://technicalmumbojumbo.wordpress.com/2010/10/17/java-concurrent-cyclicbarrier-countdownlatch/#comment-583" target="_blank">Kunal</a> inquiring if I was planning to post something on FutureTask and ExecutorCompletionService. Since he put the seed of a possible blog post in my mind, I decided to go ahead and write a post on the two concurrency classes. Additionally to make the coverage complete the post intends to cover the Executors class as well.</p>
<p><span id="more-504"></span></p>
<p>Let&#8217;s start with creating a class which spawns a thread. Java provides two approaches for creating threads, one create a Thread sub class or implement Runnable interface. Subclassing Thread is a bad idea because it constraints the developer from developing a domain specific inheritance hierarchy. The class can only extend Thread. Instead implementing Runnable interface is a more suitable option. So let&#8217;s create a new class Activity class which implements Runnable interface. Refer the code below for the class source.</p>
<p><pre class="brush: java;">
package com.concurrency;

public class Activity implements Runnable {

	@Override
	public void run() {
		System.out.println(&quot;Running concurrent activity!&quot;);
	}

}
</pre></p>
<p>To spawn a Activity thread, we create an Thread instance with the Activity instance as the constructor argument. Look at the source code of ThreadSpawner class.</p>
<p><pre class="brush: java;">
package com.concurrency.test;

import com.concurrency.Activity;

public class ThreadSpawner {

	public static void main(String[] args) {
		Thread t = new Thread(new Activity());
		t.start();
	}

}
</pre></p>
<p>This is the pre Java 5 days way of creating a java thread. In post Java 5 days, Java has introduced new classes. One of the concurrency classes added in Java 5 is the Executors class. This class provided a number of utility methods. One of the method is defaultThreadFactory which creates a ThreadFactory class instance which can be used spawn new threads. An alternative approach to creating a new thread is explained in ThreadFactoryTest class. Here&#8217;s the class source code:</p>
<p><pre class="brush: java;">
package com.concurrency.tf.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import com.concurrency.Activity;

public class ThreadFactoryTest {

	public static void main(String[] args) {
		ThreadFactory tf = Executors.defaultThreadFactory();
		Thread t = tf.newThread(new Activity());
		t.start();		
	}

}
</pre></p>
<p>Using Executors&#8217;s defaultThreadFactory, a ThreadFactory instance is created. To the ThreadFactory instance&#8217;s newThread method a Runnable instance whose thread needs to be spawned is passed. I have used the same Activity class to help understand the similarities and differences in the two approaches: the pre Java 5 and post Java 5 approach.So now the most important question is what&#8217;s the benefit of using Executors and ThreadFactory classes? I was able to figure out that using the Java 5 concurrency framework provides the newly created thread with an automatically assigned thread group name, thread pool name and thread name. Beyond that I am not sure if there are any additional benefits the Executors framework provides.</p>
<p>Parallel computing or parallelization is an important programming paradigm which speeds up a sequentially executing program. Java does not allow developers to spawn new processes; it allows spawning of threads. Breaking a task into sub activities which can be ran in parallel helps reduce the overall task processing time. However one needs to keep in mind that such an approach if uncontrolled can lead to spawning of large number of threads. Threads in large quantities can put a strain on JVM resources (CPU, memory). Therefore it is necessary to put in place a method to limit the number of threads to a threshold, the Executors framework provides such a mechanism.</p>
<p>The Executors framework allows the creation of thread pool.Executors supports creation of a cachable, fixed and scheduled thread pool. Let&#8217;s try and understand each thread pool type with an example. To begin with let&#8217;s create a Runnable implementation which can be reused for all the pools. The class we create is PoolRunnable and below is its source code.</p>
<p><pre class="brush: java;">
package com.concurrency.pool;

import java.text.SimpleDateFormat;

import com.concurrency.utils.ConcurrencyUtils;

public class PoolRunnable implements Runnable {

	private int delayTime = 0;
	
	public PoolRunnable(int delayTime) {
		this.delayTime = delayTime;
	}
	
	public PoolRunnable() {
		
	}
	
	@Override
	public void run() {
		Thread curThread = Thread.currentThread();
		SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd 'at' HH:mm:ss&quot;);
		System.out.println(df.format(new java.util.Date()) + &quot; Starting thread &quot; + curThread.getName());
		try {
			Thread.sleep(delayTime * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(&quot;@@@@@@@@@@@@@@@@@&quot;);
		System.out.println(this.toString());
		System.out.println(df.format(new java.util.Date()) + &quot; Ending thread &quot; + curThread.getName());
		System.out.println(&quot;#################&quot;);
	}

	@Override
	public String toString() {
		return ConcurrencyUtils.getThreadInfo();
	}
		
}
</pre></p>
<p>The goal of the PoolRunnable class is to spawn a thread which is to replicate a typical application behavior by sleeping for a user defined time duration. The end user configures the PoolRunnable sleep duration by passing the interval as a constructor argument. PoolRunnable also utilizes a utility class ConcurrencyUtils for its toString implementation. Here&#8217;s the source code.</p>
<p><pre class="brush: java;">
package com.concurrency.utils;

import java.text.SimpleDateFormat;

public class ConcurrencyUtils {
	
	public static String getThreadInfo() {
		StringBuilder sb = new StringBuilder();
		Thread curThread = Thread.currentThread();
		sb.append(&quot;Thread Id: &quot;);
		sb.append(curThread.getId());
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Name: &quot;);
		sb.append(curThread.getName());
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Group: &quot;);
		sb.append(curThread.getThreadGroup().getName());
		sb.append(&quot;\n&quot;);
		return sb.toString();
	}

	public static String getShortThreadInfo() {
		StringBuilder sb = new StringBuilder();
		Thread curThread = Thread.currentThread();
		sb.append(&quot;Thread Id: &quot;);
		sb.append(curThread.getId());
		sb.append(&quot;, &quot;);
		sb.append(&quot;Name: &quot;);
		sb.append(curThread.getName());
		sb.append(&quot;, &quot;);
		sb.append(&quot;Group: &quot;);
		sb.append(curThread.getThreadGroup().getName());
		sb.append(&quot;\n&quot;);
		return sb.toString();
	}

	public static String retrieveCurrentDate(){
		SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd 'at' HH:mm:ss&quot;);
		return df.format(new java.util.Date());
	}
		
}
</pre></p>
<p>To understand the cached thread pool functioning consider the following CachedPoolTest implementation:</p>
<p><pre class="brush: java;">
package com.concurrency.pool.ctp.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import com.concurrency.pool.PoolRunnable;

public class CachedPoolTest {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newCachedThreadPool();
			
		Runnable r1 = new PoolRunnable();
		svc.execute(r1);
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Runnable r2 = new PoolRunnable(1);
		svc.execute(r2);

		try {
			Thread.sleep(1200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Runnable r3 = new PoolRunnable(2);
		svc.execute(r3);

		try {
			Thread.sleep(2100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		svc.shutdown();
	}

}
</pre></p>
<p>The line 13 creates a ExecutorService which retains a handle to the cached thread pool. By default, a pool having minimum size zero and max size equivalent of maximum integer value is created.An unused thread is retained in the cached pool for a duration of 60 seconds; beyond which the thread is removed from the pool. </p>
<p>The test class CachedPoolTest executes three Runnable instances of PoolRunnable class each provided a sleep duration of 0, 1 and 2 seconds respectively. The instances are individually submitted to execute method of the ExecutorService. For proper testing it is essential that the first thread is allowed to complete before triggering the subsequent thread. This is achieved by introducing a delay(1 sec, 1.2 sec, 2.1 sec) between each execute method invocation. Here&#8217;s the test class run output:</p>
<p><pre class="brush: plain;">
2011-05-13 at 14:52:15 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 14:52:15 Ending thread pool-1-thread-1
#################
2011-05-13 at 14:52:16 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 14:52:17 Ending thread pool-1-thread-1
#################
2011-05-13 at 14:52:17 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 14:52:19 Ending thread pool-1-thread-1
#################
</pre></p>
<p>I have used concurrency utils to print thread id, name and pool information. From the output it is clear that all reuse the same thread. One more thing to note is the line 42. Invocation of shutdown method on ExecutorService is important else the Java process will not terminate.</p>
<p>I have enhanced to add a fourth Runnable instance which will be executed after 61 seconds. This is to verify if a new thread is created after the expiration of the cache thread retention duration. The test class run output proves me correct. Below is the enhanced class and its output.</p>
<p><pre class="brush: java;">
package com.concurrency.pool.ctp.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import com.concurrency.pool.PoolRunnable;

public class CachedPoolTest {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newCachedThreadPool();
			
		Runnable r1 = new PoolRunnable();
		svc.execute(r1);
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Runnable r2 = new PoolRunnable(1);
		svc.execute(r2);

		try {
			Thread.sleep(1200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Runnable r3 = new PoolRunnable(2);
		svc.execute(r3);

		try {
			Thread.sleep(2100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		try {
			Thread.sleep(61000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		Runnable r4 = new PoolRunnable();
		svc.execute(r4);

		
		svc.shutdown();
	}

}
</pre></p>
<p><pre class="brush: plain;">
2011-05-13 at 15:00:22 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 15:00:22 Ending thread pool-1-thread-1
#################
2011-05-13 at 15:00:23 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 15:00:24 Ending thread pool-1-thread-1
#################
2011-05-13 at 15:00:24 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 15:00:26 Ending thread pool-1-thread-1
#################
2011-05-13 at 15:01:27 Starting thread pool-1-thread-2
@@@@@@@@@@@@@@@@@
Thread Id: 9
Name: pool-1-thread-2
Group: main

2011-05-13 at 15:01:27 Ending thread pool-1-thread-2
#################
</pre></p>
<p>So we have looked at cached thread pool. Now let&#8217;s focus on the other types. First let&#8217;s look at the fixed thread pool. I have created the FixedThreadPoolTest class for explaining fixed thread pool. Refer the source code below:</p>
<p><pre class="brush: java;">
package com.concurrency.pool.fp;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.concurrency.pool.PoolRunnable;

public class FixedThreadPoolTest {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newFixedThreadPool(2);
		
		Runnable r1 = new PoolRunnable(2);
		svc.execute(r1);
				
		Runnable r2 = new PoolRunnable(3);
		svc.execute(r2);

		Runnable r3 = new PoolRunnable(3);
		svc.execute(r3);
		
		svc.shutdown();
		
	}
}
</pre></p>
<p>The line 11 in the test class creates a fixed thread pool containing 2 threads. I then execute three threads at nearly the same time with individual thread sleep durations 2 seconds, 3 seconds and 3 seconds respectively. the output observed is as below.</p>
<p><pre class="brush: plain;">
2011-05-13 at 15:14:26 Starting thread pool-1-thread-1
2011-05-13 at 15:14:26 Starting thread pool-1-thread-2
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 15:14:28 Ending thread pool-1-thread-1
#################
2011-05-13 at 15:14:28 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 9
Name: pool-1-thread-2
Group: main

2011-05-13 at 15:14:29 Ending thread pool-1-thread-2
#################
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 15:14:31 Ending thread pool-1-thread-1
#################
</pre></p>
<p>The test class run output shows that two threads are started simultaneously, one thread completes its run after 2 seconds. On termination of this thread, the third thread is spawned which terminates after 3 seconds. The test clearly shows that the 2 thread upper limit defined during the thread pool creation is honored and any new thread requests beyond the threshold limit are queued until existing pool thread(s) become available.</p>
<p>Sometimes during programming we have a requirement of triggering a specific functionality or a set of<br />
functionalities after a designated period of time. The Executors framework provides a facility to create scheduled thread pool. Refer the source code of the test class ScheduleConcurrencyTest</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.concurrency.schedule.test;

import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.concurrency.Calculator;
import com.concurrency.pool.PoolRunnable;

public class ScheduleConcurrencyTest {

	public static void main(String[] args) {
		SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd 'at' HH:mm:ss&quot;);
		ScheduledExecutorService svc = Executors.newScheduledThreadPool(2);
		System.out.println(df.format(new java.util.Date()) + &quot; Time Runnable&quot;);
		svc.schedule(new PoolRunnable(), 2, TimeUnit.SECONDS);
		System.out.println(df.format(new java.util.Date()) + &quot; Time Callable&quot;);
		ScheduledFuture&lt;Integer&gt; sf = svc.schedule(new Calculator(1, 3, 
			Calculator.OPERATION_ADD), 5, TimeUnit.SECONDS);
		try {
			System.out.println(&quot;Waiting for value.&quot;);
			Integer val = sf.get();
			System.out.println(df.format(new java.util.Date()) + &quot; Time Callable Retrieve&quot;);
			System.out.println(&quot;Computed Value: &quot; + val);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
		svc.shutdown();
		
	}
}
</pre></p>
<p>Refer line 17 of ScheduleConcurrencyTest. Here we create a scheduled thread pool and get a handle to the underlying pool via the ScheduledExecutorService interface. Next look at line 19. Here we schedule a PoolRunnable instance to be run after a delay of 2 seconds. Runnable implementation basically constitutes functionality which needs to be executed in parallel with the invoking application. Some times we expect the thread to do some processing and return some value. Java 5 has introduced the Callable construct. This allows threads to return values to the invoking application.</p>
<p>The ScheduledExecutorService allows execution of Callable interface after a defined time interval. I create a<br />
calculator implementation of Callable interface. The Calculator is expected to add two integer values and respond back with the sum value. The source code of Calculator class handling Callable idiosyncrasies is shown below:</p>
<p><pre class="brush: java;">
package com.concurrency;

import java.util.concurrent.Callable;

public class Calculator implements Callable&lt;Integer&gt; {
	
	public static final int OPERATION_ADD = 1;
	
	private int param1 = 0;
	private int param2 = 0;
	private int operation = 0;
	
	public Calculator(int param1, int param2, int operation) {
		this.param1 = param1;
		this.param2 = param2;
		this.operation = operation;
	}

	public int getParam1() {
		return param1;
	}

	public void setParam1(int param1) {
		this.param1 = param1;
	}

	public int getParam2() {
		return param2;
	}

	public void setParam2(int param2) {
		this.param2 = param2;
	}

	public int getOperation() {
		return operation;
	}

	public void setOperation(int operation) {
		this.operation = operation;
	}
	
	@Override
	public Integer call() throws Exception {
		int retValue = 0;
		switch (this.operation) {
		case 1:
			retValue = this.param1 + this.param2;
			break;
		// Additional cases can be similarly added for 
		//other mathematical operations
			
		default:
			retValue = 0;
			break;
		}
		return Integer.valueOf(retValue) ;
	}
}
</pre></p>
<p>Refer line 21 in the ScheduleConcurrencyTest. Here we schedule Calculator for execution after passage of 5 seconds. In line 25 we get the return value from the Calculator which can be used for further processing. The test run output is shown below.</p>
<p><pre class="brush: plain;">
2011-05-13 at 16:48:17 Time Runnable
2011-05-13 at 16:48:17 Time Callable
Waiting for value.
2011-05-13 at 16:48:19 Starting thread pool-1-thread-1
@@@@@@@@@@@@@@@@@
Thread Id: 8
Name: pool-1-thread-1
Group: main

2011-05-13 at 16:48:19 Ending thread pool-1-thread-1
#################
2011-05-13 at 16:48:22 Time Callable Retrieve
Computed Value: 4
</pre></p>
<p>Clearly line 4 and 12 of the output show that PoolRunnable instance is invoked after a delay of 2 seconds, and Calculator is invoked after completion of 5 seconds. The schedule example used above is a case where the schedule task/job is to processed on a one time basis only. However in real life scenarios, we might need the ability to trigger a task at regular intervals in time or after a fixed period after the completion of the specific task. The Executors framework provides two methods namely scheduleAtFixedRate and scheduleWithFixedDelay to implement the same.</p>
<p>Let&#8217;s take the first example of scheduleAtFixedRate. Refer the test class ScheduleIntervalTest&#8217;s source code:</p>
<p><pre class="brush: java;">
package com.concurrency.schedule.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.concurrency.ScheduleJob;

public class ScheduleIntervalTest {

	public static void main(String[] args) {
		ScheduledExecutorService svc = Executors.newScheduledThreadPool(2);
		svc.scheduleAtFixedRate(new ScheduleJob(), 2, 2, TimeUnit.SECONDS);

	}
}
</pre></p>
<p>To understand the functionality better, I have created a new Runnable implementation ScheduleJob, here&#8217;s<br />
ScheduleJob&#8217;s source code:</p>
<p><pre class="brush: java;">
package com.concurrency;

import java.text.SimpleDateFormat;

public class ScheduleJob implements Runnable {
	
	private static int counter = 0;
	
	public ScheduleJob() {
		
	}

	@Override
	public void run() {
		try {
			if (counter == 5) {
				System.out.println(&quot;Exception is thrown!&quot;);
				throw new RuntimeException(&quot;Job cannot be processed.&quot;);
			}
			SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd 'at' HH:mm:ss&quot;);
			System.out.println(df.format(new java.util.Date()) + &quot; job ran.&quot;);
			counter++;
		} catch(Throwable t) {
			t.printStackTrace();
			counter = 0;
		}
	}
}
</pre></p>
<p>The ScheduleJob has been programmed to throw a RuntimeException on its sixth run. The idea is to determine if the schedule job is affected by the exception or not. Here&#8217;s the test output run:</p>
<p><pre class="brush: plain;">
2011-05-13 at 17:13:05 job ran.
2011-05-13 at 17:13:07 job ran.
2011-05-13 at 17:13:09 job ran.
2011-05-13 at 17:13:11 job ran.
2011-05-13 at 17:13:13 job ran.
Exception is thrown!
java.lang.RuntimeException: Job cannot be processed.
	at com.concurrency.ScheduleJob.run(ScheduleJob.java:18)
	at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
	at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
	at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
2011-05-13 at 17:13:17 job ran.
2011-05-13 at 17:13:19 job ran.
:
:
:
</pre></p>
<p>The job continues running every 2nd second as defined during the scheduleAtFixedRate method invocation.<br />
Now moving on to the scheduleWithFixedDelay method. For understanding this, I am creating a new Runnable<br />
implementation ScheduleDelayJob. During the thread run, the thread sleeps for a duration which is incremented by one for each subsequent invocation. </p>
<p><pre class="brush: java;">
package com.concurrency;

import java.text.SimpleDateFormat;

public class ScheduleDelayJob implements Runnable {

	private static int counter = 1;
	
	@Override
	public void run() {
		SimpleDateFormat df = new SimpleDateFormat(&quot;yyyy-MM-dd 'at' HH:mm:ss&quot;);
		System.out.println(df.format(new java.util.Date()) + &quot; Starting run.&quot;);
		
		try {
			Thread.sleep(counter * 1000);
			counter++;
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(df.format(new java.util.Date()) + &quot; Ending run.&quot;);
	}
}
</pre></p>
<p>Refer the ScheduleDelayTest test class:</p>
<p><pre class="brush: java;">
package com.concurrency.schedule.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.concurrency.ScheduleDelayJob;

public class ScheduleDelayTest {

	public static void main(String[] args) {
		ScheduledExecutorService svc = Executors.newScheduledThreadPool(2);
		svc.scheduleWithFixedDelay(new ScheduleDelayJob(), 2, 2, TimeUnit.SECONDS);
		
	}
}
</pre></p>
<p>The following thread is scheduled to run 2 seconds after completion of the incumbent thread. Here&#8217;s the test run output:</p>
<p><pre class="brush: plain;">
2011-05-13 at 17:27:16 Starting run.
2011-05-13 at 17:27:17 Ending run.
2011-05-13 at 17:27:19 Starting run.
2011-05-13 at 17:27:21 Ending run.
2011-05-13 at 17:27:23 Starting run.
2011-05-13 at 17:27:26 Ending run.
2011-05-13 at 17:27:28 Starting run.
2011-05-13 at 17:27:32 Ending run.
2011-05-13 at 17:27:34 Starting run.
2011-05-13 at 17:27:39 Ending run.
2011-05-13 at 17:27:41 Starting run.
:
:
:
</pre></p>
<p>Note that the difference between &#8220;Starting Run&#8221; and &#8220;Ending Run&#8221; time stamps is increasing incremently by 1 second and that new thread execution is starting exactly 2 seconds after completion of the incumbent thread run.</p>
<p>Finally let&#8217;s move on to ExecutorCompletionService. To understand the significance of this class, let&#8217;s use a real life scenario. Consider a search engine, a user types in a word to search, the engine queries its database and retrieves matches and displays the end results. Now to speed up this match retrieval process, let&#8217;s say that instead of querying a single large database, the engine queries hundreds of small databases. To acheive this in an optimum fashion, instead of one thread running a sequential query on each database, it would make sense to parallelise the individual database query process and consolidate the results sequentially. That is precisely what ExecutorCompletionService endeavors to achieve.</p>
<p>Let&#8217;s create SearchFragmentResult class which replicates the individual database search thread. The<br />
SearchFragmentResult class implements Callable interface and is expected to return an integer value representing number of matches. Here&#8217;s the source code of the SearchFragmentResult class.</p>
<p><pre class="brush: java;">
package com.concurrency.exec.comp;

import java.util.concurrent.Callable;

import com.concurrency.utils.ConcurrencyUtils;

public class SearchResultFragment implements Callable&lt;Integer&gt; {

	private boolean throwException = false;
	private int delayValue = 0;
	
	public SearchResultFragment(int delay) {
		this.delayValue = delay;
	}
	
	public SearchResultFragment(int delay, boolean exceptionFlag) {
		this.throwException = exceptionFlag;
		this.delayValue = delay;
	}

	@Override
	public Integer call() throws Exception {
		System.out.println(ConcurrencyUtils.retrieveCurrentDate() + 
			&quot;: Starting &quot; + ConcurrencyUtils.getShortThreadInfo());
		if (this.throwException) {
			throw new RuntimeException(&quot;Check exception handling.&quot;);
		}
		int val = 0;
		if (this.delayValue &gt; 5) {
			val = 10 - this.delayValue;
		} else {
			val = this.delayValue*2;
		}
		Thread.sleep(val * 1000);
		System.out.println(ConcurrencyUtils.retrieveCurrentDate() + 
				&quot;: Completing &quot; + ConcurrencyUtils.getShortThreadInfo());
		return this.delayValue;
	}

}
</pre></p>
<p>The SearchFragmentResult has two overloaded constructor implementations, one accepting a delay value as input and the other accepting an exception flag value as input along with delay value. The boolean flag is used to inform the class to throw RuntimeException during its thread run. The delay value puts the thread to sleep for a computed duration time. This is just to simulate real life behavior of response time differences. Logic has been added in the run method implementation to ensure varied sleep durations.</p>
<p>Now let&#8217;s move on to the test class ExecutorCompletionSvcTest. Refer the source code below:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.concurrency.exec.comp.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.concurrency.exec.comp.SearchResultFragment;

public class ExecutorCompletionSvcTest {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newFixedThreadPool(2);
		
		ExecutorCompletionService&lt;Integer&gt; compSvc 
			= new ExecutorCompletionService&lt;Integer&gt;(svc);
		
		List&lt;SearchResultFragment&gt; inputs = new ArrayList&lt;SearchResultFragment&gt;();
		for (int i=0; i&lt;10; i++){
			SearchResultFragment frag = new SearchResultFragment(i);
			inputs.add(frag);
		}
		
		List&lt;Future&lt;Integer&gt;&gt; results = new ArrayList&lt;Future&lt;Integer&gt;&gt;();
		for (SearchResultFragment searchResultFragment : inputs) {
			Future&lt;Integer&gt; future = compSvc.submit(searchResultFragment);
			results.add(future);
		}
		System.out.println(&quot;Done submitting all requests!&quot;);
		
		boolean notDone = true;
		int result = 0;
		
		while(notDone) {
			boolean status = false;
			for (Future&lt;Integer&gt; future : results) {
				if (!future.isDone()) {
					status = true;
				}
			}
			if (!status) {
				notDone = false;
			} else {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		for (Future&lt;Integer&gt; future : results) {
			int interimVal = 0;
			try {
				interimVal = future.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
			System.out.println(&quot;Interim Val: &quot; + interimVal); 
			result += interimVal;

		}
		System.out.println(&quot;Result Value: &quot; + result);
		svc.shutdown();
	}
}
</pre></p>
<p>The test code spawns 10 threads. These threads are submitted to ExecutorCompletionService, refer line 29 in the code. The service processes them and returns the match results as integer value. The value are returned back by the individual thread using the Future interface, refer line . The Future&#8217;s state is checked to validate if the processing is complete. This is achieved by invoking Future&#8217;s isDone() method, refer line . If completed, the value is retrieved using the get() method. The returned values are added to get the total match count. Here&#8217;s the test class run output:</p>
<p><pre class="brush: plain;">
Done submitting all requests!
2011-05-13 at 18:33:56: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:33:56: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:33:56: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:33:56: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:33:58: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:33:58: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:00: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:00: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:04: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:04: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:08: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:08: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:12: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:12: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:14: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:14: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:15: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:15: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:34:16: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:34:16: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

Interim Val: 0
Interim Val: 1
Interim Val: 2
Interim Val: 3
Interim Val: 4
Interim Val: 5
Interim Val: 6
Interim Val: 7
Interim Val: 8
Interim Val: 9
Result Value: 45
</pre></p>
<p>The run output clearly shows that we created a thread pool of 2, which was honored and the threshold was not exceeded. Once all the threads completed their processing, individual values were sought and added together.</p>
<p>There is an alternative and albeit the right way of getting values from Future interfaces. Refer the source code for ExecutorCompletionSvc2Test.</p>
<p><pre class="brush: java;">
package com.concurrency.exec.comp.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.concurrency.exec.comp.SearchResultFragment;

public class ExecutorCompletionSvc2Test {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newFixedThreadPool(2);
		
		ExecutorCompletionService&lt;Integer&gt; compSvc 
			= new ExecutorCompletionService&lt;Integer&gt;(svc);
		
		List&lt;SearchResultFragment&gt; inputs = new ArrayList&lt;SearchResultFragment&gt;();
		for (int i=0; i&lt;10; i++){
			SearchResultFragment frag = new SearchResultFragment(i);
			inputs.add(frag);
		}
		
		List&lt;Future&lt;Integer&gt;&gt; results = new ArrayList&lt;Future&lt;Integer&gt;&gt;();
		for (SearchResultFragment searchResultFragment : inputs) {
			Future&lt;Integer&gt; future = compSvc.submit(searchResultFragment);
			results.add(future);
		}
		System.out.println(&quot;Done submitting all requests!&quot;);
		
		int result = 0;
		int counter = 0;
		
		while(counter != 10) {
			try {
				Future&lt;Integer&gt; response = compSvc.take();
				try {
					int interimVal = response.get();
					result += interimVal;
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			counter++;
		}
		
		System.out.println(&quot;Result Value: &quot; + result);
		svc.shutdown();
	}
}
</pre></p>
<p>Here we use the take() method on ExecutorCompletionService to retrieve the Future reference of the currently completed thread, refer line 39.</p>
<p>So now what happens if an exception is thrown? Refer the source code of two test classes </p>
<p>ExecutorCompletionSvcExceptionTest and ExecutorCompletionSvcException2Test. ExecutorCompletionSvcException2Test is the right way to do things.</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.concurrency.exec.comp.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.concurrency.exec.comp.SearchResultFragment;

public class ExecutorCompletionSvcExceptionTest {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newFixedThreadPool(2);
		
		ExecutorCompletionService&lt;Integer&gt; compSvc 
			= new ExecutorCompletionService&lt;Integer&gt;(svc);
		
		List&lt;SearchResultFragment&gt; inputs = new ArrayList&lt;SearchResultFragment&gt;();
		for (int i=0; i&lt;10; i++){
			SearchResultFragment frag = null;
			if (i == 5) {
				frag = new SearchResultFragment(i, true);
			} else {
				frag = new SearchResultFragment(i);
			}
			inputs.add(frag);
		}
		
		List&lt;Future&lt;Integer&gt;&gt; results = new ArrayList&lt;Future&lt;Integer&gt;&gt;();

		for (SearchResultFragment searchResultFragment : inputs) {
			Future&lt;Integer&gt; future = compSvc.submit(searchResultFragment);
			results.add(future);
		}
		System.out.println(&quot;Done submitting all requests!&quot;);
		boolean notDone = true;
		int result = 0;
		
		while(notDone) {
			boolean status = false;
			for (Future&lt;Integer&gt; future : results) {
				if (!future.isDone()) {
					status = true;
				}
			}
			if (!status) {
				notDone = false;
			} else {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		for (Future&lt;Integer&gt; future : results) {
			int interimVal = 11;
			try {
				interimVal = future.get();
				System.out.println(&quot;Interim Val: &quot; + interimVal); 
				result += interimVal;

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				System.out.println(&quot;Execution Val: &quot; + interimVal);
				e.printStackTrace();
			}

		}
		System.out.println(&quot;Result Value: &quot; + result);
		svc.shutdown();
	}
}
</pre></p>
<p><pre class="brush: java; wrap-lines: false;">
package com.concurrency.exec.comp.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.concurrency.exec.comp.SearchResultFragment;

public class ExecutorCompletionSvcException2Test {

	public static void main(String[] args) {
		ExecutorService svc = Executors.newFixedThreadPool(2);
		
		ExecutorCompletionService&lt;Integer&gt; compSvc 
			= new ExecutorCompletionService&lt;Integer&gt;(svc);
		
		List&lt;SearchResultFragment&gt; inputs = new ArrayList&lt;SearchResultFragment&gt;();
		for (int i=0; i&lt;10; i++){
			SearchResultFragment frag = null;
			if (i == 5) {
				frag = new SearchResultFragment(i, true);
			} else {
				frag = new SearchResultFragment(i);
			}
			inputs.add(frag);
		}
		
		List&lt;Future&lt;Integer&gt;&gt; results = new ArrayList&lt;Future&lt;Integer&gt;&gt;();

		for (SearchResultFragment searchResultFragment : inputs) {
			Future&lt;Integer&gt; future = compSvc.submit(searchResultFragment);
			results.add(future);
		}
		System.out.println(&quot;Done submitting all requests!&quot;);
		
		int result = 0;
		int counter = 0;
		
		while(counter != 10) {
			try {
				Future&lt;Integer&gt; response = compSvc.take();
				try {
					int interimVal = response.get();
					result += interimVal;
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			counter++;
		}
		
		System.out.println(&quot;Result Value: &quot; + result);
		svc.shutdown();
	}
}
</pre></p>
<p>Here&#8217;s the run output:</p>
<p><pre class="brush: plain;">
Done submitting all requests!
2011-05-13 at 18:43:47: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:47: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:47: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:47: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:49: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:49: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:51: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:51: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:55: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:55: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:55: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:59: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:59: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:43:59: Starting Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:43:59: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:44:01: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:44:01: Starting Thread Id: 8, Name: pool-1-thread-1, Group: main

2011-05-13 at 18:44:02: Completing Thread Id: 9, Name: pool-1-thread-2, Group: main

2011-05-13 at 18:44:02: Completing Thread Id: 8, Name: pool-1-thread-1, Group: main

Interim Val: 0
Interim Val: 1
Interim Val: 2
Interim Val: 3
Interim Val: 4
Execution Val: 11
java.util.concurrent.ExecutionException: java.lang.RuntimeException: Check exception handling.
	at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
	at java.util.concurrent.FutureTask.get(Unknown Source)
	at com.concurrency.exec.comp.test.ExecutorCompletionSvcExceptionTest.main

(ExecutorCompletionSvcExceptionTest.java:63)
Caused by: java.lang.RuntimeException: Check exception handling.
	at com.concurrency.exec.comp.SearchResultFragment.call(SearchResultFragment.java:26)
	at com.concurrency.exec.comp.SearchResultFragment.call(SearchResultFragment.java:1)
	at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
	at java.util.concurrent.FutureTask.run(Unknown Source)
	at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
	at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
	at java.util.concurrent.FutureTask.run(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Interim Val: 6
Interim Val: 7
Interim Val: 8
Interim Val: 9
Result Value: 40
</pre></p>
<p>As long as the main thread handles the exception, we lose only that worker thread&#8217;s computational value, the rest work fine and remain uninterrupted. As a devloper one might need to consider this possibility and design code accordingly.</p>
<p>That&#8217;s all for the moment. Kunal, I hope this helps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/504/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/504/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/504/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=504&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/05/16/java-util-concurrent-executors-thread-pools-cache-fixed-scheduled-executorcompletionservice-tutorial/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring Framework-An Introduction-Part III &#8211; Aspect Oriented Programming</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/04/20/spring-framework-an-introduction-part-iii-aspect-oriented-programming/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/04/20/spring-framework-an-introduction-part-iii-aspect-oriented-programming/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 05:13:39 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[spring]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=491</guid>
		<description><![CDATA[My previous two posts on Spring Framework covered dependency injection, bean reuse and object lifecycle, autowiring and internationalization. This post will cover Aspect Oriented Programming(AOP). All IT applications are developed with the end goal of addressing concern(s) or business requirement(s). &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/04/20/spring-framework-an-introduction-part-iii-aspect-oriented-programming/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=491&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>My previous two posts on Spring Framework covered <a title="Spring Framework – An Introduction Part I – Dependency Injection, Bean Reuse" href="http://technicalmumbojumbo.wordpress.com/2011/04/05/spring-framework-introduction-dependency-injection-bean-reuse-part-i/" target="_blank">dependency injection, bean reuse</a> and <a title="Spring Framework An Introduction Part II – Object LifeCycle, Autowiring, Internationalization(i18n)" href="http://technicalmumbojumbo.wordpress.com/2011/04/13/spring-framework-an-introduction-part-ii-object-lifecycle-autowiring-internationalizationi18n/" target="_blank">object lifecycle, autowiring and internationalization</a>. This post will cover Aspect Oriented Programming(AOP).</p>
<p><span id="more-491"></span></p>
<p>All IT applications are developed with the end goal of addressing concern(s) or business requirement(s). Object oriented programming paradigm assists modularization of concerns. Modularization facilitates reuse and improves code maintenability. However there are certain concerns like security, transactions, logging, auditing etc which pervade the entire system and are essentially cross cutting. Implementing these concerns in the conventional fashion i.e. modular coding will be lead to code scattering all over the application. We need a completely different programming paradigm to address this issue. <strong>Aspect Oriented Programming (AOP)</strong> is the very paradigm for implementing such cross cutting concerns.</p>
<p>Before we begin on AOP and the breadth of support Spring framework provides to AOP, let us first familiarize ourselves with some terms commonly associated with AOP.</p>
<p><strong>Advice</strong>: Advice is the additional code which is applied to existing code base. For example, in case we are interested in logging the processing time for every method execution, we need to add code at the start and completion of method execution, this additional code is advice.</p>
<p><strong>Join point</strong>: Join point represents a particular point during the program execution. Examples of join points are method call, method execution, object instantiation, constructor execution, field references, exception handler etc. Note Spring AOP only supports method execution, for other join points use AspectJ.</p>
<p><strong>Pointcut</strong>: Pointcut is the point of execution when the advice needs to be applied to a join point because the join point satisfies a certain condition for e.g. method name adheres to getter method format etc. For example consider we have a class with methods named getName, getPhoneNumber and calculate. Here all the three method executions represent join points; on the other hand we can define a pointcut for method calculate and apply advice for the same.</p>
<p><strong>Aspect</strong>: The combination of advice and pointcut is an aspect.</p>
<p><strong>Introduction</strong>: Introduction is addition of new methods or fields.</p>
<p><strong>Target Object</strong>: Object which is adviced by one or more aspects. It is also called advised object.</p>
<p><strong>AOP Proxy</strong>: A proxy created by AOP framework to implement advised contracts. In Spring AOP proxy is implemented using either JDK dynamic proxy or CGLIB proxy. If the target object implements an interface(s) that exposes the required methods, Spring will use the JDK’s java.lang.reflect.Proxy class. This class allows Spring to dynamically generate a new class that implements the necessary interfaces, weave in any advice, and proxy any calls to these interfaces to the target class. If the target class does not implement an interface, Spring uses the CGLIB library to generate a subclass for the target class. When creating this subclass, Spring weaves in advice and delegates calls to the subclass to the target class.</p>
<p><strong>Weaving</strong>: Incorporation of aspects in the code base is called weaving. Weaving can be done either at compile time, class load time or runtime. Spring AOP does weaving at runtime.</p>
<p><strong>Spring AOP</strong> classifies advice into the following categories:</p>
<p><strong>Before advice</strong>: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).</p>
<p><strong>After returning advice</strong>: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.</p>
<p><strong>After throwing advice</strong>: Advice to be executed if a method exits by throwing an exception.</p>
<p><strong>After (finally) advice</strong>: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).</p>
<p><strong>Around advice</strong>: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.</p>
<p>Enough of theory let&#8217;s start coding. Spring Framework supports AOP using its own Spring AOP framework or the versatile AspectJ framework. The following tutorial intends use both options in turn highlighting the similarities and differences between the two.</p>
<p>First let&#8217;s look at AspectJ. To demonstrate the AOP capabilities I create simple Java class SampleObject with suitable attributes and methods. Here&#8217;s the source code of SampleObject class.</p>
<p><pre class="brush: java;">
package com.spring.aop.aspectj;

public class SampleObject {

	public SampleObject() {

	}

	public static void test(){

	}

	public String run() {
		return &quot;First Run&quot;;
	}

	public String run(String input){
		return input;
	}

	public void exceptionHandling(){
		throw new RuntimeException(&quot;Exception Handling&quot;);
	}

	public void exceptionHandling(Object o){
		throw new RuntimeException(&quot;Exception Handling Object&quot;);
	}

	public void handle(String input){
	}

	public void handle(Integer input){
	}

	public void handle(Object input){
	}

	public void doProcess(Object input) {

	}
}
</pre></p>
<p>To enhance SampleObject with AOP capabilities we define an additional Java class AOPObject. In this class we define pointcuts and advices; definition of pointcuts is done using annotations. Refer the following source code for AOPObject. An additional utility class AOPUtils&#8217;s source code is provided below.</p>
<p><pre class="brush: java;">
package com.spring.aop.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import com.spring.aop.util.AOPUtils;

@Aspect
public class AOPObject {

	public AOPObject() {
		
	}

	public AOPObject(String input) {
		
	}

	@Pointcut(&quot;execution(* *.run(..))&quot;)
	public String marker() {
		return &quot;&quot;;
	}
	
	@Pointcut(&quot;execution(* *.run(String))&quot;)
	public void markerNew() {
		
	}

	@Pointcut(&quot;execution(* *.exceptionHandling())&quot;)
	public void markerForException() {
		
	}
	
	@Before(&quot;marker(),markerNew()&quot;)
	public void log(JoinPoint joinPoint) {
		System.out.println(&quot;+++++++++++++++++++++++++++++++++++++++&quot;);
		System.out.println(&quot;Before invoking the method: &quot; + joinPoint.toShortString());
		Object[] args = joinPoint.getArgs();
		if (args != null &amp;&amp; args.length &gt; 0) {
			System.out.println(&quot;Name: &quot; + args[0]);
		}
		Signature signature = joinPoint.getSignature();
		System.out.println(&quot;Information: &quot; + signature.toLongString());
		System.out.println(&quot;+++++++++++++++++++++++++++++++++++++++&quot;);
	}
	
	@AfterReturning(value=&quot;marker(), markerNew()&quot;,
		returning=&quot;val&quot;)
	public void logReturn(String val) {
		System.out.println(&quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;);
		System.out.println(&quot;After returning from the run method.&quot;);
		System.out.println(&quot;Ret Val: &quot; + val);
		System.out.println(&quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;);
		
	}

	@AfterThrowing(value=&quot;markerForException()&quot;,
			throwing=&quot;t&quot;)
	public void logThrow(Throwable t) {
		System.out.println(&quot;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&quot;);
		System.out.println(&quot;Processing exceptional condition during run method execution.&quot;);
		System.out.println(&quot;Exception thrown is: &quot; + t);
		System.out.println(&quot;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&quot;);
	}
	
	@After(&quot;marker(), markerNew()&quot;)
	public void logFinally(JoinPoint joinPoint) {
		System.out.println(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;);
		AOPUtils.displayJoinPointDetails(&quot;Logging finally irrespective of method execution.&quot;, joinPoint);
		System.out.println(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;);
	}
	
	@Around(&quot;markerNew()&quot;)
	public void logAround(ProceedingJoinPoint joinPoint) {
		System.out.println(&quot;#####Before method invokation.#####: &quot; + joinPoint.toShortString());
		try {
			joinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println(&quot;#####After method invokation.#####: &quot; + joinPoint.toShortString());
	}
	
	@Before(&quot;within(com.spring.aop.aspectj.Test)&quot;)
	public void withinMarker(JoinPoint joinPoint) {
		System.out.println(&quot;?????????????????????&quot;);
		System.out.println(&quot;Within Pointcut designator for Test class.&quot;);
		AOPUtils.displayJoinPointDetails(&quot;*.Test&quot;, joinPoint);
		System.out.println(&quot;?????????????????????&quot;);
	}
	
	@Before(&quot;this(com.spring.aop.aspectj.Test) &amp;&amp; execution(* doProcess(..))&quot;)
	void thisMarker() {
		System.out.println(&quot;@@@@@@@@@@@@@@@@@@@&quot;);
		System.out.println(&quot;doProcess method of Test class is invoked.&quot;);
		System.out.println(&quot;@@@@@@@@@@@@@@@@@@@&quot;);
	}
	
	@Before(&quot;args(java.lang.String))&quot;)
	void argsMarker(JoinPoint joinPoint) {
		System.out.println(&quot;[][][][][][][][][][][][][]&quot;);
		AOPUtils.displayJoinPointDetails(&quot;Following Method with String argument invoked&quot;,
				joinPoint);
		System.out.println(&quot;[][][][][][][][][][][][][]&quot;);
	}
	
	@Before(&quot;this(com.spring.aop.aspectj.CollectionContainer))&quot;)
	void thisContainerMarker() {
		System.out.println(&quot;|||||||||||||||||||||||||||||||||&quot;);
		System.out.println(&quot;'this' pointcut is invoked.&quot;);
		System.out.println(&quot;|||||||||||||||||||||||||||||||||&quot;);
	}
	
	@Before(&quot;target(com.spring.aop.aspectj.CollectionContainer))&quot;)
	void targetContainerMarker() {
		System.out.println(&quot;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;);
		System.out.println(&quot;'target' pointcut is invoked.&quot;);
		System.out.println(&quot;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;);
	}

}
</pre></p>
<p><pre class="brush: java;">
package com.spring.aop.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;

public class AOPUtils {
	
	public static void displayJoinPointDetails(String appendMessage, JoinPoint joinPoint) {
		Signature sign = joinPoint.getSignature();
		System.out.println(appendMessage + &quot; : &quot; + sign.toLongString());
	}

}
</pre></p>
<p>The first thing to notice is at line number 16 of AOPObject. To specify that this class provides AOP capabilities, the class has been annotated with @Aspect annotation. Let us know move on to the pointcut declarations. Refer line numbers 27, 32 and 37.</p>
<p><pre class="brush: java;">

	@Pointcut(&quot;execution(* *.run(..))&quot;)
	public String marker() {
		return &quot;&quot;;
	}

	@Pointcut(&quot;execution(* *.run(String))&quot;)
	public void markerNew() {
		
	}

	@Pointcut(&quot;execution(* *.exceptionHandling())&quot;)
	public void markerForException() {
		
	}
</pre></p>
<p>We have declared three methods namely marker, markerNew and markerForException.</p>
<p>Each method is annotated with a specific pointcut expression. That expression defines a constraint or limits the join points on which the advice will be applied. </p>
<p>For example consider the first expression &#8216;execution(* *.run(..))&#8217;. The expression states that this pointcut<br />
applies on the execution of all classes whose methods are named run and the point cut applies irrespective of the return type and the number of method arguments. The * immediately following the execution open bracket denotes return type, the subsequent * denotes all classes. The .. within the brackets denotes method with any argument(s). </p>
<p>In the second example, we are specifically mentioning that the pointcut selects all classes whose method name is run and accept String as an argument. The third example we are interested in all classes whose method name is exceptionHandling and accepts no arguments.</p>
<p>The method implementation defined below the pointcut has no significance beyond being a placeholder for the AOP implementation. These methods can have return type and can use the default/friendly access modifier without compromising on the AOP functionality.Now that we have identified the point cut let&#8217;s look at how we can apply advice on that point cut. For that look at the following implementation within the AOPObject source code, refer the code between the line number 42 and line number 89.</p>
<p><pre class="brush: java;">
	@Before(&quot;marker(),markerNew()&quot;)
	public void log(JoinPoint joinPoint) {
		System.out.println(&quot;+++++++++++++++++++++++++++++++++++++++&quot;);
		System.out.println(&quot;Before invoking the method: &quot; + joinPoint.toShortString());
		Object[] args = joinPoint.getArgs();
		if (args != null &amp;&amp; args.length &gt; 0) {
			System.out.println(&quot;Name: &quot; + args[0]);
		}
		Signature signature = joinPoint.getSignature();
		System.out.println(&quot;Information: &quot; + signature.toLongString());
		System.out.println(&quot;+++++++++++++++++++++++++++++++++++++++&quot;);
	}
	
	@AfterReturning(value=&quot;marker(), markerNew()&quot;,
		returning=&quot;val&quot;)
	public void logReturn(String val) {
		System.out.println(&quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;);
		System.out.println(&quot;After returning from the run method.&quot;);
		System.out.println(&quot;Ret Val: &quot; + val);
		System.out.println(&quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&quot;);
		
	}

	@AfterThrowing(value=&quot;markerForException()&quot;,
			throwing=&quot;t&quot;)
	public void logThrow(Throwable t) {
		System.out.println(&quot;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&quot;);
		System.out.println(&quot;Processing exceptional condition during run method execution.&quot;);
		System.out.println(&quot;Exception thrown is: &quot; + t);
		System.out.println(&quot;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^&quot;);
	}
	
	@After(&quot;marker(), markerNew()&quot;)
	public void logFinally(JoinPoint joinPoint) {
		System.out.println(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;);
		AOPUtils.displayJoinPointDetails(&quot;Logging finally irrespective of method execution.&quot;, joinPoint);
		System.out.println(&quot;!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&quot;);
	}
	
	@Around(&quot;markerNew()&quot;)
	public void logAround(ProceedingJoinPoint joinPoint) {
		System.out.println(&quot;#####Before method invokation.#####: &quot; + joinPoint.toShortString());
		try {
			joinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println(&quot;#####After method invokation.#####: &quot; + joinPoint.toShortString());
	}
</pre></p>
<p>We have earlier discussed the different advice types, we will apply them here to create the aspect. So let&#8217;s look at the first method log. The point cuts declared using the marker and markerNew method are combined with the before advice type in the log method. Refer the log method annotation.</p>
<p><pre class="brush: java;">
@Before(&quot;marker(),markerNew()&quot;)
</pre></p>
<p>What this does is that before invocation of the methods defined by marker and markerNew point cuts, the<br />
implementation of log method will execute. The log method can have no arguments or can have a single argument JoinPoint. Using the JoinPoint argument provides the developer with the ability to gathering metadata details around the method on whom the AOP is applied. In my current implementation I have highlighted some areas of information available like method arguments, method signature etc.</p>
<p>A method execution can return a void or a return value. In case developers are interested in intercepting the method invocation post execution, they can use the AfterReturning advice type. Refer the following code:</p>
<p><pre class="brush: java;">
   	@AfterReturning(value=&quot;marker(), markerNew()&quot;,
		returning=&quot;val&quot;)
	public void logReturn(String val) {
		System.out.println(&quot;After returning from the run method.&quot;);
		System.out.println(&quot;Ret Val: &quot; + val);
		
	}
</pre></p>
<p>In the annotation we use the value attribute to reference the pointcut and the returning attribute to provide a name for the return value. The method implementation uses the same return value name &#8216;val&#8217; along with the appropriate class type.</p>
<p>In rare occasions the method implementation throw exceptions. In case developers need to intercept these<br />
exceptions, they can use the AfterThrowing advice type. Refer line number  of the AOPObject source. Ready handle to the thrown exception is provided via the throwing attribute.   </p>
<p><pre class="brush: java;"> 
	@AfterThrowing(value=&quot;markerForException()&quot;,
			throwing=&quot;t&quot;)
	public void logThrow(Throwable t) {
		System.out.println(&quot;Processing exceptional condition during run method execution.&quot;);
		System.out.println(&quot;Exception thrown is: &quot; + t);
	}

</pre></p>
<p>Use the After advice type to do some advice processing during the finally block code run. Here&#8217;s the implementation.</p>
<p><pre class="brush: java;">
	@After(&quot;marker(), markerNew()&quot;)
	public void logFinally() {
		System.out.println(&quot;Logging finally irrespective of method execution.&quot;);
	}
 
</pre></p>
<p>Lastly developers might be interested in getting information or implementing some aspect encompassing the method execution i.e. before and after, they can use the Around advice type. Refer the sample implementation in AOPObject line number 82.</p>
<p><pre class="brush: java;">
	@Around(&quot;markerNew()&quot;)
	public void logAround(ProceedingJoinPoint joinPoint) {
		System.out.println(&quot;Before method invokation.&quot;);
		try {
			joinPoint.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println(&quot;After method invokation.&quot;);
	}
</pre></p>
<p>The source code joinPoint.proceed in line number  in the source code above controls the execution of method. The developer is free to write custom program before and after this code. Unlike using the JoinPoint class we are using ProceedingJoinPoint class which provides access to the proceed method.</p>
<p>To understand all that has been explained so far let&#8217;s create a test class AOPTest1. The source code of the class is as below:</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.aop.aspectj.SampleObject;

public class AOPTest1 {

	public static void main(String[] args) {
				
		ConfigurableApplicationContext ctx 
			= new ClassPathXmlApplicationContext (new String[] {&quot;aop1.xml&quot;});

		SampleObject obj = (SampleObject)ctx.getBean(&quot;obj&quot;);
		System.out.println(&quot;{}{}{}{}{}{}{}{}{}{}{}{}{}{}&quot;);
		obj.run();
		System.out.println(&quot;{}{}{}{}{}{}{}{}{}{}{}{}{}{}&quot;);
		obj.run(&quot;Testing....&quot;);
		System.out.println(&quot;{}{}{}{}{}{}{}{}{}{}{}{}{}{}&quot;);
		obj.exceptionHandling();
		System.out.println(&quot;{}{}{}{}{}{}{}{}{}{}{}{}{}{}&quot;);
	}
}
</pre></p>
<p>Here&#8217;s the Spring configuration file.</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd&quot;&gt;

	&lt;bean id=&quot;obj&quot; class=&quot;com.spring.aop.aspectj.SampleObject&quot; /&gt;
	&lt;bean id=&quot;aopObj&quot; class=&quot;com.spring.aop.aspectj.AOPObject&quot; /&gt;
	
	&lt;aop:aspectj-autoproxy /&gt;		
&lt;/beans&gt;
</pre></p>
<p>Running the test class generates the following output:</p>
<p><pre class="brush: plain;">
{}{}{}{}{}{}{}{}{}{}{}{}{}{}
+++++++++++++++++++++++++++++++++++++++
Before invoking the method: execution(SampleObject.run())
Information: public java.lang.String com.spring.aop.aspectj.SampleObject.run()
+++++++++++++++++++++++++++++++++++++++
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
After returning from the run method.
Ret Val: First Run
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Logging finally irrespective of method execution. : public java.lang.String 

com.spring.aop.aspectj.SampleObject.run()
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{}{}{}{}{}{}{}{}{}{}{}{}{}{}
#####Before method invokation.#####: execution(SampleObject.run(..))
[][][][][][][][][][][][][]
Following Method with String argument invoked : public java.lang.String com.spring.aop.aspectj.SampleObject.run
(java.lang.String)
[][][][][][][][][][][][][]
+++++++++++++++++++++++++++++++++++++++
Before invoking the method: execution(SampleObject.run(..))
Name: Testing....
Information: public java.lang.String com.spring.aop.aspectj.SampleObject.run(java.lang.String)
+++++++++++++++++++++++++++++++++++++++
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
After returning from the run method.
Ret Val: Testing....
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Logging finally irrespective of method execution. : public java.lang.String 
com.spring.aop.aspectj.SampleObject.run(java.lang.String)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#####After method invokation.#####: execution(SampleObject.run(..))
{}{}{}{}{}{}{}{}{}{}{}{}{}{}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Processing exceptional condition during run method execution.
Exception thrown is: java.lang.RuntimeException: Exception Handling
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Exception in thread &quot;main&quot; java.lang.RuntimeException: Exception Handling
	at com.spring.aop.aspectj.SampleObject.exceptionHandling(SampleObject.java:22)
	at com.spring.aop.aspectj.SampleObject$$FastClassByCGLIB$$6d2e8fc5.invoke(&lt;generated&gt;)
	at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
	at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint
(Cglib2AopProxy.java:688)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:150)
	at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke
(ExposeInvocationInterceptor.java:89)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept
(Cglib2AopProxy.java:621)
	at com.spring.aop.aspectj.SampleObject$$EnhancerByCGLIB$$e056b02c.exceptionHandling(&lt;generated&gt;)
	at com.spring.test.AOPTest1.main(AOPTest1.java:21)
</pre></p>
<p>Only the relevant logging statements have been retained. Let&#8217;s break the output into individual runs.</p>
<p>First let&#8217;s look at the output for the following section of the test code:</p>
<p><pre class="brush: java;">
		obj.run();
</pre></p>
<p>The output generated was </p>
<p><pre class="brush: plain;">
+++++++++++++++++++++++++++++++++++++++
Before invoking the method: execution(SampleObject.run())
Information: public java.lang.String com.spring.aop.aspectj.SampleObject.run()
+++++++++++++++++++++++++++++++++++++++
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
After returning from the run method.
Ret Val: First Run
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Logging finally irrespective of method execution. : public java.lang.String 
com.spring.aop.aspectj.SampleObject.run()
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
</pre></p>
<p>The first method to get invoked was the advice associated with the marker point cut. The next advice to get<br />
executed is AfterReturning. And the last advice to get executed is the After advice.<br />
Now let&#8217;s look at the second portion of the test code:</p>
<p><pre class="brush: java;">
obj.run(&quot;Testing....&quot;);
</pre><br />
The output generated for this code was:</p>
<p><pre class="brush: plain;">
#####Before method invokation.#####: execution(SampleObject.run(..))
[][][][][][][][][][][][][]
Following Method with String argument invoked : public java.lang.String com.spring.aop.aspectj.SampleObject.run
(java.lang.String)
[][][][][][][][][][][][][]
+++++++++++++++++++++++++++++++++++++++
Before invoking the method: execution(SampleObject.run(..))
Name: Testing....
Information: public java.lang.String com.spring.aop.aspectj.SampleObject.run(java.lang.String)
+++++++++++++++++++++++++++++++++++++++
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
After returning from the run method.
Ret Val: Testing....
&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Logging finally irrespective of method execution. : public java.lang.String 
com.spring.aop.aspectj.SampleObject.run(java.lang.String)
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#####After method invokation.#####: execution(SampleObject.run(..))
</pre></p>
<p>The first advice to be processed is Around advice. The logging statement within the logAround method is printed. </p>
<p>After invocation of the proceed method on the JoinPoint, the next advice to be processed is the args pointcut designator. We will cover this later on in the post. The next advice to be processed is the Before advice associated with the log method. On completion of the method execution the AfterReturning advice is triggered and the last advice to run is After advice. </p>
<p>Now let&#8217;s look at the output generated by running the following code:</p>
<p><pre class="brush: java;">
	obj.exceptionHandling();
</pre></p>
<p>The output generated is follows:</p>
<p><pre class="brush: plain;">
{}{}{}{}{}{}{}{}{}{}{}{}{}{}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Processing exceptional condition during run method execution.
Exception thrown is: java.lang.RuntimeException: Exception Handling
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Exception in thread &quot;main&quot; java.lang.RuntimeException: Exception Handling
	at com.spring.aop.aspectj.SampleObject.exceptionHandling(SampleObject.java:22)
	at com.spring.aop.aspectj.SampleObject$$FastClassByCGLIB$$6d2e8fc5.invoke(&lt;generated&gt;)
	at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
	at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint
(Cglib2AopProxy.java:688)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:150)
	at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke
(ExposeInvocationInterceptor.java:89)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed
(ReflectiveMethodInvocation.java:172)
	at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept
(Cglib2AopProxy.java:621)
	at com.spring.aop.aspectj.SampleObject$$EnhancerByCGLIB$$3ef22468.exceptionHandling(&lt;generated&gt;)
	at com.spring.test.AOPTest1.main(AOPTest1.java:21)
</pre></p>
<p>The AfterThrowing advice is invoked and no further processing is taking place due to the RuntimeException.<br />
The examples used so far maintained a clear demarcation between the pointcut declaration and advice. However the framework does provide an alternative to combining the two together. Refer the following piece of code in the AOPObject class at line number 92.</p>
<p><pre class="brush: java;">
	@Before(&quot;within(com.spring.aop.aspectj.Test)&quot;)
	public void withinMarker(JoinPoint joinPoint) {
		System.out.println(&quot;Within Pointcut designator for Test class.&quot;);
		AOPUtils.displayJoinPointDetails(&quot;*.Test&quot;, joinPoint);
	}
</pre></p>
<p>Here we are applying the before advice type and using the point cut designator within to state that any method executions within the Test class will be intercepted. The pointcut &#8216;within(com.spring.aop.aspectj.Test)&#8217; is integrated with the advice annotation. For your ready reference I am enclosing the source code of AOPTest2.</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.aop.aspectj.Test;

public class AOPTest2 {

	public static void main(String[] args) {
				
		ConfigurableApplicationContext ctx 
			= new ClassPathXmlApplicationContext (new String[] {&quot;aop2.xml&quot;});
		Test test = (Test)ctx.getBean(&quot;testObj&quot;);
		System.out.println(&quot;=====================================&quot;);
		test.invoke();
		System.out.println(&quot;=====================================&quot;);
		test.doProcess(&quot;&quot;);
		System.out.println(&quot;=====================================&quot;);
		
	}
}
</pre></p>
<p>aop2.xml source<br />
<pre class="brush: xml; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd&quot;&gt;

	&lt;bean id=&quot;aopObj&quot; class=&quot;com.spring.aop.aspectj.AOPObject&quot; /&gt;
	&lt;bean id=&quot;testObj&quot; class=&quot;com.spring.aop.aspectj.Test&quot; /&gt;

	&lt;aop:aspectj-autoproxy /&gt;		
&lt;/beans&gt;
</pre></p>
<p>Let&#8217;s look at the other pointcut designators like this, target and args. Refer the source code within the line<br />
numbers 100 and 127.</p>
<p><pre class="brush: java;">
	@Before(&quot;this(com.spring.aop.aspectj.Test) &amp;&amp; execution(* doProcess(..))&quot;)
	void thisMarker() {
		System.out.println(&quot;doProcess method of Test class is invoked.&quot;);
	}
	
	@Before(&quot;args(java.lang.String))&quot;)
	void argsMarker(JoinPoint joinPoint) {
		AOPUtils.displayJoinPointDetails(&quot;Following Method with String argument invoked&quot;,
				joinPoint);
	}
</pre></p>
<p>The &#8216;this&#8217; designator is used in the context of the bean. If the bean type/class matches the name specified in the this expression, the pointcut condition is considered satisfied. Note that this checks the compile time type of the bean and not the runtime type. To validate with reference to runtime type you will need to use the &#8216;target&#8217; designator.</p>
<p>The test class AOPTest2 run is displayed below:</p>
<p><pre class="brush: plain;">
=====================================
?????????????????????
Within Pointcut designator for Test class.
*.Test : public void com.spring.aop.aspectj.Test.invoke()
?????????????????????
=====================================
?????????????????????
Within Pointcut designator for Test class.
*.Test : public void com.spring.aop.aspectj.Test.doProcess(java.lang.String)
?????????????????????
@@@@@@@@@@@@@@@@@@@
doProcess method of Test class is invoked.
@@@@@@@@@@@@@@@@@@@
[][][][][][][][][][][][][]
Following Method with String argument invoked : public void com.spring.aop.aspectj.Test.doProcess(java.lang.String)
[][][][][][][][][][][][][]
=====================================
</pre></p>
<p>The output clearly shows that the invocation of invoke method causes the withinMarker method&#8217;s before advice to be triggered. Invocation of doProcess method triggers the withinMarker method&#8217;s advice is triggered for Test class and  the thisMarker method associated with advice associated with Test class and execution of doProcess method is triggered.</p>
<p>Now let&#8217;s look at the following piece of code within AOPObject.</p>
<p><pre class="brush: java;">
	@Before(&quot;args(java.lang.String))&quot;)
	void argsMarker(JoinPoint joinPoint) {
		System.out.println(&quot;[][][][][][][][][][][][][]&quot;);
		AOPUtils.displayJoinPointDetails(&quot;Following Method with String argument invoked&quot;,
				joinPoint);
		System.out.println(&quot;[][][][][][][][][][][][][]&quot;);
	}
</pre></p>
<p>The args pointcut designator checks the method arguments of all invoked methods which match to the specified method signature. The invocation of doProcess method of Test class triggers the advice associated with argsMarker method.</p>
<p>There is another pointcut designator called target which also accepts a class as its processing parameter. Let&#8217;s try and understand the difference between this and target pointcut designator. The basic difference between the two is that this designator evaluates the compile time class reference while target evaluates the runtime class reference. To understand this let&#8217;s use an example. Create a class Container and CollectionContainer. The source code of the two classes is shown below:</p>
<p><pre class="brush: java;">
package com.spring.aop.aspectj;

public class Container {

	public void add(Object o){
		
	}
	
	public void remove(Object o){
		
	}		
}
</pre></p>
<p><pre class="brush: java;">
package com.spring.aop.aspectj;


public class CollectionContainer extends Container {

}
</pre></p>
<p>The CollectionContainer bean is defined in the aop3.xml configuration file. Here&#8217;s the xml details.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd&quot;&gt;
	
	&lt;bean id=&quot;obj&quot; class=&quot;com.spring.aop.aspectj.SampleObject&quot; /&gt;
	&lt;bean id=&quot;aopObj&quot; class=&quot;com.spring.aop.aspectj.AOPObject&quot; /&gt;
	&lt;bean id=&quot;container&quot; class=&quot;com.spring.aop.aspectj.CollectionContainer&quot; /&gt;
	
	&lt;aop:aspectj-autoproxy /&gt;		
&lt;/beans&gt;
</pre></p>
<p>Here&#8217;s the test code AOP3Test:</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.aop.aspectj.Container;
import com.spring.aop.aspectj.SampleObject;

public class AOPTest3 {

	public static void main(String[] args) {
				
		ConfigurableApplicationContext ctx 
			= new ClassPathXmlApplicationContext (new String[] {&quot;aop3.xml&quot;});
		
		System.out.println(&quot;============================ Container&quot;);
		Container container = (Container)ctx.getBean(&quot;container&quot;);
		container.add(null);

		SampleObject obj = (SampleObject)ctx.getBean(&quot;obj&quot;);
		
		System.out.println(&quot;============================ handle(String)&quot;);
		obj.handle(&quot;&quot;);

		System.out.println(&quot;============================ handle(Object)&quot;);
		obj.handle(new Object());

		System.out.println(&quot;============================ doProcess(Object)&quot;);
		obj.doProcess(new Object());

		System.out.println(&quot;=============================== doProcess(String)&quot;);
		obj.doProcess(&quot;&quot;);
		
		System.out.println(&quot;============================ handle(Integer)&quot;);
		obj.handle(Integer.valueOf(1));
		
	}
}
</pre></p>
<p>We have created two new methods within the AOPObject class for Container related classes. The two methods are thisContainerMarker and targetContainerMarker. This first one uses &#8216;this&#8217; designator for CollectionContainer and second one uses &#8216;target&#8217; for CollectionContainer.</p>
<p>On running the test class let&#8217;s look at what the output the following piece of code generates:</p>
<p><pre class="brush: java;">
		Container container = (Container)ctx.getBean(&quot;container&quot;);
		container.add(null);
</pre><br />
The ouput is</p>
<p><pre class="brush: plain;">
============================ Container
&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
'target' pointcut is invoked.
&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
</pre></p>
<p>Clearly only the target pointcut is invoked, this is because the class reference used in the test code is Container and the runtime reference is CollectionContainer. The subsequent test code in AOP3Test tests whether the args designator uses runtime or static reference for processing. The output generated is as follows:</p>
<p><pre class="brush: plain; wrap-lines: false;">
============================ handle(String)
[][][][][][][][][][][][][]
Following Method with String argument invoked : public void com.spring.aop.aspectj.SampleObject.handle
(java.lang.String)
[][][][][][][][][][][][][]
============================ handle(Object)
============================ doProcess(Object)
=============================== doProcess(String)
[][][][][][][][][][][][][]
Following Method with String argument invoked : public void com.spring.aop.aspectj.SampleObject.doProcess
(java.lang.Object)
[][][][][][][][][][][][][]
============================ handle(Integer)
</pre></p>
<p>Clearly args designator works on the runtime parameter. It processes the method handle(java.lang.String) as a match as long as the runtime method argument is String. The same applies for doProcess even thought the method signature accepts Object. If the runtime argument is String it treats the method as a match.</p>
<p>Upto now we have looked at AspectJ capabilities available via the Spring Framework. AspectJ as a standalone AOP framework has far greater capabilities, however Spring has limited itself to implementing the most commonly used ones. We now move on to looking at what Spring AOP has to offer on its own.</p>
<p>Spring AOP provides a more simplified methodology of defining advice and pointcuts.Spring AOP provides an interface for each advice type. Here are the Spring AOP interfaces: MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice, AfterAdvice and MethodInterceptor. Except for MethodInterceptor the rest of the interfaces names match the advice type. The MethodInterceptor replicates the Around advice. To gain a better understanding let&#8217;s implement a Java class AOPDiffObject. Here&#8217;s the source code for AOPDiffObject.</p>
<p><pre class="brush: java;">
package com.spring.aop.spring;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterAdvice;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class AOPDiffObject implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice,
		MethodInterceptor {

	public AOPDiffObject() {
		
	}

	//Implementation of MethodBeforeAdvice interface
	@Override
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		System.out.println(&quot;########## Before Advice Start ###########&quot;);
		System.out.println(&quot;Diff:Before invoking the run method.&quot;);
		if (args != null &amp;&amp; args.length &gt; 0) {
			System.out.println(&quot;Diff:Argument Value: &quot; + args[0]);
		} else {
			System.out.println(&quot;Diff:Argument : None.&quot;);
		}
		System.out.println(&quot;########## Before Advice End ###########&quot;);
	}

	//Implementation of AfterReturningAdvice interface
	@Override
	public void afterReturning(Object returnVal, Method method, Object[] args,
			Object target) throws Throwable {
		System.out.println(&quot;########## After Returning Advice Start ###########&quot;);
		System.out.println(&quot;Diff:After returning from the run method.&quot;);
		System.out.println(&quot;Diff:Ret Val: &quot; + returnVal);		
		System.out.println(&quot;########## After Returning Advice End ###########&quot;);
	}

	//ThrowsAdvice interface does define any methods but implementations are expected to implement
	//afterThrowing method as shown below
	public void afterThrowing(Throwable throwable) throws Throwable {
		System.out.println(&quot;########## After Throwing Advice Start ###########&quot;);
		System.out.println(&quot;Diff:Exception thrown.&quot;);
		System.out.println(throwable);
		System.out.println(&quot;########## After Throwing Advice End ###########&quot;);
	}

	//Implementation of MethodInterceptor interface
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		System.out.println(&quot;########## Around Advice Start ###########&quot;);
		System.out.println(&quot;Diff:Before method invokation.&quot;);
		Object retValue = null;
		try {
			retValue = invocation.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		System.out.println(&quot;Diff:After method invokation.&quot;);
		System.out.println(&quot;########## Around Advice End ###########&quot;);
		return retValue;
	}	
}
</pre></p>
<p>The before method realization implements the before Advice, similarly afterReturning method realization implements the After returning advice, afterThrowing method realization implements the After throwing advice and invoke method realization implements the Around advice. I was not able to find an implementation for After finally advice in Spring AOP.</p>
<p>Here&#8217;s the Spring configuration file.</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd&quot;&gt;

	&lt;bean id=&quot;obj&quot; class=&quot;com.spring.aop.aspectj.SampleObject&quot; /&gt;
	
	&lt;bean id=&quot;aopObject&quot; class=&quot;com.spring.aop.spring.AOPDiffObject&quot; /&gt;
	&lt;bean id=&quot;advisor&quot; class=&quot;org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor&quot;&gt;
		&lt;property name=&quot;advice&quot; ref=&quot;aopObject&quot; /&gt;
		&lt;property name=&quot;expression&quot; value=&quot;execution(* *.run(..))&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;advisorTwo&quot; class=&quot;org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor&quot;&gt;
		&lt;property name=&quot;advice&quot; ref=&quot;aopObject&quot; /&gt;
		&lt;property name=&quot;expression&quot; value=&quot;execution(* *.run(String))&quot; /&gt;
	&lt;/bean&gt;
	
	&lt;aop:aspectj-autoproxy /&gt;		
&lt;/beans&gt;
</pre></p>
<p>In the configuration xml refer the lines 16 and 20. Here we are defining the association between pointcuts and advices. These are used for implementing aspects in the implementation code. Spring AOP provides three methods for defining pointcut expressions. Perl regex, java regex and AspectJ. I am using AspectJ for its richness and also to maintain ease of mapping between understanding the AspectJ and Spring AOP implementation.</p>
<p>For academic reasons here&#8217;s the test class and output of the test run</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.aop.aspectj.Container;
import com.spring.aop.aspectj.SampleObject;
import com.spring.aop.aspectj.Test;

public class AOPTest4 {

	public static void main(String[] args) {
				
		ConfigurableApplicationContext ctx 
			= new ClassPathXmlApplicationContext (new String[] {&quot;aop4.xml&quot;});
		SampleObject obj = (SampleObject)ctx.getBean(&quot;obj&quot;);
		obj.run();
		System.out.println(&quot;%%%%%%%%%%%%%%%%%%%%%%%%%%%%&quot;);
		obj.run(&quot;Testing....&quot;);
		
	}
}
</pre></p>
<p><pre class="brush: plain;">
19 Apr, 2011 1:53:37 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32fb4f: startup date [Tue Apr 19 13:53:37 IST 2011]; root of context hierarchy
19 Apr, 2011 1:53:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [aop4.xml]
19 Apr, 2011 1:53:37 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@544ec1: 
defining beans [obj,aopObject,advisor,advisorTwo,org.springframework.aop.config.internalAutoProxyCreator]; root of factory hierarchy
########## Around Advice Start ###########
Diff:Before method invokation.
########## Before Advice Start ###########
Diff:Before invoking the run method.
Diff:Argument : None.
########## Before Advice End ###########
########## After Returning Advice Start ###########
Diff:After returning from the run method.
Diff:Ret Val: First Run
########## After Returning Advice End ###########
Diff:After method invokation.
########## Around Advice End ###########
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
########## Around Advice Start ###########
Diff:Before method invokation.
########## Before Advice Start ###########
Diff:Before invoking the run method.
Diff:Argument Value: Testing....
########## Before Advice End ###########
########## Around Advice Start ###########
Diff:Before method invokation.
########## Before Advice Start ###########
Diff:Before invoking the run method.
Diff:Argument Value: Testing....
########## Before Advice End ###########
########## After Returning Advice Start ###########
Diff:After returning from the run method.
Diff:Ret Val: Testing....
########## After Returning Advice End ###########
Diff:After method invokation.
########## Around Advice End ###########
########## After Returning Advice Start ###########
Diff:After returning from the run method.
Diff:Ret Val: Testing....
########## After Returning Advice End ###########
Diff:After method invokation.
########## Around Advice End ###########
</pre></p>
<p>That&#8217;s all from my end at the moment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/491/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/491/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/491/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=491&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/04/20/spring-framework-an-introduction-part-iii-aspect-oriented-programming/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring Framework An Introduction Part II &#8211; Object LifeCycle, Autowiring, Internationalization(i18n)</title>
		<link>http://technicalmumbojumbo.wordpress.com/2011/04/13/spring-framework-an-introduction-part-ii-object-lifecycle-autowiring-internationalizationi18n/</link>
		<comments>http://technicalmumbojumbo.wordpress.com/2011/04/13/spring-framework-an-introduction-part-ii-object-lifecycle-autowiring-internationalizationi18n/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 06:57:22 +0000</pubDate>
		<dc:creator>Mr. President</dc:creator>
				<category><![CDATA[spring]]></category>
		<category><![CDATA[spring framework]]></category>

		<guid isPermaLink="false">http://technicalmumbojumbo.wordpress.com/?p=477</guid>
		<description><![CDATA[The part one of my post covered the basics of Spring Framework namely dependency injection, bean reuse. This post intends to take a little more deep dive into understanding the inner workings of Spring framework. The Part I tutorial clearly &#8230; <a href="http://technicalmumbojumbo.wordpress.com/2011/04/13/spring-framework-an-introduction-part-ii-object-lifecycle-autowiring-internationalizationi18n/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=477&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The <a title="Spring Framework – An Introduction Part I – Dependency Injection, Bean Reuse" href="http://technicalmumbojumbo.wordpress.com/2011/04/05/spring-framework-introduction-dependency-injection-bean-reuse-part-i/" target="_blank">part one</a> of my post covered the basics of Spring Framework namely dependency injection, bean reuse. This post intends to take a little more deep dive into understanding the inner workings of Spring framework.</p>
<p><span id="more-477"></span></p>
<p>The Part I tutorial clearly explains the significance of the configuration file, how it achieves dependency injection and facilitates bean reuse. Now let&#8217;s look at other aspects of Spring Framework.</p>
<p><strong>Spring Object Lifecycle</strong></p>
<p>Objects created using Spring framework follow their own lifecycle; details of which will be explained hereon. Consider the following spring configuration file bean-lifecycle.xml.</p>
<p><pre class="brush: xml; highlight: [8]; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;
           default-init-method=&quot;init&quot; default-destroy-method=&quot;destroy&quot;&gt;

  	&lt;bean id=&quot;object&quot; class=&quot;com.spring.bean.lifecycle.BeanObject&quot;&gt;
  	&lt;/bean&gt;
	
	&lt;bean id=&quot;specialobject&quot; class=&quot;com.spring.bean.lifecycle.SpecialBeanObject&quot; 
		init-method=&quot;initObject&quot; destroy-method=&quot;destroyObject&quot;&gt;
	&lt;/bean&gt;
		
&lt;/beans&gt;
</pre></p>
<p>Here is the source code for the classes mentioned in the bean-lifecycle.xml file.</p>
<p><pre class="brush: java;">
package com.spring.bean.lifecycle;

public class BeanObject {

	public void init() {
		System.out.println(&quot;Initialize&quot;);
	}

	public void destroy() {
		System.out.println(&quot;Destroy&quot;);
	}
}
</pre></p>
<p><pre class="brush: java;">
package com.spring.bean.lifecycle;

public class SpecialBeanObject {

	public void initObject() {
		System.out.println(&quot;Initialize Object&quot;);
	}

	public void destroyObject() {
		System.out.println(&quot;Destroy Object&quot;);
	}
}
</pre></p>
<p>During an object creation it might be necessary for the developer to initialize the bean properly with default values or undertaking some specific housekeeping activities. Similarly before destroying the bean, the developer might need to clean up. Spring framework facilitates this by allowing definition of default-init-method and default-destroy-method within the beans element, refer line number 8. All beans whose method names matches the specified init or destroy method will participate in this lifecycle event. Alternatively Spring framework allows the definition of init and destroy method at bean level using init-method and destroy-method attribute within bean element, refer line number . To understand this refer the test class below:</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifeCycleTest {

	public static void main(String[] args) {

		ConfigurableApplicationContext ctx
			= new ClassPathXmlApplicationContext (new String[] {&quot;bean-lifecycle.xml&quot;});
		ctx.close();
	}
}
</pre></p>
<p>Note the destroy methods are invoked only if context.close() method is explicitly invoked as a part of the application program.</p>
<p>Spring framework defines a number of interfaces which will be invoked during the object&#8217;s lifecycle. To understand this consider the configuration file spring-bean-lifecycle.xml.</p>
<p><pre class="brush: xml; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;
           default-init-method=&quot;initok&quot; default-destroy-method=&quot;cleanok&quot;&gt;

	&lt;bean id=&quot;bean&quot; class=&quot;com.spring.bean.lifecycle.SpringBeanLifecycle&quot;
		init-method=&quot;initObj&quot; destroy-method=&quot;cleanObj&quot;&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;sample&quot; class=&quot;com.spring.bean.lifecycle.SampleBean&quot;/&gt;		
&lt;/beans&gt;
</pre></p>
<p>The source code of the Java beans configured in the xml is shown below:</p>
<p><pre class="brush: java;">
package com.spring.bean.lifecycle;

public class SampleBean {

}
</pre></p>
<p><pre class="brush: java; wrap-lines: false;">
package com.spring.bean.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class SpringBeanLifecycle implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware,
	InitializingBean, DisposableBean, BeanPostProcessor {

	public void init() {
		System.out.println(&quot;Init bean&quot;);
	}

	public void clean() {
		System.out.println(&quot;Clean bean&quot;);
	}

	public void initObj() {
		System.out.println(&quot;Init bean Object&quot;);
	}

	public void cleanObj() {
		System.out.println(&quot;Clean bean Object&quot;);
	}

	@Override
	public void setBeanName(String name) {
		//Method implementation for BeanNameAware interface
		System.out.println(&quot;Getting bean name: &quot; + name);
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		//Method implementation for BeanClassLoaderAware interface
		System.out.println(&quot;Getting Bean Class loader.&quot;);
	}

	@Override
	public void setBeanFactory(BeanFactory fact) throws BeansException {
		//Method implementation for BeanFactoryAware interface
		System.out.println(&quot;Getting bean factory.&quot;);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//Method implementation for InitializingBean interface
		System.out.println(&quot;Init&quot;);
	}

	@Override
	public void destroy() throws Exception {
		//Method implementation for DisposableBean interface
		System.out.println(&quot;Destory&quot;);
	}

	@Override
	public Object postProcessAfterInitialization(Object arg0, String arg1)
			throws BeansException {
		//Method implementation for BeanPostProcessor interface
		System.out.println(&quot;After init: Bean Name &quot; + arg1);
		return arg0;
	}

	@Override
	public Object postProcessBeforeInitialization(Object arg0, String arg1)
			throws BeansException {
		//Method implementation for BeanPostProcessor interface
		System.out.println(&quot;Before init: Bean Name &quot; + arg1);
		return arg0;
	}
}
</pre></p>
<p>Refer the SpringBeanLifecycle class. It contains two methods init and clean which are inline with the default-init-method and default-destroy-method defined in the beans element. The setBeanName method is an implementation of the BeanNameAware interface. The setBeanClassLoader method is an implementation of the BeanClassLoaderAware interface. The setBeanFactory method is an implementation of the BeanFactoryAware interface. The afterPropertiesSet method is an implementation of InitializingBean interface and destory method is an implementation of DisposableBean interface. The postProcessAfterInitialization and postProcessBeforeInitialization methods are implementation of the BeanPostProcessor interface.</p>
<p>Here&#8217;s the test class:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.spring.test;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class SpringBeanLifeCycleTest {

	public static void main(String[] args) {

		/*Resource resource = new FileSystemResource(&quot;src/spring-bean-lifecycle.xml&quot;);
	    ConfigurableBeanFactory beanFactory = new XmlBeanFactory(resource);
	    beanFactory.addBeanPostProcessor(new SpringBeanPostProcessor());
	    Object bean = beanFactory.getBean(&quot;bean&quot;);
	    beanFactory.destroyBean(&quot;bean&quot;, bean);*/

		ConfigurableApplicationContext ctx
			= new ClassPathXmlApplicationContext (new String[] {&quot;spring-bean-lifecycle.xml&quot;});
		System.out.println(&quot;%%%%%%%%%%%%%%%%%%%%%%%%%%&quot;);
		ctx.getBean(&quot;bean&quot;);
		System.out.println(&quot;%%%%%%%%%%%%%%%%%%%%%%%%%%&quot;);
		ctx.close();
	}
}
</pre></p>
<p>Refer the commented code in the test class for an alternative way of retrieving a bean object.</p>
<p>Here&#8217;s the output of the test class run(only relevant log entries are considered):</p>
<p><pre class="brush: plain;">
Getting bean name: bean
Getting Bean Class loader.
Getting bean factory.
Init
Init bean Object
Before init: Bean Name sample
After init: Bean Name sample
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
Destory
Clean bean Object
</pre></p>
<p>The invocation order of the Spring bean is as below:</p>
<ol>
<li>setBeanName method of BeanNameAware interface.</li>
<li>setBeanClassLoader method of BeanClassLoaderAware interface.</li>
<li>setBeanFactory method of BeanFactoryAware interface.</li>
<li>afterPropertiesSet method of InitializingBean interface.</li>
<li>init-method of bean element in the configuration xml.</li>
<li>postProcessBeforeInitialization method of BeanPostProcessor interface.</li>
<li>postProcessAfterInitialization method of BeanPostProcessor interface.</li>
<li>destroy method of DisposableBean interface.</li>
<li>destroy-method of bean element in the configuration xml</li>
</ol>
<p>The default-*-method attributes defined in the beans element is overridden by the bean level definitions of init-method and destroy-method. Note that the BeanPostProcessor interface implementation does not act on SpringBeanLifecycle class but monitors the SampleBean class.</p>
<p><strong>Autowiring</strong></p>
<p>Up to now we have adopted the approach of creating a configuration file. Defining a bean, its default value and collaborators within the configuration file. The cross references between beans were explicitly defined within the configuration. However Spring also provides an alternative where it autowires or automatically selects the appropriate reference within the configuration file. Spring Framework supports the following autowiring modes:</p>
<ol>
<li>No autowiring</li>
<li>By Name</li>
<li>By Type</li>
<li>Constructor</li>
</ol>
<p>Earlier versions of Spring framework used to support an autodetect mode which is no longer supported in Spring 3.<br />
The first mode &#8216;no autowiring&#8217; is essentially what we have done so far. Actually defined the references between the various bean definitions in the configuration file.</p>
<p>The next one is By Name. This autowiring type tries to match a bean in the container whose id or name matches the name of the property. If no match is found, the property remains unwired. To understand this autowiring mode better let&#8217;s use an example. Consider the following classes Car, CarModel and Engine. Their source code is below:</p>
<p><pre class="brush: java;">
package com.spring.autowire;

public class Car {

	private String makerName = null;
	private String model     = null;
	private String name      = null;

	private Engine engine    = null;

	public String getMakerName() {
		return makerName;
	}

	public void setMakerName(String makerName) {
		this.makerName = makerName;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Engine getEngine() {
		return engine;
	}

	public void setEngine(Engine engine) {
		this.engine = engine;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;Car ###############&quot;);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Maker name: &quot;);
		sb.append(this.makerName);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Name: &quot;);
		sb.append(this.name);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Model: &quot;);
		sb.append(this.model);
		sb.append(&quot;\n&quot;);
		if (this.engine != null) {
			sb.append(this.engine.toString());
		}
		sb.append(&quot;################&quot;);
		sb.append(&quot;\n&quot;);

		return sb.toString();
	}

}
</pre></p>
<p><pre class="brush: java;">
package com.spring.autowire;

public class Engine {

	private String name  = null;
	private String model = null;
	private int capacity = 0;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public int getCapacity() {
		return capacity;
	}
	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}

	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;Engine ***************&quot;);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Name: &quot;);
		sb.append(this.name);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Model: &quot;);
		sb.append(this.model);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;Capacity: &quot;);
		sb.append(this.capacity);
		sb.append(&quot;\n&quot;);
		sb.append(&quot;**********************&quot;);
		sb.append(&quot;\n&quot;);

		return sb.toString();
	}
}
</pre></p>
<p>Create the following configuration xml beans-autowire.xml.</p>
<p><pre class="brush: xml; highlight: [8]; wrap-lines: false;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;
           default-autowire=&quot;byName&quot;&gt;

	&lt;bean id=&quot;makerName&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Toyota&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;name&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Camry&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;model&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2011&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;capacity&quot; class=&quot;java.lang.Integer&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2500&quot; /&gt;
	&lt;/bean&gt;

  	&lt;bean id=&quot;camry&quot; class=&quot;com.spring.autowire.Car&quot;&gt;
  		&lt;property name=&quot;makerName&quot; ref=&quot;makerName&quot; /&gt;
  		&lt;property name=&quot;name&quot; ref=&quot;name&quot; /&gt;
  		&lt;property name=&quot;model&quot; ref=&quot;model&quot; /&gt;
  	&lt;/bean&gt;

  	&lt;bean id=&quot;engine&quot; class=&quot;com.spring.autowire.Engine&quot;&gt;
  		&lt;property name=&quot;name&quot; ref=&quot;name&quot; /&gt;
  		&lt;property name=&quot;model&quot; ref=&quot;model&quot; /&gt;
  		&lt;property name=&quot;capacity&quot; ref=&quot;capacity&quot; /&gt;
  	&lt;/bean&gt;
	&lt;!-- Please also note that it is not currently possible to autowire so-called simple properties 
		such as primitives, Strings, and Classes (and arrays of such simple properties)--&gt;
&lt;/beans&gt;
</pre></p>
<p>Refer line number 8. Here within the beans element tag the attribute default-autowire is set to &#8216;byName&#8217;. This informs the configuration to use byName mode for autowiring. Here&#8217;s the test class to validate:</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.autowire.Car;

public class BeanAutowireTest {

	public static void main(String[] args) {

		ConfigurableApplicationContext ctx
			= new ClassPathXmlApplicationContext (new String[] {&quot;beans-autowire.xml&quot;});
		Car car = (Car)ctx.getBean(&quot;camry&quot;);
		System.out.println(car);
		ctx.close();
	}
}
</pre></p>
<p>On running the test class we observe that even though the xml did not define any explicit association between the Car&#8217;s engine property and Engine bean, due to autowiring the property has been automatically associated with the engine bean. This is because the property name within Car and bean id within the configuration xml is the same. Do note that we have explicitly wired the other primitive attributes like makerName, model etc. This is because simple attributes such as primitives, Strings and classes (and arrays of such simple properties) are not supported byName autowiring. This apparently is a feature!! An obvious limitation of byName autowiring type is that the id/name should match the property name. The developer will have to be careful in naming bean&#8217;s properties to ensure that there is no conflict. In a medium to large size project, this constraint could prove to be a serious limitation.</p>
<p>Moving on let&#8217;s look at autowiring byType mode. In this mode, the auto wiring is done by comparing the bean definition type and the type of the bean property. If both match, the property is autowired to the bean. Look at the following configuration xml beans-autowire-type.xml.</p>
<p><pre class="brush: xml; highlight: [8];">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;
           default-autowire=&quot;byType&quot;&gt;

	&lt;bean id=&quot;makerName&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Toyota&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;name&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Camry&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;model&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2011&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;capacity&quot; class=&quot;java.lang.Integer&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2500&quot; /&gt;
	&lt;/bean&gt;

  	&lt;bean id=&quot;camry&quot; class=&quot;com.spring.autowire.Car&quot;&gt;
  		&lt;property name=&quot;makerName&quot; ref=&quot;makerName&quot; /&gt;
  		&lt;property name=&quot;name&quot; ref=&quot;name&quot; /&gt;
  		&lt;property name=&quot;model&quot; ref=&quot;model&quot; /&gt;
  	&lt;/bean&gt;

  	&lt;bean id=&quot;engine&quot; class=&quot;com.spring.autowire.Engine&quot;&gt;
  		&lt;property name=&quot;name&quot; ref=&quot;name&quot; /&gt;
  		&lt;property name=&quot;model&quot; ref=&quot;model&quot; /&gt;
  		&lt;property name=&quot;capacity&quot; ref=&quot;capacity&quot; /&gt;
  	&lt;/bean&gt;
	&lt;!-- Please also note that it is not currently possible to autowire so-called simple properties 
		such as primitives, Strings, and Classes (and arrays of such simple properties)--&gt;
&lt;/beans&gt;
</pre></p>
<p>In the beans element declaration the attribute default-autowire value is changed to &#8216;byType&#8217;. Like byName, byType also does not support primitive or wrapper classes autowiring. For our example only wiring of the engine property of Car takes place using the byType autowiring mode. Here&#8217;s the test code for autowire byType.</p>
<p><pre class="brush: java;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.autowire.Car;

public class BeanAutowireTypeTest {

	public static void main(String[] args) {

		ConfigurableApplicationContext ctx
			= new ClassPathXmlApplicationContext (new String[] {&quot;beans-autowire-type.xml&quot;});
		Car car = (Car)ctx.getBean(&quot;camry&quot;);
		System.out.println(car);
		ctx.close();
	}

}
</pre></p>
<p>The final autowiring type is by constructor. It is similar to byType automode but applies to constructor arguments. If the constructor argument&#8217;s type matches the bean definition type, the constructor argument is autowired to bean. Refer the source code below of CarModel class.</p>
<p><pre class="brush: java;">
package com.spring.autowire;

public class CarModel {

	private Engine engine = null;

	public CarModel(Engine engine) {
		this.engine = engine;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append(&quot;Car Model ###############&quot;);
		sb.append(&quot;\n&quot;);
		if (this.engine != null) {
			sb.append(this.engine.toString());
		}
		sb.append(&quot;################&quot;);
		sb.append(&quot;\n&quot;);

		return sb.toString();
	}
}
</pre></p>
<p>The class defines a constructor with Engine as its argument. Refer to the configuration xml beans-autowire-constructor.xml</p>
<p><pre class="brush: xml; highlight: [8];">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;
           default-autowire=&quot;constructor&quot;&gt;

	&lt;bean id=&quot;makerName&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Toyota&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;name&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;Camry&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;model&quot; class=&quot;java.lang.String&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2011&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean name=&quot;capacity&quot; class=&quot;java.lang.Integer&quot; factory-method=&quot;valueOf&quot;&gt;
		&lt;constructor-arg value=&quot;2500&quot; /&gt;
	&lt;/bean&gt;

  	&lt;bean id=&quot;camry&quot; class=&quot;com.spring.autowire.CarModel&quot;&gt;
  	&lt;/bean&gt;

  	&lt;bean id=&quot;engine&quot; class=&quot;com.spring.autowire.Engine&quot;&gt;
  		&lt;property name=&quot;name&quot; ref=&quot;name&quot; /&gt;
  		&lt;property name=&quot;model&quot; ref=&quot;model&quot; /&gt;
  		&lt;property name=&quot;capacity&quot; ref=&quot;capacity&quot; /&gt;
  	
  	&lt;/bean&gt;
&lt;/beans&gt;
</pre></p>
<p>The default-autowire attribute in the xml is changed to constructor. There is a bean with id &#8216;camry&#8217; and type as CarModel. Using this autowiring mode, the engine bean is associated with the CarModel constructor argument. To validate refer the test class below:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.spring.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.autowire.CarModel;

public class BeanAutowireConstructorTest {

	public static void main(String[] args) {

		ConfigurableApplicationContext ctx
			= new ClassPathXmlApplicationContext (new String[] {&quot;beans-autowire-constructor.xml&quot;});
		CarModel carModel = (CarModel)ctx.getBean(&quot;camry&quot;);
		System.out.println(carModel);
		ctx.close();
	}

}
</pre></p>
<p><strong>Internationalization(i18n)</strong></p>
<p>A common requirement of enterprise application is to support internationalization(i18n). Spring framework also supports internationalization. I have created three properties file namely text.properties, text_fr_FR.properties and text_en_GB.properties.</p>
<p>Contents of text.properties<br />
<pre class="brush: plain;">
firstname=Bill
lastname=Smith
greeting=Howdy
</pre></p>
<p>Contents of text_fr_FR.properties<br />
<pre class="brush: plain;">
firstname=Bill
lastname=Smith
greeting=bonjour
</pre></p>
<p>Contents of text_en_GB.properties<br />
<pre class="brush: plain;">
firstname=Bill
lastname=Smith
greeting=Hello
</pre></p>
<p>To achieve i18n, the following configuration xml i18n.xml is used.</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd&quot;&gt;
 	
  	&lt;bean id=&quot;messageSource&quot;
		class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;&gt;
		&lt;property name=&quot;basename&quot;&gt;
			&lt;value&gt;text&lt;/value&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</pre></p>
<p>To define i18n configuration we create a bean with id &#8216;messageSource&#8217; and provide property named &#8216;basename&#8217;. The value defined for the property basename is the property file name &#8216;text&#8217;. The extensions file such as text_fr_FR and text_en_GB need not be mentioned. To gain access to the property file values refer the test code below:</p>
<p><pre class="brush: java; wrap-lines: false;">
package com.spring.test;

import java.util.Locale;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class I18NTest {

	public static void main(String[] args) {
		ConfigurableApplicationContext ctx 
			= new ClassPathXmlApplicationContext (new String[] {&quot;i18n.xml&quot;});
		String firstName = ctx.getMessage(&quot;firstname&quot;, new Object[0], Locale.US);
		String lastName = ctx.getMessage(&quot;lastname&quot;, new Object[0], Locale.US);
		String greeting = ctx.getMessage(&quot;greeting&quot;, new Object[0], Locale.US);
		System.out.println(&quot;Message: &quot; + greeting + &quot; &quot; + firstName + &quot; &quot; + lastName);

		firstName = ctx.getMessage(&quot;firstname&quot;, new Object[0], Locale.UK);
		lastName = ctx.getMessage(&quot;lastname&quot;, new Object[0], Locale.UK);
		greeting = ctx.getMessage(&quot;greeting&quot;, new Object[0], Locale.UK);
		System.out.println(&quot;Message: &quot; + greeting + &quot; &quot; + firstName + &quot; &quot; + lastName);

		firstName = ctx.getMessage(&quot;firstname&quot;, new Object[0], Locale.FRANCE);
		lastName = ctx.getMessage(&quot;lastname&quot;, new Object[0], Locale.FRANCE);
		greeting = ctx.getMessage(&quot;greeting&quot;, new Object[0], Locale.FRANCE);
		System.out.println(&quot;Message: &quot; + greeting + &quot; &quot; + firstName + &quot; &quot; + lastName);
		
	}

}
</pre></p>
<p>The Spring context object provides access to the property file values using the getMessage method. The test code to  retrieve locale specific values is illustrated in the test code.</p>
<p>That&#8217;s all for the moment. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/technicalmumbojumbo.wordpress.com/477/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/technicalmumbojumbo.wordpress.com/477/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/technicalmumbojumbo.wordpress.com/477/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=technicalmumbojumbo.wordpress.com&amp;blog=1366554&amp;post=477&amp;subd=technicalmumbojumbo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://technicalmumbojumbo.wordpress.com/2011/04/13/spring-framework-an-introduction-part-ii-object-lifecycle-autowiring-internationalizationi18n/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c41774bd27fb7e396faa7400f0646298?s=96&#38;d=wavatar&#38;r=G" medium="image">
			<media:title type="html">Mr. President</media:title>
		</media:content>
	</item>
	</channel>
</rss>
