Tag Archive for 'eclipse'

Eclipse plugin: Introduce Static Imports

The Static Import guide from Sun states:

So when should you use static import? Very sparingly! Only use it when you’d otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

Unfortunately, Eclipse didn’t provide a way to change all calls of static method/field to use static import. You can do ‘Add Import’ and Eclipse will create this static import for you but the other instances where this same method/field used will not be changed.

For example, if I have a class that contains static method like this:

package bug;

public class A {

	public static void bbb() {

	}
}

And other class that calls the static method:

package bug;

public class B {
	public B() {
		A.bbb();
		A.bbb();
	}
}

And I want to introduce A.bbb as static import. I can do Add Import (Ctrl+Shift+M) and what I will get is;

package bug;

import static bug.A.bbb;

public class B {
	public B() {
		bbb();
		A.bbb();
	}
}

Hmmm… not really nice, that says that I have to change all occurrence of A.bbb() in the same class (which can be many, after all the previously mentioned guide asked us only to use this import static when there are a lot of repetition of class name).

So I decide to do some hacks and create my first JDT extension plugins (yay!) that exactly do this. You can grab the plugin here (I might release the source later on GitHub):

firdau.si.introduceStaticImport_1.0.0.201001111558

Copy this plugin and drop it in the dropins folder. I must mention also that I use Java 6 for the development. I think Java 5 will also work but I make no guarantee.

With this plugin installed, you will get a new entry if you do right click in Java Editor.

And if you run it, the result is:

package bug;

import static bug.A.bbb;

public class B {
	public B() {
		bbb();
		bbb();
	}
}

Take it easy with the plugin, after all this is my first JDT extension plugin. I have tested it against the code of the plugin itself, but I can’t be responsible for anything that may happen. You may report the problem though…

Note also that the plugin currently is working only for static methods and I do think this should be provided by Eclipse in their default product. Unfortunately, I don’t think my code is good enough for a patch for such.

UPDATE:

The new code can also work with static field.

My Eclipse Code Formatter

A consistent code format across the project is one sign of a maintainable project. Almost all of Java IDEs provide a way to format your code, but in my opinion, Eclipse does deliver the most customizable Java formatter. Many aspects from the code can be configured using the tools.

Lately the format used by Kevin Bourrillion caught my eyes. Among other things, he chose to use method annotation without any line break. So instead of:

    @Deprecated
    @Override
    public void bar(@SuppressWarnings("unused") int i) {
        @SuppressWarnings("unused")
        int k;
    }

he used:

    @Deprecated @Override public void bar(@SuppressWarnings("unused") int i) {
        @SuppressWarnings("unused")
        int k;
    }

And for an empty constructor or an empty method, instead of the standard:

private Casts() {
}

he used:

private Casts() {}

At first, I don’t really like it, but after working with Google Collections, this format seems make sense. It reduce the number of lines and make the code a lot easier to read. Yes, the line will be longer, but today’s programmers seem to use a big monitor anyway, right?

Now I know that he uses IDEA for his IDE and he doesn’t publish his code style in the Google Collections or Google Guava, but I also don’t want to copy his style 100%, so I made my own custom style and publish it in GitHub: http://github.com/enefem/eclipse-config

You can download the style there and import it to your Eclipse. And by the way… Git rocks!

I almost forgot. Unfortunately Eclipse has a bug in the code formatter. If you use my style and you have a method or constructor that contain only comment(s), the formatter will give a result:

public Thread() {
// TODO Auto-generated constructor stub
}

Which should be:

public Thread() {
    // TODO Auto-generated constructor stub
}

I’ve reported this and you can also use the patch I provided there.

Please let me know if you have special style that I might be interested in!

Eclipse RCP: ISharedImages

One good thing of using a RCP platform is you’ve got access to standard images that are often used. That is not valid, of course, if you are so obsessed about the icons and want to customize the icons.

In Eclipse you can access the standard images by using:

PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW);

Change the parameter with one from the constant in ISharedImages. You can check the list (unfortunately not complete) from this link.

If you want the complete list (and more exciting, will be valid all the times, even if the list get updated) by running my little application. You can download the complete source code from here.

Once you run the application, you will see all the images referred from ISharedImages like here:

listISharedImages

Moreover, if you click one of the button, you will get the text on the clipboard which you can paste wherever you want.

Eclipse RCP: Creating dynamic menu

Have you ever want to create a dynamic menu to your RCP application? Do you want to compute the contents of the menu on-the-fly at runtime? This is possible and many hacks can be done to do that.

But to do the correct thing is probably what annoyed your head every day. And actually, this has been supported by the framework.

First, what you need to do is creating a menu holder for your dynamic menu. This can be done by adding a new element named ‘dynamic’ under a menu contribution.

2009-11-13_1504

Now you need to implement a class that extends CompoundContributionItem.

2009-11-13_1506

Let’s make the menu like this;

public class ContributionItem1 extends CompoundContributionItem {

    @Override
    protected IContributionItem[] getContributionItems() {
        List<IContributionItem> menuContributionList = new ArrayList<IContributionItem>();

        menuContributionList.add(new CommandContributionItem(new CommandContributionItemParameter(Activator
                .getDefault().getWorkbench(), null, ActionFactory.QUIT.getCommandId(),
                CommandContributionItem.STYLE_PUSH)));

        return menuContributionList.toArray(new IContributionItem[menuContributionList.size()]);
    }

}

This is of course not a real example. In the reality, you will want to create a dynamic menu based on the condition. If the condition is changed, the menu will be automatically changed. I hope by using this small and unreal example, you will just get the idea.

Let’s try to run the application.

2009-11-13_1527

Great!

Embedding Jetty Server in Eclipse RCP

Eclipse has a nice tutorial on how to embed a Jetty server in an OSGI framework. Unfortunately, this tutorial doesn’t help you if you want to run the server in a standalone Eclipse RCP application. One use case where you need to have a web server in your RCP application is when your application need to be able to be called by an external entity.

Fortunately, as pointed by the tutorial, Eclipse has provided a Jetty plugin in its Java IDE. The documentation of Eclipse is provided using this Jetty server.

Eclipse documentation served from Jetty server

Eclipse documentation served from Jetty server

So, how do you embed a Jetty server in your Eclipse RCP application? I assume you already have a grasp knowledge on how to create a RCP application (after all, Eclipse provided you with a simple generator for that).

First, let’s add the jetty plugin to our dependencies. Open the tab ‘Dependencies’ in your plugin configuration. Then add these six plugins to the ‘Required Plug-ins’:

  • javax.servlet
  • org.eclipse.equinox.http.jetty
  • org.eclipse.equinox.http.regstry
  • org.eclipse.equinox.http.servlet
  • org.mortbay.jetty.server
  • org.mortbay.jetty.util

2009-11-06_1535

This is actually all that we need. However, the OSGI framework will not activate these plugins automatically. And since there is no code in your application that actually refers to these plugins, they will not be activated at all! We have to force the framework to run these plugins from start. It can be done by changing the ‘Auto-Start’ value from your Run configuration.

In the list of plugins included at the launch of application you need to change the ‘Auto-Start’ value for three plugins to true (if you are lazy, you can turn the default behavior to auto start but this is another concern):

  • org.eclipse.equinox.http.jetty
  • org.eclipse.equinox.http.regstry
  • org.eclipse.equinox.http.servlet

2009-11-06_1542

Now if you run the application you can check if your server is correctly running by accessing ‘http://localhost’. This should work flawlessly except maybe if you are not allowed to run server in port 80 or there is already a server running in port 80.

You can change the port by adding an argument to the VM arguments in ‘Run Configurations’. Add this value: ‘-Dorg.eclipse.equinox.http.jetty.http.port=8888′. Change ‘8888′ to whatever port you want the server to be running.

2009-11-06_1547

Now if you are running the application, you can access it from the port you mentioned before.

The next task is to define one (or several) servlet(s) that will serve any request the server gets. To do this, you need to open the ‘Extensions’ tab from your plugin configuration and add a new extension named ‘org.eclipse.equinox.http.registry.servlets’. After that add new ’servlet’. You need to mention the class name of the servlet, and an alias for that. One note here is you need to add slash in front of the alias. For example, if you want to make the servlet accessible from ‘http://localhost:8888/webserviceInterface’, then the alias value is ‘/webserviceInterface’. Of course, you need to implement a servlet which will do the work you want.

2009-11-06_1556

Now sit down, run the application, and enjoy the service from your web server (running directly from your RCP application)!