Revisiting Java Layout Managers

As a developer I always revisit the following three problems:

  1. Find a proper IDE for each language (ok, sublime text rocks, but sometimes you need something more sophisticated)
  2. Find a cross-platform language to develop desktop application
  3. Find the best version control system for source files
  4. Find the best tool to automate software building and testing process

So far, I have a clear choice only for the #3, which is Git :). So that leaves me with #1, #2, #4. In this post we will discuss #2, since #1, #4 are really complex topics and cannot be easily covered.

For the last 18 years (time flies, oh yeah), I try to find a proper tool to create cross-platform desktop applications. Why I need that? Many of my clients need an administration tool (and yes I hate the web, so HTML-stuff is out of the picture) and they usually have a combination of Macs and PCs. It seems that the windows-dominance era passed for good.

For UI editing I used the following platforms, namely; Delphi -> Windows C API -> Java (AWT) -> Java (swing) -> C# -> XUL -> C# -> HTML/CSS/JS -> C#.

Do you notice a pattern? Yes, I revisited many times C#, which is by far the most sophisticated IDE to write UI applications. But it has one problem, it works only for the Microsoft universe, thus we are back in square one.

After lots of thought and experimentation, I tried several Java tool for RAD UI construction. Ok, officially the tools are bad. Yes real bad. Their developers should download visual studio 2003 -> 2013 and learn real IDEs are made, at least from that perspective.

I decided that I would be more productive if I wrote stuff by hand, than using any of those tools. So, layout managers is the answer to that. Of source, Java has plenty, and there are a few third party around, if you make the usual google-based-keyword round.

In addition to JGoodies, and MIG layout, I also found HTMLLayout and a set of various layout managers , which are open source and seem abandoned also.

So this is my decision (for the time being), Java but with manual UI construction using anything I can found as open source library on the web.

To that end I created a github repository name java-layout that will host all these resources. Recently, I added the htmllayout project, which I refactored, since it seems abandoned. In the future I plan to add some more stuff, regarding Java UI construction.

ps. Yes I know all about JavaFX. The concept is simple, I do not add ant library etc, if it does not have significant added value to the development process.

Simple Project Code Analysis with JSLoCCount

A few years back, when we were full in the development of SQO-OSS, we built a prototype that calculated simple size metrics for a project, based on sloccount. Back then, I thought (I was much into Software Quality back then) that it would be interested to have a Java implementation of this tool, to better integrate with the SQO-OSS architecture, which was built on the JVM platform.

I built back then, a simple utility named JSLoCCount, which calculated SLoC (Source Lines of Code), CLoC (Comment Line of Code) for many programming languages. In addition, it also provided a simple report with counters for each file type, recognizing the most popular file types based on their extensions.

I recently decided to revive this old project, and make it available on github. It is used simply by executing the following command:

java -jar jsloccount <directory>

The utility produces a print out of the SLoC and CLoC for the project, categorised by language and a file popularity report. Both reports are saved in two CSV files, in current working directory. For example, the reports for JSLoCCount itself, will look like:

Number of Files:

Java Compiled Class File, 14 / 30
Java, 11 / 30
JAR, 1 / 30
ANT Build File, 1 / 30
Other, 3 / 30

Number of Lines (comments):

Java, 544 (89)
ANT Build File, 24 (2)

and the two CSV files:

Resource Type,Source Lines of Code,Comments Lines of Code
Java,544,89
ANT Build File,24,2

and

Resource Type,File Count,Total File Count
Java Compiled Class File,14,30
Java,11,30
JAR,1,30
ANT Build File,1,30

Simple API for Regular Expressions

SARE is a small but powerful software application library, which aims to simplify every day regular expression usage. It was created a few years back and was abandoned until now that is updated and tested with the latest JDK (7). SARE is an extension API that provides event based regular expression parsing. SARE’s API is very simple. The developer need only to implement an interface, action event handler and attach it to the specific group of SARE parser. For example, the following listing shows have SARE can be used to parse each 4 digits from an IP address.

public class ExampleSARE {
    public static void main(String[] args) {
        String regex = "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)";
        String data  = "192.255.255.150";

        RegexParser sare = new RegexParser(regex);
        ConsoleOut co = new ConsoleOut();

        sare.assignAction(0, co);
        sare.assignAction(1, co);
        sare.assignAction(2, co);
        sare.assignAction(3, co);
        sare.assignAction(4, co);

        sare.process(data);
    }
}

class ConsoleOut implements IGroupAction {
    public void start() {
        System.out.println("Starting");
    }

    public void end() {
        System.out.println("End");
    }

    public void match(int count, String full, String group) {
        System.out.println("[" + count + "] - " + group);
    }
}

As you can see, SARE follows a variant of the visitor pattern. For each group defined in a regex, you can assign an object that implements the IGroupAction interface. When the method process() is invoked, the scan process begins and when a match is found, the specified IGroupAction is executed, through the match method.

SARE at the time being uses the standard JSDK regular expression library (java.util.regex.*).

This pattern provides an easy way to write less and more reusable code, when text processing is required. Current Version is 2.0. So feel free to download, experiment with the source and send me any comments.

SARE is available on github.

Eclipse Git Wizard Crash

If you try to start Eclipse opening wizard for Git and have the following problem (Indigo version, around 18/2/2012):

The selected wizard could not be started.
Plug-in "org.eclipse.egit.ui" was unable to instantiate class
"org.eclipse.egit.ui.internal.repository.NewRepositoryWizard"

Then just add as a software source the following:

http://download.eclipse.org/egit/updates-nightly

and update. It will fix the problem. I found that lying somewhere in a forum, but I lost lots of time trying to pin it down.

The Null Ambiguity

Overloading constructors in Java (not only) is good for the overall design. When used effectively it can result with correct and efficient initialisation of a class and avoidance of many lines of boiler-plate code.

Yesterday, I stumbled on the following problem. I wrote a class like the following,

public class Foo {
     public Foo(Integer i, Double d) { ... }

     public Foo(Integer i, Float f) { ... }
}

which defines a class Foo with two constructors that accept Integer and Double, and Integer and Float.

For some reason (not important right now) I wanted to initialise the first (Integer,Double) with the second parameter set as null.

This resulted as a compiler error, because the compiler actually could not decide which of the two constructors I wanted to use. Whoops … what could I do?

I could introduce a third constructor, with only one parameter and call this. Try it, you will see, that you will end up using part of the initialisation of the two others, which may complicate things (at least it did in my case).

Fascinating, isn’t it? Maybe we need a Null<Double> or Null<Float> to avoid this mess? Maybe the null value should be a generic Null<T> and use it to ensure type safety and instruct the compiler to correctly solve this ambiguity?

I do not know. My real-world problem solved with a third constructor as a work-around and some duplication of code. C’est la vie.

Is this Programmer Optimist … or not?

Browsing some source code (actually my own) and I noticed that long is used. The range for this type is from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,808.

Wow, thats a LOT of expected errors. On the other hand, better safe than sorry :).

public void setErrorCount(long e) {
    this.errors = e;
}

public long getErrorCount() {
    return errors;
}

Role-Playing Java …

Typical day, doing some work on my PhD. Creating a class name XMLUtil (I know, never happened before).

Code completion invoked in eclipse (dont’ ask), and then ..

I encountered the DRACONIAN_ERROR_HANDLER. Playing Master of Magic has some side-effects, after all that time.

Changing classpath at runtime!! (republished)

These days i’m finalising the FIRE regular expression compiler. To add a feature, the need arise to modify the classpath at runtime. It was a surprise for me when i discovered that there is no official way to modify this at runtime. I even created my own URLClassLoader (java.net), and set it as default classloader for my thread, but nothing.

I searched in google a little and found this post on a forum, which provided a class named ClassPathHacker that could add a path or file (jar) to a classpath at runtime. All this by a programmer named Antony Miguel. Well done :).

The source code of the class follows:

import java.net.*;
import java.io.*;
import java.lang.reflect.*;

public class ClassPathHacker {
	 
	private static final Class[] parameters = new Class[]{URL.class};
	 
	public static void addFile(String s) throws IOException {
		File f = new File(s);
		addFile(f);
	}
	 
	public static void addFile(File f) throws IOException {
		addURL(f.toURL());
	}	 
	 
	public static void addURL(URL u) throws IOException {			
		URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
		Class sysclass = URLClassLoader.class;
	 
		try {
			Method method = sysclass.getDeclaredMethod("addURL",parameters);
			method.setAccessible(true);
			method.invoke(sysloader,new Object[]{ u });
		} catch (Throwable t) {
			t.printStackTrace();
			throw new IOException("Error, could not add URL to system classloader");
		}		
	}	
}

and an example of usage ..

import java.io.*;

public class ClassPathAdder {
	public static void main(String[] args) {
		try {
			ClassPathHacker.add(new File("/home/user/newClassPath"));
		} catch (IOException e) {
			System.err.println("Error - " + e.toString());
		}
	}
}

Cool! 😀