Installing Android Studio on Debian Wheezy

Android Studio is the new IntelliJ IDEA based Android IDE. It succeeds the current Eclipse based IDE.

Android Studio requires Oracle Java 1.6 or later. It won’t work with OpenJDK.

Installing Oracle Java 1.7

These instructions describe how to install Oracle Java using java-common. java-common only works with Java 1.6 or 1.7. It doesn’t work with Java 8.

  • Download the latest 1.7 JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html. To find the tarball follow the links “Previous Releases – Java Archive” -> “Java SE 7” -> “Java SE Development Kit 7u..”. You’ll need the tarball not the RPM, e.g. jdk-7u67-linux-x64.tar.gz. Note: you’ll need an Oracle account to download archive versions of Java (those < Java 8).
  • Install java-common

    # apt-get install java-common

  • Create a deb file using the Java tarball,
    $ make-jpkg <downloaded tarball>
  • Install the resulting package (your deb file name will likely be different),
    # deb -i oracle-j2sdk1.7_1.7.0+update67_amd64.deb
  • Update your java links to point at this new Oracle Java package. To find the name of this package take a look in /usr/lib/jvm/. There should be a directory named j2sdk1.7-oracle (or something similar). Use this directory name in a call to update-java-alternatives.
    # update-java-alternatives -s j2sdk1.7-oracle
  • Test your system is using the correct version of Java using,
    $ java -version
     java version "1.7.0_67"
     Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
     Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)
    $ javac -version
     javac 1.7.0_67

Install the Android SDK Tools

The Android SDK Tools package contains the SDK Manager. You’ll need this to download one or more SDKs.

Download “SDK Tools Only” from https://developer.android.com/sdk/index.html. Extract the downloaded file to your applications directory, e.g. ~/apps/.

Install Android Studio

Download Android Studio from http://developer.android.com/sdk/installing/studio.html.

Unzip the downloaded file to whereever you keep your apps, e.g. ~/apps/.

To start Android Studio run <install dir>/android-studio/bin/studio.sh.

Configure the location of your Android SDK by selecting “Configure” -> “Project Defaults” -> “Project Structure” -> “Android SDK Location”. Enter the directory where you extracted the Android SDK Tools.

I find it useful to create a launcher icon. This way I can launch Android Studio by clicking Alt-F1 and entering the first few characters of the app name. To create a launcher icon from the Welcome splash screen select “Configure” -> “Create Desktop Entry”.

References

Installing Debian 7.1 “Wheezy”

Every time I install Linux, no matter what the distribution, I have the same problems; configuring video and audio. When I installed Debian 7.1 recently I documented the steps I took. Hopefully you’ll find something of use here.

My Hardware

Video: Advanced Micro Devices [AMD] nee ATI RV710 [Radeon HD 4350]
Sound: Advanced Micro Devices [AMD] nee ATI RV710/730 HDMI Audio [Radeon HD 4000 series]
Monitor: Dell SP2208WFP (with built in webcam)
WebCam: OmniVision Technologies, Inc. Monitor Webcam

Video and sound devices can be determined using lspci. The Webcam is a USB device so it can be determined using lsusb.

Video

For regular use the opensource Radeon display driver is considered adequate. If you’re a gamer or just want to squeeze every bit of performance out of your card then you might consider the AMD proprietary display driver. For my needs the opensource driver is fine.

On the first boot GNOME 3 failed to load. The installer recognized my video card and installed the correct package, xserver-xorg-video-radeon, but as documented on the wiki my card requires proprietary firmware. This firmware is available in non-free. The steps to install it are,

  1. Open up Synaptic Package Manager and select Settings, Repositories from the menu
  2. Tick the checkbox next to Non-DFSG-compatible Software (non-free)
  3. Click Close and then the Reload toolbar button
  4. Search for and install firmware-linux-nonfree
  5. Reboot

GNOME 3 should start successfully after the reboot.

Audio

When I didn’t hear any sound I thought I was going to be in for a world of pain with sound drivers, ALSA and PulseAudio. Luckily all I needed to do was select the right output device. My system has two sound devices, an onboard Intel device and the sound device on the AMD video card. My monitor is connected by HDMI. I have a soundbar on my monitor drawing it’s signal from the HDMI cable. All I needed to do was,

  1. Open up the System Settings
  2. Click the Sound icon
  3. In the Output tab select the HDMI audio device, i.e. RV710/730 HDMI Audio [Radeon HD 4000 series] Digital Stereo (HDMI)

Update (Aug-2014): HDMI audio is disabled by default in the kernel/audio driver. To enable it,

  1. Edit /etc/default/grub and append “radeon.audio=1” to the GRUB_CMDLINE_LINUX_DEFAULT variable.
  2. Open a terminal execute sudo update-grub
  3. Reboot

Source: No sound on HDMI with Radeon driver

Webcam

My monitor has a built in Webcam. It’s an OmniVision Technologies, Inc. Monitor Webcam. I managed to get it working but it’s a bit hit and miss. When then uvcvideo kernel module is loaded it should create the device /dev/video0. Sometimes it does, sometimes it doesn’t. To get it to work is a matter of removing the module and reloading. After two or three attempts it usually works. Not very satisfying but I don’t use it very often so I’m not that bothered.

$ sudo modprobe -r uvcvideo     # unload the module
$ sudo modprobe uvcvideo        # load the module

Once the module loads successfully and creates the /dev/video0 device you can use the Cheese application to test it.

Microphone

The mic didn’t appear to be working initially but as with audio out all I needed to do was select the right device and turn up the volume. I use the mic on my monitor (attached to the webcam).

  1. Open up the System Settings
  2. Click the Sound icon
  3. Select the Input tab
  4. Select the Monitor Webcam Analog Stero device
  5. Turn the volume up to 100%

After getting the hardware working these are the applications I installed.

Flash Player

The Flash Player package is avaiable from contrib.

  1. Open up Synaptic Package Manager and select Settings, Repositories from the menu
  2. Tick the checkbox next to DFSG-compatible Software with Non-Free Dependencies (contrib)
  3. Click Close and then the Reload toolbar button
  4. Search for and install flashplugin-nonfree
  5. Restart your browser if you

Reference: FlashPlayer on the Debian Wiki

Java Browser Plugin

Simply install the package icedtea-6-plugin.

gThumb

gThumb is a photo manager. I prefer it over the default, Shotwell, because it feels quicker and more lightweight. I already organise my photos in a year, month, day folder structure so I have no need for anything fancy.

While gThumb itself is very easy to install (the gthumb package) it was failing to properly list all the photos and videos in a directory containing one or more videos. The problem was it couldn’t find the image it uses to surround videos (to give the reel effect). The fix is simple,

$ sudo ln -s /usr/share/gthumb/ui/filmholes.png /usr/share/filmholes.png

Reference: Redhat Bug 842183 – Gthumb breaks file list on movies

Android Tools

The Android Tools are used when developing Android applications. After installing the Android SDK I found adb wouldn’t work. When I ran it it gave a “file not found”. The problem is down to missing shared libraries. Here are the steps I took to fix it,

$ sudo dpkg --add-architecture i386
$ sudo aptitude update
$ sudo aptitude install libstdc++6:i386 libgcc1:i386 zlib1g:i386 libncurses5:i386

Reference: Installing Android SDK tools on Debian Wheezy

Multipart form upload on Android

Android 1.5 includes Apache HttpClient 4 for the purposes of making HTTP requests. Unfortunately HttpClient 4 (or the version included with Android anyway) doesn’t appear to support multipart form uploads.

As it happens writing a solution from scratch (at the HTTP layer that is) is pretty straight forward. The main challenge is understanding how the POST request should be structured. Once you know that it’s simply a matter of putting all the pieces together.

The connection is managed using the java.net.HttpURLConnection class. There’s a few properties that need to set on the connection to ensure it can be written to and read from,

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);

A special header informs the server that this will be a multipart form submission.

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=xxxxxxxxxx");

The “boundry” can be any string. In this example it’s xxxxxxxxxx. It’s used in the body of the request to seperate each field being submitted.

Next comes the main body of the request. Each field being submitted follows the same pattern. For example, to submit a text file called “helloworld.txt” with the contents “Hello World” and using the boundry string xxxxxxxxxx here’s what the request would look like,

--xxxxxxxxxx
Content-Disposition: form-data; name="filetoupload"; filename="helloworld.txt"
Content-Type: text/plain

Hello World
--xxxxxxxxxx--

The final -- is important. It tells the server it’s the end of the submission.

Here’s a full method that’s used to upload a file to a URL. It can optionally take a username and password which is used to perform BASIC authentication.

    public static void put(String targetURL, File file, String username, String password) throws Exception {

        String BOUNDRY = "==================================";
        HttpURLConnection conn = null;

        try {

            // These strings are sent in the request body. They provide information about the file being uploaded
            String contentDisposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + file.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";

            // This is the standard format for a multipart request
            StringBuffer requestBody = new StringBuffer();
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append('\n');
            requestBody.append(contentDisposition);
            requestBody.append('\n');
            requestBody.append(contentType);
            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append(new String(Util.getBytesFromFile(file)));
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append("--");

            // Make a connect to the server
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // Put the authentication details in the request
            if (username != null) {
                String usernamePassword = username + ":" + password;
                String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
                conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
            }

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

            // Send the body
            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            dataOS.writeBytes(requestBody.toString());
            dataOS.flush();
            dataOS.close();

            // Ensure we got the HTTP 200 response code
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
            }

            // Read the response
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int bytesRead;
            while((bytesRead = is.read(bytes)) != -1) {
                baos.write(bytes, 0, bytesRead);
            }
            byte[] bytesReceived = baos.toByteArray();
            baos.close();

            is.close();
            String response = new String(bytesReceived);

            // TODO: Do something here to handle the 'response' string

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

    }

There’s nothing in this code particular to Android so it will work in any java application.

How to Create a Remote Paging Listview Using GWT-Ext

Creating a remote paging listview isn’t particularly difficult but getting to the point of knowing how all the pieces fit together can be tricky first time round. This post describes how I created a very simple remote paging listview that retrieves each page of data from an Oracle database table. As well as describing the listview I’ve also included the code for the server side that actually fetches and returns each page of data to the client.

Deploying GWT-Ext
If you’ve not used GWT-Ext before then here’s how to include it in your GWT application. First you’ll need to download GWT-Ext itself. At the time of writing 2.0.4 is the latest release, you can get it here. The real workhorse behind GWT-Ext is the Javascript library ExtJS. GWT-Ext 2.0.4 requires ExtJS 2.0.2 which you can download from here.

If you don’t already have a GWT application then GWT’s The Basics guide is a good place to start.

With your application up and running here are the steps required to deploy GWT-Ext within it.

1. Create the directory js/ext under your application’s public folder and copy the following files and directories from ExtJS into it,

adapter
resources
ext-all.js
ext-all-debug.js
ext-core.js
ext-core-debug.js

2. Edit your module file and add these lines to it,

<inherits name='com.gwtext.GwtExt'/>
<stylesheet src="js/ext/resources/css/ext-all.css"/>
<script src="js/ext/adapter/ext/ext-base.js" />
<script src="js/ext/ext-all.js" />

3. The final step it to add the GWT-Ext jar, gwtext.jar, to your application’s classpath.

The Client Side Code
GWT-Ext refers to a listview as a Grid so to avoid confusion I’ll use that term throughout the rest of this post. I used the term listview up to this point because it’s probably a more generally accepted description.

Before going into the code it’s worth spending a little time understanding the various objects that are needed to support the Grid object. The first thing worth pointing out is that GWT-Ext doesn’t use standard GWT Remote Procedure Calls to fetch the data needed in the Grid. What you do instead is provide it with a HTTP URL from which to retrieve the data. To do this you use a DataProxy object. There are three types of DataProxy, the HttpProxy, the MemoryProxy and the ScriptTagProxy. The MemoryProxy is just a static in memory data source and the ScriptTagProxy is the same as HttpProxy except that it retrieves data from a site other than the one where your Grid is hosted. So what format should the data coming back from this URL be in? Two formats are supported, JSON and XML. In order to understand the structure of this JSON or XML we need to use a RecordDef. This object contains FieldDef objects each of which describe a particular field in the data feed. Once you’ve described you data structure using a RecordDef you create either a JsonReader or an XmlReader and give it a reference to your RecordDef. Finally, to tie all these objects together you create a Store. The Store is the object you present to the Grid. It uses the DataProxy to retrieve the data and and the Reader to parse it.

With the Store defined we can turn our attention to the Grid. To define what columns the Grid should have and where the data for each column should come from we use a ColumnModel object. This object contains a number of ColumnConfig objects, one for each column. A ColumnConfig contains the column title, the name of the record in the RecordDef to populate the column with, it’s width, weather it’s sortable and how the data should be rendered. To create the Grid itself we use the GridPanel object. You can link it to the Store and ColumnModel using either the constructor or the setter methods.

The final point to note is that you’ll need to add an onRender event handler to the Grid so that the first page of data is loaded when the Grid is displayed.

Bringing all that together here’s the class I ended up with,

package com._17od.gwtexamples.client;

import java.util.Date;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.core.SortDir;
import com.gwtext.client.data.DateFieldDef;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.HttpProxy;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.JsonReader;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.util.DateUtil;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.grid.CellMetadata;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GridView;
import com.gwtext.client.widgets.grid.Renderer;
import com.gwtext.client.widgets.grid.RowSelectionModel;

public class PersonGrid implements EntryPoint {

	public void onModuleLoad() {

		Panel panel = new Panel();
		panel.setBorder(false);
		panel.setPaddings(15);

		HttpProxy dataProxy = new HttpProxy("http://localhost:8888/persons");

        final RecordDef recordDef = new RecordDef(new FieldDef[]{
                new StringFieldDef("class"),
                new DateFieldDef("dateOfBirth", "Y-m-d"),
                new StringFieldDef("firstname"),
                new IntegerFieldDef("id"),
                new StringFieldDef("lastname"),
        });

        JsonReader reader = new JsonReader(recordDef);
        reader.setRoot("persons");
        reader.setTotalProperty("totalPerons");
        reader.setId("id");

        final Store store = new Store(dataProxy, reader, true);
        store.setDefaultSort("id", SortDir.ASC);

        ColumnConfig firstNameColumn = new ColumnConfig("First Name", "firstname", 45, true);
        ColumnConfig lastNameColumn = new ColumnConfig("Last Name", "lastname", 45, true);
        ColumnConfig dateOfBirthColumn = new ColumnConfig("Date of Birth", "dateOfBirth", 45, true, dateRender);

        ColumnModel columnModel = new ColumnModel(new ColumnConfig[] {
        		firstNameColumn,
        		lastNameColumn,
        		dateOfBirthColumn});
        columnModel.setDefaultSortable(true);

        GridPanel grid = new GridPanel();
        grid.setWidth(700);
        grid.setHeight(300);
        grid.setTitle("People");
        grid.setStore(store);
        grid.setColumnModel(columnModel);
        grid.setTrackMouseOver(true);
        grid.setLoadMask(true);
        grid.setSelectionModel(new RowSelectionModel());
        grid.setStripeRows(true);
        grid.setIconCls("grid-icon");
        grid.setEnableColumnResize(true);

        GridView view = new GridView();
        view.setForceFit(true);
        grid.setView(view);

        PagingToolbar pagingToolbar = new PagingToolbar(store);
        pagingToolbar.setPageSize(15);
        pagingToolbar.setDisplayInfo(true);

        grid.setBottomToolbar(pagingToolbar);

        grid.addListener(new PanelListenerAdapter() {
            public void onRender(Component component) {
                store.load(0, 15);
            }
        });
        panel.add(grid);

        RootPanel.get().add(panel);

  	}

    private Renderer dateRender = new Renderer() {
        public String render(Object value, CellMetadata cellMetadata, Record record, int rowIndex, int colNum, Store store) {
            return DateUtil.format((Date) value, "d-m-Y");
        }
    };

}

Where Does the Data Come From?
The code below is the servlet I developed to return each page of data to the Grid. It retrieves the data from an Oracle database table called “person”. It’s not particularly complicated but it does demonstrate some challenges that are worth pointing out.

package com._17od.gwtexamples.servlets;

import java.io.IOException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.jdbc.pool.OracleDataSource;

import org.json.JSONArray;
import org.json.JSONObject;

public class GetPersonsServlet extends HttpServlet {

	private Connection connection;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

		// Display the parameters we're passed in for debugging purposes
		printParameters(req);

		// Get the limit and sort parameters off the request
		int start = req.getParameter("start") == null ? 1 : Integer.parseInt(req.getParameter("start"));
		int numberToReturn = req.getParameter("limit") == null ? 10 : Integer.parseInt(req.getParameter("limit"));
		String sortBy = req.getParameter("sort") == null ? "id" : req.getParameter("sort");
		String sortOrder = req.getParameter("dir") == null ? "asc" : req.getParameter("dir");

		// Create the SQL query used to retrieve the persons
		String sql = createMainSQLQuery(sortBy, sortOrder);

		ArrayList persons = null;
		try {

			// Get a connection to the Oracle database and put it on the object so that it's easily accessible
			connection = getConnection();

			// Execute the query to return the exact records requested
			persons = queryForPersonsUsingLimits(sql, start, numberToReturn);

			// Convert the list of persons into a JSON string
			JSONObject jsonDataToReturn = new JSONObject();
			JSONArray jsonPersons = new JSONArray(persons, true);
			jsonDataToReturn.put("totalPerons", getTotalNumberOfPersons(sql));
			jsonDataToReturn.put("persons", jsonPersons);

			// Write everything back to the requestor
			res.getWriter().print(jsonDataToReturn.toString(1));

		} catch (Exception e) {
			e.printStackTrace();
			throw new IOException(e);
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new IOException(e);
				}
			}
		}

	}

	/**
	 * Create the query used to retrieve the persons from the database.
	 * @param sortBy
	 * @param sortOrder
	 * @return
	 */
	private String createMainSQLQuery(String sortBy, String sortOrder) {

		StringBuffer sql = new StringBuffer("SELECT id, firstname, lastname, dateofbirth FROM person");
		sql.append(" ORDER BY ");
		sql.append(sortBy);
		sql.append(" ");
		sql.append(sortOrder);

		return sql.toString();

	}

	/**
	 * Wrap the query passed in with some extra SQL that pulls out the exact
	 * page of persons requested, i.e. starting at record number 10 return 20
	 * records.
	 * It's vital that the query given in 'sql' has an 'order by' clause.
	 * If it didn't then the persons could be returned in a random order
	 * making it impossible to order them into pages.
	 * @param sql
	 * @param start
	 * @param numberToReturn
	 * @return
	 * @throws SQLException
	 */
	private ArrayList queryForPersonsUsingLimits(String sql, int start, int numberToReturn) throws SQLException {

		StringBuffer sqlBuffer = new StringBuffer("SELECT * FROM (SELECT a.*, ROWNUM rnum from (");
		sqlBuffer.append(sql);
		sqlBuffer.append(") a WHERE ROWNUM <= ");
		sqlBuffer.append(start + numberToReturn);
		sqlBuffer.append(") WHERE rnum > ");
		sqlBuffer.append(start);

		Statement statement = null;
		ResultSet rs = null;

		ArrayList persons = new ArrayList();

		try {

			statement = connection.createStatement();
			rs = statement.executeQuery(sqlBuffer.toString());

			while (rs.next()) {
				Person person = new Person();
				person.setId(rs.getInt("id"));
				person.setFirstname(rs.getString("firstname"));
				person.setLastname(rs.getString("lastname"));
				person.setDateOfBirth(rs.getDate("dateofbirth"));
				persons.add(person);
			}

		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		return persons;

	}

	/**
	 * Return the total numbner of records that the given query will return.
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	private int getTotalNumberOfPersons(String sql) throws SQLException {

		int count = 0;

		StringBuffer sqlBuffer = new StringBuffer("SELECT COUNT(*) count FROM (");
		sqlBuffer.append(sql);
		sqlBuffer.append(")");

		Statement statement = null;
		ResultSet rs = null;

		try {

			statement = connection.createStatement();
			rs = statement.executeQuery(sqlBuffer.toString());

			while (rs.next()) {
				count = rs.getInt("count");
			}

		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		return count;

	}

	/**
	 * Return a database connection from the connection poll that's stored on the servlet/application context
	 * @return
	 * @throws SQLException
	 */
	private Connection getConnection() throws SQLException {
		OracleDataSource ods = (OracleDataSource) getServletContext().getAttribute("CONNECTION_POOL");
		if (ods == null) {
			ods = createConnectionPool();
			getServletContext().setAttribute("CONNECTION_POOL", ods);
		}
		return ods.getConnection();
	}

	/**
	 * Create a database connection pool
	 * @return
	 * @throws SQLException
	 */
	private OracleDataSource createConnectionPool() throws SQLException {
        String username = "replace with db username";
        String password = "replace with db password";
        String url = "jdbc:oracle:thin:@localhost:1521:XE";

        OracleDataSource ods = new OracleDataSource();
        ods.setURL(url);
        ods.setUser(username);
        ods.setPassword(password);
        ods.setConnectionCachingEnabled(true);

        return ods;
	}

	private void printParameters(HttpServletRequest req) {
		Enumeration parameterNames = req.getParameterNames();
		System.out.println("\nRequest Parameters:");
		while (parameterNames.hasMoreElements()) {
			String parameterName = (String) parameterNames.nextElement();
			System.out.println(" " + parameterName + "=" + req.getParameter(parameterName));
		}
	}

}

The first point of interest in doPost() is the code that takes the ordering and limit parameters off the request. This servlet is requested when the grid is first drawn or when the user clicks on the “Next Page” or “Previous Page” buttons. For the paging to work the data needs to be ordered. The sort parameter indicates what column to sort the data by. It uses the name you give the column in the RecordDef when creating the Grid. The dir parameter says what direction the ordering should be in, ascending or descending. The start parameter is the number of the first record to return and limit is the number of records to return.

Now that we know what the user is asking for it’s time to build the SQL query that will fetch that data. The method createMainSQLQuery() creates a query string to select the required columns and order the ResultSet.

In the next section we call getConnection(). This method (and createConnectionPool()) demonstrate how to create an Oracle connection pool using OracleDataSource and it’s method setConnectionCachingEnabled().

The method queryForPersonsUsingLimits() is where we actually execute the query. In the first section the query is wrapped in some SQL that fetches only the rows we want starting at row start and returning only numberToReturn records. I picked this up from this Ask Tom article. It’s well worth a read if you’re interested in how the ROWNUM pseudocolumn works.

The next section takes the query ResultSet, creates a Person object for each row and puts each on an ArrayList.

Back in doPost() the ArrayList of Persons is serialized to JSON text using the JSON classes freely availabe here. The method getTotalNumberOfPersons() is called to retrieve the total number of rows the query would return if we weren’t limiting the results. The reason we need this is because the Grid will have a message at the bottom saying like “Displaying 1 to 20 of 100”. The getTotalNumberOfPersons() method reuses the SQL we created earlier and simply wraps it in a SELECT COUNT(*).

Finally we write the JSON text to the output stream which is sent back to the browser.

Deploying the servlet into a web application is simply a matter of adding servlet and servlet-mapping entries to the application’s web.xml. For testing purposed I chose to use the web application created by GWT. By default this application is located in the <project dir>\tomcat\webapps\ROOT. Here are the entries I added…

<servlet>
    <servlet-name>GetPersonsServlet</servlet-name>
    <servlet-class>com._17od.GetPersonsServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>GetPersonsServlet</servlet-name>
    <url-pattern>/persons</url-pattern>
</servlet-mapping>

Here’s a sample of the JSON returned from the URL http://localhost:8888/persons?start=2&limit=3.

{
 "persons": [
  {
   "class": "class com._17od.servlets.Person",
   "dateOfBirth": "1901-01-17",
   "firstname": "Laurel",
   "id": 3,
   "lastname": "Davis"
  },
  {
   "class": "class com._17od.servlets.Person",
   "dateOfBirth": "1892-05-16",
   "firstname": "Ted",
   "id": 4,
   "lastname": "Schoenberger"
  },
  {
   "class": "class com._17od.servlets.Person",
   "dateOfBirth": "2001-05-19",
   "firstname": "Rebecca",
   "id": 5,
   "lastname": "Taylor"
  }
 ],
 "totalPerons": 20
}

The JSON implementation I’m using includes the name of the class being serialized, hence the class attribute.

Since I’ve included all the other code here’s the Person class,

package com._17od.gwtexamples.servlets;

import java.util.Date;

public class Person {

	private int id;
	private String firstname;
	private String lastname;
	private Date dateOfBirth;

	public Date getDateOfBirth() {
		return dateOfBirth;
	}

	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public int getId() {
		return id;
	}

	public void setId(int personId) {
		this.id = personId;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;

	}

}

To finish off here’s a screenshot of the Grid,

Grid Screenshot

Meteor WebSMS

As a Java5/JUnit4/Maven2 learning exercise I’ve written a simple little SMS command line utility called Meteor WebSMS. It allows you to bypass Meteor’s website and send the free web SMS messages they offer from your command line (you have to be a Meteor customer of course).

The API is completely separate from the the command line tool so it’s available if you want to use it in your own Java programs. Javadocs are here.

Since this is a learning exercise full source code and Maven pom.xml are included in the distribution. The URL is http://www.17od.com/meteor-websms.