Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

IDEs

  • submit to reddit

Eclipse Plug-in Development

By James Sugrue

14,185 Downloads · Refcard 70 of 151 (see them all)

Download
FREE PDF


The Essential Eclipse Plug-in Cheat Sheet

Eclipse consists of many plug-ins, which are bundles of code that provide some functionality to the entire system. Plug-ins contribute functionality to the system by implementing pre-defined extension points. You can provide extension points in your own plug-in to allow other plug-ins to extend your functionality. This DZone Refcard takes the user through the process of Eclipse-based plug-in development, from plug-in basics to the OSGi manifest, the plug-in manifest, hot tips, and more.
HTML Preview
Eclipse Plug-in Development

Eclipse Plug-in Development

By James Sugrue

About Eclipse Plug-ins

The Eclipse platform consists of many plug-ins, which are bundles of code that provide some functionality to the entire system. Plug-ins contribute functionality to the system by implementing pre-defined extension points. You can provide extension points in your own plug-in to allow other plug-ins to extend your functionality.

Hot Tip

Eclipse has a dedicated perspective for development of plug-ins, the PDE (Plug-in Development Environment). You can download Eclipse for RCP/ Plug-in Developers with all you need to get started from http://www.eclipse.org.

How plug-ins work

A plug-in describes itself to the system using an OSGi manifest (MANIFEST.MF) file and a plug-in manifest (plugin.xml) file. The Eclipse platform maintains a registry of installed plug-ins and the function they provide. As Equinox, the OSGi runtime, is at the core of Eclipse, you can think of a plug-in as an OSGi bundle. The main difference between plug-ins and bundles is that plug-ins use extension points for interaction between bundles.

Plug-ins take a lazy-loading approach, where they can be installed and available on the registry but will not be activated until the user requests some functionality residing in the plug-in.

the osgi manifest

MANIFEST.MF, usually located in the META-INF directory, deals with the runtime details for your plug-in. Editing of the manifest can be done through the editor provided, or directly in the MANIFEST.MF tab. The following is an example of one such manifest for a simple plug-in:


Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Myplugin
Bundle-SymbolicName: com.dzone.tests.myplugin
Bundle-Version: 1.0.0.qualifier
Bundle-Activator: com.dzone.tests.myplugin.Activator
Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6

The Eclipse OSGi Framework implements the complete OSGi R4.1 Framework specification and all of the Core Framework services. Here we list the most common manifest headers and directives.

Manifest Entry Use Example
Manifest-Version Manifest versioning information for your own records 1.0
Bundle-ManifestVersion A bundle manifest mayexpress the version of the syntax in which it is written by specifying a bundle manifest version. If using syntax from OSGi Release 4 or later, you must specify a bundle manifest version. The bundle manifest version defined by OSGi Release 4 is '2'. 2
Bundle-Name Human readable name for the plug-in. MyPlugin
Bundle-SymbolicName A unique name for this plug-in, usually in package naming convention. com.dzone.tests.myplugin
Bundle-Version The version of this plugin. This should follow the typical three number versioning format of < major version>. <minor version>. < revision> This can also be appended by an alphanumeric qualifier. 1.0.1.alpha
Bundle-Activator The activator, or plug-in class, that controls this plug-in. com.dzone.tests.myplugin.Activator
Bundle-Vendor Human readable string for the plug-in provider. DZone
Bundle-Classpath A comma-separated list of directories and jar files used to extend this bundle's functionality. lib/junit.jar,lib/xerces.jar
Require-Bundle A comma-separated list of symbolic names of other bundles required by this plug-in. rg.eclipse.ui,org.eclipse. core.runtime
Bundle-ActivationPolicy Manifest header identifying the bundle's activation policy. This replaces the deprecated Eclipse-LazyStart directive. Lazy
Bundle-Required ExecutionEnvironment Manifest header identifying the required execution environment for the bundle. The platform may run this bundle if any of the execution environments named in this header match one of the execution environments it implements. JavaSE-1.6
Export-package A list of the packages that this bundle provides for export to other plug-ins. com.dzone.tests.api

Plug-in Runtime

The Require-bundle manifest header has some extra functionality to help you manage your runtime dependencies. Bundles can be marked as optional dependencies by annotating the bundle with ;resolution:=optional.

You can also manage which version of the bundle your dependent on needs to be present using the ;bundleversion=' <values>' annotation. Here, the <values> that we refer to are a range of versions where you can specify minimum and maximum version ranges. The syntax of this range value is illustrated through these examples:

Example Meaning
3.5 Dependent only on version 3.5 of this bundle
[3.5, 3.5.1] Must be either version 3.5 or 3.5.1
[3.0, 4.0] Must be a version of 3.0 or over, but not 4.0

Additional Eclipse Bundle Headers

Eclipse provides a number of addition bundle headers and directives. These extra headers are not part of the OSGi R4.1 specification, but allow developers to use additional Eclipse OSGi Framework functionality.

Manifest Entry Use Example
Export-Package
Additional directives
are available to manage
the access restriction of
exported packages.
x-internal
The default value for this
property is false. When
internal packages are
specified as true using this
option, the Eclipse PDE
discourages their use.
x-friends
This option is similar to
x-internal, but allows
certain bundles to use the
exported packages that
have this option. Other
bundles are discouraged.
The x-internal option
takes precedence over
x-friends.
Export-Package:
org.eclipse.
foo.internal;
x-internal:=true
Export-Package:
org.eclipse.foo.
formyfriends;
x-friends:='org.
eclipse.foo.
friend1'
Eclipse-PlatformFilter
This allows you to set
particular rules for your
bundle before it can start.
osgi.nl for language
osgi.os for operating
system
osgi.arch for
architecture
osgi.ws for windowing
system
Eclipse- PlatformFilter: (& (osgi.ws=win32) (osgi.os=win32) (osgi.arch=x86))

All entries in the manifest can be internationalized by moving them to a separate plugin.properties file.

the plug-in manifest

With the Manifest.MF file looking after the runtime dependencies, plugin.xml deals with the plug-in extensions and extension points.

An extension allows you to extend the functionality of another plug-in in your system. An extension can be added through the plug-in editor's Extensions tab, or to your plugin.xml.


<extension point='org.eclipse.ui.preferencePages'>
   <page
     class='com.dzone.tests.myplugin.preferences.
       SamplePreferencePage'
           id='com.dzone.tests.myplugin.preferences.
       SamplePreferencePage'
     name='Sample Preferences'>
   </page>
</extension>

Each extension point has a XML schema which specifies the elements and attributes that make up the extension. As you can see in the listing above, each extension point has a unique identifier. The <page> element above is specified in the XML schema for the org.eclipse.ui.preferencesPages extension.

Hot Tip

Plug-ins and extension points are expected to have the same unique identifiers following the Java package naming pattern.

You can also define your own extension points, and we will detail that process in a later section.

Plug-in mode l

The plug-in class is a representation of your plug-in running in the Eclipse platform. A plug-in class in Eclipse must extend org. eclipse.core.runtime.Plugin, which is an abstract class that provides generic facilities for managing plug-ins. When using the project wizard in the PDE, this class typically gets assigned Activator as its default name. Whatever name you assign to this plug-in class, it must be the same as that mentioned in the Bundle-Activator directive of your MANIFEST.MF.

The class has start and stop methods that refer to the BundleContext and are provided by the BundleActivator interface. These methods allow you to deal with the plug-ins lifecycle, so that you can do both initialization and cleanup activities at the appropriate times. When overriding these methods be sure to always call the superclass Implementations.

Hot Tip

Plug-ins that contribute to the UI will have activators that extend AbstractUIPlugin, while non-UI plug-ins will extend Plugin.

Bundle Context

A BundleContext is associated with your plug-in when it is started. As well as providing information about the plug-in, the BundleContext can provide information about other plug-ins in the system. By providing a listener to BundleEvent, you can monitor the lifecycle of any other plug-in.

Bundle

The terms Bundle and Plug-in may be used interchangeably when discussing Eclipse. The Bundle class provides us with the OSGi unit of modularity. There are six states associated with bundles:

State Meaning
UINSTALLED The bundle is uninstalled and not available.
INSTALLED A bundle is in the INSTALLED state when it has been installed in the Framework but is not or cannot be resolved
RESOLVED Before a plug-in can be started, it must first be in the RESOLVED state.
A bundle is in the RESOLVED state when the Framework has successfully resolved the bundle's code dependencies.
STARTING A bundle is in the STARTING state when its start method is active.
If the bundle has a lazy activation policy, the bundle may remain in this state until the activation is triggered.
STOPPING A bundle is in the STOPPING state when its stop method is active.
When the BundleActivator.stop method completes the bundle is stopped and must move to the RESOLVED state.
ACTIVE A bundle is in the ACTIVE state when it has been successfully started and activated.

Lazy Loading

Plug-ins are normally set to load lazily, so that the code isn't loaded into memory until it is required. This is normally a good thing as you don't want to affect the startup time of Eclipse. If you do require your plug-in to start up and load when Eclipse launches, you can use the org.eclipse.ui.startup extension point.


<extension point='org.eclipse.ui.startup'>
   <startup class='com.myplugin.StartupClass'>
</extension>

The startup class listed above must implement the org.eclipse.ui.IStartup interface which provides an earlyStartup() method. The method is called in a separate thread after the workbench initializes.

Extension Points

The Eclipse platform provides a number of extension points that you can hook into, to provide additional functionality. The concept behind an extension point is that a class provides some extendable behavior, and publishes this behavior as an extension point. In order to run this code, the plug-in requires a host '" in this case your own plug-in.

In your plugin.xml you take this extension point and provide extra information to help it run. You will usually need to provide some class that implements a particular interface in order to do this.

Here we will run through some useful extension points in the Eclipse platform. Note, that to make some of these available for your plug-in, you will usually need to add dependencies.

Example Meaning
org.eclipse.core.runtime .preferences Allows plug-ins to use the Eclipse preferences mechanism, including the setting of default preference values.
org.eclipse.core.runtime .applications A plug-in that wishes to use the platform but control all aspects of its execution is an application.
org.eclipse.core.resources .builders Useful for IDE builders who wish to provide an incremental project builder, processing a set of resource changes.
org.eclipse.core.resources .markers Markers are used to tag resources with use information '" this marker can then be utilized in the problems view.
org.eclipse.ui.activities The activity extension point allows the filtering of plug-in contributions from users until they wish to use them.
org.eclipse.ui.editors Allows the addition of new editors to the workbench, which can be tied to particular file extension types.
org.eclipse.ui.intro When Eclipse is first started up the welcome page, or intro is displayed. This extension point allows contributions to the welcome page.
org.eclipse.ui.menus Allows custom menus to be added to the workbench either in the main menu, toolbar or popup menus through the locationURI attribute.
org.eclipse.ui.perspective Allows the addition of a perspective factory to the workbench, defining a particular layout of windows.
org.eclipse.ui.propertyPages Adds a property page for objects of a given type.
org.eclipse.ui.themes Allows the customization of the user interface, overriding the default colors and fonts.
org.eclipse.ui.views Provides the ability to add views to the workbench.

Creating your own extension points

As well as being a user of extension points, a plug-in can provide its own extensions for other plug-ins. Extension points allow loose coupling of functionality '" your plug-in exposes a set of interfaces and an extension point definition for others to use.

Extension Point Definition

You can create your extension point through the plugin.xml file, or through the Add button in the Extension Points tab of the plug-in editor.

For identifying your extension point you need to provide a unique identifier and a human readable name. At this point you can also point to a schema file and edit it afterwards. An extension point schema must have .exsd as its suffix.

Extension Point Wizard

Figure 1: The New Extension Point Wizard

Defining an Extension Point Schema

The PDE provides an editor for defining your .exsd file, consisting of three tabs. First, the Overview tab allows you to provide documentation and examples for your extension point. This is an essential step if you want your extension point to be adopted. Next, the Definition tab presents a graphical way to define your schema, while the Source tab allows editing of the .exsd XML definition.

Test_Extension

Figure 2: The Extension Point editor

When creating your extension point, you will first want to create one or more elements with attributes that will be used. Each extension point attribute has a number of associated properties:

Attribute Use
Name The name of the extension point attribute.
Deprecated Whether the attribute is deprecated or not.
Use Whether the attribute is optional, required or default. Default allows you to specify a value for the attribute if it hasn't been used.
Type The available types are Boolean, String, Java, Resource and Identifier. While Boolean and String are self '"explanatory, Resource should be used if the attribute is a file. Identifier provides a reference id for the extension point.
Extends If the type is Java this must be the name of the class that the attribute must extend.
Implements If the type is Java this must be the name of the class that the attribute must implement.
Translatable If the type is String this Boolean value indicates whether the attribute should be translated.
Restrictions If the type is String this can be used to limit the choice of value to a list of strings.
Description Attribute documentation.
References If the type is Identifier, this provides the id of the extension point that you want to reference. This will allow implementers of the extension point to easily find the id, without having to look through the plug-in registry.

Once you have created your elements and attributes for the extension point, the element can be added to a sequence for this extension. You can control the multiplicity of your extension here.

The mapping of XML to extension point declaration is simple; for users of your point, an xml element in the extension point will always appear on the left hand side tree, as part of the extension point declaration, while the xml attributes will appear as extension point attributes.

The Code Behind an Extension Point

With the extension point defined, the producer of this needs to provide some implementation that makes use of any extension point contributions.

To get a list of all the implementers of your extension point you can query the extension registry as follows, providing your extension point identifier as the parameter.


IConfigurationElement[] config = Platform.getExtensionRegistry()
   .getConfigurationElementsFor('myextid');


To use the implementing extension point, you can get the object from the IConfigurationElement.


final Object o = config[i].createExecutableExtension('class');

Useful Tools

The PDE plug-in editor provides a number of useful utilities for working with your plug-ins. The Dependencies tab in particular is essential for organizing your runtime.

The Dependencies Tab

From here you can investigate the plug-in dependency hierarchy, starting with your plug-in as the root. You can also see which plug-ins are dependent on your own plug-in, as well as find any unused dependencies. This can be useful if you previously added a dependency to use an extension point, but have found that it is since no longer required. Finally, and most importantly, the tab provides a utility for investigating for cyclic dependencies.

Another useful tool for plug-in development is the Plug-in Registry view. This can be accessed from the Window>Show View>Other..>Plug-in Development category. This view will display all the plug-ins that are currently available in your Eclipse installation.

The Dependencies Tab

Figure 4: Plug-in Registry

Hot Tip

When launching an application containing you plugin, use the -consoleLog program argument from the Run Configurations dialog to see output to the system console.

Logging

It is recommended to log to a file, rather than using System. out. The Activator or plug-in class provides a facility to access the plug-in logging mechanism through the getLog() method, returning the org.eclipse.core.runtime.ILog interface.

Each log entry using this framework is of type IStatus. Any CoreExceptions thrown in Eclipse have an associated IStatus object. An implementation of this interface, Status, is available for use. There is also a MultiStatus class which allows multiple statuses to be logged at once.

Distributing your PL ug-in

Since Eclipse 3.4, p2 has been used as the method to provision your application with new or updated plug-ins. For build managers who have used the Update Site mechanism before, there doesn't need to be any change.

To create an update site you can use the wizard provided to create a new site.xml file. Using the Software Updates menu, users can point to your update site on the web and download the plug-in.

By adding some extra functionality over this simple implementation, you can leverage p2 to add extra meta data to your update site, which will make the installation experience faster for end users.

p2 Update Site Publisher

The UpdateSite Publisher application is provided by p2 to generate an artifact.xml and content.xml files for your standard update site. You can run this application in headless mode using org.eclipse.equinox.p2.publisher.UpdateSitePublisher. The following shows an example of how to run this application, taken from the p2 wiki.


java -jar <targetProductFolder>/plugins/org.eclipse.equinox.
launcher_*.jar
 -application org.eclipse.equinox.p2.publisher.UpdateSitePublisher
 -metadataRepository file:/<some location>/repository
 -artifactRepository file:/<some location>/repository
 -source /< location with a site.xml>
 -configs gtk.linux.x86
 -compress
 -publishArtifacts

Read more about p2 at http://wiki.eclipse.org/Equinox/p2

Enha ncing your plug-in

When developing your plug-in, you should be aware of the wide variety of projects available in the Eclipse eco-system that help make your development easier and faster. This section gives an overview of just a few of the useful projects that exist, and explains how they can be used in your project.

Eclipse Modeling Project
http://eclipse.org/modeling/

The Eclipse Modelling Project provides a large set of tools for model driven development. The most popular part of this project is the Eclipse Modelling Framework (EMF). Using this technology, you can define a model in the ecore format, generate Java code to represent, serialise and de-serialise the model. Other tools within the modelling project utilise EMF to provide more specialised frameworks for developers.

The Connected Data Objects (CDO) project provides a threetier architecture for distributed and shared models.

The Graphical Modelling Framework (GMF) allows you to generate graphical editors for your model based on EMF and the Graphical Editing Framework (GEF). For developers who want to provide textual editor for their own language or DSL, XText provides a EBNF grammar language and generates a parser, meta-model and Eclipse text editor from this input.

Eclipse Communication Framework
http://eclipse.org/ecf

If your plugin requires any communication functionality, the ECF project is the first place to look. ECF consists of a number of bundles that expose various communication APIs. These APIs range from instant messaging, dynamic service discovery, file transfer to remote and distributed OSGi. Real-time shared editing functionality is also available in the framework, allowing you to collaborate remotely on anything that you are editing within your plug-in's environment.

Business Intelligence and Reporting Tools
http://eclipse.org/birt

BIRT is an open source reporting system based on Eclipse. BIRT provides both programmatic access to report creation, as well as functionality to create your own report template within the Eclipse IDE. While BIRT allows you to generate reports in file formats such as PDF, it is also possible to use BIRT on an application server to serve reports through a web browser.

Equinox
http://eclipse.org/equinox

As we have described in this card, Equinox is the Eclipse implementation of the OSGi R4 core framework specification, and provides the real runtime for all your plug-ins. However, as well as running your plug-ins on the desktop on an instance of Eclipse, you can take Equinox and run it on a server, allowing your plug-in to run on browsers as well as the desktop.

Rich Ajax Platform
http://eclipse.org/rap

With the emergence of the web as a real platform for rich applications, the Rich Ajax Platform allows you to take a standard RCP project, and with some minor modifications, make it deployable to the web. This idea of single-sourcing is key to the RAP project, and reduces the burden for developers to make an application ready for either the desktop or the web.

The same programming model is used, while qooxdoo is used for the client side presentation of your SWT and JFace widgets.

About The Author

Photo of author James Sugrue

James Sugrue

James Sugrue is a software architect at Pilz Ireland, a company using many Eclipse technologies. James is also editor at both EclipseZone and Javalobby. Currently he is working on TweetHub, a Twitter client based on RCP and ECF. James has also written previous Refcardz covering EMF and Eclipse RCP.

Zone Leader: EclipseZone, Javalobby

Twitter: @dzonejames

Recommended Books

eclipse

This book presents detailed, practical coverage of every aspect of plug-in development--with specific solutions for the challenges you’re most likely to encounter.


Eclipse Platform

In Eclipse Rich Client Platform, two leaders of the Eclipse RCP project show exactly how to leverage Eclipse for rapid, efficient,cross-platform desktop development.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Getting Started with Eclipse RCP

By James Sugrue

15,448 Downloads · Refcard 62 of 151 (see them all)

Download
FREE PDF


The Essential Eclipse RCP Cheat Sheet

The Eclipse Rich Client Platform (RCP) provides a foundation for building and deploying rich client applications. It includes Equinox, a component framework based on the OSGi standard, and an integrated update mechanism for deploying desktop applications from a central server. This DZone Refcard introduces you to the Eclipse plug-in development environment and shows you how to add key functionality to your RCP application using Views, Perspectives and Editors. Learn how to add a Menu to your Plug-in, create a Help system for your user, and how to brand and productize your Eclipse RCP application.
HTML Preview
Getting Started with Eclipse RCP

Getting Started with Eclipse RCP

By James Sugrue

About the Rich client platform

The Eclipse Rich Client Platform (RCP) is a platform for building and deploying rich client applications. It includes Equinox, a component framework based on the OSGi standard, the ability to deploy native GUI applications to a variety of desktop operating systems, and an integrated update mechanism for deploying desktop applications from a central server. Using the RCP you can integrate with the Eclipse environment, or can deploy your own standalone rich application.

Introducing the Plug-in development environment

To get started in developing your own plug-ins, first download a version of Eclipse including the Plug-in Development Environment (PDE). Eclipse Classic is the best distribution for this.

When developing plug-ins, you should use the Plug-in Development perspective. You'll notice this perspective provides another tab in your Project Navigator listing all the plug-ins available.

To create an RCP application, go to the File menu and select New > Project where you will be presented with the new project wizard. From here choose Plug-in Project.

New project wizard

Figure 1: The New Project Wizard

The next screen allows you to assign a name to your plugin. Usually, plug-in name follow Java's package naming conventions. RCP applications should be targeted to run on a particular version of Eclipse, here we choose to run on Eclipse 3.5.

RCP Project Settings Page

Figure 2: RCP Project Settings Page

The next page in the project wizard allows you to set some important attributes of your plug-in. This page allows you to specify whether your plug-in will make contributions to the UI. In the case of RCP plug-ins, this will usually be true. You can choose whether to create your own RCP application, or to create a plug-in that can be integrated with existing Eclipse installations.

The following table summarizes other plug-in settings and what they mean for your application. All of these settings can be changed in the generated MANIFEST.MF file for your project at any stage.

Attribute Name Default Value Meaning
id <project name> The identifier for this RCP plug-in
Version 1.0.0.qualifier The plug-in version. Multiple versions of any plug-in are possible in your Eclipse environment provided they have unique version numbers
Name RCP Application The readable name of this plug-in
Provider The second part of your project package name. The provider of this plug-in

Hot Tip

Get started quickly with your first RCP application by using the included RCP Mail Template, available when you choose to create a standalone RCP application.

Manifest.mf explained

The generated META-INF/MANIFEST.MF file is the centre of your RCP plug-in. Here you can define the attributes, dependencies and extension points related to your project. In addition, you may have a plugin.xml file. The contents of both these files are show in the plug-in manifest editor.

Plug-In manifest editor

Figure 3: The plug-in manifest editor

The Overview tab in this editor allows you to change the settings described earlier in the new project wizard. It also provides a shortcut where you can launch an Eclipse application containing your new RCP plug-in.

The Dependencies tab describes how this plug-in interacts with others in the system. All plug-ins which you are dependent on will need to be added here.

The Runtime tab allows you to contribute packages from your own plug-in to others to use or extend. You can also add libraries that don't exist as plug-ins to your own project in the Classpath section.

Hot Tip

While you may change your build path through the Dependencies or Runtime tab, changing dependent plug-ins in the Java Build Path of the project properties tab will not reflect properly in the plug-ins manifest.

The Extensions tab is where you go to define how this plug-in builds on the functionality of other plug-ins in the system, such as for adding menus, views or actions. We will describe these extension points in more detail in the relevant sections. The Extension Points tab allows you to define your own extensions for other plug-ins to use.

The Standar d Widget Toolkit and Jface

While developing UI code for your RCP application, it is important to understand the Standard Widget Toolkit (SWT). This is a layer that wraps around the platform's native controls. JFace provides viewers, in a similar way to Swing, for displaying your data in list, tables, tree and text viewers.

The UI toolkits used in Eclipse applications are a large topic, so we assume that the reader will be aware of how to program widgets in SWT and JFace.

Adding a menu to your plug-in

One of the first things that you will want to do with your RCP plug-in is to provide a menu, establishing its existence with the Eclipse application that it is built into. To do this, as with any additions to our plug-in, we start in the Extensions tab of the plug-in manifest editor.

Up to Eclipse 3.3 Actions was the only API available to deal with menus, but since then the commands API has become available, which we will focus on here.

To add a menu in the command API you will need to follow similar steps to these:

Declare a command

To do this we use the org.eclipse.ui.commands extension point. Simply click on the Add... button in the Extensions tab and chose the relevant extension point.

First, you will need to associate this command with a category. Categories are useful for managing large numbers of commands. From the org.eclipse.ui.commands node, select New > Category. The required fields are a unique ID and a readable name.

After this right click on the node and choose New>Command. The important attributes for a command are listed below.

Attribute Name Required Use
id Yes A unique id for this command
Name Yes A readable name for the command
Description No A short description for display in the UI
CategoryID No The id of the category for this command (that you described in the previous step).
DefaultHandler No A default handler for this command. Usually you will create your own handler.

Declare a Menu Contribution for the Command

To create a menu, you will first need to add the org.eclipse. ui.menus extension point. From the created node in the UI, select New>menuContribution. The required attribute for the menu contribution is it's locationURI, which specifies where the menu should be placed in the UI. This URI takes the format of [scheme]:[id]?[argument-list]

An example of the more useful locationURI's in the Eclipse platform follow:

Attribute Name Required
menu:org.eclipse.ui.main.
menu?after=window
Insert this contribution on the main menu bar after the Window menu
menu:file?after=additions Inserts contribution in the File menu after the additions group
toolbar:org.eclipse.ui.main.
toolbar?after=additions
Insert this contribution on the main toolbar
popup:org.eclipse.ui.popup.
any?after=additions
Adds this contribution to any popup menu in the application

Once the location of your contribution is chosen, click on New>command on this contribution to define the menu. The following attributes exist for each command:

Attribute Required Use
commandId Yes The id of the Command object to bind to this element, typically already defined, as in our earlier step. Click Browse... to find this
Label No The readable label to be displayed for this menu item in the user interface
id No A unique identifier fo this item. Further menu contributions can be placed under this menu item using this id in the locationURI
mnemonic No The Character within the label to be assigned as the mnemonic
icon No Relative path to the icon that will be displayed to the left of the label
tooltip No The tooltip to display for this menu item

Hot Tip

Defining a toolbar item is a similar process. Based on a menuContribution with the correct locationURI, select New>Toolbar providing a unique id. Create a new command under the toolbar similar to the menu item approach.

Create a Handler for the Command

The final extension point required for the menu is org.eclipse. ui.handlers. A handler has two vital attributes. The first is the commandId which should be the same as the command id specified in the beginning. As you can see, this is the glue between all three parts of the menu definition.

You will also need to create a concrete class for this handler, which should implement the org.eclipse.core.commands. IHandler interface.

Hot Tip

Clicking on the class hyperlink on the manifest editor will pop up a New Class Wizard with the fields autofilled for this.

Finally, you will need to define when this command is enabled or active. This can be done programmatically in the isEnabled() and isHandled() methods. While this is easiest, the recommended approach is to use the activeWhen and enabledWhen expressions in the plug-ins manifest editor which avoids unnecessary plug-in loading.

Hot Tip

Once you have added in an extension point plugin. xml will become available. All extension points can be added through the manifest editor, or in XML format through this file.

Views

In an RCP applications Views are used to present information to the user. A viewer must implement the org.eclipse. ui.IViewPart interface, or subclass org.eclipse.ui.parts.ViewPart.

Difference between perspective, editor and view

Figure 4: An illustration of the difference between perspective, editor and view.

To create a View, you will need to add the org.eclipse. ui.views extension point. In order to group your views, it is useful to create a category for them. Select New>Category from the org.eclipse.ui.views node to do this. The required fields are a unique ID and a readable name.

Next, choose New>View from the extension point node and fill in the necessary details.

Attribute Required Use
id Yes The unique id of the View
name Yes A readable name for this view
class Yes The class that implements the IViewPart interface
category No The id of the category that contains this view. This category should be used if you wish to group views together in the Show Views... dialog.
icon No The image to be displayed in the top left hand corner of the view
allowMultiple No Flag indicating whether multiple views can be instantiated. The default value is false.

The code behind the view is in a class that extends org.eclipse.ui.ViewPart. All controls are created programmatically In the createPartControl() method in this class.

To facilitate lazy loading, a workbench page only holds IViewReference objects, so that you can list out the views without loading the plug-in that contains the view definition.

When created, you will see your view in the Window>Show View>Other... dialog

Hot Tip

It's good practice to store the view's id as a public constant in your ViewPart implementation, for easy access.

Loose Coupling

To facilitate loose coupling, your ViewPart should implement org.eclipse.ui.ISelectionListener. You will also need to register this as a selection listener for the entire workbench:


getSite().getWorkbenchWindow().getSelectionService().
addSelectionListener(this);

This allows your view to react to selections made outside of the view's own context.

Editors

An editor is used in an Eclipse RCP application when you want to create or modify files, or other resources. Eclipse already provides some basic text and Java source file editors.

In your plug-in manifest editor, add in the org.eclipse. ui.editors extension point, and fill in the following details

Attribute Required Use
id Yes The unique id of this editor
name Yes A readable name for this editor
icon No The image to be displayed in the top left hand corner of the editor when it is open
extensions No A string of comma separated file extensions that are understood by the editor
class No The class that implements the IEditorPart interface
command No A command to run to launch and external editor
launcher No The name of a class that implements IEditorLauncher to an external editor
contributorClass No A class that implements IEditorActionBarContributor and adds new actions to the workbench menu and toolbar which reflect the features of the editor type
default No If true this editor will be used as the default for this file type. The default value is false
filenames No A list of filenames understood by the editor. More specific than the extensions attribute
matchingStrategy No An implementation of IEditorMatchingStrategy that allows an editor to determine whether a given editor input should be opened

Editors implement the org.eclipse.ui.IEditorPart interface, or subclass org.eclipse.ui.parts.EditorPart.

Like views, to facilitate lazy loading, a workbench page only holds IEditorReference objects, so that you can list out the editors without loading the plug-in that contains the editor definition.

Perspectives

Perspectives are a way of grouping you views and editors together in a way that makes sense to a particular context, such as debugging. By creating your own perspective, you can hook into the Window>Open Perspective dialog.

To create a perspective, you need to extend the org.eclipse.ui.perspectives extension point.

Attribute Required Use
id Yes The unique id of this perspective
name Yes A readable name for the perspective
class Yes The class that implements the IPerspectiveFactory interface
icon No The image to be displayed related to this perspective
Fixed No Whether this perspective can be closed or not. Default is false

The class driving the perspective implements org.eclipse. ui.IPerspectiveFactory. This class has one method createInitialLayout(), within which you can use the IPageLayout.addView() method to add views directly to the perspective. To group many views together in a tabbed fashion, rather than side by side, IPageLayout.createFolder() can be used.

Hot Tip

When running your application you need to ensure that you have all required plug-ins included. Do this by checking your Run Configurations. Go to the plugins tab and click Validate Plug-ins. If there are errors click on Add Required Plug-ins to fix the error.

Preferences

Now that you have created a perspective and a view for your RCP application, you will probably want to provide some preference pages. Your contributed preference pages will appear in the Window>Preferences dialog.

To provide preference pages you will need to implement the org.eclipse.ui.preferencePages extension in the plug-in manifest editor.

Attribute Required Use
id Yes The unique id of this preference page
name Yes A readable name for the preference page
class Yes The class that implements the IWorkbenchPreferencePage interface
category No Path indicating the location of the page in the preferences tree. The path may be defined using the parent preference page id or a sequence of ids separated by "/". If no category is specified, the page will appear at the top level of the preferences tree.

While the preference page class will implement org.eclipse. ui.IWorkbenchPreferencePage, it is useful to extend org. eclipse.jface.preference.FieldEditorPreferencePage as it provides createFieldEditors() method which is all you need to implement, along with the init() method in order to display a standard preference page. A complete list of FieldEditors is provided in the org.eclipse.jface.preference package.

Loading and Storing Preferences

Preferences for a plug-in are stored in an org.eclipse.jface. preference.IPreferenceStore object. You can access a plug-ins preference through the Activator, which will typically extend org.eclipse.ui.plugin.AbstractUIPlugin. Each preference you add to the store has to be assigned a key. Preferences are stored as String based values, but methods are provided to access the values in number of formats such as double, int and Boolean.

Property Sheets

While preferences are used to display the overall preferences for the plug-in, property sheets are used to display the properties for views, editors or other resources in the Eclipse environments. By hooking into the Properties API, the properties for you object will appear in the Properties view (usually displayed at the bottom of your Eclipse application).

The Properties view will check if the selected object in the workspace can supports the org.eclipse.ui.views. properties.IPropertySource interface, either through implementation or via the getAdapter() method of the object. Each property gets a descriptor and a value through the IPropertySource interface.

Help

All good applications should provide some level of user assistance. To add help content to the standard Help>Help Contents window, you can use the org.eclipse.help.toc extension point. Add a number of toc items to this extension point, the only mandatory attribute for each toc entry is the file that contains the table of contents definition.

Hot Tip

To see a quick example of what help content should look like, choose the Help Content item from the Extension Wizards tab when adding to the plug-ins manifest.


<toc label="Getting Started" link_to="toc.xml#gettingstarted">
<topic label="Main Topic" href="html/gettingstarted/
maintopic.html">
<topic label="Sub Topic" href="html/gettingstarted/
subtopic.html" />
</topic>
<<topic label="Main Topic 2">
<topic label="Sub Topic 2" href="html/gettingstarted/
subtopic2.html" />
</topic>
</toc>

Each topic entry should have a link to a HTML file with the full content for that topic. The above XML extract from a table of contents file illustrates this. There is also the choice to use the definition editor for help content. This will open by default in Eclipse when choosing a toc file.

Cheat Sheets

Another user assistance mechanism used in Eclipse is a cheat sheet, which guides the user through a series of steps to achieve a task. To create your initial cheat sheet content, use the New>Other...>User Assistance>Cheat Sheet. This presents you with an editor to add an Intro and a series of items, with the option to hook in commands to automate the execution of the task.

To add this cheat sheet to your plug-in manifest, the cheat sheet editor has a Register this cheat sheet link on the top right hand corner. When registering the cheat sheet you will need to provide it with a category and a description.

Cheat sheet registration dialog

Figure 5: Cheat sheet registration dialog

Clicking finish on this dialog will add the org.eclipse. ui.cheatsheets.cheatSheetContent extension point to your manifest. You can modify the details of the cheat sheet from here if necessary.

Features

You can help the user to load up your plug-in(s) as a single part, by combining them into one feature. Eclipse provides a wizard to create your feature through the New Project> Plug-in Development >Feature Project wizard.

This wizard generated a feature.xml file which has an editor, similar to the plug-in manifest editor, where you can change the details of your feature.

The most important section is the Plug-ins tab, which lists the plug-ins required for your feature. The Included Features tab allows you to specify sub-features to include as part of your feature. On the Dependencies tab, you can get all the plugins or features that you are dependent on by clicking on the Compute button.

A simple feature.xml may look as follows:


<?xml version="1.0" encoding="UTF-8"?>
<feature
id="my.feature"
label="Feature"
version="1.0.0.qualifier"
provider-name="James">
<description url="http://www.example.com/description">
[Enter Feature Description here.]
</description>
<copyright url="http://www.example.com/copyright">
[Enter Copyright Description here.]
</copyright>
<license url="http://www.example.com/license">
[Enter License Description here.]
</license>
<requires>
<import plugin="org.eclipse.ui"/>
<import plugin="org.eclipse.core.runtime"/>
</requires>
<plugin
id="com.dzone.refcard.rcpapp"
download-size="0"
install-size="0"
version="0.0.0"
unpack="false"/>
</feature>

Branding

The feature also provides a single location where you can define all the branding for your application. In the Overview tab, you can assign a Branding Plug-in to the feature.

The branding plug-in needs to contain the following artefacts:

Item Purpose
about.html A HTML file that will be displayed in the Plug-in Details>More Info dialog
about.ini This file contains most of the branding information for the feature described below
about.properties Used for localisation of the strings from the about.ini file. The values are referenced using the %key notation

about.ini

Property Purpose
aboutText Multiline description containing name, version number and copyright information. Will appear in the About>Feature Details>About Features dialog.
featureImage A 32x32 pixel icon representation of the feature to be used across the relevant About dialogs

All of the icons and files referenced by the about.ini file should be placed in this plug-in also.

Product Branding

A product is an entire distribution of an RCP application, rather than a feature intended to be part of an existing distribution. As such, products have additional branding requirements. To specify these extra parameters, a contribution to the org. eclipse.core.runtime.products extension point is required.

The product must be assigned the application to run, the name of the product (for the title bar) and a description. Further properties are added as name/value pairs underneath the product.

Hot Tip

An application can be provided by using the org. eclipse.core.runtime.applications extension point

Property Purpose
windowImages The image used for this application, in windows and dialogs. This should be in the order of the 16x16 pixel image, followed by the 32x32
aboutImage Larger image to be placed in the About dialog
aboutText Multiline description containing name, version number and copyright information. Will appear in the About>Feature Details>About Features dialog.

You can also provide most of these details in the Branding tab of the generated .product file.

Splash Screen

The .product file that is generated while creating your product includes a Splash tab. Here you can specify the plug-in that contains the splash.bmp file for your Splash screen. Typically, this should reside in your branding plug-in. The splash screen can also be customized with templates, and can include a progress bar with messages.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

IntelliJ IDEA

Updated for 8.1

By Hamlet DArcy

7,701 Downloads · Refcard 52 of 151 (see them all)

Download
FREE PDF


The Essential IntelliJ IDEA Cheat Sheet

IntelliJ IDEA Looking to update your IntelliJ IDEA IDE? In this DZone Refcard, updated for IntelliJ IDEA 8.1, author Hamlet D’Arcy helps you navigate the various facets of this world-class IDE, including the Editor, Project, and Structure panes. With a rich collection of editing shortcuts, debugging tips and techniques for writing less code, IntelliJ newbies and IDEA-savvy developers will both benefit with this cheat sheet by their side. Still using IntelliJ IDEA 6.0? Relax, our original IntelliJ IDEA Refcard is exactly what you need.
HTML Preview
IntelliJ IDEA

IntelliJ IDEA

By Hamlet D'Arcy

ABOUT INTELLIJ IDEA

Software developers know the importance of using the best tool for the job. Often this means choosing a world-class integrated development environment (IDE), which JetBrains’ IntelliJ IDEA certainly is. But the best developers don’t just have the right tools, they are experts in those tools. This is a guide to becoming that expert. The basics of navigating and understanding the IDE are covered; but this guide is really about unlocking all the powerful features of the tool and helping you be more productive.

Getting Yourself Oriented

Editor

The three most important elements of the IDE are the Editor pane (a), where your code is shown, the Project pane (b), where your project’s contents are shown, and the Structure pane (c), where the details of the open object are shown.

Editor Pane: Shows the currently active file, with recently viewed files in the tab bar. IntelliJ IDEA shows the most recently used files in the tabs, and there is seldom a need to manually close tabs. If the maximum number of tabs is reached, then the oldest tab is closed when a new tab is opened. Also, there is seldom a need to save a file; file saving is performed automatically in the background. The IDE supports syntax highlighting for many languages, but is also language aware and shows syntax errors as they occur.

Navigate faster by learning these commands:

Back Ctrl+Alt+Left Move back to the last cursor position
Forward Ctrl+Alt+Right Move forward to the next cursor position
Next Tab Alt+Right Activate tab to the right of the active one
Previous Tab Alt+Left Activate tab to the left of the active one
Goto Line Ctrl+G Go to a specific line in the active file
Goto Last Edit
Location
Ctrl+Shift+Backspace Go to the position of the last edit

Hot Tip

Toolbar icons are shown throughout this guide, but you’ll be much faster if you learn the key bindings. The mouse is slow: stop using it! IntelliJ IDEA key bindings have received praise over the years, and many believe they are simply better than other IDE’s default bindings. If you’re switching from another tool, consider learning the new bindings rather than loading an alternate key map. The KeyPromoter plugin can help you with this.

Edit faster by learning these commands:

Move Statement Up Ctrl+Shift+Up Moves the current code block up in the file
Move Statement Down Ctrl+Shift+
Down
Moves the current code block down in the file
Copy/Paste Line Ctrl+C /
Ctrl+V
When nothing is selected, copy, cut, and paste operate on the entire line
Clipboard Stacking Ctrl+Shift+V When copying text, the IDE remembers your previous copies. Use Ctrl+Shift+V to show the clipboard history dialog and paste from a previous copy instead of the most recent clipboard contents
Select/Unselect Word at Caret Ctrl+W /
Ctrl+Shift+W
Selects and unselects the word at the caret. Quickly select or unselect the word, statement, block, and method by repeating this action. Experiment to learn how this works differently depending on where your cursor starts
Toggle Bookmark F11 Sets or removes a bookmark on the current line, which shows as black in both the left and right gutter
Comment/
Uncomment
Ctrl+/ Comments out current selection, or removes comments from current selection. This is supported across many languages
Column Mode Ctrl+Shift+
Insert
Column mode allows you to select a rectangular fragment of code. Effectively using this can greatly speed up bulk edits on structured data like SQL or csv files

Getting Yourself Oriented, continued

Project Pane: Shows the contents of the current project, allowing you to view the project as files, packages, or scopes (more about this later). Objects in the project view visually indicate their type with an icon (which also appears on the editor tabs).

Find objects faster by learning what the icons mean:

code Class code Class with main( )
(indicated by green triangle)
interface Interface interface public
Protector Abstract Class Protector protected
Enumeration Enumeration package package
Exception Exception private private
Annotation Annotation ReadOnly Read Only (indicated by lock)
TestCase Test Case (indicated by red and
green triangles)
Not in version control (object
name appears in red)
FinalClass Final Class (Indicated by pin) In version control (object name
appears black, or blue if edited)

Properly configuring the Project pane makes it more effective:

Autoscroll Autoscroll to Source When an object or method is clicked in the Project pane, that item is opened in the Editor pane.
AutoscrollFrom Autoscroll from Source When an item is opened in the Editor pane, that item is scrolled to in the Project pane
StructurePane Show structure Shows the Structure pane (explained next) as a window nested within the Project pane
FinalClass Show/Hide Members Shows the methods and properties of objects within the Project pane
FinalClass Sort by type Sorts the Java classes by type from the most abstract to the most concrete

Structure Pane: Shows the structure of the active file, including methods, properties, and inner classes. Leaving this pane open helps you quickly locate the desired point within a class. Make this pane more useful by tweaking the configuration options:

Autoscroll Autoscroll to source Properties Show properties
AutoscrollFrom Autoscroll from source inherited Show inherited
visibility Sort by visibility ShowFields Show fields
SortAlphabetically Sort alphabetically non-public Show non-public
GroupMethods Group Methods by defining type

Hot Tip

IntelliJ IDEA provides almost endless amounts of configuration through the Settings (Ctrl+Alt+S) window. Use the search box to quickly find what you need. Just start typing what the option might be called and the window will highlight to show which buttons lead to a panel containing that keyword. Wildcards work too!

Finding What You Need

IntelliJ IDEA sets itself apart by offering incredibly advanced ways to find objects and files within large projects. Mastering the act of finding what you need is key to faster development.

Goto Class Ctrl+N Provides dialog for finding classes. Accepts wildcards, camel case, and package prefixes. For example, “BOS” matches BufferedOutputStream, “Str*Buff” matches StringBuffer, and “java.lang.I” matches all objects starting with “I” in the java.lang package. Use Up/Down error to select the class, and Shift+Up/ Down or Ctrl+Click to perform multiple selections.
Goto File Ctrl+Shift+N Provides a similar dialog for finding files that are not classes. For example, “*spring*xml” matches any xml files with the word “spring” in the name, and “*Test.groovy” matches any test case implemented in Groovy.

The navigation bar is a useful alternative to the Project pane. This horizontal bar provides breadcrumb style navigation based on the active file. To navigate to a different package, simply click the + to expand a node higher up in the tree. The navigation bar can be a faster alternative to the Project pane.

navigationbar

You can also use Alt+Home to quickly open the navigation bar from the current editor pane.

Navigating a single class is done through the Structure pane (described earlier) and the file structure popup.

File Structure Popup: (Ctrl+F12) allows quick navigation to methods, fields, and properties. Use the Up/Down arrows to select an entry, or (better) use the search as you type field. Just start typing to narrow the list down. The field provides wildcard and camel case matching. Selecting an entry scrolls the active file to that entry’s declaration.

Navigating large object oriented codebases is greatly simplified by learning these commands:

Ctrl+B /
Middle Click
Go to declaration. Navigates to the declaration of the selected instance or type.
Ctrl+Alt+B Go to implementers or overriders of the selected method. Clicking the icon in the left gutter performs the same action
Ctrl+U Go to the parent of the selected method or type. Clicking the icon in the left gutter performs the same action
Ctrl+Mouse
Over
Shows the declaration of a local variable or field in a popup window
Ctrl+H Opens the Type Hierarchy pane for the active class. This pane explores the super and subclasses of the current object with a variety of different views
Ctrl+Shift+H Opens the Method Hierarchy pane for the active method. This pane explores the definitions and implementations of the current method.
F4 Jump to Source. Many tool windows display objects within project. Used from a tool window, F4 universally opens the element from the tool in the editor. If you’re in the Ant, Hierarchy, or Find window, then F4 will open the selection in the editor pane.

Finding usages is an important feature of any IDE. Being Java aware, IntelliJ IDEA offers more intelligent searching than simple string matching.

Highlight Usages in File (Ctrl+Shift+F7) takes the current mouse selection and highlights all occurrences of that element in the file. The Editor pane and the right gutter provide visual keys to where the occurrences appear. Use F3 and Shift+F3 to jump to the next and previous occurrence.

Finding What You Need, continued

Show Usages Popup (Ctrl+Alt+F7) takes the current mouse selection and searches the project for any references made to the field or type. Results appear in an in-editor popup window.

Show Usages in Find Panel (Alt+F7) behaves the same as the Show Usages Popup, except that results are displayed in the Find pane. Learning to operate the Find pane with the keyboard helps you move faster to the intended object.

Rerun Rerun the last find
Shift+Esc Rerun Close the Find pane
Ctrl+NumPad + Expand Expand all the nodes in the list
Ctrl+NumPad - Collapse Collapse all the nodes in the list
Ctrl+Alt+Up Rerun Navigate to the previous occurrence
Ctrl+Alt+Down Rerun Navigate to the next occurrence
Ctrl+E Recent Find Usages dialog. Quickly jump to a past search result.

Hot Tip

Turn on Scroll to Source in the Find pane and use Ctrl+Alt+Up and Ctrl+Alt+Down to quickly cycle through the usages in the main editor window.

Search Structurally (Ctrl+Shift+S) and Replace Structurally (Ctrl+Shift+M) allows searching (and replacing) references using patterns. Again, this is Java aware and done structurally, and is not just text string search and replace. This very rich feature is best explained with an example. Here are the steps to find any factory methods within the project (ie, methods whose name starts with “create”):

  • Open Search Structurally (Ctrl+Shift+S)
  • Click “Copy the existing template” and select method calls, which is $Instance$.$MethodCall$($Parameter$)
  • Click “Edit variables” and select MethodCall
  • For the MethodCall variable, enter “create.*” in the Text / Regular Expression. This is the regular expression for the word create followed by any number of other characters
  • Click “Find” to open the Find pane showing all the factory methods

Scopes

Often, you only want to search a subset of your project, for instance just the test or production source. IntelliJ IDEA provides Scopes to create smaller filesets used in searching, replacing, and inspections. Some default scopes are “Project Production Files”, “Project Test Files”, and “Changed Files”. Fine tune your searching by defining your own scope, perhaps based on a set of packages. Scopes can also be helpful to speed up searches on large projects. Here are the steps to define a scope:

  1. Open Settings (Ctrl+Alt+S) and select Scopes
  2. Click Rerun to create a new scope
  3. Select a package to include from the project browser. Use include and include recursively to broaden the fileset, and exclude and exclude recursively to narrow the fileset
  4. Save. New Scope is now available for many operations

Finding Documentation

There are many ways to find documentation on objects within your project and dependencies. Master these commands to get the information you need without leaving the IDE:

Ctrl+P Parameter Info. Displays quick information on the parameter types (and overloading options) of a method call when the caret is within the parenthesis of a method declaration
Ctrl+Q Quick Documentation Lookup. Displays Javadoc in a popup for the item at the caret
Ctrl+Shift+I Quick Definition. Displays the source code for the item at the caret
Shift+F1 External Javadoc. Opens an external browser to the Javadoc for the item at the caret. May require setting Javadoc locations within Settings (Ctrl+Alt+S) Project Settings (1)

Hot Tip

Is an option you need buried deep in the menu system? Use Ctrl+Shift+A to bring up the Action finder. Type the name of the action you’re looking for and IntelliJ IDEA searches the keymap, menus, and toolbars for the item you need to invoke. Wildcards and camelCase works, of course

Running and Debugging Your Project

Running and debugging the project is an essential part of any IDE. The easiest way to run an application is to right click the object within the Editor pane and select Run. This works for classes with main() and test cases. You can also right click the object and do the same thing in the Project pane. To run tests in an entire package simply right click the package.

Manage run targets by using the Run/Debug configurations window, adding any VM parameters or advanced settings you may need. Open the window by clicking Edit Configurations within the toolbar's dropdown.

Toolbar Dropdown

Common run targets can be saved here for future runs.

Running an entry point will display the Run pane. This pane provides diagnostics on the running process. Get the information you need from running processes by learning to use the pane:

Ctrl+F5 Run Run the last target
pause Pause execution
Ctrl+F2 stop Stop execution
Ctrl+Break Dump Thread Dump Thread information to a new window or clipboard
Ctrl+Alt+Up Move Up Move Up Stack Trace, opening the Editor pane to the exception location
Ctrl+Alt+Down Move Down Move Down Stack Trace, opening the Editor pane to the exception location

Running and Debugging Your Project, continued

When debugging an application, the IDE provides a variety of ways to set breakpoints and watchpoints. The easiest is to click the left gutter of the line or method on which you want a breakpoint. More advanced breakpoints are available through the Breakpoints window (Ctrl+Shift+F8).

Line Break on the specified line of code
Exception Break when the specified exception is thrown
Method Break when the specified method is called
Field Break when the specified field instance is accessed or changed

Once stopped on a breakpoint, the Debug pane will open. This pane provides features common to all debuggers, as well as more advanced, uncommon actions.

Alt+F10 ExecutionPoint Show Execution Point
F8 Step Over Step Over
F7 Step Into Step Into
Shift+F7 Smart Step Into. Pick which method to step into when multiple calls exist on one line.
Alt+Shift+F7 Force Step Force Step Into
Shift+F8 Step Out Step Out
Drop Frame Drop Frame
Ctrl+Alt+Up Previous Frame Previous Stack Frame
Ctrl+Alt+Down Next Stack Frame Next Stack Frame
Alt+F9 Cursor Run to Cursor

Hot Tip

Control what not to step into in Settings (Ctrl+Alt+S) Debugger (G). Exclude certain library classes using the “Do not step into” list, skip simple getters, skip constructors, and more.

Once in the debugger, several panels provide different views of the application state. The Frames Panel shows the current stack frames on the selected thread, and you can navigate quickly between frames and threads. The Variables Panel shows any variables currently in scope. And the Watches Panel shows expanded information on selected variables. When entering variables to watch, autocompletion and smart-type both work.

Expression Evaluation (Alt+F8) allows quick execution of code snippets or blocks. From this window you can reference any in-scope variable of the application. It works a bit like a REPL window open with the current breakpoint’s environment, and is most useful in code fragment mode, where you can evaluate multi-line statements.

Hot Tip

Drop Frame within the debugger pops the current stack frame and puts control back out to the calling method, resetting any local variables. This is very useful to repeatedly step through a function, but be warned: field mutations or global state changes will remain.

Code Coverage: IntelliJ IDEA offers code coverage statistics using the EMMA or IntelliJ IDEA toolkit. Enable tracking in the Code Coverage tab of the Run/Debug Configurations window. The built in runner provides more accurate branching coverage when tracing is enabled. Results appear in several places:

Package Coverage Project pane shows % class and % line coverage per package
Class Coverage Project pane shows % class and % line coverage per class
Line Coverage Editor pane left gutter shows red for uncovered line, green for covered line

Code Coverage Data (Ctrl+Alt+F6) displays a list of previous runs, and selecting an entry shows the coverage data for that run. You can use this to compare coverage between subsequent runs.

Hot Tip

Under certain circumstances, code coverage may make your automated tests fail because instrumented bytecode is different than normal bytecode (I’ve seen this happen when remote CORBA interfaces were invoked). If this happens then simply exclude the affected classes from code coverage within the Run/Debug Configurations window.

Write Less Code

Typing less to produce more is a feature of any modern IDE. IntelliJ IDEA provides top tier code completion support, as well as many other code generation, file template, and refactoring features.

Code Completion: Leveraging code completion is essential to productivity:

Ctrl+Space Basic. Completes the names of in-scope classes, methods, fields and keywords. Also complete paths, when appropriate
Ctrl+Shift+Space Smart Type. Displays a suggestion list where the type of the object required can be inferred from the code, such as in the right hand side of assignments, return statements, and method call parameters
Ctrl+Alt+Space Class Name. Completes the names of classes and interfaces. Accepts camel case matching on input
Ctrl+Shift+Enter Complete Statement. Adds closing punctuation and moves cursor to next line
Alt+Slash Expand Word. Cycles through suggested word choices, highlighting the prototype in the editor

Hot Tip

Confused by all the options? Just start using them and let muscle memory take over. It works.

Code Generation: Letting the IDE infer the code you need to create and drop in the appropriate template can be a huge time saver.

Ctrl+O Override Methods... quickly specify a parent method to override and create a stub implementation
Ctrl+I Implement Methods... quickly specify a parent method to implement and create a stub
Code->Delegate Methods... Delegate Methods... creates adapter classes by delegating method calls to member fields. A small wizard guides you through the delegation
Ctrl+Alt+T Surround With... surrounds the current selection with a variety of code wrappers, like if/else, for, try/catch, synchronized, Runnable, and more

Write Less Code, continued

Generate (Alt+Insert) provides its own set of powerful options for code generation:

Constructor Select any of your object’s fields from a list to create a constructor with the proper parameters and body
Getter Select a field from a list to create an accessor method
Setter Select a non-final field from a list to create a mutator method
equals() /
hashCode()
Provides a dialog to automatically create equals() and hashCode() methods based on your object’s fields

Live Templates are fragments of commonly occurring code, which can be inserted into the active file in a variety of ways. Learning the live templates will save you many, many keystrokes. A full list is available in Settings (Ctrl+Alt+S) Live Templates.

To insert a live template, press Ctrl+J followed by the following keys:

psf public static final thr throw new
itar Iterate elements of an
array
sout Prints a string to
System.out
itco Iterate elements of
collection
soutm Prints the current class and method name to System.out
ritar Iterate elements of array
in reverse order
soutv Prints the value of a variable to System.out
toar Stores members of
Collection in Array
psvm main() method declaration

Hot Tip

Logging live templates are very useful, but many projects use log4J or Commons Logging instead of System.out. Replace the System.out calls with your framework within Settings (Ctrl+Alt+S) Live Templates.

Surround with Live Template (Ctrl+Alt+J) will surround the current selection with a block of code. Some of the useful surrounds are:

B Surround with { }
R Surround with Runnable
C Surround with Callable

Hot Tip

Use the existing surrounds templates to create your own, like surround with SwingUtilities.invokeLater() or new Thread().start()

Live Template in Multiple Languages: Many live templates exist for languages other than Java. JSP, XML, Spring definitions, and more all exist. Here are some examples of templates from other platforms and toolsets:

sb Creates an XML based Spring bean definition
sbf Creates an XML based Spring bean definition instantiated by a factory method (many more Spring intentions exist, too)
itws Generate Axis web service invocation (many more flavors of web services supported, too)
CD Surround with CDATA section
T Surround with <tag></tag>

Hot Tip

The free keymap from JetBrains provides a larger list of live templates. Post the keymap next to your monitor to learn the live templates quickly.

Refactoring: IntelliJ IDEA offers excellent refactoring support. Refactoring is aware of comments, reflection, Spring, AOP, JSP, and more. When the refactoring features are unsure on the safety of a refactoring, a preview mode is invoked so that you can verify the changes. Refactoring works on more than just Java code too: many refactorings exists for XML files as well as other languages. Learning the refactoring tools (and reading the refactoring literature, for that matter) is well worth your time. Here are some of the more common refactorings:

Rename Shift+F6 Renames a package, class, method, field or variable
Move F6 Moves an entity
Change Signature Ctrl+F6 Change the method or class name,parameters, return type, and more
Extract Method Ctrl+Alt+M Moves the current selection to a new method, replacing duplicates if found
Inline Ctrl+Alt+N Takes a method, variable, or inner class and replaces usages with a unique definition
Introduce Variable Ctrl+Alt+V Moves the selected expression into a local variable
Introduce Field Ctrl+Alt+F Moves the selected local variable into a field,prompting you for how initialization should occur
Introduce Constant Ctrl+Alt+C Moves the selected variable or field into a static final field, replacing duplicates if found
Introduce Parameter Ctrl+Alt+P Moves the selected local variable into a parameter argument, updating any callers in the process
Extract Interface Moves a set of methods from the object onto an interface, updating callers to reference the interface if possible
Pull Member Up Move a method from a subclass up to an interface or parent class
Encapsulate Fields Provides getter and/or setters for the selected field

Hot Tip

Ctrl+Shift+J will join two lines together, which is a sort of shorthand for inline variable.

Improve Your Project ’s Quality

The IDE’s features aren’t just about writing code faster, they are also about coding more accurately. Understanding the intentions, inspections, and analysis tools are key to keeping code high quality.

Intentions: Keeps code clean by flagging potential problems in the Editor pane as they occur, and then offers an automated solution. An available intention is signaled by a lightbulb appearing in the left gutter, and the suggested fix can be applied by pressing Alt+Enter. There are several types of intentions:

  • n “Create from usage” intentions allow you to use new objects and methods without defining them first. Need a new method? Just call it from code; IntelliJ IDEA will prompt you to create it, inferring the parameter and result types. This works for classes, interfaces, fields, and variables. If the missing reference is in all capital letters, then it will even create a constant for you.

Improve Your Project’s Quality, continued

  • n “Quick fix” intentions find common mistakes and makes context-based suggestions on how to fix them. Examples of issues flagged with a quick fix are assigning a value to the wrong type or calling a private method.
  • “Micro-refactorings” fix code that compiles but could be improved. Examples are removing an unneeded variable and inverting an if condition.

Some of the intentions or fixes might violate your coding standard. Luckily, they can all be configured within Settings (Ctrl+Alt+S) Intentions.

Intentions and Quick Fixes are indicated by different icons in the left gutter, but in practice there is little need to differentiate between the two:

Icon Box

Inspections: Keeps code clean by detecting inconsistencies, dead code, probable bugs, and much, much more. The near-1000 default inspections can do a lot to enforce common idioms and catch simple bugs across the project. There are way too many inspections to list, but here are examples to provide a flavor of what inspections can do:

  • Flag infinite recursion or malformed regular expression
  • Catch error handling issues like continue within finally block or unused catch parameter
  • Find threading issues like await() outside a loop or non-thread safe access
  • Error on Javadoc issues like missing tags or invalid links

Inspections work with many languages and tools beyond the Java language, like Spring, JSF, Struts, XML, JavaScript, Groovy, and many others. The inspection set is highly configurable through Settings (Ctrl+Alt+S) Errors. Each inspection can carry its own set of options, and most can be shown as warnings or errors within the IDE. When an inspection violation is shown in the right gutter, Alt+Enter triggers the suggestions to be shown.

Some inspections appear within the Editor pane, while others appear within the Inspection pane when they are run as a batch. To run inspections for a scope, go to Analyze Inspect Code in the menu.

Inspection settings can be configured and shared across the team. An “IDE” inspection profile is saved within the user’s $HOME directory, but a “Project” profile is saved within the IDEA project file. This means a shared, version controlled project file can be created which contains the team’s inspections.

Hot Tip

By default, IDEA uses a great set of inspections, but many more options are not turned on by default. Check out http://hamletdarcy.blogspot.com/ 2008/04/10-best-idea-inspections-youre-not.html to see some non-default inspections you might want to use.

Code Analysis: Provides several different views of dependencies and duplicates within your project. These tools help you modularize your code and find areas of potential reuse. All of the following features are available from the Analyze menu.

The Dependency Viewer provides a split tree-view of your project with a list panel at the bottom. From here you can navigate the dependencies or mark certain undesirable dependencies as illegal. Which analysis feature chosen determines what the Viewer displays:

Dependencies Left: Your packages. Right: Packages your code depends on
Backward Dependencies Left: Your packages. Right: Packages that depend on your
code. Bottom: Line by line usages
Cyclic Dependencies Left: All of your packages that have a cyclic dependency. Right: The objects that form the cycle. Bottom: Line by line usages

Not all analysis tools report to the Dependency Viewer, however. Module Dependencies uses a separate panel to display dependencies across all the included modules within the project. This is useful for multi-module projects. Dependency Matrix launches the Dependency Structure Matrix in a separate window. This tool helps you visualize module and class dependencies across the project using a colored matrix.

Locate Duplicates: Finds suspected copy and pastes within your project or desired scope. Use this to find and consolidate duplicate modules or statements. The results are displayed in the Duplicates pane, which ranks the copy/paste violations and allows you to extract methods on the duplicates by simply clicking the Eliminate duplicates icon Icon1

Work as a Tea m

IntelliJ IDEA includes many features that allow team members to collaborate effectively.

Version Control (VC) integration exists for Subversion, Git, CVS, Perforce, StarTeam, Visual SourceSafe, TFS, and ClearCase. When enabled, local changes appear as a blue bar in the left gutter:

Version Control

Clicking the blue bar displays some VC options, including a quick line diff (displayed), a rollback of the line changes, or a full file diff in the IntelliJ IDEA Diff Viewer. More VC options are available from the menu or by right-clicking the active editor:

View History See revision history for active file with check-in comments
View
Differences
Launch the side-by-side file comparison window. Merge changes from one file to another, accept non conflicting changes, and more
Annotate Show the user ID of the last person to touch each line in the left gutter

Local History can be used even if you don’t have version control. The IDE keeps track of saves and changes to files, allowing you to rollback to previous versions if desired. Older versions can also be labeled, making it easy to find previous save points.

Shared Project: The project file can be put in version control, keeping all environments up to date as changes are made. Use this guide to the project files to determine what files need to be shared:

.ipr Contains project info like module paths, compiler settings, and library locations. This should be in version control
.iml Used in a multi-module project, each module is described by an .iml file. This should be in version control
.iws Contains workspace and personal settings. This should not be in version control

Work as a Team, continued

File Templates: Shared file templates provide a common starting point for frequently typed code. Templates exist, and can be changed, for creating new classes, interfaces, and enumerations. Templates for includes, like a copyright notice, can also be stored and shared, as well as code templates, like default catch statements and method bodies. Modify the file templates in Settings (Ctrl+Alt+S) File Templates.

Ant Integration: Many projects use Ant as a common build script, and IntelliJ IDEA offers integration with it. Features include syntax highlighting, code completion, and refactorings. Several inspections and intention settings are also available. Use the Ant Build Window to run one or several Ant targets. For larger projects with many targets, use the filter targets feature to hide uncommon targets. The Maven build system is also supported.

Work With the Database

IntelliJ IDEA 8 ships with a data source editor and JDBC console. Once configured with a JDBC or SQL data source, the console is a great environment for working with the database, providig SQL syntax completion, error and syntax highlighting, and completion of the table and column names. Middle click entities like table names or columns to navigate to their definition in the DDL view, and run the entire script (Ctrl+Enter) or snippits (Ctrl+Shift+Enter) using the controls provided. The results pane can be copied to the clipboard as comma separated values. You can also use parameters within the scripts, which are variables marked with the @, #, $, or ? characters. Any parameters found are displayed in the parameters Pane, and from there they can be edited without modifying the SQL source script.

Endless tweaking awaits

A massive amount of configuration options are available in Settings (Ctrl+Alt+S). Beyond that, you may wish to experiment with different plugins. Plugins are installed and managed using Settings (Ctrl+Alt+S) Plugins. Many plugins exist, adding features like Scala, Ruby, or web framework support. JetBrains holds plugin contests annually, so check the site periodically.

About The Author

Photo of author Hamlet D’Arcy

Hamlet D’Arcy

Hamlet D’Arcy has been writing software for over a decade, and has spent considerable time coding in Groovy, Java, and C++. He’s passionate about learning new languages and different ways to think about problems, and recently he’s been discovering the joys of both F# and Scheme. He’s an active member and speaker at the Groovy Users of Minnesota and the Object Technology User Group, and is involved with several open source projects including the Groovy language and the IDEA Jet- Groovy plugin. He blogs regularly at http://hamletdarcy.blogspot.com, tweets as HamletDRC, and can be contacted at hamletdrc@gmail.com.

Recommended Book

Easy PHP Websites with the Zend Framework

For new users, IntelliJ IDEA in Action is a logically organized and clearly expressed introduction to a big subject. For veterans, it is also an invaluable guide to the expert techniques they need to know to draw a lot more power out of this incredible tool. You get a broad overview and deep understanding of the features in IntelliJ IDEA.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Eclipse Tools for Spring

The SpringSource Tool Suite

By Gordon Dickens

13,795 Downloads · Refcard 147 of 151 (see them all)

Download
FREE PDF


The Essential SpringSource Tool Suite Cheat Sheet

This cheat sheet covers the SpringSource Tool Suite (STS), an Eclipse-based IDE that includes many useful Spring developer plugins out of the box. These tools include visual editors, project validators, and a Spring dashboard. The suite can be used for development in Spring Roo, Groovy, Grails, Gradle, Spring tcServer, and Spring Insight. This Refcard will walk you through installation, configuration, validation, Bean navigation, Spring Aspect Oriented Programming, and analysis. Whether youre new to Spring development or a veteran on the framework, you need to get your hands on this card.
HTML Preview
Eclipse Tools for Spring: The SpringSource Tool Suite

Eclipse Tools for Spring:The SpringSource Tool Suite

By Gordon Dickens, Chariot Solutions

ABOUT SPRINGSOURCE TOOL SUITE

SpringSource Tool Suite (STS) is an Eclipse-based IDE with pre-installed plugins that provides valuable features for Spring developers. In addition to support for the core Spring framework, STS also provides visual editors, project validators, and Spring Dashboard for other projects such as Spring Roo, Grails, Groovy, Gradle, tcServer, and Spring Insight.

The main plugin for STS is Spring IDE, which provides the fundamental Spring tooling features. STS comes preconfigured with many other plugins such as M2Eclipse for Maven, Web Tools Platform (WTP), Data Tools Platform (DTP), and AspectJ Development Tools (AJDT) and JUnit tooling.

Why use STS?

  • Content aware XML Spring Bean editing and refactoring
  • Content-aware Spring shortcuts for Java classes
  • Visualizers for graphical configuration editing
  • Validators for project configuration
  • Dashboard
  • Spring tcServer and Insight
Getting STS

STS is available from SpringSource: http://www.springsource.com/developer/sts

STS version numbers are different than the Eclipse versions. When choosing versions from the Spring site, go the current version of STS to see the supported Eclipse versions.

When installing STS from the native installer, it prompts you to install optional products such as Spring Roo, Apache Maven, and tcServer Developer edition. If these features are already installed and configured, uncheck these products.

Already have Eclipse?

If you already have Eclipse 3.6, download the STS plugin as follows:

  1. Before installing STS, ensure you have the current JDK installed.
  2. Download the bookmarks file from: http://dist.springsource.com/release/TOOLS/composite/e3.6/bookmarks.xml.
  3. In Eclipse, select Preferences -> Install/Update -> Available Update Sites.
  4. Click the “Import…” button, select the downloaded “bookmarks. xml”, and click “Open” to finish the import.

If you are using another version of Eclipse, find installation instructions here: http://www.springsource.com/products/eclipsedownloads.

Manage the plugin sites from Help > Install New Software… Clicking the “Available Sites” link shows the currently configured plugin sites.

The Dashboard

When you start STS, one of the first things you will see is the Spring Dashboard. At the bottom of this view are two tabs: Dashboard and Extensions. The Dashboard tab contains five sections:

  1. Create – Spring, Java, Grails & Groovy Projects
  2. Updates – Update information for STS
  3. Tutorials – Spring, Security, Web, Web Flow, WS
  4. Help & Docs – Forums, JIRA, STS New & Noteworthy
  5. Feeds - RSS announcements from Spring and Spring Blog posts

The Extensions tab contains two tabs:

  1. Extensions tab provides options for installing Roo, Groovy, Grails, and other useful extensions such as Google (GWT & GAE), CloudFoundry, DataNucleus, EGit, FindBugs, PMD, and more.
  2. The Find Updates tab checks for extension updates.

Hot Tip

To Manage the Dashboard: Preferences > Spring > Dashboard Add Spring blogs like: http://gordondickens.com/wordpress/feed/

PROJECT CONFIGURATION

To take advantage of Spring tooling features, add the Spring Project Nature to each project. Then you can view the project in Spring Project Explorer and define bean config files and config sets.

If you’re using Maven, you can configure this in your pom.xml file using the maven-eclipse-plugin:



<build>
...
  <plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-eclipse-plugin</artifactId>
	<version>2.8</version>
	<configuration>
	  <downloadSources>true</downloadSources>
	  <downloadJavadocs>true</downloadJavadocs>
	  <wtpversion>1.5</wtpversion>
	  <additionalBuildcommands>
		<buildCommand>
		  <name>org.springframework.ide.eclipse.core.springbuilder</
name>
		</buildCommand>
	  </additionalBuildcommands>
	  
	  <additionalProjectnatures>
		<projectnature>
		  org.springframework.ide.eclipse.core.springnature
		</projectnature>
	  </additionalProjectnatures>
	</configuration>
  </plugin>
...
</build>



Once the Maven Eclipse plugin is installed, you can generate the Eclipse project files from the command prompt with:


mvn eclipse:eclipse

Hot Tip

A project configured with Spring Project Nature will have an “S” over the project, bean config files and directory icons containing bean config files.
Spring Perspective

The Spring Perspective is an Eclipse perspective displaying views such as Spring Explorer and other standard Eclipse views: Servers, Spring Explorer, Task List, Outline, Console, Markers, and Progress. This is a convenient layout that can be customized to your liking.

Spring Explorer View

This view provides the ability to see the Bean Config files within Spring projects. Here you can view the beans graph visualizer, create bean config files, define Bean Config sets, define new beans, validate beans, and openf MVC request mappings.

Bean Config files are XML files defining beans and bean relationships within a project. If you are using a project and don’t remember where the Bean Config files are located, open Spring Explorer. Within Spring Explorer, right-click a config file and choose from several options:

  • Open Dependency Graph - the visualizer for bean relationships. This is the same as the “Bean Graph” tab available in the bean editor.
  • New Bean Definition - provides a dialog for entering bean definitions.
  • RequestMapping - opens a view for MVC applications showing all the request mappings configured in this file. Validate - validates the bean configuration file based on the Spring Bean
  • Validate - will validate the bean configuration file based on the Spring Bean validation configuration settings in preferences.
  • Properties - opens project beans, validation, config set dialog. In this dialog we have the option to scan for more configuration files with the “Scan” Button.
Window 1
Project Explorer View

This view provides you with the ability to look at the project by its component types such as Spring Elements, Bean Config Files, Bean Config Sets, Web Service components, Java Resources, and more.

Window 2

Once you have added Spring Project Nature to your project, you can create or mark bean config files.

Creating a Spring config file – From Package Explorer, click the directory for the XML file and choose:

File > New > Spring Bean Configuration File

Locating Spring config files - from Spring Explorer view, right-click the project:

Properties > Spring > Beans Support “Scan” button the directory for the XML file and choose: File > New > Spring Bean Configuration File

Hot Tip

Bean config files will appear with the “S” over the directory and file.
Bean Config Sets

Bean config sets allow you to group bean config files together. Using Config Sets provides the ability to validate beans and bean relationships defined within multiple bean config files. Validation also provides suggestions via content assist when editing.

This feature is particularly useful when you have infrastructure beans such as dataSource defined within a test config file and the application’s entity, services, etc defined in a common bean config file that is the same for all deployment platforms. You do not have the ability to assign config sets to any components or tests. This is unnecessary as STS performs cross-file validation on all config sets.

If the bean config files within a config set do not define all referenced beans, mark a config set by checking the “Is incomplete” checkbox. If checked, the BeansConfigValidator doesn’t complain about missing bean references within this config set.

Spring MVC Request Mappings

Spring MVC is very powerful and easy to configure using annotations. The MVC Request Mappings view displays the request mappings for an MVC project. In Spring Explorer, right-click an MVC project, config file, or config set and select RequestMappings to see the URL details in a tabular view. If it is not an MVC application, this view is empty. The view provides the following details:

  • Resource URL
  • Resource Method: GET, POST, etc.
  • Handler Method
  • JavaDoc

Within the view, Double click on line to go to the code.

Windows 3

STARTING A PROJECT FROM SCRATCH

Spring Project

This option is extremely bare bones and only creates a basic Java project with src directory and Spring Project Nature added. No Spring dependency jars or other structures are configured. It is recommended to use the Spring Template Projects instead.

See the Spring Dashboard for quick links to create Spring, Groovy, Grails, and Spring Roo projects.

Spring Template Project

From the File > New menu, you can create a Spring project using the predefined templates from SpringSource. These templates provide a convenient starting point for different Spring projects.

The projects created from these templates are configured as Maven projects with the necessary project (JAR) dependencies.

Note: Many of the templates may require manual updating of project configuration. Updating configuration is often in two main areas: version dependencies in pom.xml and bean config file namespaces for the latest project versions.

BEAN CONFIGURATION

Bean Editing

The bean editor in STS provides features beyond a standard XML editor. In the java editor, you are already familiar with content assist. Spring adds content assist when typing in bean declarations. For example, in the bean config editor (and throughout Eclipse), you can use camel case when typing bean names. This provides the ability to enter the class name without having to know the full package or spelling of the bean.

For example:

If you want to configure JmsTemplate, type <bean class=“JT”/> and press CTRL-Space after the “T” to get a long list of beans matching J and T. Narrow by <bean class=“JmT”/> then press CTRL-Space after the “T” to get a shorter list where you can choose JmsTemplate. The complete package and classname is entered for you.

When configuring properties of a bean, content assist provides you with the available properties that you can set in the XML config.

<bean id=“jmsTemplate” class=“…JmsTemplate”> <property name=“”/> </bean>

By hitting CTRL-Space within the quotes of the property name, you are prompted with all of the properties available to set.

Spring also provides XML templates to quickly insert config within the xml files. For example, on a blank line in the bean config editor, type “bean” and press CTRL-Space.

Windows 4

Choose Bean - Inserts a Bean Tag and below shows the example of what will be inserted into the code:

<bean id=”id” class=”class”>

</bean>

Hot Tip

View, add or modify XML bean templates in Preferences > Spring > Beans Support > XML Templates
Windows 5
Bean Editor Tabs

A series of Tabs will display at the bottom of the editor based on the content of the XML namespaces used. Overview tabs for specific namespaces include JDBC, Spring Integration, Spring Batch and Web Flow.

Windows 6
  • Source – The XML editor
  • Namespaces - Choose namespaces to include/exclude in the configuration file, without the risk of typos.
  • Configure the namespace discovery in Preferences > Spring > Beans Support > Namespaces
  • Overview - General overview of the beans within a bean definition file. A tree hierarchy shows the beans, nested beans and bean properties.
  • Namespace specific tabs – provide bean information for namespaces we have selected. Such as: context, jee, tx, etc.

Beans Graph – Display’s graphical representation of beans (see Visualizers below)

Hot Tip

<Configure the namespace discovery by selecting Preferences > Spring > Beans Support > Namespaces.

VALIDATION

Spring project validation rules are available in Preferences > Spring > Project Validators section.

Spring Validator

There is only one option to verify Spring is in the classpath. This validator is disabled by default. There are three categories: Bean validation, STS validation, and Spring validation.

Bean Validation

There are 15 rules available, most enabled by default. These rules validate bean names, aliases, deprecation, @Required annotation, constructor injection, and Autowired annotation types (@Autowired, @Resource, @EJB).

Bean Rule Description
Required Property Validates @Required annotation
Annotation-based
Auto wiring
Validates @Autowired, @Resource and @EJB annotations
Bean Alias Validates alias names associated with bean
Bean Class Validates a bean class
Bean Constructor
Argument
Validates non-abstract bean’s constructor arguments
Bean Definition Holder Validates Root bean’s name and aliases
Bean Definition Validates a bean’s definition
Bean Deprecation Validates init, destroy and setters are not deprecated
Bean Factory Validates a factory beans and factory methods
Bean Init and Destroy
Method
Validates non-factory beans init and destroy method
Bean Method Override Validates bean method override
Bean Property Validates bean’s property accessor method is in bean class
Bean Reference Validates bean references depends-on attribute, a value holder or collection type
XML Parsing Problems Validates XML file is parseaable
XSD Tool Annotation Validates attributes based on schema
STS Validator

The eight STS validator options are project-wide validation rules.
These validators are disabled by default.

STS Rule Description
Driver Manager Data Source Validates the project does not use this class
Bean Inheritance Recommends bean inheritance for simplification
Import Elements at Top Recommends imports before other bean definitions
Parent Beans not Abstract Validates that parent beans are not abstract
Too Many Beans Validates too many beans in file – approx. 80 beans
Unnecessary Ref Check for ref elements and recommends ref attribute instead. <property … ref=””/> instead of <property …><ref bean=””/></property>
Dedicated Namespace Syntax Checks for cases where dedicated namespaces can be used

Once enabled, from Package Explorer view, R-Click on the project and select validate.

STS Validation errors will be displayed in the Markers and Problems views.

Once corrected actions are made, you may need to remove the validation markers. R-Click on project > Spring Tools > Remove Validation Markers and then validate again.

Bean Refactoring

The Bean Config editor provides the ability to refactor bean definitions. In the editor, right-click on a bean definition, select “Refactor…” and you will see three options:

  • Refactor Property Element – Nested ref and value tags.
  • Move Bean Element (class)… - Move class to another package.
  • Rename Bean Element (id, class, property name)…- Rename bean id, can search for literal string references and similarly named classes.

BEAN NAVIGATION & ANALYSIS

Within STS, you can quickly open a bean or view bean cross references or bean outline from the Eclipse Search and Navigate menu options.

Finding Spring Beans

From Search > Beans, you can conduct a wildcard search for beans by name, class, property name, beans referencing, and child beans.

Navigate > Open Spring Bean displays a search box where you can search for class names using camel-case.

Beans Quick Cross References

Within the bean config editor, select Navigate > Beans Quick Cross References to show the beans cross references for the current bean file. From here, you can jump to the bean declaration.

Note:

  • Beans Cross References view is for Spring
  • Cross References view is for AspectJ
Beans Quick Outline

Within the bean config editor, select Navigate > Beans Quick Outline to display an outline list of all bean declarations and property settings. You can search for a specific bean by ID and click a bean to see its definition.

Beans Cross References View

This view shows cross references based on the open file. By default, this view is empty until you click the “Link with Editor” in the title bar of the view (gold arrows).

Windows 7

SPRING ASPECT ORIENTED PROGRAMMING (AOP)

Spring AOP support in STS is extends the installed AspectJ Development Tools (AJDT) plug-in.

Spring Aspects Tooling

Spring AOP support in STS extends the installed AspectJ Development Tools (AJDT) plug-in.

Right-click on a project. Under Spring Tools, there is an option to enable Spring Aspects Tooling. This enables AJDT weaving features within a project.

With this setting, AJDT weaves itself into JDT with features:

  • TD-aware reconciling/eager parsing
  • TD-aware content assist
  • TD-aware type hierarchies
  • Search for aspect elements using standard Java search and Open Java type

Source: http://wiki.eclipse.org/JDT_weaving_features

AOP Event Trace

The AOP Event Trace view provides log-like detail during a project build. The view logs information about the Spring IDE’s internal AOP model creation.

To enable this feature:

  • Add spring-aspects.jar to the project.
  • Right-click project > Spring Tools > Enable Spring Aspects Tooling.
  • Select Preferences > AspectJ Compiler > Other > Check Verbose & Pointcut matching timers.
Windows 9
Spring Pointcut Matches

From the Search menu, we can use Spring AOP Pointcut expressions and test pointcuts such as:

execution(void set*(*))

bean(transactionManager)

Windows 8

VISUALIZERS

STS provides the ability to graphically view and edit Spring configuration. The five visualizers are beans, Spring Integration, Spring Batch, Web Flow, and Aspects.

Beans Graph

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

The Beans Graph provides a visual diagram of the Beans and Bean Relationships within a config file or config set.

Within a Bean Config file, the tab “Beans Graph” displays beans within the file.

Windows 10

From Project Explorer, expand the project under Spring Elements, right-click the Config Set name, and choose “Open Dependency Graph”.

Windows 11

Set preferences for Beans Graph in Preferences > Spring > Beans Support

  • Display Inner Beans
  • Display Infrastructure Beans
  • Display Extended Content (Autowired beans)

This feature is enabled by default in Preferences > Spring> Beans Support > Editor > Enable embedded graph pages.

Integration Graph

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

When using Spring Integration, the “integration-graph” tab is available in the beans config editor. The graph displays the standard Hohpe/Woolf diagrams from the Enterprise Integration Patterns book.

This visualizer is editable using the tool pallet on the left. The tool pallet only shows tools based on the namespaces included in the XML file.

Windows 12
Batch Graph

When using Spring Batch, you see the batch-graph tab in the beans config editor. This visualizer is editable.

Windows 13
Web Flow Graph

Spring Web Flow provides you with the ability to design Stateful page flows. The bean config editor provides the ability to edit the flows in XML or visually from the flow-graph tab.

Windows 14
Aspect Visualization

To see visualize Spring AOP aspects, select Preferences > Visualizer under Visualizers and then check Spring AOP Provider. You can also do this from the Visualizer view by clicking the down arrow in the view’s title bar and choosing preferences.

In the view tools, select the “Hide Unaffected Bars” to show only the classes affected by aspects.

Note: You do not need to enable Spring aspects tooling for this feature to work.

Windows 15

About The Authors

Gordon Dickens

Gordon Dickens is an instructor/mentor/consultant for Chariot Solutions (chariotsolutions.com) with experience in the IT consulting for over 15 years. Gordon’s background includes presenting at conferences and user groups on Spring, Groovy & Grails, with experience developing Spring, Hibernate, Grails, Roo and OSGi applications. Gordon blogs at technophile.gordondickens.com and actively tweets open source tips at (twitter.com/gdickens). Gordon is a contributor to Spring Roo in Action manning.com/rimple and very active in the Spring Framework, Roo, Spring Integration and Spring Batch projects. He currently teaches Maven and Spring as a Certified Spring Instructor by SpringSource.

Recommended Book

Spring Roo in Action Book

Roo is a lightweight Java development tool that works within existing processes, to rapidly produce high-quality, 100% Java code. Roo enforces correct coding practices and patterns and instantly integrates not only with Spring, but also with virtually every mainstream Java technology.

Roo in Action is unique book that teaches how to code Java in Roo, with a particular focus on Spring-based applications. It starts by getting into the Roo mindset, along with a quick-and-dirty guide to setting up Roo effectively. Through hands-on examples, readers will learn how Roo creates well-formed application structures and supports best practices and tools.

Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose: Release of MeeGo 1.2

The much anticipated release of MeeGo 1.2 has officially been announced this week! MeeGo 1.2's OS is home to several reference kernels, including those for the Intel Atom and ARMv7 platform. Linux and Windows are the currently supported platforms.  A Mac OS...

0 replies - 19393 views - 05/20/11 by Katie Mckinsey in Daily Dose

Daily Dose: JRockit Now Free To Download!

As a result of Oracle's strategy to merge HotSpot and JRockit into a single best-of-breed JVM, JRockit is now free for development and internal production use on general purpose computers. Use in external production and other non-general computers is...

0 replies - 19008 views - 05/18/11 by Jim Moscater in Daily Dose

Daily Dose: Google App Engine 1.5.0 Released At Google IO

As a kickoff to Google IO, Google announced the release of Google App Engine 1.5.0. The addition of long running instances has added a new level of control over  the kinds of applications that can be run on the infrastructure. Pull Queues, another new...

0 replies - 14723 views - 05/11/11 by Katie Mckinsey in Daily Dose

Daily Dose: Ruby on Rails Will Now Support HTTP Streaming

The new release of the Ruby on Rails web development framework, version 3.1, will feature HTTP support.  This additional support will serve to improve overall page performance by allowing the browser to "get expensive assets like stylesheets and...

0 replies - 21433 views - 04/25/11 by Katie Mckinsey in Daily Dose

Daily Dose: Apple Releases Final Version of Xcode 4 IDE

Xcode 4 is ready for action!  This version of Apple's popular IDE is sleeker and more refined than its predecessor.  Xcode editing tools and Interface Builder are consolidated into a single application.  The Assistant feature anticipates which files...

0 replies - 24803 views - 03/10/11 by Katie Mckinsey in Daily Dose

Daily Dose - Will NetBeans Have to Remove JUnit?

NetBeans Platform Architect Jaroslav Tulach recently posted some surprising news on the JUnit Yahoo Group.  "We have new lawyers," he said, and they're concerned about the JUnit license—the Common Public License, which is a bit dated in Tulach's...

0 replies - 14538 views - 01/18/11 by Mitchell Pronsc... in Daily Dose

Daily Dose - Eclipse 3.7 and 4.1 Hit Milestone 4

Eclipse 3.7 "Indigo" and Eclipse 4.1, which is still aimed at early adopters, received new features in milestone 4 this week.  For both Eclipse versions, the milestone brings Equinox updates for the OSGi R4.3 spec, memory usage upgrades for p2, and...

0 replies - 22602 views - 12/14/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - IntelliJ IDEA X: Faster, Smarter, Plus a Free Android IDE!

It's been a little more than a year since IntelliJ IDEA 9 was released and a free and open source version of the IDE became available—this turned out to be a great decision.  Today,  IntelliJ IDEA 10 is here.  Along with a 2x speed upgrade for initial...

0 replies - 20961 views - 12/10/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Red Hat Acquires Makara

With their Apache-licensed DeltaCloud project and now with today's acquisition of a Cloud tech startup called Makara, RedHat is building a broad foundation for its position in the PaaS sphere.  I wrote about the emergence of Makara early this year and I was...

0 replies - 17546 views - 12/01/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - NetBeans 7 Starts Living Up To Its Name

A new beta release of NetBeans 7.0 is the first to provide JDK 7 support, allowing developers to choose Java 7 (still in development) as their target platform in the platform manager.  This means NetBeans 7 users can start experimenting with things like...

1 replies - 24711 views - 11/23/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Bob Lee Won't Support the Java SE "Charade"

This week, Bob Lee, who is best known for leading JSR-330 (Dependency Injection for Java) and creating Guice, declined an invitation to participate in the Java SE 7 and 8 expert groups.  The decision was tough, but he made it in response to Oracle applying...

2 replies - 23232 views - 11/18/10 by Mitchell Pronsc... in Daily Dose