How to set a custom DNS server with Java System properties

Recently I was in the position of having to override the system default DNS server configuration with a custom DNS server for a Java app. Expecting this to be easily achievable along the line of the well-known http.proxyHost/http.proxyPort JVM parameters I whipped out Google.

Turned out to not to be so simple.

Obviously I got some search hits, but no simple recipe for the simple configuration change I was looking for. After spending some time with the leads I was able to conclude that, as a consequence of  an apparent exemple of over-engineering by Sun, the following is explicitly required just to change the JVM DNS server:

//Override system DNS setting with Google free DNS server
System.setProperty("sun.net.spi.nameservice.nameservers", "8.8.8.8");
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");

Mercurial tooling reaching the tipping point

The MercurialEclipse context menu certainly looks comprehensive..

A tipping point can be defined as the levels at which the momentum for change becomes unstoppable.

I’d venture to state that distributed version control system Mercurial reached its tipping point when version 1.6.0 of MercurialEclipse recently was released.  At least for me. 🙂 During the last years I’ve been consistently and repeatedly underwhelmed with the state of Mercurial tooling in my favoured integrated development enviroment, resorting to use hg at the command line exclusively.  Command line interfaces are good for many things but it’s hard to let go of the comforts of a good GUI when one is used to the brilliant Subclipse Subversion plugin.

MercurialEclipse is a quantum leap. I sincerely hope the availability of first class Eclipse support for Mercurial will be the tipping point for distributed version control systems in general and Mercurial in particular!

Top Clojure Links

On my quest to pick up Clojure during 2010 I’m primarily accompanied by the very solid Programming Clojure by Stuart Halloway. I’ve however also stumbled upon some interesting, cool, thought-provoking etc. Clojure resources on the web. So here goes – in no particular order:

Clojure – Functional Programming for the JVM by R. Mark Volkmann is both a great introductory article and a handy reference. Actually a cheap aspiring functional programmers alternative to Programming Clojure!

MiGLayout: The one Java layout manager that does it all by Chris Hardin is another of the many excellent Java News Briefs by Object Computing, Inc. (OCI). MIGLayout is a Java Swing UI layout manager which is as powerful and expressive as the Clojure programming language. This makes MIGLayout an excellent choice for all your Clojure UI needs!

Full Disclojure is a series of easily digested screen casts highlighting a particular feature of Clojure in each episode. The screen casts are accompanied by clear audio and the well-paced action takes place directly at the REPL (as it should!). Full Disclojure is on an accessible level for newbies and covers, among other topics, many of the cool features introduced in Clojure 1.1.0.

Hot Code Swapping is not the exclusive domain of Erlang!

Put a Spotlight on a MacPort

OS X essentiality MacPorts has a convenient command line user interface for querying and browsing available software packages. For instance a simple "ports info pine” will net:

pine @4.64 (mail)
Variants:             darwin_9, ssl_plain
Description:          Pine is a tool for reading, sending, and managing
                      electronic messages that was designed with novice
                      users inmind.
Homepage:             http://www.washington.edu/pine/

Platforms:            darwin
License:              unknown
Maintainers:          sean@fuzzymagic.com

A more graphical option for the occasional port lookup is to use OS X built-in file indexing system Spotlight that happily provides as-you-type matching of available ports in the local ports tree.

The corresponding port file directory will typically be the top match when searching for well-known unix software.

Weighing in on programming language investment options for 2010

In the classic text The Pragmatic Programmer: From Journeyman to Master Andrew Hunt and David Thomas make a very convincing case for practicing software developers to pick up a new programming language each year as a part of a deliberate knowledge investment plan. The software industry can be a pretty fast-moving place sometimes, and keeping on top of (or even ahead of) the latest trends can be a pretty smart thing career-wise, particularly so in a recession. Also, new languages broadens ones horizons, and analogous with picking up new natural languages can further proficiency in ones mother tongue (bread-and-butter programming language).

The language of 2009 was Groovy for me. As a (primarily) Java developer you simply gotta love the groovy! I would like to describe the language as a super charged version of Java that shares most of Java syntax, but requires far less boiler plate code, supports dynamic typing and the closures Sun successfully has been able to keep out of the Java programming language up til now¹. Groovy is extremely interoperable with Java: groovy source code compiles to Java bytecode and calling Java code from Groovy or vice verse is trivial. The Groovy take on the famous Ruby-On-Rails web application framework, Grails, is an impressive invention even if it has its problems.

The Programmatic Programmer argues that one should, just in conventional investing, diversify ones portfolio. For 2010 I’m ready to take on a language that shares far fewer traits with my current personal, as well and most of the industry’s, primary bread-and-butter language Java than Groovy does. Maybe even a  functional programming language. I decided on short listing Scala, Erlang and Clojure.

The short list

Scala appears to enjoy tremendous momentum for the moment. If Groovy is Java on steroids, Scala is Java 2.0. Founder of the Groovy programming language James Strachan has openly stated that if Scala had been around in 2003, Groovy would probably never has seen the light of day. Scala supports a mixed imperative/functional programming model and is a statically typed language with an advanced type system. Scala compiles to JVM bytecode and is Java interoperable on the same level as Groovy. Unfortunately Scala appears be be a quite complex language – the “authoritative tutorial” on the language, Programming in Scala by language founder Martin Odersky, contains more than 750 pages.

Erlang is a  functional language with its origin within the telecommunication industry. Erlang has a strong focus on efficient concurrent execution and fault tolerance. Erlang is of Swedish origin, fully functional and has a syntax very different compared to C syntax language. On the down side, Java interoperability is very weak as Erlang compiles to a none-JVM bytecode. Also, Erlang momentum appears to currently be rather diminutive.

Clojure is a LISP and thus both homoiconic and very functional in nature. The syntax is completely dissimilar to C languages, being much smaller and relying on liberal usage of lots and lots of nice parentheses. Clojure is fully JVM-interoperable and appears to have some traction within the developer community, perhaps not on the level of Scala but there’s definitely some momentum out there.

What investment option did you go with for this year?

¹) Late 2009, Sun finally – obviously much overdue – announced that we can expect closures to be included in Java 1.7 after all.

OS X Essentials: MacPorts

There is plenty of great  Mac software available. Among my favorites are the instant messaging client Adium, the editor TextMate and the media center Plex. This is software that is OS X-only – stuff I really miss when I run Linux. However there is now way around the fact that Linux has an advantage when it comes to general Unix software. Most stuff is only an apt-get away in Debian-derived Linux distributions, while you need to Google around to find a disk image when you are on a Mac, or – even uglier – download and untar something under /usr/local or similar.

However it is in fact perfectly possible to achieve an apt-get level of convenience on a Mac! The silver bullet is MacPorts – a Mac implementation of the BSD ports system. The only problem is just that MacPorts is a ports implementation meaning that only source code is pulled from the net, all binaries are built locally (in the case of MacPorts with the Apple Xcode tool chain). MacPorts is thus a bad fit for the impatient (especially if one for instance would aspire to install the Gimp port with all its dependencies). I’ve no complaints with regard to the user interface (command line based just as apt-get) or port availability and upstream synchronization frequency. Everything I have desired to install so far has successfully been pulled down, configured, built and installed under the MacPorts prefix /opt/local.

I was delighted to find that MacPorts even provided a port of Java build tool staple Maven.

Review: Practical API Design: Confessions of a Java Framework Architect

I’m a bit behind schedule with regard to my book reviewing commitment but I’ve at least been able to finish off a couple of the volumes I committed to and now I am ready to share some views on Practical API Design by Jaroslav Tulach.

This book is a rather personal presentation by Tulach – the author is constantly relating to his personal experiences as developer/architect of the Netbeans platform (on which the famous IDE is built).  Tulach doesn’t refrain from lengthy, and sometimes rather esoteric, argumentations and analogies even going so far as to comparing API design with astronomical observations.

There are some golden nuggets here and there, some techniques and observations that were new to me, but in general I think there is too little meat and too much padding. The book is perhaps of most interest to designers of very long living API:s with a large number of disparate users, for lowly general Java devs like me there are far more rewarding reads among the books that have recently been published in the field of software engineering. A suggestion would be the extremely “meaty” Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin (a.k.a Uncle Bob).

Testing logging behaviour in four code lines flat

Update: Testing logging without Mockito is also viable.

Adding assertions for logging behaviour to my unit tests have been a long standing item om my ToDo list. This imperfection have been a nagging thorn in my side since it obvious that logging is a critical aspect (no AOP pun intended) of any commercial system of importance. But I thought that it must be hard and boring work to add tests for logging. To be honest I’m no fan of boring work. Recently I finally got around to take a shot at it and found it surprisingly easy to accomplish in a mavenized Spring project with the help of the everyone’s favorite Java mocking library: Mockito.

Originally I though I had to modify all the classes under test to accept a log4j Logger as constructor argument and mock that logger in the unit test. This would have required quite a lot of code rewrite since most classes in the project simply use:

Logger.getLogger(this.getClass())

to get access to a logger instance. Also I don’t like the idea to “pollute” the constructors with additional arguments, most classes had just enough dependencies passed in that way as it were.

Next up was an idea to write a custom log4j Appender and add a log4j.properties to src/test/resources with:

log4j.rootLogger=ERROR,TESTAPPENDER
log4j.appender.TESTAPPENDER=com.my.fantastic.MockedAppender

The main problem with this approach is that MockedAppender instance would be shared by all unit tests, forcing manual (ugly!) resets of its state between test invocations.

Then I discovered that log4j provides an API for dynamic Appender configuration at runtime! What it all boiled down to became surprisingly succinct when some Mockito magic was applied. In fact only four code lines (ignoring imports, and other noise) bought me the capability to make assertions about the logging behavior of the code under test!

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class FooTest {
	private Appender appenderMock;
	@Before
	public void setupAppender() {
		appenderMock = mock(Appender.class);
		Logger.getRootLogger().addAppender(appenderMock);
	}
	@After
	public void removeAppender() {
		Logger.getRootLogger().removeAppender(appenderMock);
	}
	@Test
	public void testMethod()  {
		doStuffThatCausesLogging();
		verify(appenderMock).doAppend((LoggingEvent) anyObject());
	}
}

Using Mockito’s handy ArgumentCaptor class it’s dead simple to make stronger assertions, with regard to for instance the level the message was logged at:

		ArgumentCaptor arguments = ArgumentCaptor.forClass(LoggingEvent.class);
		verify(appenderMock).doAppend(arguments.capture());
		assertThat(arguments.getValue().getLevel(), is(Level.WARN));

Ergo – I have no longer any excuse for settling for anything less than comprehensive unit tests, adding tests for logging is actually quite trivial using modern tools!

OS X Essentials: MenuMeters

My Mac is dead silent. Even more so after I replaced the already quiet hard drive with a completely silent SSD.

With no audible indication of e.g. swapping/thrashing I was in dire need of some kind of system monitor, capable of at least displaying CPU and memory usage. I wanted the monitor to visible on the desktop all the time but at the same time I’m quite stingy with my screen real estate. This disqualifies CPU monitors implemented as Dashboard Widgets since Widgets are only displayed on the screen when a special key is pressed. It is possible to hack OS X to always display widgets on top of the desktop but widgets steel screen estate. I’m not a big fan of widgets anywhere really – not on cell phones, not in Vista nor in OS X. I find them distracting toys for the most part.

The option I finally settled on was Menumeters which is informative, unobtrusive, pretty (enough) and highly configurable through its own pane in “System Preferences”.

MenuMeters lives (surprise, surprise!) in the rightmost portion of my Snow Leopard menu bar thus preserving my screen estate. Wide-screen monitors generally have ample free space in the OS X menu bar.

Review: Agile Project Management with Scrum

The Scrum course I recently attended didn’t only net me a Certified Scrum Master diploma – a copy of Ken Schwaber’s Agile Project Management With Scrum was also handed out. Overall I found the most recent addition to my software engineering book shelf quite accessible, of modest length (about 150 pages) and divided into logical chapters that don’t need to be consumed in succession.

The main bulk of the book is is a large number of case studies focusing different aspects of the Scrum process, such as the role of the Product Owner, Scrum Master etc. Every case study is followed by a short summary outlining the lesson Schwaber think can be learned from it. I think this approach is quite nice and makes for an entertaining read.

However, authored in 2003 as the book is some passages have a somewhat dated feel. Also, Scrum sprint length is consistently assumed to be 30 days with no convincing argument presented on why this would be the ideal iteration length.