Fixing “XMLGregorianCalendarImpl is internal proprietary API and may be removed in a future release”

While running builds I noticed the following warning from Maven..

XMLGregorianCalendarImpl is internal proprietary API and 
may be removed in a future release 

Rightfully so if you’re not using the correct convention for this..



type.setDate(new XMLGregorianCalendarImpl());


A quick look at Stackoverflow shows this: http://stackoverflow.com/a/5402007/1410035

In short you need to leverage a factory pattern and get an instance of the underlying implementation. The following snippet is an example of this:

import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import java.util.GregorianCalendar;
//
//
private XMLGregorianCalendar now;
//
//

now = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());

And your code will be in better shape and future-proofed as well.

Scripts to select the default Java version on MacOS

Thanks to superuser.com I found a neat trick to make it easy to list your installed Java versions and switch between them. Just add these to your .bashrc file:


#
#
#
alias java_ls='/usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d[,_]" | cut -d , -f 1 | colrm 1 4 | grep -v Home'

function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    export PATH=$JAVA_HOME/bin:$PATH
    java -version
}

The java_ls command reduces the output of java_home -V to just return the version numbers and java_use is just a shortcut for the exports and path updates you’d normally use.

Reversing a String in Java

Today I’m going to go ‘back to basics’ a bit and talk about string manipulation in Java. In particular, let’s talk about reversing a string. Something that is taught in every 100-level computer science class. The premise is simple enough. Take a string as input, return a string with the sequence of letters reversed.

So that means:

FOXTROT

Is turned into:

TORTXOF

Reversing a string is simple enough: Starting from the end of the source string take each character and append it to a new string. When you have reached the beginning of the source string return the result. It’s the approach you take that determines if you really know your Java coding, however.

In Java, the String object is immutable. This means that you cannot change it. And making a ‘change’ to a string actually creates a new string and disposes of the old one. Consider the following:

	String input = "FOXTROT";
	String s = "";

	for (int i= input.length(); i > 0 ; --i ) {
		s = s + input.charAt(i-1);
	}

Or rather what the Java compiler will actually turn the above code into:

	String input = "FOXTROT";
	String s = "";

	for (int i= input.length(); i > 0 ; --i ) {
		s = (new StringBuilder()).append(s).append(input.charAt(i-1)).toString();
	}

(Be thankful you don’t actually ever have to write that out yourself)

New strings are created for each iteration. One that will include all the characters from the previous iterations plus a new string that represents the current letter in your input variable. The previous version of the string and the character that was converted into a string are flagged to be garbage collected until the final result, “TORTXOF”, is created.

So you might think that’s not so bad. Just a few bytes, right? But if you do something like this when you’re parsing files with thousands of lines of text, it can add up fast. And when you build up a lot of objects for flagging for garbage collection you cause the JVM’s garbage collector to invoke more often, affecting your performance of your software and the scalability of the software you’re creating.

A more memory-savvy approach is to leverage the StringBuilder class. You can also use the StringBuffer class, which is synchronized and used if you need to write something that is thread-safe (which is a completely different topic). StringBuilder, since it’s not synchronized, has the benefit of also being faster.

So taking this into account the above code would look something like this:

	StringBuilder sb = new StringBuilder();
	String input = "FOXTROT";
	String s = "";

	for (int i=input.length(); i > 0 ; --i ) {
		sb.append(input.charAt(i-1));
	}
		

	s = sb.toString();

In this example, we’re down to two string objects: One for the input and one result. Far less GC will occur. Less overhead and work for the JVM and better scalability for your application.

The complete class shown for this example is below. Java is definitely a language that’s geared toward programmer productivity. But learning *how* the Java language itself works makes sure that you leverage it for maximum machine productivity as well.

package com.codethought.java101;

/**
 *	Simple string reverse utility class.  If you want to learn more about all the fun
 *  things you can do with String manipulation in Java I've provided the link below.
 *
 *  Note the use of a StringBuffer.  Strings are immutable.
 *  Meaning that if you change one - say by catenation - the previous version gets
 *  sent off to GC (garbage collection).  To minimize impact to GC, StringBuilders 
 *  can be used to create the string you need (since they're mutable).  When you 
 *  are done, you just call toString() on the builder and call it good.  You can find more out
 *  at:
 *  
 *  http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
 *  http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html
 *  
 *  @author David Orriss Jr
 */

class StringReverser  {

    /**
     * Reverses the string given to it.  
     * 
     * @param 	input 	the string to be reversed
     * @return null if null string is sent, the exact input for short strings, or the reversed string
     */
	public String reverse (String input) {
		StringBuilder sb = new StringBuilder();
		
		//defensive coding in the event someone tries to use a null string
		//you could also just let an NPE trigger.  personal choice
		if (input==null) {
			return null;
		}
		
		if (input.length()<2) {
			return input;
		}
		//strings are zero-based (see referenced docs for details).
	    //subtract 1 in the call to charAt, decrement to 'step back' 
		//down thru the string.
		for (int i=input.length(); i > 0 ; --i ) {
			sb.append(input.charAt(i-1));
		}
		
		return sb.toString();
	}
	
}

Getting Started with Grails

Grails is an open-source, rapid web application development framework that provides a super-productive full-stack programming model based on the Groovy scripting language and built on top of Spring, Hibernate, and other standard Java frameworks.

At least that’s what the marketing hype says.

My take – Grails is an open-source answer to Rails for the Java Enterprise crowd.  It’s got all the flexibility of Ruby on Rails with the added benefit of being able to quickly leverage Java SDK resources from within the underlying language (called Groovy).  I’ve recently been working with Grails and a can say it’s an excellent platform for rapidly developing web front-ends that can work with your existing enterprise infrastructure.  Even better, it can work with almost seamlessly with your current/legacy Java application codebase.  But the trick to all of this is getting started.  The available documentation that you find online could be FAR better (and I’ll talk about that in other posts) but here are some resources and books that I’ve found to be excellent starting points.

Programming Groovy: Dynamic Productivity for the Java Developer

by Venkat Subramaniam

Vslg To become proficient at Grails, you need to understand the Groovy Programming language, it’s constructs, and it’s importance in contrast to the Java ecosphere. Dr. Subramaniam’s book provides an excellent foundation and starting point. I’ve kept the printed edition in my backpack with me and refer to it regularly. I’ve found the information and insights Dr. Subramaniam provides to be invaluable.You can order the printed and PDF book editions at the Pragmatic Programmer’s Website:


http://pragprog.com/book/vslg/programming-groovy

Getting Started with Grails, Second Edition

Scott Davis & Jason Rudolph

LandingPageCoverSo you’ve started reading about Groovy, but you need to find out more about Grails… This book is the next logical step in that progression. Davis’ and Rudolph’s book provides a step-by-step example showing how to create a basic application (called Racetrack) that takes you along the same development lines that the Depot application in the Dave Thomas/David Heinemeier Hansson Rails book does. You’ll learn how to leverage the underlying Hibernate layer via GORM (Grails Object Relational Mapping), connecting to external databases, the basics for developing robust MVC-based applications using GSP and Grails controllers, implementing basic security and user authentication, and working with the vast plugin library available to Grails developers. The best part is you can the book is in a “try before you buy” model. You can download the book for free from the InfoQ website, and if you find you like the book and find it useful, you can support the author’s efforts and buy a print version. I found the book valuable and was able to get a basic version of an application completed for a project in a day after working through the Racetrack example.

http://www.infoq.com/minibooks/grails-getting-started

The Groovy Language Homepage

Before you can do Grails – you need to get Groovy. Go here and get your Groove on.

http://groovy.codehaus.org/

The Grails Quick Start

Get grails direct from the source at Grails.org. If you want to spin up a Grails application and you are familiar with Ruby and Rails – this will get you going fast. Be sure to read the Installation section for getting the Grails environment configured and running before you use the Quick Start or you’ll get nowhere fast.

http://grails.org/Quick+Start

Finding the Android Dev Phone 1 ROM Images

For some reason the ROM Images for the Android Dev Phone 1 have the links missing from the main ADP-1 download site. When you go to http://developer.htc.com/adp.html You’re greeted with a table of ROM images and file names but the links have been removed:

FirefoxScreenSnapz010.jpg

(You can click on the image to see the full-size version of the table.)

After some digging around I found that someone on the Android Developer List has found that the files are still on the website, only the links to them have been removed from the ADP-1 page. Creating the URL links are simple enough. You just start them with http://member.america.htc.com/download/RomCode/ADP and send with the file you want (i.e. ota-radio-2_22_19_26I.zip) The challenge here is that you cannot access those files directly, you have to be re-directed from http://developer.htc.com. If you’re a Linux or Mac user, this is solved with a simple shell script and the wget command. Modify the script for the ROM images that you want to download and you’re in business.

#!/bin/sh
IDIOTS1="http://developer.htc.com"
IDIOTS2="http://member.america.htc.com/download/RomCode/ADP"
wget "--referer=$IDIOTS1" "$IDIOTS2/ota-radio-2_22_19_26I.zip"
wget "--referer=$IDIOTS1" "$IDIOTS2/signed-dream_devphone_userdebug-img-14721.zip"
wget "--referer=$IDIOTS1" "$IDIOTS2/signed-dream_devphone_userdebug-ota-14721.zip"

If you’re a Windows user, you can accomplish the same thing if you have Cygwin installed: http://www.cygwin.com/


The script source for fetching the ROMs came from this discussion at The Android Developer mailing list. Thanks to Noah Tilton.

Installing Java 1.5 back into Snow Leopard

EDIT: This no longer works as of 10.6.5 without some additional tweaks. I have to update the post accordingly.

In an amazing moment of WTF I discovered this morning that after installing Mac OS X 10.6 (aka Snow Leopard) that the only version of Java running on it was 1.6. Now as an end-user, people probably won’t care. And I can kind of understand why Apple did it, given that Sun has done and End of Service Life for J2SE 5.0 (also known as Java 1.5). However a bunch of us still use earlier Java versions in active development projects. This was incredibly short-sighted of Apple. I’d guess that the 1.5 version probably exists on Snow Leopard Server Edition, but I’m not interested in paying for the server license when I don’t run OS X servers. However, it’s possible to bring back Java 1.5 onto your Snow Leopard installation. There are a few other pages that explain how to do this but I’ll re-iterate the steps I used here because it uses the most recent J2SE 5.0 release:

Preparation:

First, get Java for Mac OS X 10.5 Update 5 from Apple.

Next get Pacifist from CharlesSoft. This is a great utility. It’s saved my butt a few times. Especially when I needed to get something from an Apple installation package without having to re-run the installer. This qualifies as one of those times. If you don’t already have a registered copy, get one. It’s worth US $20.

How to install.

1. Use Finder to go to System > Library > Frameworks > JavaVM.framework > Versions and delete the two aliases (symlinks) "1.5" and "1.5.0". If you skip this step you will lose your Java 1.6 installation that comes with Snow Leopard. That would be bad. So don’t skip this step!

2. In finder, open JavaForMacOSX10.5Update5.pkg that’s inside JavaForMacOSX10.5Update5.dmg with Pacifist. Drill down to Contents > System > Library > Frameworks > JavaVM.framework > Versions.

3. In Pacifist, select 1.5 and 1.5.0, right-click, and chose Install to Default Location.

You can probably do the same thing with the 1.4 installation if you need it. I didn’t try.. but it would probably work.

Update 12-4-2009:After installing the latest Java update for OS X 10.6 I was greeted with the following change to my Java Frameworks directory. FinderScreenSnapz003.jpg

Apparently the updater saw fit to move my Java installation for 1.5 aside during the update and recreate it’s own aliases/symlinks. If this happens to you follow step one, and rename the 1.5.0 1 folder back to the original name.


Thanks to the following articles from which I borrowed and stole heavily…

chxo internets
oneswarm.org
daveyshafik.com

Subversion and Snow Leopard

Along with so many others, I upgraded to Snow Leopard. Overall the upgrade went without a hitch. However, I noticed that my Subversion repository was no longer available from Subclipse or via the Web Browser. Not good.

So I did some digging around and upon finding this article from Patrick Rice http://patrick-rice.net/daybook/2009/09/20/subversion-snow-leopard-etc/ I was up and working again in a few minutes.

Apparently with the Snow Leopard upgrade, the Apache mod_dav_svn configuration was removed from /etc/apache2/other/svn.conf. Patrick references the following article. It’s extremely educational and informative: How To: Manage Your Own Subversion Repository In Leopard. The details still apply in Snow Leopard, as well.

Following these articles I just created a new /etc/apache2/other/svn.conf.

LoadModule dav_svn_module /usr/libexec/apache2/mod_dav_svn.so

<Location /svn>
    DAV svn

    SVNParentPath /Users/Shared/svn

    AuthType Basic
    AuthName "Subversion repository"
    AuthUserFile /etc/apache2/svn-auth-file
    Require valid-user
</Location>

Restart the Apache server (via Sharing in the System Preferences application). And you should have your repository back.

Manually Update your T-Mobile G1 to OS 1.5 (Cupcake)

T-Mobile was supposed to release Android OS 1.5 (originally code-named ‘Cupcake’) was supposed to be released the week of May 18th. However T-Mobile decided to delay the release.

Enter the Android community… Someone has found the downloadable version of Cupcake, signed and ready to install on the T-Mobile G1! And with a few simple steps, you can install it before the T-Mobile OTA (over-the-air) push.

Now, without any further ado – the following warning:

WARNING: T-Mobile does not support manual installations and will not assume responsibility for any device problems or failures that occur from following these instructions.

*NOTICE: This can be a risky procedure, and if you make a mistake and brick your phone: T-Mobile, the T-Mobile Forums, authors of this post (i.e. ME), or other subsequent discussions, nor any party, company, corporate entity, individual, or estate; living or dead, associated or otherwise connected with the above shall not be held liable for any damage you do to your device, others devices, your person, other people/living things, or property belonging to you any other entity in the known universe should you attempt to root your phone. You take full responsibility and liability for any action you choose to take to attempt to gain root access to your phone. Do this at your own risk.

  1. Go download the Android 1.5 ‘Cupcake’ release here.
  2. Rename the downloaded file from signed-kila-ota-148830.de6a94ca.zip to update.zip and place it at the root i.e the very top directory of your Micro SD card. (If you added the file to your microSD card by connecting the handset to your computer via USB [rather than using a dedicated microSD card reader], make sure to unmount it and disconnect the USB cable now.
  3. Turn off your G1 Make sure it is completely powered off. Now again turn it on by holding the Home+End keys until you see T-Mobile G1 logo.
  4. From the icon screen, open the keyboard and hit Alt+L.
  5. Press Alt+S to begin the update. Remember, the update needs to be in the root of the Micro SD card and needs to be named update.zip.
  6. Once it finishes, follow the onscreen instructions and press Home+Back to finish.
  7. G1 Phone will reboot a few times to flash different parts of the firmware.

If all went well, you should now be running Android Release 1.5 on your T-Mobile G1…!

And, yes.. I installed it using the above steps.. and it’s working great..!

Android – Matching minSdkVersion to API version

In my last post I mentioned the android:minSdkVersion attribute to <uses-sdk> tag. As of SDK 1.5 the attribute values used correspond to the following API releases:

minSdkVersion API Version
1 1.0
2 1.1
3 1.5

You can read more about all of this at http://developer.android.com/sdk/android-1.5.html