JDepend Plugin for Eclipse

The other day I came across another interesting static source code analysis plugin for eclipse: JDepend. JDepend calculates a number of quality metrics for Java packages (therewith it has a slightly different unit of analysis to other tools, which focus on methods, classes or projects).

I found that Andrey Loskutov has created an excellent eclipse plugin based on JDepend called JDepend4Eclipse.

After installation of the plugin, context menus for packages (not projects) will feature another item ‘Run JDepend analysis’.

Executing this analysis will result in a nicely formatted report being generated. The results can easily be interpreted with the JDepend documentation.

I tend to build very small modules, in which I place a kind of factory for concrete implementations along with some essential interfaces in the main package of the module. It seems that JDepend is not fond of this practice, since the factory depends on the concrete implementations (in the .internal* packages) and these in turn depend on the essential interfaces within the main package. However, I am not yet convinced that this practices is very bad, as long as circular reference between modules are avoided.

Eclipse and SVN to manage Apache Web Server

In order to configure a simple Apache Web Server, I found myself many a time connecting to a UNIX system using putty, fiddling around with various configuration files using pico or vim. I don’t want to count the times I deleted some configuration I later missed dearly or forgetting to close some xml element. Two of the main problems for me were:

(1) As much as some might be convinced of the productivity of text-based editors like pico and vim, for me it just doesn’t fly. Of course one shouldn’t use the mouse for everything but windows, the mouse cursor, tabs, and various visualizations such as trees seem just too useful to me to be completely abandoned.

(2) I have become too used to the convenience of a versioning system when developing source code. Although I know there are various ways to backup a UNIX-based system, I would like all the convenience modern source code management systems offer in organizing the versions of text-based files.

I decided to try using two established technologies to address these problems:

  • Eclipse is a well-known integrated development environment primarily for the Java programming language, allowing for many conveniences in editing text-based files.
  • Subversion (or SVN) is a centralized versioning system for just about anything. Although Subversion can be very cumbersome at times (talk about deleting folders …), it is supported by many platforms and can become almost usable when one knows of its limitations.

The following is a description of the necessary steps to set up a development environment for Apache web server configuration files (and basically any other kind of configuration files one might encounter on a remote server) build on eclipse and subversion.

Step 1: Install Subversion on your web server

Installing Subversion on the various flavours of UNIX is very straightforward and Google quickly yields useful instructions. Here, for instance the instructions for Ubuntu Server.

Please note that you need to install subversion on your web server primarily for the SVN command line client, so omit any configuration steps regarding setting up a subversion server.

You can check the success of this step by typing in your remote console ‘svn –version’.

Step 2: Install Subversion Server

It is sensible to install a subversion server on a different machine than your web server. This will also allow for an easy way to backup various configuration files from your web server.

Again, there are numerous instructions for setting up a subversion server. See for instance, this post for setting one up on Ubuntu. One of the easiest ways is using VisualSVN to install a subversion server as a windows service.

Step 3: Create a Repository on your Subversion Server

You can either use one for your already set up repositories (if you use subversion for other project) or create a new repository dedicated for web server configurations.

In VisualSVN, you can right click ‘Repositories’ and select ‘Create New Repository’ which opens the dialog given below.

Step 4: Create a project in your repository

Since the folders in which the configuration files lie on the web server are already filled with files and folder, we need first to create an empty project on the subversion server.

In VisualSVN, we can right click the newly created repository and create a new Project Structure as shown below.

Step 5: Add the folders on your web server to version control

After we have created a ‘skeleton’ project on the SVN server, we can start to upload the configuration files from the web server.

For this we go to the folder, from which we want to upload the files. For instance, /etc/apache2.

cd /etc/apache2

In this folder, we initialize the SVN checkout operation:

sudo svn checkout https://%5Byour SVN server]/svn/webRepro/webMyApacheConf/trunk/ .

Next, we can add the folders we want under version control. For instance, the folder conf:

sudo svn add conf

Finally, we commit and upload the files to the SVN server:

sudo svn commit

Step 6: Import the files into eclipse

In order to import the files uploaded to the subversion server, we need to install the Subversive eclipse plugin. After doing so, the following option should be available under File / Import:

In the following dialog, we first specify our SVN repository (../webRepro/) and the project (../webRepro/webMyApacheConf). Note that you should select the ‘trunk’ folder rather than the project root.

Chose to check out the project as a project configured using the New Project Wizard.

As type for the project, select General / Project.

Step 7: Edit configuration files in eclipse

Now, the configuration files from your web server should be available as eclipse project.

Just click and edit these files in the eclipse editors. If you have made changed, right click the project and select Team / Commit, which will commit the changed files to the subversion server.

Step 8: Import changed files to web server

Finally, if you have changed files in eclipse, you need to reimport these files onto your web server. For this connect to your web server and navigate to the directory you have placed under version control. For instance:

cd /etc/apache2

To download the changed files, type

sudo svn update

As a result, the changed files should be downloaded to your web server.

Then, don’t forget to restart your server to see the effect of the changes.

 

 

 

 

Convert IMG to ISO on Windows 7

In order to mount an image file on VirtualBox, I needed to convert an IMG image file into an ISO format (VirtualBox does not support mounting IMG files). There seem to be a myriad of applications available for this purpose; many of them commercial or at least shareware.

With OSFMount I found a free and handy tool for this purpose. Download and install the software, then mount the IMG file you need to convert.

Right click the mounted drive and select “Save to image file…”.

Choose “RAW CD Image (*.iso)” and Voilà! You have an ISO file, which can be mounted by VirtualBox.

‘Google Sites’ hosted Sites Speed: Slow as!

Google offers free web hosting as part of their ‘Google Sites‘ service. Anyone with a Google (gmail) account can sign up for a website with an address such as https://sites.google.com/site/%5Byoursitename%5D.

Google sites has some nice features, first and foremost that editing the website can be easily done online. Just click the edit button on your site and you can start. Moreover, although there is a large number of free webhosting providers, it often is doubtful for how long they will continue to host your website.

Google is usually a strong advocator of increasing the speed of the web; offering various tools and services for web content providers to monitor and control their services as well as improve their performance. It is all the more surprising that the load time of google hosted sites seems not to be very impressive.

Of course, from New Zealand most web pages appear to be loading with increased latency, but luckily there are a great number of web services available, which help to measure page load time from different locations and systems. I used the service http://www.webpagetest.org/ to test the load time of the google sites hosted page https://sites.google.com/site/eclipsemaven/.

Below I have listed a sample from the load time from a location in the US and in Europe. Google sites appear to be hosted in the US, so there is a slightly longer load time from the European locations. However, establishing the initial connection in both cases did not take much time. The most time seemed to be spent rendering the page on google’s server (time to first byte). As an advocator of fast page loading time, I would really have thought better of google.

From US location:

From European location:

(Test were performed on different days at different times)

Other hosting provider:

As a comparison, a simple page hosted by a budget web hosting provider in Germany:

Test from US location. In this test, the ‘Time to First Byte’ is significantly lower. I

Maven and Eclipse: New Website

After having published a number of posts on Maven and integration between Maven and eclipse in particular, I have been thinking for a while to summarize some best practices in a post. I have found that these best practices are actually too long and too interdependent to fit nicely in a blog post. Therefore, I have created a little webpage: http://eclipsemaven.mxro.de/.

I will start to publish a number of templates for Maven pom.xml files there. The first two templates are already defined:

Most notably, I have found that it safes lots of trouble to separate clearly between projects, which establish a dependency to a third party library, and those, which implement new logic. This is of particular importance when defining the projects as OSGi bundles. Since the OSGi metadata can be defined automatically by Maven, I think there is no excuse to write any module without OSGi metadata: maybe someone will require it at some point in time and it also aids in improving modularity (Walls, 2009).

Relocating SVN repository for multiple projects in eclipse workspace

Although an SVN server is possibly a fixed anchor in dynamic and distributed development efforts, even these servers might have to be relocated from time to time. Surprisingly, this can be done quite swiftly, even in complex set ups, for instance an eclipse workspace comprised of dozens of projects stored on a number of different repositories. In the following, a few simple steps are listed to inform eclipse of the relocation of an SVN server or repository.

First, the SVN repositories view must be opened. This can be accomplished through Menu / Show View / Other …

And then selecting the view “SVN Repositories” under SVN (please note that Subversion must be installed for this view to be present).

The opened view shows all the SVN repositories, which are used by projects in the workspace (or which have been defined in eclipse otherwise). The SVN repositories here should correspond to the SVN labels/server addressed displayed after the project name in the eclipse workspace overview.

Now, right click the SVN repository, you want to relocate. And select “Location Properties” in the pop up menu.

Here, you can specify the new address of your SVN repository. Just rewrite the given URL (in the example, you would rewrite for instance “https://olddomain.com/svn/MxModules” to “https://newserver.com/svn/MxModules” )

Click finish and the repository locations of all projects in the eclipse workspace using the repository will be updated to the new location.

Hint:

Make sure that the repository you want to move FROM is available when the relocation operation is performed. Otherwise, eclipse might produce all kind of undesirable errors.

NullPointerException after mvn eclipse:eclipse

Problem

Today I came across a strange error when generating eclipse metadata using maven.

Running “mvn eclipse:eclipse” results in :


[ERROR] Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.8:eclipse (default-cli) on project mxGWTUtils: Execution default-cli of goal org.apache.maven.plugins:maven-eclipse-plugin:2.8:eclipse failed. NullPointerException -> [Help 1]

org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.8:eclipse (default-cli) on project

[…]

Caused by: java.lang.NullPointerException

at org.apache.maven.artifact.versioning.ComparableVersion.parseVersion(ComparableVersion.java:353)

at org.apache.maven.artifact.versioning.ComparableVersion.<init>(ComparableVersion.java:344)

at org.apache.maven.artifact.versioning.DefaultArtifactVersion.parseVersion(DefaultArtifactVersion.java:111)

at org.apache.maven.artifact.versioning.DefaultArtifactVersion.<init>(DefaultArtifactVersion.java:47)

at org.apache.maven.artifact.DefaultArtifact.compareTo(DefaultArtifact.java:433)

at org.apache.maven.artifact.DefaultArtifact.compareTo(DefaultArtifact.java:43)

at java.util.TreeMap.compare(TreeMap.java:1188)

at java.util.TreeMap.put(TreeMap.java:531)

at java.util.TreeSet.add(TreeSet.java:255)

at org.apache.maven.plugin.ide.AbstractIdeSupportMojo.getProjectArtifacts(AbstractIdeSupportMojo.java:786)

at org.apache.maven.plugin.ide.AbstractIdeSupportMojo.doDependencyResolution(AbstractIdeSupportMojo.java:560)

at org.apache.maven.plugin.ide.AbstractIdeSupportMojo.execute(AbstractIdeSupportMojo.java:507)

at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)

Analysis

After a while, I have found out that this error is caused by using Maven version ranges (e.g. “[0.2.0,)” meaning any version larger than 0.2.0) rather than exact version numbers.

So, for instance a dependency like the following will cause the NullPointerException:


<dependency>

<groupId>de.mxro.thrd.guavagwt</groupId>

<artifactId>thrdGuavaGwt</artifactId>

<version>[0.0.1,)</version>

</dependency>

Whereas the following specification of the dependency will cause the NullPointerException to disappear:


<dependency>

<groupId>de.mxro.thrd.guavagwt</groupId>

<artifactId>thrdGuavaGwt</artifactId>

<version>0.0.1</version>

</dependency>

Solution

In my case, this problem was caused by upgrading from Java 1.6 22 to Java 1.7.

Therefore, downloading a version of Java 1.6 and specifying its directory as JAVA_HOME solves the problem. A short solution that took me long to find. Who would have suspected this bug is cause by Java?

Java 8: Key Features (I would love to see)

There has been not little critizim of the slow progress made in the core of Java. Java 6 has been released on the 11th of December 2006 (!). Java 7 saw the light of the day almost five years later this July.

Competing languages, most notably C# in Microsofts .NET environment have doubtlessly benefitted from Java’s inability to catch up with new developments in IT. Yet, according to the famous TIOBE community index, the most popular language in both 2006 and 2011 is: Java. Most notably, challenged only by C, a language not necessarily known to be at the forefront of language innovation.

In the general discussion of the standstill of Java, the possible advantages of the absence of change in the core of Java are seldom mentioned. Maybe Java is so popular today not despite of but because of the few changes, which have been made to the core language. Of course, when compared to C# such advantages appear to be few. Indeed, many programming tasks can be accomplished much easier in C# or many other languages. However, it must be noted that C# (and many other languages) live in an ecosystem, which is fundamentally different to the Java ecosystem.

C#, for instance, is heavily dominated by Microsoft. This centralized ecosystem has significant advantages to implement change quicker. The entire toolchain can be centrally adjusted to any planned changes. But Java? The language has long outgrown the bosom of its inventors. Take Android, take Spring, take the Google Web Toolkit: the breadth and depth of commercial and open source projects in the Java space outscales any of its competitors easily.

To give just a few examples of the breadth of the ecosystem: Google web toolkit, for instance, has a lot and yet very little to do with Java. While the Google Web Toolkit builds on the Java syntax, it deploys applications for JavaScript engines rather the Java Virtual Machine. On the other hand, a number of languages such as Groovy and Scala, use a Syntax completly different from Javas, yet run on the Java Virtual Machine.

It is this diversity, which makes drives the success of the Java ecosystem. There have been a number of research studies investigating innovation in various context. One common finding is that more diverse systems provide more significant innovations in the long run than better integrated ones (Lazer and Friedman, 2007).

However, it can be argued that such diversity could only emerge as a result of the relatively few changes to the core foundations of Java. Therefore, of all the possible features, we could envision for Java 8, it is especially one I would like to see: that it devises from its predecessor as little as possible.

However, it is not that I wouldn’t believe there are a number of things ‘wrong’ with the Java language, or at least outdated. I would like to see the following problems mitigated

Too Many Blocking Calls

I believe that most expierenced programmers will reach a point at which they will begin to strive for simplicitly or ‘beauty’ in their code (Case and Piñeiro, 2006). Callbacks in Java are ugly. Very ugly. Which in itself is not such a big deal. But programmers avoiding callbacks is a big deal. Many applications written in Java are cluttered with blocking calls to the file system or external servers, possibly as a result of programmers striving for simplicitly avoiding them.

Often, the introduction of lambdas as first order constructs in Java is proposed as one of the key features for Java 8. However, I strongly oppose anything increasing complexity at the core of a language. Adding another first order construct is an example for a measure dramatically incresing complexity. However, I do believe that the syntax for callbacks could be significantly simplified, encouraging developers to write code in a more ‘functional’ style.

Java 6:

component.writeData(s).andThen(new WriteCallback() {
public void onWriteComplete() {
System.out.println("I/O operation complete ");
}
});

Java 8 (I hope):

component.writeData(s).andThen(
{System.out.println("I/O operation complete "); }
);

(adapted from Groovy, of course)

Over-Specification of Types

Writing code an untyped language can be a quite revealing expiernce: I can create working programs, wihtout having to tell the compiler in every step, what are the types of my objects. Java generics (as seen in Java 6) are problably one of the most gruesome examples of type overspecification. But lets consider a simpler example:

String s = "my string";
int i = s;

In this example the Java compiler would sensibly warn us that the second statement is invalid. A possibly very important information to avoid bugs in the programm. But, more importantly, modern integrated development environment such as eclipse will issue a warning pointing to the second statement in the moment it is typed in the source code editor. Moreover, there is often tooling available, which will propose an automatic correction for the problem. This is not possible in an untyped language.

However, the given code is also an example for type overspecification. When we define the variable s, it is a very easy excerise for the compiler to infer the type of the variable without need to specify the type of the variable. I would love to have a special build in type, by which I could tell the compiler: please take your best guess at specifiying the type of the variable and warn of any problems, which may arise when using this type. The following code, for instance, should issue the same warning on the second line as the code snippet given above.


object s = "my string";
int i = s;

(type inference is popular in Scala, of course)

Restlet Quickstart

The Restlet framework is one of the possible options to provide Restful web services in Java. In many framework comparison, Restlet is criticized for being a little bit difficult to understand as well as to perform slightly worse than competing frameworks (e.g. Apache Wink, Jersey, …) (Sangeetha, 2011). However, Restlet is also a very flexible framework and it is very lightweight, in that it has very few dependencies to heavyweight components, for instance servlet containers. This enables Restlet to play nicely with a number of technologies including Google Android, Google App Engine and Google Web Toolkit applications.

The tutorials on the Restlet homepage appear to be a bit confusing and outdated. Therefore, I have assembled a little example to get started with Restlet in a few traceable steps.

Add Maven Dependency

Restlet offers a wealth of different editions and optional extensions and it is a little bit difficult to determine the right Maven dependencies. For this basic scenario, we want to run a little server deployed as local Java application. For this purpose, the ext.simple extension is required (here I use the latest milestone release 2.1-M7 – the examples should also work with later releases although this is not guaranteed)


<dependency>

<groupId>org.restlet.jse</groupId>

<artifactId>org.restlet</artifactId>

<exclusions>

<exclusion>

<groupId>org.osgi</groupId>

<artifactId>org.osgi.core</artifactId>

</exclusion>

</exclusions>

<version>2.1-M7</version>

</dependency>

<dependency>

<groupId>org.restlet.jse</groupId>

<artifactId>org.restlet.ext.simple</artifactId>

<version>2.1-M7</version>

</dependency>

In addition, the Restlet repository must be specified


<repositories>
<repository>
<id>maven-restlet</id>
<name>Public online Restlet repository</name>
<url>http://maven.restlet.org</url>
</repository>
</repositories>

<span style="color: black;">

Create a Small Standalone Server

If these dependencies are established, the following server can be implemented:


import org.restlet.Component;
import org.restlet.data.Protocol;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.routing.Router;

public class RestletServerTest extends ServerResource {

public static void main(final String[] args) throws Exception {
// Create a new Component.
final Component component = new Component();

// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);

final Router router = new Router(component.getContext().createChildContext());

router.attach("/test", RestletServerTest.class);

// Attach the sample application.
component.getDefaultHost().attach("/restlet", router);

// Start the component.
component.start();
}

@Override
@Get
public String toString() {
return "hello, world";
}

}

Execute this application and open http://localhost:8182/restlet/test. You should see the message ‘hello, world’.

Provide a Domain Object

In order to provide a domain object, a few more steps need to be undertaken. First, we need to specify the domain object:


import java.io.Serializable;

public class Person implements Serializable {

private static final long serialVersionUID = 1L;

public String name;
public int age;

public Person(final String name, final int age) {
super();
this.name = name;
this.age = age;
}

}

Secondly, we need an interface and a ServerResource implementation for the service, which provides the domain object. The interface does not need to extend any other interface but must use the GET, PUT, DELETE annotations provided by Restlet.


import org.restlet.resource.Get;

public interface PersonResource  {

@Get
public Person retrieve();

}
<pre>

The ServerResource implementation must extend ServerResource and implement the interface PersonResource:


import org.restlet.resource.ServerResource;

public class PersonServerResource extends ServerResource implements PersonResource {

private static volatile Person person1 = new Person("Peter", 40);

@Override
public Person retrieve() {

return person1;
}

}
<pre>

Finally, the main routine starting the server needs to be altered. Also, a little client is added, which reads out the domain object from the server:


import org.restlet.Component;
import org.restlet.data.Protocol;
import org.restlet.resource.ClientResource;
import org.restlet.routing.Router;

public class RestletServerTest  {

public static void main(final String[] args) throws Exception {
// Create a new Component.
final Component component = new Component();

// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);

final Router router = new Router(component.getContext().createChildContext());

router.attach("/person", PersonServerResource.class);

// Attach the sample application.
component.getDefaultHost().attach("/restlet", router);

// Start the component.
final Thread t = new Thread() {

@Override
public void run() {
try {
component.start();
} catch (final Exception e) {
e.printStackTrace();
}
super.run();
}

};

t.run();

final ClientResource cr = new ClientResource("http://localhost:8182/restlet/person");

final PersonResource resource = cr.wrap(PersonResource.class);
final Person person = resource.retrieve();

System.out.println(person.name);

}

}
<pre>

The domain object is serialized using the Java Serialization mechanism. We can also navigate to http://localhost:8182/restlet/person using a web browser. However, only a binary file will be downloaded by the server. Restlet does provide extensions to provide the domain objects serialized as in RDF, XML and JSON format.

Emulate a RPC Call Using Domain Objects

Apart from reading domain (and writing using PUT) domain objects, Restlet can easily be used to implement a kind of remote procedure calls (RPC) or functionality similar to Java Remote Method Invocation (RMI). Such calls being made over Restlet do not only have the advantage of running cleanly over HTTP but are also rather performant when compared to remote invocations building on XML serializations (Java Serialization, although slow, is often faster than XML Serialization) such as used by XML-RPC or SOAP/WDSL based web services.

First we change the PersonResource Service description and define a POST service, which makes a copy of a person object.

import org.restlet.resource.Post;

public
interface PersonResource {

@Post
public Person copy(Person p);

    

}

Next we change the implementation of the service:

import org.restlet.resource.ServerResource;

public
class PersonServerResource extends ServerResource implements PersonResource {

    

    @Override

    public Person copy(final Person p) {

        return p;

    }

    

}

And finally change the main method. Note here too that here we run the server and client as part of a unit test (so add JUnit dependency to your pom). This highlights how easy it is to build (almost) fully blown integration tests based on Restlet, which in addition execute very fast.


import org.junit.Assert;
import org.junit.Test;
import org.restlet.Component;
import org.restlet.data.Protocol;
import org.restlet.resource.ClientResource;
import org.restlet.routing.Router;

public class RestletServerTest  {

@Test
public void test_server() throws Exception {
// Create a new Component.
final Component component = new Component();

// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);

final Router router = new Router(component.getContext().createChildContext());

router.attach("/person", PersonServerResource.class);

// Attach the sample application.
component.getDefaultHost().attach("/restlet", router);

// Start the component.
final Thread t = new Thread() {

@Override
public void run() {
try {
component.start();
} catch (final Exception e) {
e.printStackTrace();
}
super.run();
}

};

t.run();

final ClientResource cr = new ClientResource("http://localhost:8182/restlet/person");

final PersonResource resource = cr.wrap(PersonResource.class);
final Person originalPerson = new Person("Peter", 20);
final Person copiedPerson = resource.copy(originalPerson);

Assert.assertFalse(originalPerson == copiedPerson);

Assert.assertTrue(originalPerson.name.equals(copiedPerson.name));

System.out.println(copiedPerson.name);

}

}
<pre>

Resources

Restlet Documentation Hello World Application in JavaSE

Maven and Eclipse Indigo

It has been a while since the new release of the eclipse IDE, Indigo, has been released. One of the most interesting new features seems to be a better integration with Maven.

After some very unsuccessful attempts using eclipse IAM and the m2eclipse plugin, I became a bit sceptical of Maven integration into the eclipse IDE. In particular, I want to use the eclipse plugin development environment (PDE) alongside Maven, which seemed impossible at the time. At the moment, I use the eclipse:eclipse Maven Mojo to generate eclipse project files (with PDE support). The projects compile in eclipse and unit test etc run. Just for any Maven specific tasks, I need to change to the command line (eg deploying projects, changing dependencies between projects).

Now I have seen a few negative comments about the new Maven features in eclipse (see below). After spending a lot of time getting eclipse PDE and Maven working together well, I feel a bit anxious to change to eclipse Indigo.

Resources

Changing from m2eclipse to m2e (Eclipse 3.7 – Indigo)

Maven and Eclipse, Top Eclipse Indigo Feature #10 (critique in the comments)