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