Home Programming Eclipse Plug-in Development Beginner's Guide - Second Edition

Eclipse Plug-in Development Beginner's Guide - Second Edition

By Alex Blewitt
books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Creating Your First Plug-in
About this book
Eclipse is used by everyone from indie devs to NASA engineers. Its popularity is underpinned by its impressive plug-in ecosystem, which allows it to be extended to meet the needs of whoever is using it. This book shows you how to take full advantage of the Eclipse IDE by building your own useful plug-ins from start to finish. Taking you through the complete process of plug-in development, from packaging to automated testing and deployment, this book is a direct route to quicker, cleaner Java development. It may be for beginners, but we're confident that you'll develop new skills quickly. Pretty soon you'll feel like an expert, in complete control of your IDE. Don't let Eclipse define you - extend it with the plug-ins you need today for smarter, happier, and more effective development.
Publication date:
August 2016
Publisher
Packt
Pages
458
ISBN
9781783980697

 

Chapter 1. Creating Your First Plug-in

Eclipse – an IDE for everything and nothing in particular.

Eclipse is a highly modular application consisting of hundreds of plug-ins, and can be extended by installing additional plug-ins. Plug-ins are developed and debugged with the Plug-in Development Environment (PDE).

In this chapter we will:

  • Set up an Eclipse environment for doing plug-in development

  • Create a plug-in with the new plug-in wizard

  • Launch a new Eclipse instance with the plug-in enabled

  • Debug the Eclipse plug-in

 

Getting started


Developing plug-ins requires an Eclipse development environment. This book has been developed and tested on Eclipse Mars 4.5 and Eclipse Neon 4.6, which was released in June 2016. Use the most recent version available.

Eclipse plug-ins are generally written in Java. Although it's possible to use other JVM-based languages (such as Groovy or Scala), this book will use the Java language.

There are several different packages of Eclipse available from the downloads page, each of which contains a different combination of plug-ins. This book has been tested with:

These contain the necessary Plug-in Development Environment (PDE) feature as well as source code, help documentation, and other useful features. The RCP and RAP package should not be used as it will cause problems with exercises in Chapter 7, Understanding the Eclipse 4 Model and RCP Applications.

It is also possible to install the Eclipse PDE feature in an existing Eclipse instance. To do this, go to the Help menu and select Install New Software, followed by choosing the General Purpose Tools category from the selected update site. The Eclipse PDE feature contains everything needed to create a new plug-in.

 

Time for action – setting up the Eclipse environment


Eclipse is a Java-based application; it needs Java installed. Eclipse is distributed as a compressed archive and doesn't require an explicit installation step.

  1. To obtain Java, go to http://java.com and follow the instructions to download and install Java.

    Tip

    Note that Java comes in two flavors: a 32-bit installation and a 64-bit installation. If the running OS is 32-bit, then install the 32-bit JDK; alternatively, if the running OS is 64-bit, then install the 64-bit JDK.

  2. Running java -version should give output like this:

    java version "1.8.0_92"
    Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
    Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)
    
  3. Go to http://www.eclipse.org/downloads/ and select the Eclipse IDE for Eclipse Committers distribution.

  4. Download the one that matches the installed JDK. Running java -version should report either of these:

    • If it's a 32-bit JDK:

      Java HotSpot(TM) Client VM
      
    • If it's a 64-bit JDK:

      Java HotSpot(TM) 64-Bit Server VM
      

    Note

    On Linux, Eclipse requires GTK+ 2 or 3 to be installed. Most Linux distributions have a window manager based on GNOME, which provides GTK+ 2 or 3.

  5. To install Eclipse, download and extract the contents to a suitable location. Eclipse is shipped as an archive, and needs no administrator privileges to install. Do not run it from a networked drive as this will cause performance problems.

  6. Note that Eclipse needs to write to the folder where it is extracted, so it's normal that the contents are writable afterwards. Generally, installing in /Applications or C:\Program Files as an administrator account is not recommended.

  7. Run Eclipse by double-clicking on the Eclipse icon, or by running eclipse.exe (Windows), eclipse (Linux), or Eclipse.app (macOS).

  8. On startup, the splash screen will be shown:

  9. Choose a workspace, which is the location in which projects are to be stored, and click on OK:

  10. Close the welcome screen by clicking on the cross in the tab next to the welcome text. The welcome screen can be reopened by navigating to Help | Welcome:

What just happened?

Eclipse needs Java to run, and so the first step involved in installing Eclipse is ensuring that an up-to-date Java installation is available. By default, Eclipse will find a copy of Java installed on the path or from one of the standard locations. It is also possible to specify a different Java by using the -vm command-line argument.

If the splash screen doesn't show, then the Eclipse version may be incompatible with the JDK (for example, a 64-bit JDK with a 32-bit Eclipse, or vice versa). Common error messages shown at the launcher may include Unable to find companion launcher or a cryptic message about being unable to find an SWT library.

On Windows, there is an additional eclipsec.exe launcher that allows log messages to be displayed on the console. This is sometimes useful if Eclipse fails to load and no other message is displayed. Other operating systems can use the eclipse command; and both support the -consolelog argument, which can display more diagnostic information about problems with launching Eclipse.

The Eclipse workspace is a directory used for two purposes: as the default project location, and to hold the .metadata directory containing Eclipse settings, preferences, and other runtime information. The Eclipse runtime log is stored in the .metadata/.log file.

The workspace chooser dialog has an option to set a default workspace. It can be changed within Eclipse by navigating to File | Switch Workspace. It can also be overridden by specifying a different workspace location with the -data command-line argument.

Finally, the welcome screen is useful for first-time users, but it is worth closing (rather than minimizing) once Eclipse has started.

Creating your first plug-in

In this task, Eclipse's plug-in wizard will be used to create a plug-in.

 

Time for action – creating a plug-in


In PDE, every plug-in has its own individual project. A plug-in project is typically created with the new project wizard, although it is also possible to upgrade an existing Java project to a plug-in project by adding the PDE nature and the required files by navigating to Configure | Convert to plug-in project.

  1. To create a Hello World plug-in, navigate to File | New | Project…

  2. The project types shown may be different from this list but should include Plug-in Project with Eclipse IDE for Eclipse Committers or Eclipse SDK. If nothing is shown when you navigate to File | New, then navigate to Window | Open Perspective | Other | Plug-in Development first; the entries should then be seen under the New menu.

  3. Choose Plug-in Project and click on Next. Fill in the dialog as follows:

    1. Project name should be com.packtpub.e4.hello.ui.

    2. Ensure that Use default location is selected.

    3. Ensure that Create a Java project is selected. The Eclipse version should be targeted to 3.5 or greater:

  4. Click on Next again, and fill in the plug-in properties:

    1. ID is set to com.packtpub.e4.hello.ui.

    2. Version is set to 1.0.0.qualifier.

    3. Name is set to Hello.

    4. Vendor is set to PacktPub.

    5. For Execution Environment, use the default (for example, JavaSE-1.8).

    6. Ensure that Generate an Activator is selected.

    7. Set Activator to com.packtpub.e4.hello.ui.Activator.

    8. Ensure that This plug-in will make contributions to the UI is selected.

    9. Rich client application should be No:

  5. Click on Next and a set of templates will be provided:

    1. Ensure that Create a plug-in using one of the templates is selected.

    2. Choose the Hello, World Command template:

  6. Click on Next to customize the sample, including:

    1. Java Package Name, which defaults to the project's name followed by .handlers

    2. Handler Class Name, which is the code that gets invoked for the action

    3. Message Box Text, which is the message to be displayed:

  7. Finally, click on Finish and the project will be generated.

  8. If an Open Associated Perspective? dialog asks, click on Yes to show the Plug-in Development perspective.

What just happened?

Creating a plug-in project is the first step towards creating a plug-in for Eclipse. The new plug-in project wizard was used with one of the sample templates to create a project.

Plug-ins are typically named in reverse domain name format, so these examples will be prefixed with com.packtpub.e4. This helps to distinguish between many plug-ins; the stock Eclipse IDE for Eclipse Committers comes with more than 450 individual plug-ins; the Eclipse-developed ones start with org.eclipse.

Note

Conventionally, plug-ins that create additions to (or require) the use of the UI have .ui. in their name. This helps to distinguish those that don't, which can often be used headlessly. Of the more than 450 plug-ins that make up the Eclipse IDE for Eclipse Committers, approximately 120 are UI-related and the rest are headless.

The project contains a number of files that are automatically generated based on the content filled in the wizard. The key files in an Eclipse plug-in are:

  • META-INF/MANIFEST.MF: The MANIFEST.MF file, also known as the OSGi manifest, describes the plug-in's name, version, and dependencies. Double-clicking on it will open a custom editor, which shows the information entered in the wizards; or it can be opened in a standard text editor. The manifest follows standard Java conventions; line continuations are represented by a newline followed by a single space character, and the file must end with a newline.

  • plugin.xml: The plugin.xml file declares what extensions the plug-in provides to the Eclipse runtime. Not all plug-ins need a plugin.xml file; headless (non-UI) plug-ins often don't need to have one. Extension points will be covered in more detail later; but the sample project creates an extension for the commands, handlers, bindings, and menus' extension points. Text labels for the commands/actions/menus are represented declaratively in the plugin.xml file, rather than programmatically; this allows Eclipse to show the menu before needing to load or execute any code.

    Note

    This is one of the reasons Eclipse starts so quickly; by not needing to load or execute classes, it can scale by showing what's needed at the time, and then load the class on demand when the user invokes the action. Java Swing's Action class provides labels and tooltips programmatically, which can result in slower initialization of Swing-based user interfaces.

  • build.properties: The build.properties file is used by PDE at development time and at build time. Generally it can be ignored, but if resources are added that need to be made available to the plug-in (such as images, properties files, HTML content and more), then an entry must be added here as otherwise it won't be found. Generally the easiest way to do this is by going to the Build tab of the build.properties file, which will gives a tree-like view of the project's contents. This file is an archaic hangover from the days of Ant builds, and is generally useless when using more up-to-date builds such as Maven Tycho, which will be covered in Chapter 12, Automated Builds with Tycho.

Pop quiz – Eclipse workspaces and plug-ins

Q1. What is an Eclipse workspace?

Q2. What is the naming convention for Eclipse plug-in projects?

Q3. What are the names of the three key files in an Eclipse plug-in?

Running plug-ins

To test an Eclipse plug-in, Eclipse is used to run or debug a new Eclipse instance with the plug-in installed.

 

Time for action – launching Eclipse from within Eclipse


Eclipse can launch a new Eclipse application by clicking on the run icon, or via the Run menu.

  1. Select the plug-in project in the workspace.

  2. Click on the run icon to launch the project. The first time this happens, a dialog will be shown; subsequent launches will remember the chosen type:
  3. Choose the Eclipse Application type and click on OK. A new Eclipse instance will be launched.

  4. Close the Welcome page in the launched application, if shown.

  5. Click on the hello world icon in the menu bar, or navigate to Sample Menu | Sample Command from the menu, and the dialog box created via the wizard will be shown:

  6. Quit the target Eclipse instance by closing the window, or via the usual keyboard shortcuts or menus (Cmd + Q on macOS or Alt + F4 on Windows).

What just happened?

Upon clicking on run in the toolbar (or via Run | Run As | Eclipse Application) a launch configuration is created, which includes any plug-ins open in the workspace. A second copy of Eclipse—with its own temporary workspace—will enable the plug-in to be tested and verify that it works as expected.

The run operation is intelligent, in that it launches an application based on what is selected in the workspace. If a plug-in is selected, it will offer the opportunity to run as an Eclipse Application; if a Java project with a class with a main method, it will run it as a standard Java Application; and if it has tests, then it will offer to run the test launcher instead.

However, the run operation can also be counter-intuitive; if clicked a second time, and in a different project context, then something other than the expected launched might be run.

A list of the available launch configurations can be seen by going to the Run menu, or by going to the dropdown to the right of the run icon. The Run | Run Configurations menu shows all the available types, including any previously run:

By default, the runtime workspace is kept between runs. The launch configuration for an Eclipse application has options that can be customized; in the preceding screenshot, the Workspace Data section in the Main tab shows where the runtime workspace is stored, and an option is shown that allows the workspace to be cleared (with or without confirmation) between runs.

Launch configurations can be deleted by clicking on the red delete icon on the top left, and new launch configurations can be created by clicking on the new icon. Each launch configuration has a type:

  • Eclipse Application

  • Java Applet

  • Java Application

  • JUnit

  • JUnit Plug-in Test

  • OSGi Framework

The launch configuration can be thought of as a pre-canned script that can launch different types of programs. Additional tabs are used to customize the launch, such as the environment variables, system properties, or command-line arguments. The type of the launch configuration specifies what parameters are required and how the launch is executed.

When a program is launched with the run icon, changes to the project's source code while it is running have no effect. However, as we'll see in the next section, if launched with the debug icon, changes can take effect.

If the target Eclipse is hanging or otherwise unresponsive, in the host Eclipse instance, the Console view (shown by navigating to Window | View | Show View | Other | General | Console menu) can be used to stop the target Eclipse instance.

Pop quiz: launching Eclipse

Q1. What are the two ways of terminating a launched Eclipse instance?

Q2. What are launch configurations?

Q3. How are launch configurations created and deleted?

Have a go hero – modifying the plug-in

Now that the Eclipse plug-in is running, try the following:

  • Change the message of the label and title of the dialog box to something else

  • Invoke the action by using the keyboard shortcut (defined in plugin.xml)

  • Change the tooltip of the action to a different message

  • Switch the action icon to a different graphic (if a different filename is used, remember to update it in plugin.xml and build.properties)

 

Debugging a plug-in


Since it's rare that everything works first time, it's often necessary to develop iteratively, adding progressively more functionality each time. Secondly, it's sometimes necessary to find out what's going on under the cover when trying to fix a bug, particularly if it's a hard-to-track-down exception such as NullPointerException.

Fortunately, Eclipse comes with excellent debugging support, which can be used to debug both standalone Java applications as well as Eclipse plug-ins.

 

Time for action – debugging a plug-in


Debugging an Eclipse plug-in is much the same as running an Eclipse plug-in, except that breakpoints can be used, the state of the program can be updated, and variables and minor changes to the code can be made. Rather than debugging plug-ins individually, the entire Eclipse launch configuration is started in debug mode. That way, all the plug-ins can be debugged at the same time.

Although run mode is slightly faster, the added flexibility of being able to make changes makes debug mode much more attractive to use as a default.

Start the target Eclipse instance by navigating to Debug | Debug As | Eclipse Application, or by clicking on debug in the toolbar.

  1. Click on the hello world icon in the target Eclipse to display the dialog, as before, and click on OK to dismiss it.

  2. In the host Eclipse, open the SampleHandler class and go to the first line of the execute method.

  3. Add a breakpoint by double-clicking in the vertical ruler (the grey/blue bar on the left of the editor), or by pressing Ctrl + Shift + B (or Cmd + Shift + B on macOS). A blue dot representing the breakpoint will appear in the ruler:

  4. Click on the hello world icon in the target Eclipse to display the dialog, and the debugger will pause the thread at the breakpoint in the host Eclipse:

    Note

    The debugger perspective will open whenever a breakpoint is triggered and the program will be paused. While it is paused, the target Eclipse is unresponsive. Any clicks on the target Eclipse application will be ignored, and it will show a busy cursor.

  5. In the top right, variables that are active in the line of code are shown. In this case, it's just the implicit variables (via this), any local variables (none yet), as well as the parameter (in this case, event).

  6. Click on Step Over or press F6, and window will be added to the list of available variables:

  7. When ready to continue, click on resume or press F8 to keep running.

What just happened?

The built-in Eclipse debugger was used to launch Eclipse in debug mode. By triggering an action that led to a breakpoint, the debugger was revealed, allowing the local variables to be inspected.

When in the debugger, there are several ways to step through the code:

  • Step Over: This allows stepping over line by line in the method

  • Step Into: This follows the method calls recursively as execution unfolds

    Note

    There is also a Run | Step into Selection menu item; it does not have a toolbar icon. It can be invoked with Ctrl + F5 (Alt + F5 on macOS) and is used to step into a specific expression.

  • Step Return: This jumps to the end of a method

  • Drop to Frame: This returns to a stack frame in the thread to re-run an operation

 

Time for action – updating code in the debugger


When an Eclipse instance is launched in run mode, changes made to the source code aren't reflected in the running instance. However, debug mode allows changes made to the source to be reflected in the running target Eclipse instance.

  1. Launch the target Eclipse in debug mode by clicking on the debug icon.

  2. Click on the hello world icon in the target Eclipse to display the dialog, as before, and click on OK to dismiss it. It may be necessary to remove or resume the breakpoint in the host Eclipse instance to allow execution to continue.

  3. In the host Eclipse, open the SampleHandler class and go to the execute method.

  4. Change the title of the dialog to Hello again, Eclipse world and save the file. Provided the Build Automatically option in Project menu is enabled, the change will be automatically recompiled.

  5. Click on the hello world icon in the target Eclipse instance again. The new message should be shown.

What just happened?

By default, Eclipse ships with the Build Automatically option in Project menu enabled. Whenever changes are made to Java files, they are recompiled along with their dependencies if necessary.

When a Java program is launched in run mode, it will load classes on demand and then keep using that definition until the JVM shuts down. Even if the classes are changed, the JVM won't notice that they have been updated, and so no differences will be seen in the running application.

However, when a Java program is launched in debug mode, whenever changes to classes are made, Eclipse will update the running JVM with the new code if possible. The limits to what can be replaced are controlled by the JVM through the Java Virtual Machine Tools Interface (JVMTI). Generally, updating an existing method and adding a new method or field will work, but changes to interfaces and superclasses may not be.

Note

The Hotspot JVM cannot replace classes if methods are added or interfaces are updated. Some JVMs have additional capabilities that can substitute more code on demand. Other JVMs, such as IBM's, can deal with a wider range of replacements.

Note that there are some types of changes that won't be picked up, for example, new extensions added to the plugin.xml file. In order to see these changes, it is possible to start and stop the plug-in through the command-line OSGi console, or restart Eclipse inside or outside of the host Eclipse to see the change.

Debugging with step filters

When debugging using Step Into, the code will frequently go into Java internals, such as the implementation of Java collections classes or other internal JVM classes. These don't usually add value, so fortunately Eclipse has a way of ignoring uninteresting classes.

 

Time for action – setting up step filtering


Step filters allow for uninteresting packages and classes to be ignored during step debugging.

  1. Run the target Eclipse instance in debug mode.

  2. Ensure that a breakpoint is set at the start of the execute method of the SampleHandler class.

  3. Click on the hello world icon, and the debugger should open at the first line, as before.

  4. Click on Step Into five or six times. At each point, the code will jump to the next method in the expression, first through various methods in HandlerUtil and then into ExecutionEvent.

  5. Click on resume to continue.
  6. Open Preferences and then navigate to Java | Debug | Step Filtering. Select the Use Step Filters option.

  7. Click on Add Package and enter org.eclipse.ui, followed by a click on OK:

  8. Click on the hello world icon again.

  9. Click on Step Into as before. This time, the debugger goes straight to the getApplicationContext method in the ExecutionEvent class.

  10. Click on resume to continue.
  11. To make debugging more efficient by skipping accessors, go back to the Step Filters preference and select Filter Simple Getters from the Step Filters preferences page.

  12. Click on the hello world icon again.

  13. Click on Step Into as before.

  14. Instead of going into the getApplicationContext method, the execution will drop through to the getVariable method of the ExpressionContext class instead.

What just happened?

Step Filters allows uninteresting packages to be skipped, at least from the point of debugging. Typically, JVM internal classes (such as those beginning with sun or sunw) are not helpful when debugging and can easily be ignored. This also avoids debugging through the ClassLoader as it loads classes on demand.

Typically it makes sense to enable all the default packages in the Step Filters dialog, as it's pretty rare to need to debug any of the JVM libraries (internal or public interfaces). This means that when stepping through code, if a common method such as toString is called, debugging won't step through the internal implementation.

It also makes sense to filter out simple setters and getters (those that just set a variable or those that just return a variable). If the method is more complex (like the getVariable method previously), then it will still stop in the debugger.

Constructors and static initializers can also be filtered specifically.

Using different breakpoint types

Although it's possible to place a breakpoint anywhere in a method, a special breakpoint type exists that can fire on method entry, exit, or both. Breakpoints can also be customized to only fire in certain situations or when certain conditions are met.

 

Time for action – breaking at method entry and exit


Method breakpoints allow the user to see when a method is entered or exited.

  1. Open the SampleHandler class, and go to the execute method.

  2. Double-click in the vertical ruler at the method signature, or select Toggle Method Breakpoint from the method in one of the Outline, Package Explorer or Members views.

  3. The breakpoint should be shown on the line:

    public Object execute(...) throws ExecutionException {
    
  4. Open the breakpoint properties by right-clicking on the breakpoint or via the Breakpoints view, which is shown in the Debug perspective. Set the breakpoint to trigger at method entry and method exit.

  5. Click on the hello world icon again.

  6. When the debugger stops at method entry, click on resume .
  7. When the debugger stops at method exit, click on resume .

What just happened?

The breakpoint triggers at the time the method enters and subsequently when the method's return is reached. Note that the exit is only triggered if the method returns normally; if an uncaught exception is raised, it is not treated as a normal method exit, and so the breakpoint won't fire.

Other than the breakpoint type, there's no significant difference between creating a breakpoint on method entry and creating one on the first statement of the method. Both give the ability to inspect the parameters and do further debugging before any statements in the method itself are called.

The method exit breakpoint will only trigger once the return statement is about to leave the method. Thus any expression in the method's return value will have been evaluated prior to the exit breakpoint firing. Compare and contrast this with the line breakpoint, which will wait to evaluate the argument of the return statement.

Note that Eclipse's Step Return has the same effect; this will run until the method's return statement is about to be executed. However, to find when a method returns, using a method exit breakpoint is far faster than stopping at a specific line and then doing Step Return.

Using conditional breakpoints

Breakpoints are useful since they can be invoked on every occasion when a line of code is triggered. However, they sometimes need to break for specific actions only—such as when a particular option is set, or when a value has been incorrectly initialized. Fortunately, this can be done with conditional breakpoints.

 

Time for action – setting a conditional breakpoint


Normally breakpoints fire on each invocation. It is possible to configure breakpoints such that they fire when certain conditions are met; these are known as conditional breakpoints.

  1. Go to the execute method of the SampleHandler class.

  2. Clear any existing breakpoints, by double-clicking on them or using Remove All Breakpoints from the Breakpoints view.

  3. Add a breakpoint to the first line of the execute method body.

  4. Right-click on the breakpoint, and select the Breakpoint Properties menu (it can also be shown by Ctrl + double-clicking—or Cmd + double-clicking on macOS—on the breakpoint icon itself):

  5. Set Hit Count to 3, and click on OK.

  6. Click on the hello world icon button three times. On the third click, the debugger will open up at that line of code.

  7. Open the breakpoint properties, deselect Hit Count, and select the Enabled and Conditional options. Put the following line into the conditional trigger field:

    ((org.eclipse.swt.widgets.Event)event.trigger).stateMask==65536
    
  8. Click on the hello world icon, and the breakpoint will not fire.

  9. Hold down Alt + click on the hello world icon, and the debugger will open (65536 is the value of SWT.MOD3, which is the Alt key).

What just happened?

When a breakpoint is created, it is enabled by default. A breakpoint can be temporarily disabled, which has the effect of removing it from the flow of execution. Disabled breakpoints can be easily re-enabled on a per breakpoint basis, or from the Breakpoints view. Quite often it's useful to have a set of breakpoints defined in the code base, but not necessarily have them all enabled at once.

It is also possible to temporarily disable all breakpoints using the Skip All Breakpoints setting, which can be changed from the corresponding item in the Run menu (when the Debug perspective is shown) or the corresponding icon in the Breakpoints view. When this is enabled, no breakpoints will be fired.

Conditional breakpoints must return a value. If the breakpoint is set to break whether or not the condition is true, it must be a Boolean expression. If the breakpoint is set to stop whenever the value changes, then it can be any Java expression. Multiple statements can be used provided that there is a return keyword with a value expression.

Using exceptional breakpoints

Sometimes when debugging a program, an exception occurs. Typically this isn't known about until it happens, when an exception message is printed or displayed to the user via some kind of dialog box.

 

Time for action – catching exceptions


Although it's easy to put a breakpoint in the catch block, this is merely the location where the failure was ultimately caught, not where it was caused. The place where it was caught can often be in a completely different plug-in from where it was raised, and depending on the amount of information encoded within the exception (particularly if it has been transliterated into a different exception type) may hide the original source of the problem. Fortunately, Eclipse can handle such cases with a Java Exception Breakpoint.

  1. Introduce a bug into the execute method of the SampleHandler class, by adding the following just before the MessageDialog.openInformation() call:

    window = null;
    
  2. Click on the hello world icon.

  3. Nothing will appear to happen in the target Eclipse, but in the Console view of the host Eclipse instance, the error message should be seen:

    Caused by: java.lang.NullPointerException
      at com.packtpub.e4.hello.ui.handlers.SampleHandler.execute
      at org.eclipse.ui.internal.handlers.HandlerProxy.execute
      at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute
    
  4. Create a Java Exception Breakpoint in the Breakpoints view of the Debug perspective. The Add Java Exception Breakpoint dialog will be shown:

  5. Enter NullPointerException in the search dialog, and click on OK.

  6. Click on the hello world icon, and the debugger will stop at the line where the exception is thrown, instead of where it is caught:

What just happened?

The Java Exception Breakpoint stops when an exception is thrown, not when it is caught. The dialog asks for a single exception class to catch, and by default, the wizard has been pre-filled with any class whose name includes *Exception*. However, any name (or filter) can be typed into the search box, including abbreviations such as FNFE for FileNotFoundException. Wildcard patterns can also be used, which allows searching for Nu*Ex or *Unknown*.

By default, the exception breakpoint corresponds to instances of that specific class. This is useful (and quick) for exceptions such as NullPointerException, but not so useful for ones with an extensive class hierarchy, such as IOException. In this case, there is a checkbox visible on the breakpoint properties and at the bottom of the breakpoints view, which allows the capture of all Subclasses of this exception, not just of the specific class.

There are also two other checkboxes that say whether the debugger should stop when the exception is Caught or Uncaught. Both of these are selected by default; if both are deselected, then the breakpoint effectively becomes disabled. Caught means that the exception is thrown in a corresponding try/catch block, and Uncaught means that the exception is thrown without a try/catch block (this bubbles up to the method's caller).

 

Time for action – inspecting and watching variables


Finally, it's worth seeing what the Variables view can do.

  1. Create a breakpoint at the start of the execute method.

  2. Click on the hello world icon again.

  3. Highlight the openInformation call and navigate to Run | Step Into Selection.

  4. Select the title variable in the the Variables view.

  5. Modify where it says Hello in the bottom half of the variables view and change it to Goodbye:

  6. Save the value with Ctrl + S (or Cmd + S on macOS).

  7. Click on resume, and the newly updated title can be seen in the dialog.

  8. Click on the hello world icon again.

  9. With the debugger stopped in the execute method, highlight the event in the Variables view.

  10. Right-click on the value and choose Inspect (by navigating to Ctrl + Shift + I or Cmd + Shift + I on macOS) and the value is opened in the Expressions view:

  11. Click on Add new expression at the bottom of the Expressions view.

  12. Add new java.util.Date() and the right-hand side will show the current time.

  13. Right-click on the new java.util.Date() and choose Re-evaluate Watch Expression. The right-hand-side pane shows the new value.

  14. Step through the code line by line, and notice that the watch expression is re-evaluated after each step.

  15. Disable the watch expression by right-clicking on it and choosing Disable.

  16. Step through the code line by line, and the watch expression will not be updated.

What just happened?

The Eclipse debugger has many powerful features, and the ability to inspect (and change) the state of the program is one of the more important ones.

Watch expressions, when combined with conditional breakpoints, can be used to find out when data becomes corrupted or used to show the state of a particular object's value.

Expressions can also be evaluated based on objects in the variables view, and code completion is available to select methods, with the result being shown with Display.

Pop quiz: debugging

Q1. How can an Eclipse plug-in be launched in debug mode?

Q2. How can certain packages be avoided when debugging?

Q3. What are the different types of breakpoints that can be set?

Q4. How can a loop that only exhibits a bug after 256 iterations be debugged?

Q5. How can a breakpoint be set on a method when its argument is null?

Q6. What does inspecting an object do?

Q7. How can the value of an expression be calculated?

Q8. How can multiple statements be executed in breakpoint conditions?

Have a go hero – working with breakpoints

Using a conditional breakpoint to stop at a certain method is fine if the data is simple, but sometimes there needs to be more than one expression. Although it is possible to use multiple statements in the breakpoint condition definition, the code is not very reusable. To implement additional reusable functionality, the breakpoint can be delegated to a breakpoint utility class.

  1. Create a Utility class in the com.packtpub.e4.hello.ui.handlers package with a static method breakpoint that returns a true value if the breakpoint should stop, and false otherwise:

    public class Utility {
      public static boolean breakpoint() {
        System.out.println("Breakpoint");
        return false;
      }
    }
  2. Create a conditional breakpoint in the execute method that calls Utility.breakpoint().

  3. Click on the hello world icon again, and the message will be printed to the host Eclipse's Console view. The breakpoint will not stop.

  4. Modify the breakpoint method to return true instead of false. Run the action again. The debugger will stop.

  5. Modify the breakpoint method to take the message as an argument, along with a Boolean value that is returned to say whether the breakpoint should stop.

  6. Set up a conditional breakpoint with the expression:

    Utility.breakpoint(
     ((org.eclipse.swt.widgets.Event)event.trigger).stateMask != 0,
     "Breakpoint")
  7. Modify the breakpoint method to take a variable Object array, and use that in conjunction with the message to use String.format() for the resulting message:

    Utility.breakpoint(
     ((org.eclipse.swt.widgets.Event)event.trigger).stateMask != 0,
     "Breakpoint %s %h",
     event,
     java.time.Instant.now())
 

Summary


In this chapter, we covered how to get started with Eclipse plug-in development. From downloading the right Eclipse package to getting started with a wizard-generated plug-in, you should now have the tools to follow through with the remainder of the chapters of this book.

Specifically, we learned these things:

  • The Eclipse SDK and the Eclipse IDE for Eclipse Committers have the necessary plug-in development environment to get you started

  • The plug-in creation wizard can be used to create a plug-in project, optionally using one of the example templates

  • Testing an Eclipse plug-in launches a second copy of Eclipse with the plug-in installed and available for use

  • Launching Eclipse in debug mode allows you to update code and stop execution at breakpoints defined via the editor

Now that we've learned how to get started with Eclipse plug-ins, we're ready to look at creating plug-ins that contribute to the IDE, starting with SWT and Views—which is the topic of the next chapter.

About the Author
  • Alex Blewitt

    contacted on 30 aug 16 _____________ Dr Alex Blewitt has over 20 years of experience in Objective-C and has been using Apple frameworks since NeXTstep 3.0. He upgraded his NeXTstation for a TiBook when Apple released Mac OS X in 2001 and has been developing on it ever since. Alex currently works for an investment bank in London, writes for the on-line technology news site InfoQ and has published two other books for Packt publishing. He also has a number of apps on the Apple AppStore through Bandlem Limited. When he's not working on technology, and if the weather is nice, he likes to go flying from the nearby Cranfield airport. Alex writes regularly at his blog, http://alblue.bandlem.com, as well tweeting regularly from Twitter as @alblue. Acknowledgements This book would not have been possible without the ongoing love and support of my wife Amy, who has helped me through both the highs and lows of life. She gave me the freedom to work during the many late nights and weekends that it takes to produce a book and its associated code repository. She truly is the Lem of my life. I'd also like to thank my parents, Ann and Derek, for their encouragement and support during my formative years. It was this work ethic that allowed me to start my technology career as a teenager and to incorporate my first company before I was 25. I'd also like to congratulate them on their 50th wedding anniversary in 2015, and I look forward to reaching that goal with Amy. Thanks are due especially to the reviewer of this version of the book: Antonio Bello, as well as the previous version of this book: Nate Cook, James Robert and Arvid Gerstmann, who provided excellent feedback on the contents of this book during development and caught many errors in both the text and code. Any remaining errors are my own. I'd also like to thank my children Sam and Holly for inspiring me and hope that they too can achieve anything that they set their minds to. Finally, I'd like to thank Ben Moseley and Eren Kotan, both of whom introduced me to NeXT in the first place and set my career going on a twenty year journey to this book.

    Browse publications by this author
Latest Reviews (5 reviews total)
Wie soll man ein Buch bewerten, das nach zwei Wochen immer noch nicht ausgeliefert wurde ?
Informativ aber leider viele Fehler und Sprünge im Code
Good, practical, easy to understand book.
Eclipse Plug-in Development Beginner's Guide - Second Edition
Unlock this book and the full library FREE for 7 days
Start now