Category Archives: eclipse

Introduction to Eclipse Command

Command in Eclipse represents task. Anything can be a task. In the example in the picture above, I used ‘delete’ as example. A command can have several handlers, which are active on different conditions. In the previous example, I used three handlers which active depend on the type of the object.

Commands can be triggered from one or more place(s). We can define a menu that call a command or define a context menu for that. We can also bind a keyboard shortcut to call a command and we can as well programmatically call a command from our code. And that’s just some examples.

Command, architecturally, is representation of controller. Using command should made it easy for developer to get a big picture of what an application does. Just list all the command and that should be it.

You can find more about command in these links.

What is Eclipse-RCP-based Application?

To get the answer of that question, we need to take a look at the global architecture of an Eclipse-RCP-based application. This picture below can summarize the information.

SWT is Standard Widget Toolkit for Java. Developed by IBM and later by Eclipse Foundation, the purpose of SWT is to give native performance and look to Java application. SWT is implemented using JNI and so is not write-once-run-anywhere-library (WORA). This mean that each OS need specific SWT distribution.

JFaces is a layer above SWT which provides more convenience classes for generic application. JFaces is a WORA library.

OSGi is a standard developed by consortium with the same name to provide Java environment that is more dynamic. The goal is extensible, loosely-coupled applications with modules behind it.

Equinox is Eclipse implementation of OSGi.

Eclipse Core and Eclipse UI are classes that form the platform of Eclipse. All Eclipse-RCP-based applications will use this classes. Among other things, it provides extension framework, command framework (and somewhat-deprecated Action framework), and basic application-window management.

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.

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.

Little Java Generic Quiz

Let say I have following code:

interface TestGeneric {

   public Integer test(List<Integer> a);
   public Boolean test(List<Boolean> a);

}

Can you guess what are the answers for following questions?

  • TestGeneric will be reported as error by Java 6 (true/false)
  • TestGeneric will be reported as error by Java 7 (true/false)
  • TestGeneric will be reported as error by Eclipse 3.5 using Java 6 (true/false)
  • TestGeneric will be reported as error by Eclipse 3.5 using Java 7 (true/false)
  • TestGeneric will be reported as error by (upcoming) Eclipse 3.6 using Java 6 (true/false)
  • TestGeneric will be reported as error by (upcoming) Eclipse 3.6 using Java 7 (true/false)

What’s your guess?

The correct answer is (highlight to see the answer): false, true, false, (can Eclipse 3.5 run Java 7?)?, true, true.

The fact that statement 1 is false is related to this bug entry: http://bugs.sun.com/view_bug.do?bug_id=6182950

Eclipse (as 3.6M2) offered a more consistent behavior by considering all cases as compile error as discussed here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=289247

And this op4j used exactly this feature and will not be compiled under Java 7 or using Eclipse 3.6.

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!