Archive for category Uncategorized

Using GCD with Blocks

GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects.

Queues are a C typedef viz. dispatch_queue_t. GCD offers three kinds of queues, main, concurrent and serial.

Main queue is automatically created by the system and associated with your application. You can get it by using dispatch_get_main_queue().

Concurrent queue can be created using dispatch_get_global_queue and it executes the tasks, submitted in the form of block in FIFO order, however, the tasks run concurrently and can finish in any order.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);


Serial queues execute tasks in a strict FIFO serial order one at a time. To create serial queue use dispatch_queue_create which takes the name of the queue as first argument and options (currently NULL) as second argument.

dispatch_queue_create(“com.example.MyQueue”, NULL);

Submitting a block to Queue for Execution

You can submit a block to queue for execution using two of GCD provided functions:

dispatch_async OR dispatch_sync

Both the functions accept queue as the first argument and block as the second argument. dispatch_async returns immediately and executes the task asynchronously while dispatch_sync blocks execution until the provided block returns.

One good demonstration of using GCD API’s with concurrent and main queue and blocks is this blog entry from Jeff Kelly’s blog:

I also like Andy’s blog entry on testing or debugging block based API’s using the code snippet he created:

In fact, you can use Jeff’s idea of async loading of table cells along with Andy’s code snippet to test the async loading.






Leave a comment

Objective C – Some basics

If you are developing for the iOS platform, its invaluable to have foundational knowledge in Objective C. This brief blog posts covers some fundamental terms in objective C, hope you will find it useful.

1. Protocols – Protocols in objective C are equivalent to Interfaces in Java. They contain method definitions, either required or optional methods, which the implementing class implements. A good example is UITableViewDataSource Protocol. A class can implement multiple Protocols. For more details, refer to :

2. Categories – A category allows you to add methods to an existing class even if you do not have a the source code available for that class! Categories offers a neat alternative to subclassing by allowing you to extend the functionality of a class. For example, to add functionality to class named MyCategoryClass you can write the following code:

#import “MyCategoryClass.h”

@interface MyCategoryClass (CategoryName)

//method declarations



The category name indicates that the methods are additions to a class declared elsewhere, not a new class. Note that you cannot use a category to add additional instance variables to a class.

3. Properties – Properties provide a simple way to declare and implement an object’s accessor methods. There are two key parts to understanding properties in objective C, declaration and implementation.

You would normally declare a property in class header file.

Property Attributes —

Mutability – readwrite or readonly, default is readwrite

e.g. @property (readonly) int voltage;

Lifetime Specifiers — unsafe-unretained (default) e.g. @property int voltage (voltage in this case is unsafe unretained)

strong — ensures that a strong reference or ownership is kept to the passed-in object.

weak — does not imply ownership of the object pointed to. E.g. in case of parent child relationship, parent should have a strong reference to child, however, the child should have a weak reference. So that when child is deallocated, the parent reference to child can be released.

copy — in this case the setter will make a copy of the new object passed and set the pointer to point to the copied object.

e.g. @property (copy) NSString *serialNumber;

– (void) setSerialNumber: (NSString *) newSerialNumber {

newSerialNumber = [newSerialNumber copy];

[serialNumber release]; // releasing the original pointer

serialNumber = newSerialNumber;


4. Key Value Coding

KV is the ability to set and read property using its name. e.g. if we have a property name productName declared in a class whose instance is ‘a’, we can use the following code:

[a setValue@”Washing Machine” forKey@”productName”];





Leave a comment

Android 101 – The basic building blocks of an Android Application

This post talks about the basics and fundamentals of Android development. So if you know java and eager to program for the Android platform, read on.

I recently developed an iOS app for a large organization and published it on itunes. Received some good feedback, however, turns out that half of the users have Android phones. So i started looking at developing an Android version of the iOS app. Plus according to Google, more than 350,000 android devices are being shipped on any given day which translates to 1 million new Android users every 3 days!

Compared to iPhone, Android has quite a few vendors shipping different kinds of Android phones (LG, Samsung, Motorola, HTC, etc.). However, good news is that now there is a one common platform on which to develop Android apps – the latest one is called honeycomb 🙂

So lets start with the basics. And Android app is a collection of several different components viz. Activity, Service, Content Provider, Broadcast Receiver, Intents; all of them are defined in AndroidManifest.xml.

1. Activity – This is how you write an Android user interface. A single activity defines a single screen with a user interface. When you write a user interface for your home screen it will most likely extend the Activity class. It defines simple lifecycle methods like onCreate, onResume, onPause which lets you handle interruptions.

2. Service – it does the majority of processing for your application. Its the logic behind the user interface. E.g. performing a long running process in the background. You can sub class the Service class to write your own custom service.

3. Content Provider – This provides a uniform singular interface to the content & data. The content can be from your app being exposed to the system or other apps or it could be system content e.g. pictures on your phone, contact lists exposed or available to your app via the Content Provider interface. It provides a consistent interface to retrieve/store data via RESTful model supporting CRUD operations.

4. Broadcast Receiver – The application modules communicate with each other using the broadcast receiver. Messages can be initiated by the system or the app. E.g. if a user is using your app and a phone call comes in, the Broadcast Receiver interface will notify your app and your can code to handle that interruption (by possibly delegating to your service). You can opt to receive messages statically via declaring in the manifest file or dynamically by programmatically registering it the code which extends the Broadcast Receiver interface.

5. Intents – Of all the main components we discussed so far, this is the most interesting. Intents can be implicit or explicit. E.g. an explicit intent can be to invoke another screen when a button is pressed on the Activity (UI) in context. An implicit intent is when you create an intent and hand it off to the system to handle it. A good example discussed in one of google I/O boot camp was the barcode example, where the app creates an implicit intent of type SCAN and provide it to another app which handles scanning and returns the resultCode back to the calling application. 

Typically you define all the components of your Android app in the manifest file. You can state the features, permissions and sdk version in the manifest. The application tag will have sub tags defining activities, services, receivers and intents.

Having discussed the main components, lets move on now to our first basic task – creating a simple user interface.

In the Android World a UI is a hierarchy of Views and ViewGroups which can be defined either programmatically or in XML layout files. E.g. to create a simple linear layout i can define the following in my xml file (e.g. main.xml under the layout folder of your application resource package):

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout …>

   <TextView android:id=”@+id/text”

                   android:text=”Hello World!” …/>


Though we used linear layout here, its considered best practice to use RelativeLayout to cater for multiple size screens.

In the next post we will use the above discussed concepts to build a simple Android application.

Feedback and Questions are appreciated.

Leave a comment

Create a simple Java Web App using Maven and Deploy to Heroku

This blog post will feature on creating a simple web application with a Maven Archetype plugin. The web application will:

  • Run in an embedded web application server (Jetty Server)
  • Have some dependencies added
  • Contain a simple servlet
  •  Generate a WAR file for deploying on heroku

1. Using Maven archetype:generate to create a web app which has an embedded Jetty Server (jetty-archetype-assembler) and a java class which starts the Jetty Server.

mvn archetype:generate -DarchetypeGroupId=org.mortbay.jetty.archetype -DarchetypeArtifactId=jetty-archetype-assembler -DarchetypeVersion=7.5.1.v20110908 -DgroupId=com.heroku.webapp -DartifactId=heroku1
thanks to John Simone & heroku team for working with Jetty team in creating this jetty-archetype-assembler!

2. This will generate a Java web project with standard web application structure. Inspect the pom.xml file and note that it has a maven app assembler plugin which will generate a script that sets up the required class path and runs the web application.


Important —

Use your favorite editor and delete this line from the pom.xml file:


This is necessary because this archetype relies on the local maven repository being present at runtime, which is not the case once the app is deployed on heroku.

3. Compile the project using mvn compile.

mvn compile
[INFO] Scanning for projects…
[INFO] ————————————————————————
[INFO] Building heroku1 1.0-SNAPSHOT
[INFO] ————————————————————————
[INFO] — maven-resources-plugin:2.4.3:resources (default-resources) @ heroku1 —
[INFO] Using ‘UTF-8’ encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ heroku1 —
[INFO] Compiling 1 source file to /Users/ssharaf/heroku/heroku1/target/classes
[INFO] ————————————————————————
[INFO] ————————————————————————
[INFO] Total time: 2.079s
[INFO] Finished at: Thu Nov 17 20:40:08 PST 2011
[INFO] Final Memory: 8M/81M
[INFO] ————————————————————————


4. Now we can package it using mvn package:

mvn package

Output —

[INFO] Scanning for projects…
[INFO] ————————————————————————
[INFO] Building heroku1 1.0-SNAPSHOT
[INFO] ————————————————————————
[INFO] — maven-resources-plugin:2.4.3:resources (default-resources) @ heroku1 —
[INFO] Using ‘UTF-8’ encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] — maven-compiler-plugin:2.3.2:compile (default-compile) @ heroku1 —
[INFO] Nothing to compile – all classes are up to date
[INFO] — maven-resources-plugin:2.4.3:testResources (default-testResources) @ heroku1 —
[INFO] Using ‘UTF-8’ encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/ssharaf/heroku/heroku1/src/test/resources
[INFO] — maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ heroku1 —
[INFO] Nothing to compile – all classes are up to date
[INFO] — maven-surefire-plugin:2.7.2:test (default-test) @ heroku1 —
[INFO] No tests to run.
[INFO] Surefire report directory: /Users/ssharaf/heroku/heroku1/target/surefire-reports

There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] — maven-jar-plugin:2.3.1:jar (default-jar) @ heroku1 —
[INFO] Building jar: /Users/ssharaf/heroku/heroku1/target/heroku1-1.0-SNAPSHOT.jar
[INFO] — appassembler-maven-plugin:1.1.1:assemble (default) @ heroku1 —
[INFO] ————————————————————————
[INFO] ————————————————————————
[INFO] Total time: 2.496s
[INFO] Finished at: Thu Nov 17 20:41:15 PST 2011
[INFO] Final Memory: 5M/81M
[INFO] ————————————————————————


5. Next we create a Procfile which will define the process we want to run i.e. our main web app

I use VI editor on MAC.

e.g. vi Procfile

web:sh target/bin/webapp


6. Initialize the Git Repository by typing:

git init

now add the files using:

git add .

now commit the files to the repository using:

git commit -m “added heroku1 to the heroku cloud”

7. Now we are ready to create the Cedar Stack on heroku

$heroku create -s cedar

this will provision an application with some random name like cold-summer-876. Also it will configure git repository on heroku.

You can rename this to your app by using the heroku rename command.

e.g. $heroku rename heroku1

8. Lastly push the local git repository to heroku.

git push heroku master

This will take the whole git repository and upload it to heroku. Heroku recognizes it as java application using POM file and will use the dependencies defined to download appropriate artifacts. It will create a slug, which is basically a run time application instance. This slug gets replicated to a new dyno when we scale the app.

9. Now we can visit the app by using the command:

$heroku open

10. Some simple management commands to manage the app:

a. $heroku ps (shows the running processes)

b. $heroku log -t (will tail the logs)

c. $heroku scale web=2 (scale the web processes to 2)

d. $heroku releases (will show the last 2 releases)

Rel Change By When
—- ———————- ———- ———-
v33 Deploy d075337 ssharaf@salesforce.. 12 minutes ago
v32 Deploy 973f6e4 ssharaf@salesforce.. 16 minutes ago

Note that the content in the blog post was inspired by the tutorials on github by James Ward.


, , ,

Leave a comment

Java on Heroku

I will be doing a 3 part series on Java on Heroku — using Heroku’s latest cedar platform.
Stay tuned…

Leave a comment