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();
	}
	
}

Ruby 1.9, TextMate and Segmentation fault errors

While tinkering with Ruby 1.9 in TextMate I found that Ruby was segfaulting on the TextMate Ruby Bundle output screen.

/Users/codethought/Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RubyMate/catch_exception.rb:16: [BUG] Segmentation fault
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]

Turns out you can fix the error yourself… as I found at rubyflow.com

http://www.rubyflow.com/items/6795-solution-to-ruby-1-9-3-segfaulting-when-using-textmate-ruby-b

To quote here:

Edit the catch_exception.rb file in your Ruby bundle in TextMate. To get into it on my machine I had to do:

mate Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RubyMate/catch_exception.rb

Then, comment out the require “cgi” line. And then remove all references to CGI::escapeHTML.

But a simpler way is to go is to download the change that someone else made from github and install it yourself.

https://gist.github.com/1354592

And put the new version catch_exception.rb in the following directory yourself:

Applications/TextMate.app/Contents/SharedSupport/Bundles/Ruby.tmbundle/Support/RubyMate/

And your problem will be resolved.

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

ADT and the ‘Debug Certificate Expired’ Error

Ran into this just this morning. I started up my Eclipse for Android environment and had all my projects greeting me with the error; “Debug certificate expired on 10/1/2011”. It’s an easy enough fix.

Delete your debug certificate under ~/.android/debug.keystore (on Linux and Mac OS X); the directory is something like %USERHOME%/.androidon Windows.

The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.

Problem solved.

Open Terminal Here in Snow Leopard using Automator

A subject that has been visited plenty of times is having an “Open Terminal Here” ability from the Finder. For developers, it’s a easy way to look at files or folders and then jump quickly to a shell for the folder and execute shell commands (like mv or cp). Or to execute a build using make or ant.

I decided to make a version of that would work off the “Services” context menu. If you control-click a file and select Services | Open Terminal Here you’ll be taken to the folder containing that file. A control-click on a folder will take you to the folder you selected.

To use it, just unzip this file and put it in your ~/Library/Services folder.

Open Terminal Here.zip

The code itself is pretty straightforward:

(* 
   Workflow - Open Terminal Here 
   By David Orriss Jr - November 2010
   Another "Open Terminal Here" option.  This time as a service workflow in Automator

   For Snow Leopard
*)
on run {input, parameters}
	
	set the_path to (the POSIX path of input)
	
	set AppleScript's text item delimiters to "/"
	
	
	if the_path does not end with "/" then
		set parentPath to (items 1 thru -2 of text items of the_path) as string
		set the_path to parentPath
	end if
	
	set cmd to "cd " & quoted form of the_path & " && echo $'\ec'"
	
	tell application "System Events" to set terminalIsRunning to exists application process "Terminal"
	
	tell application "Terminal"
		activate
		if terminalIsRunning is true then
			do script with command cmd
		else
			do script with command cmd in window 1
		end if
	end tell
end run

Seconds, Minutes, Hours – Converting Time Units in Ruby

I’m sure you’ve probably seen this question in your programming classes.. I decided I wanted to play with Ruby again and was remind of this problem, so thought it might be fun as a simple exercise to do this in Ruby.

The problem is to take a long integer and convert it to hours, minutes and seconds. This is a common issue in games, for example, where a countdown timer is represent internally in seconds. But players don’t want to see some huge number like 43678 seconds. They’d rather see 12:07:58 for hours, minutes and seconds. A couple of uses of the mod operator, and a couple of uses of the built-in formatter and you’re good to go.
Update: I wanted to clean up the code a bit more and put the ruby equivalent of a “main” via the __FILE__ check. This way you can just reuse the code via require if you so desire.

#!/usr/bin/env ruby

class TimeFormatter

  def format_time (timeElapsed) 

    @timeElapsed = timeElapsed

    #find the seconds
    seconds = @timeElapsed % 60

    #find the minutes
    minutes = (@timeElapsed / 60) % 60

    #find the hours
    hours = (@timeElapsed/3600)

    #format the time

    return hours.to_s + ":" + format("%02d",minutes.to_s) + ":" + format("%02d",seconds.to_s)
  end
end

if __FILE__ == $0
  formatter = TimeFormatter.new

  puts formatter.format_time(43678)
end

require: command not found in ruby

While I was getting some old Ruby code of mine out to convert ruby code to pretty HTML-formatted code suitable for blogging from Wolfman’s Howlings I got the following error:


$ ./ruby2html.rb 
./ruby2html.rb: line 9: require: command not found
./ruby2html.rb: line 10: require: command not found
./ruby2html.rb: line 11: require: command not found
./ruby2html.rb: line 14: syntax error near unexpected token `('
./ruby2html.rb: line 14: `    code= File.read(ARGV[0])'

Never saw this problem before, but obviously it was frustrating.

What had happened was I hadn’t deleted the tab spaces before the #!/usr/bin/env ruby line.

Apparently if there is any white space before the #!/usr/bin/env ruby the script will not run.

Swell.. 😐

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.