Tag Archives: eclipse

Eclipse Helios: 5 JDT Improvements

Helios has been released. This simultaneous release includes more projects but many people still regard Eclipse as Java IDE. So in this post, I want to share the most important JDT improvements that I think will be loved by most Java developers.

Java Formatter Improvements

I’ve discussed this improvements on my other post.

Package Abbreviation

This is a very nice touch improvement especially if you’re working with a big projects. The abbreviation can be set on Preference โ†’ Java โ†’ Appearance. Check the Abbreviate package names box and set the rules.

Better Generic Support

The support for Java generic is improved. In the formatter, in the javadoc, in the javadoc hover… Overall. Is better. This is including the fix for my little generic quiz and bugs mentioned in the bug list.

New Icon for Build Problems

It’s always weird seeing a project with error but no resource is marked as error. With this new icon, I hope I will be less confused next time I encounter a build problems.

Debugger detailed view

This is the one I love most. I discussed this feature before on my other post. The problem is, changing the properties via dialog isn’t really comfortable. With this improvement, you can edit all breakpoint properties without opening any dialog.

Eclipse Tips: Debugging your multi-thread application

One of difficulty in debugging a multi-thread application is that there are several threads running at one time and if you are defining a standard breakpoint in your application, it will only break the related thread. The other threads will be still running.

Eclipse actually has provided a tool to break all threads in the same JVM which can be quite useful in such case. You must open the breakpoint properties window from your breakpoint definition and there you will get a dialog like following.

2009-08-20_1649

The bottom combo box can be changed to suspend VM.

2009-08-20_1649b

If you do something like this your entire VM will be suspended in case of a breakpoint is reached. That won’t make creating a multi-thread any easier, but at least the tool will help you locate the bug you create.

Maven Plugin: Java Code Formatter

Enforcing code format in an organization needs discipline. And the best way to do that is by doing some automation. A plugin for Maven will be a easy decision if your organization has used Maven to manage the build.

This plugin is one plugin that exactly does that. The backbone on the plugin comes from Eclipse Java Formatter, which I still endorse as the best in the industry.

Compared to Jalopy, which is now not free, I find Eclipse formatter has the flexibility we often needed. Although it is not bug-free, for most cases it is more than enough.

However, I concerned by the fact that official maven doesn’t have the latest jar of Eclipse JDT. It still only has version 3.3 of it. Hopefully they will have it soon, especially after Helios is released, which bring a lot of improvement to the Java formatter.

Eclipse: Copy Qualified Java Name

Eclipse has a nice feature to copy qualified name from a resource and this is very useful to create documentation or working with XML. For example:

Say that I need the full qualified name from class CaseFormat. What I have to do is:

  1. Click on + beside CaseFormat.java.
  2. Right click on CaseFormat (not CaseFormat.java).
  3. Select Copy Qualified Name.
  4. There you go, you can paste the full qualified name of class CaseFormat anywhere you want.

But that’s kind of a lot of steps, isn’t it?

OK… you can create a keyboard shortcut for Copy Qualified Name but still you have to expand CaseFormat.java before you can do that. If you don’t expand the *.java node what you’ll get is: ‘/guava/src/com/google/common/base/CaseFormat.java’ instead of ‘com.google.common.base.CaseFormat’.

This problem is kind of annoying and if you have to do this a lot of time, it will certainly damage your productivity.

So here is a tiny plugin to solve the problem.

com.satukubik.copyqualifiedname_1.0.0

You can download it, save it to your dropins folder, and restart Eclipse. After that a shortcut Ctrl+Shift+C is available for you to copy qualified java name without having to expand the *.java node.

For those who are curious, I’ve put the source code of the plugin here: http://code.google.com/a/eclipselabs.org/p/copyqualifiedjavaname/. Feel free to clone, suggest improvement, or report a bug.

Eclipse Heliosโ€™ Java Formatter Improvement

A new milestone of Eclipse 3.6 just released with a long new and noteworthy list.

Instead of discussing what’s new from this release, I want to discuss a set of improvement from its Java Formatter. I still love Eclipse’s Java Formatter and with these new improvements, I even love it more. This improvements unfortunately didn’t make their way to list of new and noteworthy, hence the reason why I wrote this blog post.

First, we can now turn off the formatter for some part of your code that you don’t want to format automatically. This is achieved by defining special tags.

This is very useful to format a part of your code that will if formatted will be uglier. For example:

		// [format off]
		foo(           "|------------|\n"            +
		    "-----------|------------|-----------\n" +
	         "----------|   FORMAT   |----------\n"  +
	          "--------- |          | ---------\n"  +
	            "-------  |        |  -------\n"  +
	                      "--------");

No tools can keep this formatting no matter what are you trying, right? ๐Ÿ˜‰

The next improvement is very beautiful. This is result of bug entry 59891 which is posted five years ago (! just to make sure that you understand its complexity).

Basically the problem is if you have nested method calls, Eclipse can’t group the arguments based on their call level. So if you have something like:

public class Main {
    public static void main(
            String[] args) {
        foo(bar(1, 2, 3), baz(4, 5, 6, 7));
    }
}

In case the editor set to wrap on 40th characters, you will get:

public class Main {
    public static void main(
            String[] args) {
        foo(bar(1, 2, 3), baz(4, 5, 6,
                7));
    }
}

With the improvement, you will get:

public class Main {
    public static void main(
            String[] args) {
        foo(bar(1, 2, 3),
                baz(4, 5, 6, 7));
    }
}

Very nice!

A longer example (based on post on StackOverflow.com).

With old formatter, the best you can get is:

		Options options = new Options().addOption(OPTION_HELP_SHORT,
				OPTION_HELP, false, "print usage information").addOption(
				OPTION_VERSION_SHORT, OPTION_VERSION, false,
				"print version and exit").addOption(
				OptionBuilder.withLongOpt(OPTION_PROPERTIES)
						.hasArg()
						.withArgName("FILE")
						.withType(File.class)
						.withDescription("specify a user properties file")
						.create());

Or anything explained on the original post. With the new improvement, you can set the formatter to get something like this:

		Options options = new Options()
				.addOption(OPTION_HELP_SHORT, OPTION_HELP, false,
					"print usage information")
				.addOption(OPTION_VERSION_SHORT, OPTION_VERSION, false,
					"print version")
				.addOption(	OptionBuilder
									.withLongOpt(OPTION_PROPERTIES)
									.hasArg()
									.withArgName("FILE")
									.withType(File.class)
									.withDescription("specify a user properties file")
									.create());

Beautiful, isn’t it? Just one bug maybe since there is a white space before OptionBuilder.

Beside those two, Helios also bring further supports for formatting annotations and various bug fixes. You can check the whole list by clicking this link.

Visual Editor in Eclipse Galileo

For a long time I have tried to install Visual Editor into my Eclipse Galileo and never get it work until recently.

The secret is explained in the Wiki:

With “Eclipse IDE for Java EE Developers”, you should NOT check the Java EMF Model Utilities (org.eclipse.jem.util) plugins since there are already installed.

Ugh… I think I have tried it before but why only now it is working? Anyway, I’m glad that I have it.

For those who are not aware, Visual Editor is an GUI editor for Eclipse. It can be used to assist Swing or SWT application creation. I never like Netbeans Matisse or SWT Designer because I can’t modify the code like I want. I know that Visual Editor is pretty slow, but to get a code that I can enhance manually tastes better than the alternative.

And more importantly, I like the way it codes my Swing application. Here’s an example:

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class TTT extends JFrame {

   private static final long serialVersionUID = 1L;
   private JPanel jContentPane = null;
   private JLabel jLabel = null;
   private JButton jButton = null;
   private JTextField jTextField = null;
   private JSlider jSlider = null;

   /**
    * This is the default constructor
    */
   public TTT() {
      super();
      initialize();
   }

   /**
    * This method initializes this
    *
    * @return void
    */
   private void initialize() {
      this.setSize(300, 196);
      this.setContentPane(getJContentPane());
      this.setTitle("JFrame");
   }

   /**
    * This method initializes jContentPane
    *
    * @return javax.swing.JPanel
    */
   private JPanel getJContentPane() {
      if (jContentPane == null) {
         jLabel = new JLabel();
         jLabel.setText("JLabel");
         jContentPane = new JPanel();
         jContentPane.setLayout(new BorderLayout());
         jContentPane.add(jLabel, BorderLayout.CENTER);
         jContentPane.add(getJButton(), BorderLayout.EAST);
         jContentPane.add(getJTextField(), BorderLayout.SOUTH);
         jContentPane.add(getJSlider(), BorderLayout.NORTH);
      }
      return jContentPane;
   }

   /**
    * This method initializes jButton
    *
    * @return javax.swing.JButton
    */
   private JButton getJButton() {
      if (jButton == null) {
         jButton = new JButton();
         jButton.setHorizontalAlignment(SwingConstants.TRAILING);
         jButton.setText("Test");
         jButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
               System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
            }
         });
      }
      return jButton;
   }

   /**
    * This method initializes jTextField
    *
    * @return javax.swing.JTextField
    */
   private JTextField getJTextField() {
      if (jTextField == null) {
         jTextField = new JTextField();
         jTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            @Override public void keyTyped(java.awt.event.KeyEvent e) {
               System.out.println("keyTyped()"); // TODO Auto-generated Event stub keyTyped()
            }
         });
      }
      return jTextField;
   }

   /**
    * This method initializes jSlider
    *
    * @return javax.swing.JSlider
    */
   private JSlider getJSlider() {
      if (jSlider == null) {
         jSlider = new JSlider();
      }
      return jSlider;
   }

} // @jve:decl-index=0:visual-constraint="10,10"

See how it creates a getter for every components? The getter should prepare a component with its properties and also its listener initialization. It makes every method pretty small and readable. There is no long methods with several components and listeners initialization.

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: 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)!