Too Shiny

It is rare that I see a laptop I find worthwhile mentioning. In general, I have had good experience with the Dell Precision line. They have adequate processing power, they are well-built, and Dell doesn’t do too bad in the Greenpeace Greener Electronics ranking. Unfortunately, the M4x00 and M6x00 are a little too heavy for the mobile aspects of my everyday requirements. Which is why I was actually excited to read about the new M3800. All the power, but with much less weight. And it even looks quite nice. Seemed almost too good to be true.

And indeed, alas, they had to ruin it. They gave it a glossy display. Which is pretty much my primary exclusion criterion for laptops. There might be use cases for those (sending morse signals when stranded on a remote island comes to mind), but they don’t intersect with my more modest/pragmatic set of applications (software development and such).

Interestingly, maybe not all is lost. Dell has a forum for addressing such and similar issues, and somebody else has already vocalized this same issue there. If you feel similarly (or just feel charitable), please, add your voice there! Who knows, perhaps the powers that be will have mercy. Until then, the search for the perfect workstation laptop continues.

Leave a comment

Move those Modal Dialogs in GNOME 3

By default, GNOME 3 will attach modal dialogs to the parent window’s upper border. That can be quite annoying, e.g., when you would like to reference information hidden beneath the dialog in the parent window. You can change this behavior through GNOME’s own dconf configuration system. In Ubuntu, you will need to install the dconf-tools package (but not the dconf package, interestingly), e.g., by issuing:

sudo apt-get install dconf-tools

dconf gives you access to GNOME’s hierarchical key/value settings. The interesting one here is the boolean

/org/gnome/shell/overrides/attach-modal-dialogs

You can either browse through the settings using the dconf-editor, or you can show + change the values directly using the command line dconf read or dconf write command:


dconf write /org/gnome/shell/overrides/attach-modal-dialogs false

Et voilà! New modal dialogs (even from already running applications) should now open with full mobility.

Leave a comment

Super Key in Kubuntu

In both Windows and Gnome, the Super key (the one with the Windows icon) can be used as a shortcut, e.g., to open the application launcher. Very handy. Unfortunately, in KDE, the key is restricted to only be used as a modifier. There has been a long discussion about this since 2009, and the outcome is yet unclear. For the time being, Hans at hanschen.org has created ksuperkey. It is a very small & simple tool which you include in your auto-startup settings, and it will make the Super key send ALT+F1, which is the default shortcut for the application launcher.

Leave a comment

Java Graph Visualization with JUNG

Unfortunately, my first brush with JGraph was indicative of what was to follow. So, after having waded through Object upon Exception upon Object, I gave up and turned to JUNG instead. Granted, it’s older (the latest version being from around January 2010), but it’s new enough to use generics (well, most of the time at least), and it makes use of classes other than Object in its API. There are many nice examples available online, and they actually work. A slight drawback is the bag of dependencies – JUNG requires around ten to twelve more JARs. (But, hey, it’s Java, who would expect anything less?)

Even though it’s old & AWT-centered, you can use JUNG with SWT via the SWT_AWT utilities:

final Composite graphViewComposite = new Composite(parent, SWT.NONE
| SWT.EMBEDDED);
final Frame graphFrame = SWT_AWT.new_Frame(graphViewComposite);

GridDataFactory.fillDefaults().grab(true, true)
.applyTo(graphViewComposite);

graphFrame.add(getJungGraphPane());
graphFrame.pack();
graphFrame.setVisible(true);

Note that the SWT.EMBEDDED argument is crucial, otherwise you will get an IllegalArgumentException with the questionably informative message “Argument not valid”. The whole example code is hidden below:

/**
 * JUNG graph embedded in an SWT GUI
 * 
 * @author Hans Bering
 */
package swtJung;

import java.awt.Frame;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.visualization.GraphZoomScrollPane;
import edu.uci.ics.jung.visualization.VisualizationViewer;

public class GraphGui extends ApplicationWindow {

	public GraphGui() {
		super(new Shell());
	}

	private static Graph<String, Integer> getGraph() {
		final Graph<String, Integer> g = new UndirectedSparseGraph<String, Integer>();
		g.addVertex("v1");
		g.addVertex("v2");
		g.addVertex("v3");

		g.addEdge(42, "v1", "v2");
		g.addEdge(23, "v1", "v3");

		return g;
	}

	private static GraphZoomScrollPane getJungGraphPane() {
		final Graph<String, Integer> g = getGraph();
		final VisualizationViewer<String, Integer> viewer = new VisualizationViewer<String, Integer>(
				new CircleLayout<String, Integer>(g));
		viewer.setDoubleBuffered(true);

		final GraphZoomScrollPane paneWithGraph = new GraphZoomScrollPane(
				viewer);
		return paneWithGraph;
	}

	@Override
	protected Control createContents(final Composite parent) {

		final Composite graphViewComposite = new Composite(parent, SWT.NONE
				| SWT.EMBEDDED);
		final Frame graphFrame = SWT_AWT.new_Frame(graphViewComposite);

		GridDataFactory.fillDefaults().grab(true, true)
				.applyTo(graphViewComposite);

		graphFrame.add(getJungGraphPane());
		graphFrame.pack();
		graphFrame.setVisible(true);

		return parent;
	}

	public void run() {
		this.setBlockOnOpen(true);
		this.open();
		Display.getCurrent().dispose();
	}

	public static void main(final String[] args) {
		new GraphGui().run();
	}
}

For my current simple needs, JUNG provides enough layouts and graph customization options. Should I ever need more, the next candidate would most likely be prefuse. Their homepage is hopelessly out of date, but development is ongoing.

Leave a comment

Adventures in 3rd Party Code: JGraph

I am looking into how to visualize graphs in Java, and I came across JGraph. The home page announces it as “The most popular Java Graph Visualization Library”, and it lists some quotes to prove its impressiveness (impressivity?): “… one of the best open source Swing components we have found around the world” and “… should be part of the Swing core (it is that good).” They even managed to get someone from the MIT into that list.

So, that sounds promising. But then I looked at the documentation. It mentions classes called mxGraph and mxGraphModel, which is surprising given that one of the major Java naming conventions is that class names should be capitalized. (Although, if you want to be really picky, you could probably interpret the original convention as only saying the internal words in a class name should be capitalized.) And the code fragments make for good examples of why following code conventions would have been a good thing. After more than seven years of Java development, I find reading lower case classes in code confusing – well, confusing might be too strong, but it made me have to backtrack and reread code portions more than a couple of times. E.g., the following line tricked me into looking at the source code to find out what fancy design pattern that method call was using:

mxGraph myGraph = new mxGraph();

Then my palm met my head. Perhaps it’s just because my native Tongue also has Noun Capitalization. Anyway, that’s perhaps a minor eyebrow raiser, but not really that big an issue. What I do consider a major faux pas, however, is neatly summarised in the following line from the mxGraph class API documentation:

Object addCell(Object cell)

The edge part is even better:

Object addEdge(Object edge, Object parent, Object source, Object target, Integer index)

Yes. Object is what goes in, and Object is what comes out; in apparently most or all of the API dealing with graphs. People fail elementary Java classes for less. The really amusing stuff happens at runtime. Because, of course, even though the API says Object, it does not mean Object. Given the API, you could think the following works:

mxGraph myGraph = new mxGraph();
Object cellNo1 = myGraph.addCell(new String("Cell No. 1"));

Nothing in that will make the compiler cry. But the stacktrace begs to differ:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to com.mxgraph.model.mxICell
	at com.mxgraph.model.mxGraphModel.parentForCellChanged(Unknown Source)
	at com.mxgraph.model.mxGraphModel$mxChildChange.execute(Unknown Source)
	at com.mxgraph.model.mxGraphModel.execute(Unknown Source)
	at com.mxgraph.model.mxGraphModel.add(Unknown Source)
	at com.mxgraph.view.mxGraph.cellsAdded(Unknown Source)
	at com.mxgraph.view.mxGraph.addCells(Unknown Source)
	at com.mxgraph.view.mxGraph.addCell(Unknown Source)
	at com.mxgraph.view.mxGraph.addCell(Unknown Source)
	at com.mxgraph.view.mxGraph.addCell(Unknown Source)
	at org.lai.opt.model.actions.JGraphXTest.main(JGraphXTest.java:9)

So, yes, there is a type requirement for that argument – and at runtime you will find out what it is. They’re basically throwing Java’s static typing safety nets over board. And it’s not like they don’t have the interface they know they want. Why is it not in the method’s signature? The good news is this might be an effective way to force people to make sure they have unit-tested every last single decision branch in their Object-riddled code.

Enough said for now. I would stop looking at the library (or even calling it one) at this point if it hadn’t been mentioned favorably on pages other than its own homepage. But I guess I will have to engage in some type guessing – after all, the pictures in the user manual do look quite nice. Stay tuned, I’m sure I’ll be back with more on this.

Leave a comment

Wrapping Java Fields in Static Anonymous Inner Class Constants

First-class functions really are a nice thing. Joel Spolsky devoted a whole blog entry to them. Java, sadly, doesn’t have first-class functions. This lack can make itself annoyingly noticeable when you have a class with many properties, and you need to formulate constraints and rules for these properties.

Enter the Element

Consider the following simple example of a class Element with a single integer property width:

class Element {
	private int width;
	int getWidth() { return width; }
}

If you had to check that the sum of the widths across a given collection of elements stayed within a given limit, you might do something like the following:

class CheckConstraints {
	static boolean isWidthSumWithinLimit(final Iterable<Element> elements, final int limit) {
		int sum = 0;
		for (final Element e : elements) {
			sum += e.getWidth();
		}
		return sum <= limit;
	}
}

More Constraints – the Python Way

Simple enough. But then, of course, your requirements change, and your element gets an additional property height:

class Element {

	private int width;
	private int height;

	int getWidth() {
		return width;
	}

	int getHeight() {
		return height;
	}
}

And, inevitably, you need to check the same constraint for that new field. Conceptually, all you need to do in isWidthSumWithinLimit is to replace the one tiny little call to getWidth() with getHeight(). (And perhaps give the method a different name.) If you had first-class functions, extracting that call out of the method would be easy. In Python (which has first-class functions), our Element could look like this:

class Element:

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def getWidth(self):
        return self.width

    def getHeight(self):
        return self.height

And the constraints could be checked in this way:

# the general sum checking case
def isSumWithinLimit(elements, getter, limit):
    return sum([getter(e) for e in elements])

# the special case for widths
def isWidthSumWithinLimit(elements, limit):
    return isSumWithinLimit(elements, Element.getWidth, limit)

# the special case for heights
def isHeightSumWithinLimit(elements, limit):
    return isSumWithinLimit(elements, Element.getHeight, limit)

I.e., we pass the Element functions Element.getWidth and Element.getHeight as the getter argument into the general isSumWithinLimit, where they are called as getter(e). And everything is well.

The Java Way: Anonymous Inner Classes

In principle, you can pass around functions in Java. You just have to take the detour of wrapping your function in an interface and passing instances of said interface around via anonymous inner classes. Following that route, the Java equivalent of the above Python code could look like the following:

First, we define the interface which, given an Element, lets us pick the value we are interested in:

interface IntGetter {
	Integer get(final Element e);
}

Then we define a general version of our sum constraint check using that interface:

	static boolean isSumWithinLimit(final Iterable<Element> elements, final IntGetter getter, final int limit) {
		int sum = 0;
		for (final Element e : elements) {
			sum += getter.get(e);
		}
		return sum <= limit;
	}

And finally, we define our two special cases for width and height using anonymous inner IntGetter instances:

	// ... the width
	static boolean isWidthSumWithinLimit(final Iterable<Element> elements, final int limit) {
		return isSumWithinLimit(elements, new IntGetter() {
			@Override
			public Integer get(final Element e) {
				return e.getWidth();
			}
		}, limit);
	}

	// ... and the height
	static boolean isHeightSumWithinLimit(final Iterable<Element> elements, final int limit) {
		return isSumWithinLimit(elements, new IntGetter() {
			@Override
			public Integer get(final Element e) {
				return e.getHeight();
			}
		}, limit);
	}

So the general isSumWithinLimit method can handle whatever field we can make accessible via an IntGetter. On the one hand, this helps the checking method concentrate on its core functionality of summing up numbers and comparing them to a limit. It no longer has to care about where those numbers come from. On the other hand, unfortunately, the code is horrendously long and verbose.

Extracting to Constants

It gets worse if you wanted to introduce more checks, such as the isEachWithinLimit check, which compares every element individually to a given limit. As with the sum check, we define a general case based using an IntGetter:

	static boolean isEachWithinLimit(final Iterable<Element> elements,
			final IntGetter getter, final int limit) {
		for (final Element e : elements) {
			if (getter.get(e) > limit)
				return false;
		}
		return true;
	}

And if we want to use that check for widths, we write a specialized check using an anonymous inner class:

	// the specific case for the width
	static boolean isEachWidthWithinLimit(final Iterable<Element> elements, final int limit) {
		return isEachWithinLimit(elements, new IntGetter() {
			@Override
			public Integer get(final Element e) {
				return e.getWidth();
			}
		}, limit);
	}
// ...

We find ourselves duplicating the anonymous width-specific IntGetter class. Consequently, for n properties and m constraints, our code’s verbosity could well be in O(n*m). As a simple remedy against both the bulkiness of the specialized check methods and the duplication of each specific getter class, we can extract the getter classes into static constants on the Element:

class Element {
	private int width;
	private int height;

	int getWidth() {
		return width;
	}

	int getHeight() {
		return height;
	}

	static IntGetter WIDTH = new IntGetter() {
		@Override
		public Integer get(final Element e) {
			return e.getWidth();
		}
	};

	static IntGetter HEIGHT = new IntGetter() {
		@Override
		public Integer get(final Element e) {
			return e.getHeight();
		}
	};
}

With these in place, we can formulate our various constraint checks a little less verbosely. The two general constraint checks don’t change, but the special cases do:

	// sum of widths
	static boolean isWidthSumWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isSumWithinLimit(elements, Element.WIDTH, limit);
	}

	// each width
	static boolean isEachWidthWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isEachWithinLimit(elements, Element.WIDTH, limit);
	}

	// sum of heights
	static boolean isHeightSumWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isSumWithinLimit(elements, Element.HEIGHT, limit);
	}

	// each height
	static boolean isEachHeightWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isEachWithinLimit(elements, Element.HEIGHT, limit);
	}

Finally, each case has been reduced to the one-liner it really should be – quite similar to the original Python example code.

When there’s more than just Elements

So far, the static anonymous inner class constants have given us something like first-class fields on Element. We can generalize the code to work with classes other than Element by making the IntGetter and the constraints generic with respect to the class on which they are called:

interface IntGetter<E> {
	Integer get(final E e);
}

The constants in Element don’t have to change much. They just have the type parameter added:

class Element {

	// ... snip ...

	static IntGetter<Element> WIDTH = new IntGetter<Element>() {
		@Override
		public Integer get(final Element e) {
			return e.getWidth();
		}
	};

	static IntGetter<Element> HEIGHT = new IntGetter<Element>() {
		@Override
		public Integer get(final Element e) {
			return e.getHeight();
		}
	};
}

And we have to generify the general checker methods to allow other types:

	// the general cases
	static <E> boolean isSumWithinLimit(final Iterable<E> elements,
			final IntGetter<E> getter, final int limit) {
		int sum = 0;
		for (final E e : elements) {
			sum += getter.get(e);
		}
		return sum <= limit;
	}

	static <E> boolean isEachWithinLimit(final Iterable<E> elements,
			final IntGetter<E> getter, final int limit) {
		for (final E e : elements) {
			if (getter.get(e) > limit)
				return false;
		}
		return true;
	}

Now, if we get a new class Thing with an integer property depth, we wrap depth in a static anonymous inner class constant:

class Thing {
	private int depth;

	static IntGetter<Thing> DEPTH = new IntGetter<Thing>() {
		@Override
		public Integer get(final Thing e) {
			return e.depth;
		}
	};
}

And without further changes, we can call all our constraint checks on things and their depths:

	static boolean isEachDepthWithinLimit(final Iterable<Thing> things,
			final int limit) {
		return isEachWithinLimit(things, Thing.LENGTH, limit);
	}

So, for the price of defining the static anonymous inner class constants, we can pass them around as fields. If you have few of these fields, and you have a lot of repetitive handling to do with them, using static anonymous inner class constants can help you elegantly reuse significant portions of the handler code.

Hidden below is the whole source for this small example along with a simple main class:

/**
 * Demonstration of simple Anonymous Inner Class Constants
 * 
 * NB: Code does not reflect best practices with regard to packaging, etc.
 * 
 * @author Hans Bering
 */
package simple.ex3;

import java.util.ArrayList;
import java.util.List;

interface IntGetter<E> {
	Integer get(final E e);
}

class Element {

	private final int width;
	private final int height;

	Element(final int width, final int height) {
		this.width = width;
		this.height = height;
	}

	int getWidth() {
		return width;
	}

	int getHeight() {
		return height;
	}

	static IntGetter<Element> WIDTH = new IntGetter<Element>() {
		@Override
		public Integer get(final Element e) {
			return e.getWidth();
		}
	};

	static IntGetter<Element> HEIGHT = new IntGetter<Element>() {
		@Override
		public Integer get(final Element e) {
			return e.getHeight();
		}
	};
}

class Thing {

	private final int length;

	Thing(final int length) {
		this.length = length;
	}

	static IntGetter<Thing> LENGTH = new IntGetter<Thing>() {
		@Override
		public Integer get(final Thing e) {
			return e.length;
		}
	};
}

class ConstraintChecker {

	static <E> boolean isSumWithinLimit(final Iterable<E> elements,
			final IntGetter<E> getter, final int limit) {
		int sum = 0;
		for (final E e : elements) {
			sum += getter.get(e);
		}
		return sum <= limit;
	}

	static <E> boolean isEachWithinLimit(final Iterable<E> elements,
			final IntGetter<E> getter, final int limit) {
		for (final E e : elements) {
			if (getter.get(e) > limit)
				return false;
		}
		return true;
	}

	static boolean isWidthSumWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isSumWithinLimit(elements, Element.WIDTH, limit);
	}

	static boolean isEachWidthWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isEachWithinLimit(elements, Element.WIDTH, limit);
	}

	static boolean isHeightSumWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isSumWithinLimit(elements, Element.HEIGHT, limit);
	}

	static boolean isEachHeightWithinLimit(final Iterable<Element> elements,
			final int limit) {
		return isEachWithinLimit(elements, Element.HEIGHT, limit);
	}

	static boolean isEachLengthWithinLimit(final Iterable<Thing> things,
			final int limit) {
		return isEachWithinLimit(things, Thing.LENGTH, limit);
	}
}

public class Example {

	public static void main(final String... args) {
		final Element e1 = new Element(2, 5);
		final Element e2 = new Element(4, 3);

		final List<Element> elements = new ArrayList<>();
		elements.add(e1);
		elements.add(e2);

		System.out.println(String.format("elements width sum check = %s",
				ConstraintChecker.isWidthSumWithinLimit(elements, 5)));
		System.out.println(String.format("elements each height check = %s",
				ConstraintChecker.isEachHeightWithinLimit(elements, 5)));

		final Thing t1 = new Thing(7);
		final Thing t2 = new Thing(1);

		final List<Thing> things = new ArrayList<>();
		things.add(t1);
		things.add(t2);

		System.out.println(String.format("things sum length check = %s",
				ConstraintChecker.isSumWithinLimit(things, Thing.LENGTH, 5)));
	}
}

Evidently, there are endless possibilities to using anonymous inner class constants. You can turn them into generic properties by giving them a generic type parameter on their return value; or make them modifiable by adding a set method; probably add some generic serialization, default handling, etc. – Have fun!

Leave a comment

Lombok’s @Data Annotation & Mutable Classes

As comfortable as it seems, Lombok’s @Data annotation is not without danger. It generates a hashCode method based on all data fields of the annotated class, regardless of whether they are mutable or not. This means you have to be very careful about using instances of such classes in collections based on hashCode, such as HashSet. “How to Write an Equality Method in Java” has a concise description of this problem under “Pitfall #3: Defining equals in terms of mutable fields“. Long story short: If you add an instance of such a class to a HashSet, then change a mutable field, calling contains on the set will (probably) yield false for the instance you just added, yet you will (paradoxically) still be able to find the instance in the set through iteration.

Leave a comment

Follow

Get every new post delivered to your Inbox.