In-Depth

Practical Eclipse

Apply these usage and technical tips to a world-class IDE brimming with features.

I thought I'd start off with a set of tips for using Eclipse more effectively. I've found these tips useful in my day-to-day work. Some are usage tips, and some are technical tips. I trust you will find them useful too.

One thing I disliked about Eclipse originally (and in fact still do dislike) is the lack of a built-in XML editor. Other IDEs provide excellent editors that include at least syntax highlight but also completion of XML statements. Eclipse does in fact come with an XML editor, it's just not called that; it's called the Ant editor. While the Ant editor is not perfect at editing general XML, it does a more than adequate job.

To use the Ant editor as a general XML editor, you need to select Windows > Preferences to open the Preferences dialog, open the Workbench section of the tree, and choose File Associations (see Figure 1). Click the Add button next to the File Types area and enter *.xml. Click the Add button next to the Associated Editors area, choose the Ant editor, and click OK. Now, any time you double-click an XML file it will open for editing in the Ant editor.

Templates and Style
In the same Preferences dialog open the Java portion of the tree, and under the Editor section you will see a Templates section. It contains coding templates that you can use in your code. As an example of using a template, create a new Java class and open the class in the editor. Type main and press Ctrl-Spacebar. You should see a pop-up window (see Figure 2); select the first main and the code for a main method will be entered for you.

However, if you look at the templates you will see that they can do more that just insert static code. The templates are live. In the main method that you just created, type for and press Ctrl-Spacebar. Choose for – iterate over array. A for loop will be added to your code, with the cursor on a variable called i. If you change the variable name, notice that it is changed in the correct places in the code. If you press Tab, you will get to the array reference, and if there is more than one array you will see a list of the arrays that could be iterated over. Eventually you will be left with the cursor in the body of the loop.

There are many such templates, and you can extend these by writing your own. For example, among my favorite templates are sysout and syserr; however, I now do most of my work in JDK 5.0, have started using System.out.printf, and I wanted to use it as a template. The easiest way to do so is to edit an existing template. I copied the sysout template to one I called printf and made the body look like this:

System.out.printf(
   "${word_selection}${}\n");
   ${cursor}

Save the template. In your code, type printf and press Ctrl-Spacebar to insert the template into your code.

If you're like me you love writing code but hate writing documentation, even though Java makes this easy (well easier) with Javadoc. Eclipse can help too. Simply place the cursor before any method or class definition, type /** and then press Enter. You'll get an outline of the javadoc, which should look something like this:

/**
   * 
   * @param proxy
   */
ListenThread(HttpProxy proxy)
{
      // code here
}

The cursor will be positioned, ready for you to edit the documentation.

Code style is one of the great debates among programmers. For example, where do you place your braces? Do you indent case from switch? Where does the while keyword go? And of course we all know that we are correct, that our style is the only one that matters. If you have a house style, or if you have personal preferences, then Eclipse can help enforce that style throughout your code.

Select Windows > Preferences, and select Java > Code Style > Formatter. In the right-hand pane you can select New to create a new set of preferences, give it a name, and then change the preferences to suit yourself. The most contentious issues are going to be the location of braces, but you also get control over line wrapping, white space, comments, and so on. You can also export and import profiles, which are extremely useful for teamwork.

Once you've selected your preferences you can open a Java file and choose Source > Format (Ctrl-Shift-F). You can also reformat multiple files at once. In the package explorer select the group of files you want to reformat, right-click, and then select Source > Format.

Refactoring
One of the most powerful Eclipse features is its refactoring support. This support requires a full article to discuss in depth, but it's worth noting here because it is so important. In the introduction to his informative book on the subject, Martin Fowler said "Refactoring is the process of changing a software system in such a way that it does not alter external behavior of the code yet improves on its internal structure." When refactoring you really also must have unit tests in place (see the next tip); otherwise, how can you know that the external behavior of the code has not changed?

Eclipse offers several refactorings, and we'll take a look at just a couple using them as an example to understand the process. Take these two methods:

byte[] decryptKey(
   byte[] encryptedKeyBytes) 
   throws 
   NoSuchAlgorithmException, 
   InvalidKeySpecException, 
   NoSuchPaddingException, 
   InvalidKeyException, 
   BadPaddingException, 
   IllegalBlockSizeException, 
   InvalidAlgorithmParameter
   Exception
{ 
      String alg = 
         "PBEWithMD5AndDES";

      PBEParameterSpec spe = 
         createPBEParameterSpec();

      KeySpec ks = new PBEKeySpec(
passphrase.toCharArray());
      SecretKeyFactory skf = 
         SecretKeyFactory.
         getInstance(alg);
      SecretKey sk = skf.
         generateSecret(ks);
      Cipher cipher = Cipher.
         getInstance(alg);
      cipher.init(
         Cipher.DECRYPT_MODE, sk, 
         spe);

      return cipher.doFinal(
         encryptedKeyBytes);
}

and 

byte[] encryptKey() throws 
   NoSuchAlgorithmException, 
   InvalidKeySpecException, 
   NoSuchPaddingException, 
   InvalidKeyException, 
   BadPaddingException, 
   IllegalBlockSizeException, 
   InvalidAlgorithmParameter
   Exception
{
      String alg = 
         "PBEWithMD5AndDES";

      PBEParameterSpec spe = 
         createPBEParameterSpec();

      KeySpec ks = new PBEKeySpec(
         passphrase.toCharArray());
      SecretKeyFactory skf = 
         SecretKeyFactory.
         getInstance(alg);
      SecretKey sk = skf.
         generateSecret(ks);
      Cipher encrypt = Cipher.
         getInstance(alg);
      encrypt.init(
         Cipher.ENCRYPT_MODE, sk, 
         spe);
      return encrypt.doFinal(
         secret.getEncoded());
}

These methods use a key to encrypt and decrypt data. They are very similar and in fact have one block of code in common: the code that creates the key.

There is a refactor called Extract Method, which takes a block of code and puts it in its own method. Do this by highlighting the block of code and then selecting Refactor > Extract Method (Alt-Shift-M). In the Extract Method dialog (see Figure 3) enter a name for the method, and make sure that the parameter name is what you want. Select OK and you should get the new method:

private SecretKey createKey(
   String algorithm) throws 
   NoSuchAlgorithmException, 
   InvalidKeySpecException
{
      KeySpec ks = new PBEKeySpec(
         passphrase.toCharArray());
      SecretKeyFactory skf = 
         SecretKeyFactory.
         getInstance(algorithm);
      SecretKey sk = skf.
         generateSecret(ks);
      return sk;
}

You can now replace the method code in all other places it is used with a call to your new method. The two prior methods—encryptKey() and decrytptKey()—are in different classes that extend the same base class, so ideally createKey() should be a method in the base class. Enter another refactor: Pull Up. You use this refactor to move methods up the class hierarchy. If we do this with createKey(), it will also change the protection level from private to protected to allow the method to be called in the derived class. The final code looks like:

protected SecretKey createKey(
   String algorithm) throws 
   NoSuchAlgorithmException, 
   InvalidKeySpecException
{
      KeySpec ks = new PBEKeySpec(
         passphrase.toCharArray());
      SecretKeyFactory skf = 
         SecretKeyFactory.
         getInstance(algorithm);
      SecretKey sk = skf.
         generateSecret(ks);
      return sk;
}

After making the changes, rerun the unit tests to ensure that nothing is broken.

JUnit with Ant
I mentioned that you must have unit tests if you are going to refactor to prove that your changes have not broken the code. Eclipse has very good support for JUnit; however, I tend to use Ant to build and test my code, and I use the JUnit test within Ant. If you load an Ant build file into Eclipse and run a JUnit Ant task, you are likely to see:

BUILD FAILED: 
   D:\home\kevinj\Java\Security   tests.xml:94: Could not create 
   task or type of type: junit.

This message means that Ant could not find the task or a class this task relies on. Ant is trying to load the JUnit JAR files. When using Ant outside of the IDE you have to place junit.jar in the %ANT_HOME%/lib directory. That task doesn't work when using Eclipse because it uses its own version of Ant. Instead junit.jar must be placed in Eclipse's Ant directory, that is, in %ECLIPSE_HOME%/plugins/org.apache.ant_1.6.2/lib (obviously the version of Ant may vary with the version of Eclipse).

Eclipse is a world-class IDE with many features. We have only scratched the surface here, and over the coming months we'll explore more—and in greater depth—features that Eclipse offers.

As seems to be the way of first columns, I'd like to request reader feedback. I have some topics I'd like to write about, and colleagues of mine have come up with other ideas. Now I'd like to know what you would like. E-mail me directly or through the magazine.