Thursday, 3 July 2014

Apple’s Swift Language Revolution

After a couple of years of doing strictly Objective C development, I welcomed Apple’s course change to its new Swift language. Objective C is quite powerful, of course, but its syntax looks like no other language out there.

But Swift, as per Apple’s intent, looks very much like other higher level scripting languages, and is designed to help “reduce barriers to entry” for developers who want to move onto this new platform.

So, I recently came across an on-line tech quiz that included this puzzle:
“Given a block of text (such as this one), write an application to reverse the order of the words but not the letters.”

A common solution would be to split the block of text into an array of words, and then push each word onto a stack. The reverse order comes from simply popping each word from the stack to create a reversed sentence.

In Python or Java, this would barely take a page of code, but how would one do this in Swift?

Swift has no built in Stack collection (at least, not that I’ve found so far), but it would be easy enough to make one. I’d want a Stack class that would let me push() an item, pop() an item, and let me know if the stack isEmpty().

So to solve this puzzle, one can create a Stack in Swift:

import Cocoa

class Stack {

    var array = Array()
    func push(item:String) {
    func isEmpty() ->Bool {
        return array.count == 0
    // we declare the pop() function to return an Optional value, meaning it can return nil if there's nothing in the array to pop.
    func pop() ->String? {
        let itemCount = array.count
        if (itemCount == 0) {
            return nil
        } else {
            return array.removeAtIndex(itemCount-1)

// Now we'll try the stack on the puzzle.
let sentence = "Given a block of text (such as this one), write an application to reverse the order of the words but not the letters."

// parse the original sentence into an array of words
let words:String[] = sentence.componentsSeparatedByString(" ")

// create an instance of our Stack class.   The class itself does not change, so it can be declared as a constant via the "let" keyword.
let stack:Stack = Stack()
for word in words {

// Now we'll create a reverse string by popping values off our stack and concatenating them with space separators.
var reverse_string = ""
var i = 0
while !stack.isEmpty() {
    if i > 0 {
        reverse_string += " "
    reverse_string += stack.pop()!

// print our starting point and our end result

A Swift implementation measures reasonably well against a Python implementation, with a similar user-defined Stack class. Python’s list class has a built-in pop() method, and the language has a “join” method, which makes the Python implementation shorter:

class Stack:
    def __init__(self):
        self.__storage = []
    def push(self, item):
    def isEmpty(self):
        return len(self.__storage) == 0
    def pop(self):
        return self.__storage.pop()
sentence = "Given a block of text (such as this one), write an application to reverse the order of the words but not the letters."
words = sentence.split()

stack = Stack()
for word in words:

reverse_words = []
while not stack.isEmpty():
print sentence
print ' '.join(reverse_words)

Swift also compares well to a Java implementation, even thought Java, of course, actually already has a Stack class, not to mention a handy StringBuilder class:

import java.util.*;

public class SentenceReverser {
    public static String reverseThisSentence(String sentence) {

        String[] words = sentence.split(" ");
        Stack<String> stack = new Stack<String>();

        for (String word : words) {

        StringBuilder sb = new StringBuilder()
        int i = 0;

        while (! stack.isEmpty()) {
            if (i > 0) {
                sb.append(" ");
        return sb.toString();
    public static void main(String[] args) {
        String sentence = "Given a block of text (such as this one), write an application to reverse the order of the words but not the letters.";    

Certainly, there are more lines of code in the Swift example, and that might also be due in part to the limits of my knowledge of the language.

But I think someone with a Python, Java or Javascript background can look at Swift and can pretty well understand the code’s intention.

Sunday, 29 July 2012

Android and GCM – Broadcast Yourself

At the 2012 Google IO conference, Google announced the release of Google Cloud Messaging, AKA GCM, as a replacement for its Cloud to Device Messaging (C2DM) protocol. Being new to cloud messaging, I was glad to have the chance to start with something fresh, knowing that I did not have to unlearn any earlier protocols to get this under my belt.

But I found very few examples, most of which only gave me partial explanations, so after battling through some basic GCM concepts and actually getting the thing to work, I’ve started putting together this tutorial of the fundamentals.

This tutorial will demonstrate the use of GCM for the broadcast of messages to an Android client from a Tomcat server. It will also make use of sending broadcastintents from a service and receiving those broadcastintents from an app’s activity. The end result will look something like this screenshot, where a web server displays a JSP page for a message to be transmitted, next to a DroidAtScreen capture of a broadcast message.


I’ve uploaded two zip files – one containing the Android client and one containing the Tomcat service. You should be able to download either file, unzip to a folder, and then import the unzipped folder as a project in Eclipse.

NOTE: You’ll need to have an instance of Tomcat configure to work from within your Eclipse environment, or you’ll need to manually compile and deploy a WAR file from the provided source.

NOTE2: You’ll also need to update the Java code in the projects to make use of your PROJECT ID, Android device’s generated registration ID, and the browser key that’s returned when you generate your GCM project in Google’s console.


You will need to have a running instance of Tomcat that you can control through Eclipse. You will also need an Android device, and a Google developer login ID. Finally, you must be running the latest (r20) version of the Eclipse ADT.

Some GCM Fundamentals

I’ll need to put a diagram here.

  1. A developer creates a Google APIs GCM project, which generates a project id and a “browser” id to be used in the project’s server-based code.
  2. An Android app registers the device its running on with GCM, using that project id, which generates a registration id. The app should transmit that registration id to the project’s server
  3. The project’s server code can now send a broadcast message to any registered devices by communicating with the GCM service, using the browser id. For java-based projects, there is a jar file that facilitates this communication.

The GCM Demo – The Big Picture

This project should be built in three steps:

  • Create a Google APIs project at the Google portal, and generate and save the project id and API keys.
  • Build and run the Android client app, letting it register with GCM, and capture the generated device app key.
  • Build the web service, using the browser key to send to GCM, and using the captured device app key to broadcast to your target device

Project Build, More Detail:

You’ll see a lot of steps listed below, which might seem daunting at first. But most of the pre-coding setup steps are quite straightforward, and you should be able to get your projects set up in about 20 minutes before you have to code anything.

Most of the information for steps 1 and 2 was taken verbatim from this
GCM Getting Started guide:

Continue Reading

Saturday, 26 May 2012

Android vs iOS – a Continuing Existential Choice

After spending a bit of time developing Android apps, I’ve recently started working in iOS, using XCode 4.3 on a MacBook Pro. It’s a challenge to essentially start from scratch in iOS after getting comfortable with Android. I feel like I’ve just climbed a mountain and reached a nice plateau, only to see that there’s another steep mountain ahead.

Two recent essays on the current state of iOS vs Android have convinced me to at least start this new learning curve. One is this article from which, among other things, highlights the differences in revenue generation between iOS and Android. As of the spring of 2012, iOS is still clearly ahead of Android.

The other is this article from, which shows some interesting graphics that highlight the fragmentation issues that Android developers face. With the diversity of hardware and of Android OS versions out there, developers face a major challenge in building an app that can reach a large share of that market.

Time to pick up that backpack and continue climbing.

Tuesday, 24 April 2012

ActionBarSherlock : New Life for Old Android SDKs

The Issue

Android’s look and feel options have evolved significantly from the first SDK releases, now 4-ish or so years ago. Android 4.0, the API 14 release, labelled “Ice Cream Sandwich” (ICS, for short), includes many new native enhancements, not the least of which is the ActionBar.

But many Android devices do not yet have ICS, and many, like my Droid Bionic phone, might never get an ICS upgrade. This means that, for the short term, unless an Android developer is targeting an Android 4.0 device, he ordinarily can not make use of newer, more attractive user interface features.

A Solution

However, ActionBarSherlock, by Jake Wharton, provides a way for developers targeting older Android OS devices to include these latest features in their apps. According to the home site, the library is compatible with Android OS versions down to 1.6, and it is smart enough to switch over to the native Android OS if a library feature is available natively.

This tutorial is designed to help you get started with ActionBarSherlock (I’ll refer to it as ABS). It will just scratch the surface, but hopefully it will give you enough of a start with this library to encourage you to experiment, and to work through the demos that come with the library.

This tutorial is a work in progess, and will be expanded and corrected as time permits.


One can set up ActionBarSherlock to use in one’s own projects by following these steps:

  1. If you don’t already have it, update your list of Android SDK versions to include API 14. Even though you will most likely be building an app for an earlier API version, the ActionBarSherlock library requires API 14.
  2. Download and unzip the library from the ActionBarSherlock site. Unzip it to a place where you can find it later (if you don’t mind).
  3. Using the Eclipse ADT, create a project from existing source, using the “Library” folder from the downloaded and expanded ABS folder. Tag this as an Android library.
  4. Create a new Android project, using Android SDK 14 as your target SDK, and include the ActionBarSherlock library as part of your project. Your ActionBarSherlock app will still be able to run on older Android OS devices
  5. In your project’s AndroidManifest.xml, you must specify a theme for each activity. (You can also set the theme programmatically, but only do that if you plan on changing themes dynamically within your project.)
  6. Your Android activities can now be defined as descendants of SherlockActivity. Or, you can have an actionbar that’s an activity-level variable.

This demo will show these two options (a SherlockActivity, and an Activity with an ActionBarSherlock object), and screen shots of this project running on my Droid Bionic running OS 2.3.4 (roughly API level 10) are near the bottom of this post.

Continue Reading

Tuesday, 3 April 2012

Essbase and the Outside World

Olap4j is an open-source java API for OLAP. It can be used in much the same way as a JDBC driver would be used for relational data sources.

I made some very small changes to the driver source code, which should now make it possible for a variety of client-side tools to retrieve metadata and run MDX queries against Oracle Essbase. Specifically, this update lets Olap4j retrieve data from Essbase via XMLA.

For this to work, Essbase needs to be deployed as a HPS service, which one can do through the EAS console. I will post notes on this in a day or two, with screenshots.

Thank you, Luc Boudreau and Julian Hyde, for letting me post a few lines of code!

Monday, 19 March 2012

An Android REST Client and Tomcat REST Webservice

Project Overview

This post will describe simple client-server communications between an Android app and a web service using REST techniques, particularly GET and POST. For this demo, we will be sending and receiving data for a simple Java class called Person, which includes a firstName, lastName and email address. The data stored in an instance of this class will be transmitted from our web service in JSON format.

NOTE: This post is a work in progress and will be updated and corrected, as time permits.


This demo assumes that you have a version of Eclipse that can create a “Dynamic Web Project”, and that you have an instance of the Tomcat servlet container that you can control through Eclipse. This demo also assumes that you have the Android SDK, at least one Android Virtual Device (AVD), and have the Eclipse ADT plugin.

Another important requirement is that your Android device needs to be on the same network as your Tomcat server. The simplest way to do this would be to make sure you are running your emulator on the same computer that is running Tomcat.

About REST

REST – “Representational State Transfer” is a technique that makes use of standard web protocols for the implementation of a web service. A RESTful web service uses the standard HTTP GET PUT DELETE and POST actions to submit, retrieve or modify server-side data.

Commonly, in a REST web service, the standard HTTP actions are used as follows:

  • GET – retrieves or queries for data, usually using passed criteria
  • PUT – creates a new entry, record
  • DELETE – removes a resource
  • POST- updates a resource or creates a resource

The data that is transmitted uses standard MIME types, including images, video, text, html, XML and JSON.
Continue Reading

Wednesday, 14 March 2012

An Android Stock Reader Using the Google Stock API


The Android app described in this post will cover the following concepts:

  • Performing a lengthy task in a separate thread with our own AsyncTask
  • Submitting a HTTP request and handling HttpResponse data
  • Creating a progress dialog
  • Handling XML data with XMlPullParser


You should have the Android SDK installed, and the Eclipse Android add-in, and you should be able to use Eclipse to generate a basic Android app and run it either on a real device or on an Android Virtual Device (AVD).

The Google Stock Web Service

They do not advertise it very much, but Google provides a stock API that returns current price information for a set of symbols submitted as a URL.  These prices should not be used for making buying or selling decisions: the data is probably several minutes behind the actual current price, and there’s not much information about how these prices are gathered or how accurate they are.

Details on the scope and accuracy of Google’s Stock API can be found here

But this is still a nice source for experimenting with consuming data from a web service.  One submits a query to the URL with an appropriately formatted sequence of symbols, and the web service returns price, volume, company name and other information in XML format.
Continue Reading