Archive for ‘Uncategorized’

April 22, 2012

MockHttpServer for Testing Android HTTP Client

While developing an Android project, I needed to test an HTTP client service layer running in my application.  I wanted to ensure I unit tested features such as ability to send/receive headers, request http resources, and deal with HTTP response codes properly. However, I did not want to run my JUnit tests using an external HTTP server. This would create a dependency on yet another technology that I would have to launch with Maven. Furthermore, using an external server would make it difficult to validate unit test cases from the server side.

MockHttpServer

You may already know that Android’s library comes with a version of Apache’s HttpComponent. While Android promotes the use of HttpComponent for mostly client side development, the provided APIs include the server-side pieces as well. So, you can create your own HTTP server running on Android.

MockHttpServer is a wrapper around the HttpComponent’s HttpService API. MockHttpServer provides a simple interaction point where developers simply provide an implementation of HttpRequestHandler.
The MockHttpServer handles the setup and thread management. The following shows how to use the MockHttpServer to enumerate and test the expected headers from the client:

        private final static int SVR_PORT = 8585;
        private final static String SVR_ADDR = "http://localhost:" + SVR_PORT;
...
	public void testHeaderEnumerations () throws Exception{
		// setup mock server and handler for given path
        MockHttpServer server = new MockHttpServer(SVR_PORT);
        server.start();

        server.addRequestHandler("/test1", new HttpRequestHandler() {

            @Override
            public void handle(HttpRequest req, HttpResponse rsp, HttpContext context) throws HttpException, IOException {
            	int headerCount = 0;
                String headers = "Accept Accept-Charset";
                HeaderIterator it = req.headerIterator();
                while (it.hasNext()){
                    Header h = (Header) it.next();
                    if(headers.contains(h.getName())){
                        headerCount++;
                    }
                }
                Assert.assertEquals(3, headerCount);
            }
        });

        // setup client connection
        URL url = new URL(SVR_ADDR + "/test1");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Accept", "text/xml");
        conn.addRequestProperty("Accept", "Audio/mpeg");
        conn.addRequestProperty("Accept-Charset", "utf-8");

        try{
        	conn.getInputStream();
        }finally{
        	conn.disconnect();
        }

        server.stop();
	}

The top portion of the code sets up the HttpRequestHandler implementation. This is where one specifies how the server would handle the incoming HTTP request. In the implementation above, we are enumerating and validating incoming HTTP headers. The second portion of the code sets up the client call to the MockHttpServer instance. Here, for simplicity, we are using an instance of HttpURLConnection to make the HTTP request to the MockHttpServer.

Link to project - https://github.com/vladimirvivien/workbench/tree/master/android-tutorials/MockHttpServer

April 10, 2012

Jmx-Cli: A Command-Line Console to JMX

One of the reasons I created the Clamshell-Cli Framework originally was to develop a text-based console for JMX.  Well, it is here. Introducing Jmx-Cli: Jmx-Cli a command-line interface console for JMX. It was developed using the Clamshell-Cli framework (
http://code.google.com/p/clamshell-cli/
) to prove that the framework was flexible enough to create a useful tool.

Installing Jmx-Cli

  1. Download the current distribution from
    https://github.com/vladimirvivien/jmx-cli/downloads
    .
  2. Unzip at the location of your choosing (jmx-cli-home).
  3. Cd to jmx-cli-home
  4.  From the command prompt, type > java -jar cli.jar

If all works ok, you should see:

    /#####                                /######    /##   /##
   |__  ##                               /##__  ##  | ##  |__/
      | ##   /######/####    /##   /##  | ##  \__/  | ##   /##
      | ##  | ##_  ##_  ##  |  ## /##/  | ##        | ##  | ##
 /##  | ##  | ## \ ## \ ##   \  ####/   | ##        | ##  | ##
| ##  | ##  | ## | ## | ##    >##  ##   | ##    ##  | ##  | ##
|  ######/  | ## | ## | ##   /##/\  ##  |  ######/  | ##  | ##
 \______/   |__/ |__/ |__/  |__/  \__/   \______/   |__/  |__/

A command-line tool for JMX
Powered by Clamshell-Cli framework 

http://code.google.com/p/clamshell-cli/

Getting Started

Using Jmx-Cli is straight forward. From the prompt type ‘help’ to get a list of available commands:

      exit       Exits ClamShell.
      help       Displays help information for available commands.
        ps       Displays a list of running JVM processes (similar to jps tool)
   connect       Connects to local or remote JVM MBean server.
     mbean       Creates a label for identifying an MBean
      desc       Prints description for specified mbean.
      list       Lists JMX MBeans.
      exec       Execute MBean operations and getter/setter attributes.

Command Hints

You can also get command hints from the prompt by pressing on the tab key. This will list all available combinations of input. You can narrow down the hints by typing a few letters of the command then press tab.

Connecting to a JVM

To connect to a running local JVM, do the followings:

1. Use the ‘ps’ command to get a list of JMV processes running locally:

> ps
1444	cli.jar
1740	org.apache.catalina.startup.Bootstrap

2. use the ‘connect’ command to attach to a running process

> connect pid:1740

The sequence above connects to a running instance of Tomcat server.

Listing MBeans

Once connected to a JVM, you can query available MBeans that are running in that JVM. Use the ‘list’ command to retrieve lists of MBeans.

> list filter:"Catalina:*"

The command above will list all MBeans running in the “Catalina” domain.  You can label the list for future reference by typing:

> list filter:"Catalina:*" label:true

MBean list [Catalina:*]

     [$0] Catalina:type=Server
     [$1] Catalina:realmPath=/realm0/realm0,type=Realm

Describing an MBean

Once you have a list, you can select a bean to describe. The following describes bean with label ‘Catalina:port=8080,type=Connector’:

> desc bean:"Catalina:port=8080,type=Connector"

MBean: Catalina:port=8080,type=Connector (org.apache.catalina.mbeans.ConnectorMBean)
Implementation of a Coyote connector

Attributes:
     port : int (rw) - The port number on which we listen for requests
     useIPVHosts : boolean (rw) - Should IP-based virtual hosting be used? 
     redirectPort : int (rw) - The redirect port for non-SSL to SSL redirects
     minSpareThreads : int (rw) - The number of request processing threads that will be created
     secure : boolean (rw) - Is this a secure (SSL) Connector?
     acceptCount : int (rw) - The accept count for this Connector
     maxThreads : int (rw) - The maximum number of request processing threads to be created
     URIEncoding : java.lang.String (rw) - Character encoding used to decode the URI
     modelerType : java.lang.String (r) - Type of the modeled resource. Can be set only once
     packetSize : int (rw) - The ajp packet size.
     processorCache : int (rw) - The processor cache size.
...
     xpoweredBy : boolean (rw) - Is generation of X-Powered-By response header enabled/disabled?
     stateName : java.lang.String (r) - The name of the LifecycleState that this component is currently in
     allowTrace : boolean (rw) - Allow disabling TRACE method
     useBodyEncodingForURI : boolean (rw) - Should the body encoding be used for URI query parameters
     secret : java.lang.String (w) - Authentication secret (I guess ... not in Javadocs)

Operations:
     destroy():void
     pause():void
     stop():void
     resume():void
     start():void
     init():void

The same command can be issued using the associated label of the bean from the list (see above):

> desc bean:$28

Execute an Operation

Jmx-cli lets you execute operation on your management beans as well. The next examples shuts down the Tomcat connector for port 8080:

> exec bean:"Catalina:port=8080,type=Connector" op:"stop"

References

1. https://github.com/vladimirvivien/jmx-cli – Jmx-Cli home page

2 http://code.google.com/p/clamshell-cli/ – Clamshell-Cli Framework web site

November 19, 2011

A Pattern for Creating Custom Android Content Providers

When creating apps in Android, you have access to numerous data sources. In fact, Android comes with a built-in instance of SQLite, provides access data to local storage, gives direct access to remote resources over HTTP. In additions to these native data providers, you can setup your own application to be a data provider. Since Android does not allow applications to share data directly with one another, you can make your data accessible to (components in your application or) other applications using the ContentAPI. For instance, Android has a phonebook content provider which lets you search, add, modify contacts.

A ContentProvider is a first-class Android component (like Activity, Service, etc). It is registered in the manifest file like any other high-level components. You can read about Android ContentProviders from Android’s website at:

The intent of this write up is to present a simple approach to create and work with your own ContentProvider. It is not meant to be an introduction to data storage in Android. If you have not used data storage in Android, visit the Android’s developer web site and look for data storage.

ContentProvider Overview

As mentioned above, one of the primary purposes for the use of ContentProvider is data sharing.  Since databases and other internal data stores are application-scoped, there’s no way to share information between applications.  A content provider lets you expose access to your application’s data in a structured and uniform manner.

ContentProdviders are considered data access objects (a software pattern).  Their backing data store can be a database, data from local storage, data from a remote server over HTTP, or a custom data source.  For this write up, I will use the SQLite database as the backing datastore for the sample content provider that will be be demonstrated.  This will keep things simple since the API for SQLite maps nicely to the method used by the ContentProvider API.

The Example

Imagine a simple application that keeps track of your favorite restaurants and save that information in the local SQLite database.  For the sake of keeping things simple, the code only saves a few columns about the restaurants including name, address, city, state, etc. You can download the example from its GitHub location at
https://github.com/vladimirvivien/workbench/tree/master/android-tutorials/ContentProviderSample
.

How to Do It

The ContentProvider API is a bit heavy and can be complex.  To get a custom ContentProvider written, you need to implement several boilerplate methods. This writeup makes things easier by providing a set of guidelines for implementing your own ContentProvider. Here is how to do it:
  • Define data model – figure out what will be in stored
  • Create a Descriptor class – to help describe the data that you will work with.  This is not part of any of the APIs.  It is a class that I have used to help with with creation of providers.
  • Create a Database Class – the database class is implemented as a SQLiteOpenHelper intended to help with creation/management of the database instance itself.
  • Define your ContentProvider – the content provider will use the classes created above to install the database, access, and manipulate the data in it.  This is also the class that Activity classes will use to access the data.

Define the Data Model

While it may sound trivial, the first step to this pattern is to figure out what your data will look like. Recall that the ContentProvider exposes data in tabular form, so listing out your data columns is a good first step for your design.  For our favorite restaurant example, we will use the following fields which represent the name and address of our favorite eateries:

  • ID
  • NAME
  • ADDRESS
  • CITY
  • ZIP

It’s good practice to define an ID column as an identifier for the data row. The ContentProvider’s URI mechanism uses the ID to refer to saved data entities.

Descriptor Class

The Descriptor class is not part of the ContentProvider API. I use it as a registry for meta data that describes the content exposed by the ContentProvider class. The Descriptor class manages the following meta data:
  • URI Authority – the authority portion of the URI representing this entity.  In our example it is “com.favrestaurant.contentprovider”
  • URI Matcher – this is an internal registry used to map a URI path (serviced by the ContentProvider) to an integer value.
  • Entity Class – an inner static class that represents the entity to be managed by the ContentProvider. In our example, this class is called Restaurant. It exposes meta data such as the entity name, supported URIs, etc.
  • Class EntityClass.Cols – the entity class provides an inner class called Cols. As you may have guessed, this class exposes the name of the columns to exposed by the ContentProvider for the entity.
public class ContentDescriptor {
	public static final String AUTHORITY = "demo.contentprovider.restaurant";
	private static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
	public static final UriMatcher URI_MATCHER = buildUriMatcher();

	private ContentDescriptor(){};

	private static  UriMatcher buildUriMatcher() {
        final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
        final String authority = AUTHORITY;

        matcher.addURI(authority, Restaurant.PATH, Restaurant.PATH_TOKEN);
		matcher.addURI(authority, Restaurant.PATH_FOR_ID, Restaurant.PATH_FOR_ID_TOKEN);

        return matcher;
	}

	public static class Restaurant {
		public static final String NAME = "restaurant";

		public static final String PATH = "restaurants";
		public static final int PATH_TOKEN = 100;
		public static final String PATH_FOR_ID = "restaurants/*";
		public static final int PATH_FOR_ID_TOKEN = 200;

		public static final Uri CONTENT_URI = BASE_URI.buildUpon().appendPath(PATH).build();

		public static final String CONTENT_TYPE_DIR = "vnd.android.cursor.dir/vnd.favrestaurant.app";
		public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.favrestaurant.app";

		public static class Cols {
			public static final String ID = BaseColumns._ID; // convention
			public static final String NAME = "restaurant_name";
			public static final String ADDRESS  = "restaurant_addr";
			public static final String CITY = "restaurant_city";
			public static final String STATE = "restaurant_state";
			public static final String ZIP = "restaurant_zip";
		}

	}
}

What’s going on…

  • The first thing to notice in the code above is the definition of variables AUTHORITY and BASE_URI. Together these form the URI that identifies the ContentProvider. The URI is used by Android for registering the ContentProvider as part of the application. As you will see later, a ContentResolver class will locate and use the ContentProvider based on the provided URI.
  • Private method buildMatcher() creates an instance of URIMatcher for the ContentProvider.
  • Inner class Restaurant exposes meta data that defines the Restaurant entity managed by the associated ContentProvider.
  • Furthermore, inner class Restaurant.Cols define meta values for the columns associated with the Restaurant entity.

If none of this makes sense, read on to see how the Descriptor class is used.

The Database Class (SQLiteOpenHelper)

Since the backing data store for our ContentProvider implementation is a database, we will use the SQLLite API here to define the database. The purpose of class RestaurantDatabase is to create, install, and help manage the SQLLite database. The Android’s ContentProvider API (along with the ContentResolver class) uses this class to run DDL scripts to install and update the database. If you implement the onUpgrade() method and change the version of the database, the database will be upgraded automatically next time the code is executed.

The one notable portion of the code below is its use of the ContentDescriptor class (see defined above) to provide meta data the table and fields used in the database.

public class RestaurantDatabase extends SQLiteOpenHelper {
	private static final String DATABASE_NAME = "fav_restaurnt.db";
	private static final int DATABASE_VERSION = 2;

	public RestaurantDatabase(Context ctx){
		super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + ContentDescriptor.Restaurant.NAME+ " ( " +
				ContentDescriptor.Restaurant.Cols.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
				ContentDescriptor.Restaurant.Cols.NAME + " TEXT NOT NULL, " +
				ContentDescriptor.Restaurant.Cols.ADDRESS 	+ " TEXT , " +
				ContentDescriptor.Restaurant.Cols.CITY + " TEXT, " +
				ContentDescriptor.Restaurant.Cols.STATE + " TEXT, " +
				ContentDescriptor.Restaurant.Cols.ZIP + " TEXT, " +
				"UNIQUE (" +
					ContentDescriptor.Restaurant.Cols.ID +
				") ON CONFLICT REPLACE)"
			);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion < newVersion){
        	db.execSQL("DROP TABLE IF EXISTS " + ContentDescriptor.Restaurant.NAME);
        	onCreate(db);
        }
	}

}

The ContentProvider Class

Next, we implement the ContentProvider class with the logic for data access and update. The ContentProvider API exposes several methods for inserting, updating, querying, and deleting data. The example code only implements the insert() and query() methods. Note the usage of the ContentDescriptor to provide naming and configuration meta data for the ContentProvider.

public class RestaurantContentProvider extends ContentProvider {
	private RestaurantDatabase restaurantDb;

	@Override
	public boolean onCreate() {
		Context ctx = getContext();
		restaurantDb = new RestaurantDatabase(ctx);
		return true;
	}

	@Override
	public String getType(Uri uri) {
		final int match = ContentDescriptor.URI_MATCHER.match(uri);
		switch(match){
		case ContentDescriptor.Restaurant.PATH_TOKEN:
			return ContentDescriptor.Restaurant.CONTENT_TYPE_DIR;
		case ContentDescriptor.Restaurant.PATH_FOR_ID_TOKEN:
			return ContentDescriptor.Restaurant.CONTENT_ITEM_TYPE;
        default:
            throw new UnsupportedOperationException ("URI " + uri + " is not supported.");
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = restaurantDb.getWritableDatabase();
		int token = ContentDescriptor.URI_MATCHER.match(uri);
		switch(token){
			case ContentDescriptor.Restaurant.PATH_TOKEN:{
				long id = db.insert(ContentDescriptor.Restaurant.NAME, null, values);
				getContext().getContentResolver().notifyChange(uri, null);
				return ContentDescriptor.Restaurant.CONTENT_URI.buildUpon().appendPath(String.valueOf(id)).build();
			}
            default: {
                throw new UnsupportedOperationException("URI: " + uri + " not supported.");
            }
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = restaurantDb.getReadableDatabase();
		final int match = ContentDescriptor.URI_MATCHER.match(uri);
		switch(match){
			// retrieve restaurant list
			case ContentDescriptor.Restaurant.PATH_TOKEN:{
				SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
				builder.setTables(ContentDescriptor.Restaurant.NAME);
				return builder.query(db, null, null, null, null, null, null);
			}
			default: return null;
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}
}

What’s going on…

  • The onCreate() method is called when the provider is instantiated (by the ContentResolver class). It is, in turn, used to bootstrap the database via the RestaurantDatabase class (see above) instance db.
  • The getType() method uses the ContentDescriptor.URI_MATCHER (see ContentDescriptor above) to lookup the MIME type for a given URI.
  • All of the data access & update methods (including query(), insert(), update(), and delete()) take a URI parameter. The URI provides hints such as the entity (and cardinality) being queried or updated. For instance, in our example, if the URI to passed to the query() method looks like content://com.favrestaurant.contentprovider/restaurants/* the method will return all restaurant rows in the database. This is accomplished by using the ContentDescriptor.URI_MATCHER to determine how to process the URI.

Using the ContentProvider

Once you have all of your pieces in place, you can access the data exposed by the content provider using the ContentResolver. There are certainly more robust ways to use to access data from a ContentProvier. This write up shows the simplest (non-production ready) way of doing it. You should investigate which way works best for your use (see http://developer.android.com/guide/topics/providers/content-providers.html).


public class FavRestaurantActivity extends Activity {
	TextView txtName;
	TextView txtAddr;
	TextView txtState;
	TextView txtCity;
	TextView txtZip;

    ContentResolver contentResolver;
    Cursor cur;
    SimpleCursorAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ...
        contentResolver = this.getContentResolver();
    }

    @Override
    public void onStop() {
    	super.onStop();
    	if(cur != null) cur.close();
    }

    private void loadContent() {
        cur = this.getContentResolver().query(ContentDescriptor.Restaurant.CONTENT_URI, null, null, null, null);
    	...
    }

    private void saveContent(){
    	ContentValues val = new ContentValues();
    	val.put(ContentDescriptor.Restaurant.Cols.NAME, (this.txtName.getText() != null) ? this.txtName.getText().toString() : null);
    	val.put(ContentDescriptor.Restaurant.Cols.ADDRESS, (this.txtAddr.getText() != null) ? this.txtAddr.getText().toString() : null);
    	val.put(ContentDescriptor.Restaurant.Cols.CITY, (this.txtCity.getText() != null) ? this.txtCity.getText().toString() : null);
    	val.put(ContentDescriptor.Restaurant.Cols.STATE, (this.txtState.getText() != null) ? this.txtState.getText().toString() : null);
    	val.put(ContentDescriptor.Restaurant.Cols.ZIP, (this.txtZip.getText() != null) ? this.txtZip.getText().toString() : null);
    	contentResolver.insert(ContentDescriptor.Restaurant.CONTENT_URI, val);
    	loadContent();
    }
}

What is going on…

  • First, let me point out that the code used above to access data from the Activity class is not optimal for production. You should optimize any io-bound code that has propensity to hang the UI by using an asynchronous task. Nevertheless, the code presented above uses an instance of ContentResolver to access data managed by the backing ContentProvider. The ContentResolver uses the URI value passed in to select the proper ContentProvider registered in the AndroidManifest.xml file (not shown).
  • The saveContent() shows how you can use the Descriptor class to create an instance of ContentValues (from the ContentProvider API) to save data. Each column is mapped to its value using the ContentProvider to provide the column name.
  • Conclusion

    This write up provides a guide for those of you, brave enough, to use the ContentProvider API directly. I have introduced the Descriptor class as a container to register meta data to describe the data element captured by the ContentProvier. The hope is to make using the ContentProvider API more organized and provide some structure when putting your own data access code together.

October 7, 2011

Loader/Launcher – A Pattern to Bootstrap Java Applications

There is still a great number of Java developers out there who are not doing web apps. They use the JDK’s Java launcher directly to bootstrap their apps using public static void main() (abbreviated thereafter as PSVM). And if you are one of those developers, you understand the implications of having a large classpath. It is not uncommon to see shell command with no less than a dozen jars listed on the classpath.

Of course over the years many options have been provided to help with this issue. One of the most recent is from Java 6 where you can reduce the length of the command to launch your Java application by specifying wildcards values in the classpath as shown below:

$ java -cp path1/*.jar:path2:/*:path3/*.jar package.name.ClassName

This write up proposes an alternative approach where your code loads your application’s classes programatically. This pattern, named Loader/Launcher, separates the loading of your application’s classes from the booting of your application logic. The idea is to provide your own loader class that will load your classpath then delegates further bootstrapping responsibilities to a launcher class. One benefit of this approach is that your command to launch your application can be reduced to something like this (no matter the size of your class dependency graph):

$ java -jar package.name.ClassName

The Loader/Launcher Pattern

The way that the Loader/Launcher pattern works is to de-entangle class-loading concerns from application execution concerns. The loading of classes is handled by a Main class with a PSVM method. The native Java command-line launcher loads the Main class. The execution of the application is delegated to a launcher class that implements the Launcher interface. The Launcher is instantiated and invoked by the Main class.

Loader/Launcher Sequence

Loader/Launcher Sequence

To implement this pattern, you will need the following high-level components:

  • The Launcher interface that will be used as a starting point for your app.
  • The Main class where a PSVM method is defined.
  • A Launcher implementation to execute the application.

The Launcher Interface

Implementation of this interface is intended to be the starting point of your application’s bootup process. Instead of starting your application directly in the PSVM method, as is done traditionally, you would relocate the logic for your application’s boot up sequence in a class that implements this interface. When the PSVM method is invoked by the native Java launcher, it would delegate the boot sequence of your application to your Launcher instance (see interface below Listing-1).

public interface Launcher {
	public int launch(Object ... params);
}

Listing-1

This is a simple interface with a single method, launch(). The method takes an array of objects that can be used to pass in arguments to launcher. The method’s signature makes easy to maintain the semantic of PSVM when using the Launcher.

The Main Class

The Main class is designed to be the starting point for the native Java launcher by exposing a PSVM method. The role of this class, in the Loader/Launcher Pattern, is summed up below:
It creates and loads the application’s classpath. Internally, it instantiates a ClassLoader that is used to load the application’s classpath from a specified location.
Once the classpath is in place, it creates an instance of Launcher, from the classpath, to boot up the application by calling launch().

Listing-2 shows the content of a Main class.

public class Main {
	private static String CLASSPATH_DIR = "lib";
	private static String LIB_EXT = ".jar";
	private static String LAUNCHER_CLASS = "demo.launcher.AppLauncher";

	private static ClassLoader cl;
	static{
		try {
			cl = getClassLoaderFromPath(
				new File(CLASSPATH_DIR),
				Thread.currentThread().getContextClassLoader()
			);
			Thread.currentThread().setContextClassLoader(cl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Returns a ClassLoader that for the provided path.
	private static ClassLoader getClassLoaderFromPath(File path, ClassLoader parent) throws Exception {
		// get jar files from jarPath
		File[] jarFiles = path.listFiles(new FileFilter() {
			public boolean accept(File file) {
				return file.getName().endsWith(Main.LIB_EXT);
			}
		});
		URL[] classpath = new URL[jarFiles.length];
		for (int j = 0; j < jarFiles.length; j++) {
			classpath[j] = jarFiles[j].toURI().toURL();
		}
		return new URLClassLoader(classpath, parent);
	}

	public static void main(String[] args) throws Exception{
		Launcher launcher = Launcher.class.cast(
			Class.forName(LAUNCHER_CLASS, true, cl).newInstance()
		);
		launcher.launch(new Object[]{"this string is capitalized"});
	}
}

Listing-2

The first thing to notice is the static declarations at the start of the listing. The first three declarations setups the “lib” directory as the location for the classpath, provides “.jar” as the file extension, and specifies demo.launcher.AppLauncher as the name of the Launcher class to load from the classpath. The static code block uses method getClassLoaderFromPath() to initialize a URLClassLoader instance (that points to the lib directory) that will serve as the class loader for the rest of the application.

When the public static void main() method in the Main class is invoked (by the Java launcher), it searches and loads an instance of class demo.launcher.AppLauncher which implements Launcher. Then, the code calls Launcher.launch() to delegate the execution of the rest of the application by passing in a String parameter.

The Launcher Class

The Launcher class is responsible for starting up the application-specific logic. Implementation of the launch() method maintains the same signature as the the PSVM method from the Main class to maintain the familiar semantic. Parameters are passed in as arrays of objects and the method is expected to return an integer. A return value of 0 means everything is OK while anything else means something up to the discretion of the implementor. Listing-3 shows a simple implementation of the Launcher class.

public class AppLauncher implements Launcher {
	public int launch(Object ... args) {
		String result = org.apache.commons.lang3.text.WordUtils.capitalize((String)args[0]);
		System.out.println (result);
		return 0;
	}
}

Listing-3

How It Works

This implementation uses Apache Commons-Lang to capitalize the value of an argument that was passed in. While this is a simple example, it shows exactly how the pattern would work.  When the application is invoked from the command-line using

$ java -jar demo.launcher.Main

The Main class resolves the classpath by loading jars from the jar directory.  The classpath directory contains all jars that satisfies the dependency graph of the application.  In this example the application depends on the Apache-Commons Lang jar.  When Main instantiates its ClassLoader instance, the jar will be added on the classpath and thus be available for use.

An Example

You can download example code that shows how this works from the location below:
An example –
https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher

The example comes in three separate projects:

  • Launcher-Api – contains the definition of the Launcher interface.
  • Launcher-Impl – contains an implementation of the Launcher interface.
  • Laucnher-Main – contains the Main class that is used as the starting point of the application.

Conclusion

The Loader/Launcher Pattern is an attempt to decouple two distinct activities that occur when a Java application is started: that of class loading and and application start up. The pattern uses a Main class as the entry point from the Java native launcher and is used to  load the application’s classpath from a given location.  The act of activating the application is then relegated to a Launcher class.  The launcher is responsible for actually starting up the application-specific logic in the code.  Some of the benefit of adopting this pattern is, firstly, the tighter control over how classes are loaded.  You no longer have to rely on the native Java launcher to resolve your classpath.  Another benefit is the separation of concerns for the start up sequence of the app.  The pattern provides a location, the Launcher interface, where to define what should happen when the application itself (not loading of classpath) is starting.  Hope this was helpful.

Reference


https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher
 - the example


http://code.google.com/p/clamshell-cli/
 - tool that uses this pattern

Tags:
October 5, 2011

Try to Be Like Steve

All of us in the tech field (specially those in position to create) have an undeniable responsibility to those who use our creation. Steve showed that our creation can be imaginative, usable, and of quality. He showed us that user experience is also a feature. Usability starts from the moment your users open that box and pull out the shiny new toy and ends with their ability to effectively use your products to be productive, entertained, or enlightened.

The best tribute to Steve is to imitate some of his legacies. So, in your next project, make your creation better. If you are designing an API, add that extra function that makes your developers productive; if you are creating a web site , add that feature that will surprise and make your users smile; if you are creating a new product, plan to make it great, plan to make it usable, plan to make it awesome.

I can only hope that the people at Apple don’t fall prey to the temptation of only pleasing the Street but continue Steve’s long-term strategic vision of bringing quality and imaginative products out to the market. As Apple’s recent history attests to, people will gravitate toward quality and the Street will take notice.

Thank you Steve Jobs 

June 18, 2011

Returning to Blogging

I haven’t written down my thoughts in so long using blog that I forgot I had a blogging website.  Last couple of years have been moving fast so I adopted a medium that moves just fast, Twitter.  However, Twitter can be noisy.  While Twitter is a good source for info junky like myself, the stream of text that it provides tend to drown quickly good ideas and posts as they are swept away with every refresh.  So, to provide a more permanent place to my rant, ideas, and thoughts, I have decided to return back to blogging.

Yes, it will be fun again.
August 26, 2010

The JavaFX Cookbook

You know that feeling you have after you run (if you run) a long distance that you have been trying to break for the longest.  Well, I have that same feeling of hard-work-pays-off with the publishing of my first book “JavaFX 1.2 Application Development Cookbook.”  As of yesterday, 8/25/10, I received a note from Packt Publishing that the book is going to the printer and I will have my copies soon.

Despite all the delays and the inevitable curve balls life throws at you (I had quite a few last and this year), the book is done.  Like anything worth doing its a gratifying feeling.  Now, let’s see if Oracle will come out with some extraordinarily good news for JavaFX  (at JavaOne 2010) to give wind to my JavaFX wings.

Go to
http://www.javafxcookbook.com/
for how-to’s and tutorials and (if you don’t mind) pick up a copy of the book.  Thanks!

July 8, 2010

iPhone 3GS + iOS 4.0 = Wait for 4.1

Couple weeks ago I updated my phone to the new iOS4.  I was excited to be able to play Pandora in the background while texting (or doing whatever else to enjoy multitasking).  After I download the new version of Pandora multitasking, I was able to run Pandora and do something else on the phone without Pandora stopping.

Besides multitasking there are some other nice features in 4.0 that I like:

  • GUI Speed – that is the first thing you notice, things are snappier
  • Folders – group application into folders
  • App Tray – double click the home button and you get a list of currently running/paused apps that you can quickly switch from
  • Camera – got nice update, simulated shutter speed is improved, digital zoom added
  • Bluetooth – voice command works via bluetooth now

However, my excitement started to wear thin as I notice some annoyances that keep reoccurring:

  • Phone Crash – the most annoying is the phone crashing.  Prior to 4.0, I never had to do a restart on my phone.  With 4.0 I had to do that 3 times already.  Sometimes in the middle of a conversation phone becomes unresponsive and must be restarted
  • More frequent drop calls 
  • Bluetooth transition slow – now, phone will ring first before it switch to my car

Conclusion: iOS4 is great, but wait for iOS 4.1 if you own the 3GS.  Hopefully that will address some of the issues I mentioned (actually the iPhone4 has its own set of bugs that 4.1 will also address, so just wait).

August 5, 2009

Google Buys On2. JavaFX Gains?

When Google purchased YouTube back in 2006, the Flash video (FLV) format got an astronomical boots almost overnight. The media format became even more popular, the Flash/Flex pair gained notoriety as a viable platform, Adobe fortified its arsenals in the battle for media dominance. This single act shadowed other players such as Real, Microsoft, and to a certain extent Apple’s QuickTime (when was the last time you embedded a Microsoft Media Player on your website).

Today (in TechChruch), it was announced that Google is purchasing On2, the media compression technology company behind many of the most popular media codecs including FLV. This has the potential to change the course of online video technologies once again. One can only imagine some of the implications this purchase will have

  • It moves Google higher in the media compression food chain and gives it complete control of the most popular codecs used on the web.
  • Google may open source the current proprietary VP6 (on which Flash video is based) & VP7 codec formats that On2 licenses to companies. They may decide to provide needed support for the Ogg Theora format and make it first class citizen in the compression stack.
  • With Google’s push of HTML5 which includes the notion of built-in video/audio support, one can rightly guess that we will see On2 technologies in Chrome Browser, Chrome OS, and Android and anywhere else Google control (which is wide and far).
  • As Ogg (Vorbis and Theora) becomes the open source format of choice for media delivery, Google will wield its influence on the format and direction of media deliver on the web.

Why am I rambling about On2, Ogg, and video codec formats? Well, it all has to do with JavaFX. One of the selling point of JavaFX is portable playback of Video/Audio basedon VP6 (consequently FLV). With the purchase of On2, Google will have a direct control of the destiny of media codec supported by JavaFX. Depending on how Google proceeds, we, in the Java community, may see positive developments for JavaFX and this is how:

  • Google open sources the On2 codec stack: big win for JavaFX (to a certain extent Adobe). This will imply that JavaFX applications can take part in the online media revolution with lowered entry points.We probably will see Java bindings to the codec’s API’s which means building both encoders and players in Java/JavaFX.
  • If the stack is open source, this may also mean eventual support on JavaFX mobile platforms.
  • Google may make On2 encoding tools available for free: another win for JavaFX! More videos being created with the supported On2 formats means more opportunities for JavaFX developers to create players.

Or, Google may decide to just sit on the technologies use them to further their ambitions in Mobile, desktop OS, and web markets. Only time will tell.

July 30, 2009

NetBeans 6.7.1 + Mac OS = Sweetness

I just updated my netbeans to 6.7.x on the Mac and the difference is vivid.
Even faster start time
Snappier GUI
On the Mac, the new look makes it look native
Plus all the other goodies (Groovy, JavaFX, etc)

Follow

Get every new post delivered to your Inbox.