Identifiers and JavaBeans

Identifiers are what we use to identify parts of our code, whether this is a class, method or a variable. There are some ground rules on the names we can give to these identifiers, and it is good to understand the ground rules regarding these.

There are 3 levels, or aspects of identifiers, and are summarised as follows

Legal Identifiers – Java has keywords which the compiler uses, and also other rules on what can be used as an identifier, so in order to get your code compiling (and hopefully running too) you’ll need to make sure the names you choose for your variables/classes/methods are legal, more on this below

Suns’ Java Code conventions – Technically, you only really need to adhere to the legal identifier rules, but Sun has its own conventions on identifiers and it is good practice to follow suit. You should really familiarise yourself with these and try to follow their conventions where at all possible.

JavaBeans naming standards – A further set of recommended indentifier rules. Once again you’re not forced to follow these, but it is good practice to do so, and makes your code more clear and readable to other users.

As I mentioned above, you only have to follow the legal identifier naming rules, but it is good practice to follow the conventions in place as it will make your code a lot neater and easier to read for others. Think of it like this, if you need some help with your coding, and you post some samples to a forum, you’ll get much better responses if people can understand what your code is doing.

Legal Identifiers

OK, so legal identifiers, your variable names will either be legal (this is good!) or illegal (Bad, very bad, compiler will throw its toys out of the pram). In order to be a legal identifier, you must follow the following rules

  1. First letter must be a letter (a, b, c etc), or a currency character ($ for example), or one of the connecting characters such as the underscore (_)
  2. First letter must NOT be a number
  3. After the first character, things get more relaxed, and you are able to use any combinations of letters, numbers, currency characters or connecting strings (underscores etc)
  4. You can’t use a Java keyword as an indentifier, this would make it illegal
  5. Identifiers are case sensitive, that means that the variable myVariable is different to MYVARIABLE

Here are some perfectly legal identifiers

  • String _s;
  • String $s;
  • String ______s;
  • String _$;
  • String this_isAnIncredibly_long_but_perfectly_valid_identifier;

And here are some illegal identifiers, using these will throw an error so memorise the rules and steer clear!

  • String ::;
  • String s#
  • String .myString;
  • String 1s;
  • String -s;

Suns’ Java Code Conventions

Wouldn’t it be great if every Java developer was writing code that followed a set of rules for naming conventions? That would be ideal wouldn’t it? Well in the real world its not going to just happen, but Sun have taken a good step toward achieving this by releasing the Java Code Conventions. This is a short, brief set of guidelines that Sun has produced to help steer developers onto a best practice track of naming our identifiers. It recommends some of the following approaches

Classes
For naming your classes, Sun recommend that you start off with a capital letter, and if you have multiple words then you concatenate them making the first letter of each word a capital, a term often refered to as CamelCase. Classes should also typically be nouns, being names of things, the following are good examples

  • Person
  • Student
  • TextBook

Interfaces
Interfaces should follow the same rules as classes, except the name should typically be an adjective instead of a noun, this helps a coder to indentify them as an interface or a contract easier. A few good examples are

  • Runnable
  • Drawable
  • Serializable
  • Throwable

Methods
The first letter of the method name should be lower case, then the usual camelCase rules should apply, some examples are as follows

  • getColor
  • isAvailable
  • doSomething

Variables
Same as with methods, the first letter should be lower case, then camelCase. Some examples are as follows

  • myString
  • myCar
  • player
  • studentReferenceNumber

Constants
Contants should be named in upper case, using the underscore as the connecting character between words. Constants are created by declaring the variable as static and final. Some examples are as follows

  • HOST_NAME
  • PORT_NUMBER
  • MAX_WIDTH

JavaBeans Naming Standards

When you become more involved in your Java development, you will most likely come across the notion of JavaBeans, these are like objects which have instance properties. Typically these properties will be set as private, and you will be using accessor methods to obtain or set them.

Imagine that you have a class called Person, which may have properties such as name and age. The indentifiers I’ve already mentioned just now follow the Sun code convention, however you may wish to make them private, meaning you will most likely need to provide accessor methods, which would follow the Sun conventions, such as

getName
setAge

Ideally, for setting a variable you should create a method prefixed with set, and for getting a variable you should prefix with get.
With booleans, is it good practice to prefix with is, such as isAvailable

Summary

So there you have it, I’ve hopefully explained the basics that you need to know for identifiers. Just remember that your identifiers must at least be legal, but it is also good practice to follow the Sun and JavaBeans naming conventions where at all possible. Please see the following links for further reading. Any comments/suggestions greatly appreciated!

Tutorial; How to call Yahoo! REST web services the easy way!

I’ve got some requirements where I need to call a REST web service from an Android device, so I figured I’d get back to basics, and try to call a REST service through a simple Java application, just to see if I can get it working.

After trawling the web for what seemed like hours, I was finally able to come up with a simple yet effective solution. Consider the following

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * This simple class demonstrates how to call a 
 * REST web service provided by Yahoo! Developer Network APIs
 * @author james.elsey
 * @date 05/October/2010
 */
public class RestTest {

	public static void main(String[] args) 
	{
		
		String yahooAppId = "sam.A2DV34EOgopFWeVeqLVnaoTVmEIVZnVtd58o5IRCsZ4kcwBTSp4gVl9E7hnnbRxDgRo-";
		String URL = "http://where.yahooapis.com/geocode?location=701+First+Ave,+Sunnyvale,+CA&appid=";

		String URLtoCall = URL + yahooAppId;
		
		try 
		{
			String responseString = httpGet(URLtoCall);
			
			// Do something with the returned response, currently just printing to console
			System.out.println(responseString);
		} 
		catch (IOException e) 
		{
			// Handle exception here, currently just printing stack trace
			e.printStackTrace();
		}

	}
	
	/**
	 * Call URL and buffer response into a String
	 * @param urlString URL to be called
	 * @return String The response XML String
	 * @throws IOException
	 */
	public static String httpGet(String urlString) throws IOException 
	{
		  URL url = new URL(urlString);
		  HttpURLConnection conn =
		      (HttpURLConnection) url.openConnection();

		  // Check for successful response code or throw error
		  if (conn.getResponseCode() != 200) 
		  {
		    throw new IOException(conn.getResponseMessage());
		  }

		  // Buffer the result into a string
		  BufferedReader buffrd = new BufferedReader(
		      new InputStreamReader(conn.getInputStream()));
		  StringBuilder sb = new StringBuilder();
		  String line;
		  while ((line = buffrd.readLine()) != null) 
		  {
		    sb.append(line);
		  }

		  buffrd.close();
		  conn.disconnect();
		  return sb.toString();
	}
	
}

This simple piece of code will create a URL to be called, call it, and print out the result which in this case is an XML String. This is a particualry basic way of consuming a REST service, and using 3rd party libraries such as Apache HTTP Commons may provide a cleaner and more effective solution

This will give you a XML String response, its up to you how you deal with the response, you can parse it using SAX for example. In my next tutorial I’ll look at parsing, and how we can intergrate this all with an Android application

I was quite impressed with the documentation and support provided by the Yahoo! Developer Network, I will certainly be using this more frequently as their web services are easier to use than Googles, which is an odd occasion

Some thoughts and opinions on ITIL v3 Foundation

After recently sitting a course and exam for ITIL v3 Foundation, I thought it would be a good idea to reflect on some of the topics covered while they are fresh on my mind, and to also provide good future references.

I will try to cover the topics the exam requires you to know in order to pass, I’ll try to write an easy to understand guide, as when I was researching for specifics I was often overloaded with information and found it quite difficult to understand, hopefully I can target those that want a quick and brief introduction.

I will organise all my posts under a resources page, which should link out to the relevant articles, to keep it nice and tidy

Game development in process…

I’ve been a video gamer since I can remember, completed countless titles on various formats and enjoy the challenge they provide, however I’ve discovered a new challenge, creating them.

I’m not a games designer by trade, and have no prior experience, unless you can include some tic-tac-toe games I did at college. This is purely a learning process, and to have some fun on the side

I’ve decided to try and come up with a game. I’ve always been a fan of the RPG genre of gaming, and was really into Pokemon back in the day along with various other console RPGs, and recently MMORPG games on the PC. I’m trying to develop a concept that builds upon some of the very good features of these games, Pokemon had a very addictive gameplay where you would hunt for creatures to capture. There were various colours and types of creature to get, making the hunt fun for the player, something to aim for.

Other RPG games focus around character progression, the idea that you can take a character and customise it really makes the character feel personal, and the gamer sub-consiouclsly builds up a relationship with the imaginary character.

My aim is to create a game where players can hunt for creatures, but can also progress their character in diverse routes, harnessing the core features of addictiveness, and customisation. I’m by no means making this a business adventure, and probably won’t get very far, but I’m a big fan of side projects and like to keep thinking and developing ideas.

My secondary goal of this is to try to generate visitors to the blog, to help share knowledge that I gain, to promote my work and my reputation, and to also earn some financial rewards through Ad revenue.

A good friend of mine, Lee, has recently taken his first step in games design, and has created an application that interfaces with a popular online browser game, Lord of Ultima. This is a strategy/RTS type game, and he was cleverly able to create a planner which allows players to plan their next moves to determine their future positions in the game. Lee is getting a substantial amount of unique visitors per month, and has really tapped into a good niche. He is also working on a new teamed RPG style game, and after a few discussions this prompted my thinking into creating my own work of art.

I plan to keep my code open source, to allow people to see what is under the hood, as is not often possible with games, this will hopefully demonstrate some of my code crafting skills, and enable the community to comment and suggest improvements and such. I may allow other developers to become code-committers if the situation arises.

I’ll keep my Open Source page updated where I can, mostly working on ideas at the moment but hope to have something up before christmas

Android; Querying data from your phone book; names, addresses, postcodes, emails etc

One of the more useful features of Android is the ability to obtain data from elements of Android itself, such as the phone book. Your application may require data from your phone itself, such as your contacts, and more specific items such as all your contacts email addresses, or postcodes. In this post I will help explain how you can obtain this data. There are some details on the Android documenation, but the examples are not particularly clear.

The easiest method for retreiving multiple contact data at a time is to first obtain all the unique contact IDs, and then use those in further loops to query for other data. I had researched multiple ways of obtaining this data, but most references that I could find on the web were refering to version 1.6 of Android, which uses the People class. The below version is fully updated for 2.2.

Contact IDs

The first task you need to do is to obtain the IDs for your contacts, please have a look at the following snippet, then refer to the description below to understand what is happening

Cursor cursor = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0)
{
	while (cursor.moveToNext())
        {
	    // Pick out the ID, and the Display name of the
            // contact from the current row of the cursor
            String id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
            String name = cursor.getString(cursor.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME));
            // Do something with the values you have,
            // such as print them out or add to a list
            System.out.println("Current contact on this iteration is : " + name);

            // This is where we query for Emails, Addresses etc
            // Add snippets below into here, depending on what you need
	}
}
cursor.close();

The above code will query the CONTENT_URI provider, this contains the contacts ID and Display name. We need to do this first so we can retain the contact ID and use it in where clauses when obtaining other data. I will explain more about how the querying works at a later date.

So, run the above and you will get the ID and name for each contact on iteration. So if you have 5 contacts in your phone book, it will loop through 5 times and print out each of their IDs and names. I’d suggest you do something more useful that just printing them out, add them into a collection so you can use this elsewhere

Contact Addresses, including postcodes

From the above code, we already have the contact Ids, so lets use those to pick out the addresses for contacts. Have a look at the following

String addrWhere = ContactsContract.Data.CONTACT_ID
		+ " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";

// We already have the contact Id in id, so lets use it in the where clause
String[] addrWhereParams = new String[] {id,
		ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };

// Run the query, using the where params
Cursor addrCur = getContentResolver().query(
						ContactsContract.Data.CONTENT_URI,
						null,
						addrWhere,
						addrWhereParams,
						null);
while (addrCur.moveToNext()) {
String postalCode = addrCur
	.getString(addrCur
	.getColumnIndex(ContactsContract.CommonDataKinds
					.StructuredPostal.POSTCODE));
String streetName = addrCur
	.getString(addrCur
	.getColumnIndex(ContactsContract.CommonDataKinds
					.StructuredPostal.STREET));
String cityName = addrCur
	.getString(addrCur
	.getColumnIndex(ContactsContract.CommonDataKinds
					.StructuredPostal.CITY));
System.out.println("Postcode is " + postalCode);
System.out.println("Street name is " + streetName);
System.out.println("City name is is " + cityName);
}
addrCur.close();

Using the contact ID we obtained earlier, we use this to pick out the addresses for that particular contact. I have only picked out the POSTCODE, STREET and CITY, but there are several others specified in the Android documenation

Contact Email addresses
Contact Phone numbers
Others

Android; Using intents to refresh tab content

As part of my MeCercana application, I needed to refresh data in some form. My application has 3 tabs, one of the tabs displays contacts from the contacts book, this works great if you switch the phone off after adding a new contact, but that isn’t ideal.

What I needed, was a way to refresh, or re-query the data on demand, the best way to do this was to bind an intent onto the tab, so each time you click the tab icon it fires off that Intent and thus simulates a forced refresh.

This is how I setup my tab, I created an Activity called DefaultActivity, which acts as the tab container

public void onCreate(Bundle savedInstanceState)
{
	    super.onCreate(savedInstanceState);
    	    setContentView(R.layout.main);

	    Resources res = getResources();
	    TabHost tabHost = getTabHost();
	    TabHost.TabSpec spec;
	    Intent intent;

	    // Create an Intent to launch an Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, MyContactsActivity.class);
	    // Initialize a TabSpec for each tab and add it to the TabHost
	    spec = tabHost.newTabSpec("myContacts");
	    spec.setIndicator("", res.getDrawable(R.drawable.ic_tab_contacts));
	    //Adding a flag into the intent, will use this later
            intent.putExtra("RefreshContacts", true);
	    spec.setContent(intent);
	    tabHost.addTab(spec);

            // Repeat the above to add more tabs
}

Don’t worry too much about what the above does, I’ll explain that in another post, but as a quick heads up, it creates some tabs and assigns some layouts to them. An Intent is bound to a tab host, which basically means if you click the tab icon it will issue that Intent. This is particulary useful as we can put extra data onto the intent, and then use it at the other end

Right, now over to the target activity. So we’ve bound an intent onto the tab button, now lets see what happens.

        @Override
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    drawUI();
	}

	/**
	 * This is called immediately after the onCreate() method is run, and also when an activity
	 * is started, such as startActivity(intent)
	 */
	@Override
	public void onStart()
	{
		super.onStart();
		drawUI();
	}

	/**
	 * Placeholder method to initialise data and UI
	 */
	public void drawUI()
	{
		setContentView(R.layout.contactsview);
                // Do stuff in here such as querying for contacts
        }

Firstly, the onCreate method is called, and in here we initialise anything that is important for the activity to run. Secondly, the onStart method will be called immediately after. Both of these use the common method of drawUI, which takes care of getting the data and putting it on screen.

The reason for this approach, is to firstly setup the data if it is the first time we are running this activity. Secondly the onStart is called when we start the activity (from the button) so therefore we need to run the drawUI method again to refresh the data.

Simple! Any questions/comments/suggestions, then please let me know!

Android; Implementing global state; share data between Activities and across your application

If your developing an Android application, chances are you will have multiple activities that perform various tasks. One of my first questions when I was investigating Android, was how can I pass data between my Activities? Moreover, how can I retain some form of state, globally throughout my application, so I can dynamically pass data without having to persist to a datastore between Activities.

The solution; Use the applications Context

Firstly, you should create a new class that will behave as our global object, for example :

package com.jameselsey.domain;

import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import android.app.Application;

/**
* This is a global POJO that we attach data to which we
* want to use across the application
* @author James Elsey
*
*/
public class GlobalState extends Application
{
private String testMe;

public String getTestMe() {
return testMe;
}
public void setTestMe(String testMe) {
this.testMe = testMe;
}
}

The above class declares one String, with accessor methods. Soon we will see how this object will be available throughout the application. You can add anything you want onto this object, in my application I have a List of other domain classes that I wanted to use elsewhere in my application.

Right, now that you have your global class defined, you need to specify this in your AndroidManifest file, otherwise the application won’t know where to find this class, and you will get a ClassNotFoundException

Locate your application tag, and add this into it :

android:name="com.jameselsey.domain.GlobalState"

It must reference your fully qualified global state class

Now you have it set, your ready to start putting data in, and pulling data out, use the following

// Set values
GlobalState gs = (GlobalState) getApplication();
gs.setTestMe("Some String");</code>

// Get values
GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

And thats it! Off you go!

Converting UK Postcodes to co ordinates to use in Android

If your developing applications on Android, and are looking at using the Maps API, chances are you are going to want to plot items on the map, and in order to do that you need to know the longtitude and latitude of the location you wish to mark.

I’ll assume that you already have a solid base to work from, as in a working Android application with a MapView enabled.

To locate an item on the map you need to use a GeoPoint, example below

private float longtitude;
private float latitude;
GeoPoint p = new GeoPoint((int)(latitude * 1E6), (int)(longtitudel * 1E6));

Notice the usage of float values, the easiest way of getting from a postcode to a co ordinate is to obtain the longtitude and latitude values from a conversion website, and then to add it to the above forumla. The reason being is because it is incredibly difficult to find the int values of a co ordinates, so it is easier to get a float value and convert

In brief, do the following

  1. Go to MyGeoPosition.com and enter your postcode
  2. From the URLs it generates, take the longtitude and latitude values, then enter them in the above float variables
  3. Generate your GeoPoint using the above formula
  4. Start plotting!

Incrementing and Decrementing, the operators

The operators for incrementing and decrementing in Java has been irritating me for some time now, just when I think I understand whats going on, I try a mock exam for SCJP and I get caught out. So I’ve decided to sit down, do a bit of reading, and drill it out.

Take this example, what do you think the output will be?

int a = 1;
int b = 5;
System.out.print("a++ is : " + a++);
System.out.print("++b is : " + ++b);

The output will be :

1
6

Right heres the explanation. We have two things going on here, we have a Postfix(b++) operator and a Prefix(++b) operator.

What this means, in plain and simplest English is as follows

<em>a++ means, use the value of a in the executing statement, THEN increment it</em>

<em>++b means, BEFORE we use the value of b, increment it</em>

So there you have it, if the operator comes before the variable <em>(Prefix)</em>, it means do the incrementing/decrementing before you evaluate the expression in question, and if the operator comes after <em>(Postfix)</em>, then use the current value of the variable, and when thats done, increment it (maybe for use next time, such as in a loop?)

The same works for the decrementing operator, such as –a or a–

Simples

FTP: How to download all files, directories and sub-directories

I’ve recently decided to cancel my hosting package with 1and1, as I don’t really have much use for it any more what with all the freebies Google is dishing out.

I needed to take a backup of all my files, and unfortunately mget doesn’t (or at least at the time) doesn’t support the downloading of directories, luckily there is another tool to help, <a href=”http://en.wikipedia.org/wiki/Wget”>wget</a>.

This example of wget will download all files (the -r specifies recursively) from a directory on the domain

<code>wget -r ftp://account_name:password@mydomain.com/directoryname</code>