when maven encounters eclipse - ibm software · pdf filemaven's features via eclipse,...

29
When Maven encounters Eclipse Skill Level: Intermediate Gilles Dodinet ([email protected]) Consultant 07 Jun 2005 Maven is a powerful tool, but you need to integrate it into one of the popular integrated development environments (IDEs) to bring its power closer to hand and make your work easier, thus increasing your productivity and project quality. Mevenide integrates Maven smoothly into Eclipse and helps reduce the learning curve when faced with Maven for the first time. This tutorial provides a concrete example of how to make Maven and Eclipse collaborate. Section 1. Before you start About this tutorial Maven is a build tool that significantly increases project quality by providing a high-level view of the build process. Today's project complexity requires robust integrated development environments (IDEs) like Eclipse to leverage productivity. You could get more from both tools if they were more tightly integrated. Making them collaborate isn't impossible, and Mevenide aims to achieve that goal. This tutorial shows you how to integrate Maven and Eclipse in a more fluid development cycle. It's written for developers with relatively little Eclipse and Maven experience. At the end of the tutorial, you'll understand the stakes underlying this topic, and you'll be able to handle complex Maven projects and completely pilot them from within Eclipse. "Exploiting Maven in Eclipse" (see Resources) compares Maven to other technologies, and gives you insight into where Maven and Eclipse meet and how you can make these tools collaborate. In this tutorial, you'll learn how to benefit from When Maven encounters Eclipse © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 29

Upload: duongthuan

Post on 18-Mar-2018

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

When Maven encounters EclipseSkill Level: Intermediate

Gilles Dodinet ([email protected])Consultant

07 Jun 2005

Maven is a powerful tool, but you need to integrate it into one of the popular integrateddevelopment environments (IDEs) to bring its power closer to hand and make yourwork easier, thus increasing your productivity and project quality. Mevenide integratesMaven smoothly into Eclipse and helps reduce the learning curve when faced withMaven for the first time. This tutorial provides a concrete example of how to makeMaven and Eclipse collaborate.

Section 1. Before you start

About this tutorial

Maven is a build tool that significantly increases project quality by providing ahigh-level view of the build process. Today's project complexity requires robustintegrated development environments (IDEs) like Eclipse to leverage productivity.You could get more from both tools if they were more tightly integrated. Making themcollaborate isn't impossible, and Mevenide aims to achieve that goal.

This tutorial shows you how to integrate Maven and Eclipse in a more fluiddevelopment cycle. It's written for developers with relatively little Eclipse and Mavenexperience. At the end of the tutorial, you'll understand the stakes underlying thistopic, and you'll be able to handle complex Maven projects and completely pilot themfrom within Eclipse.

"Exploiting Maven in Eclipse" (see Resources) compares Maven to othertechnologies, and gives you insight into where Maven and Eclipse meet and howyou can make these tools collaborate. In this tutorial, you'll learn how to benefit from

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 29

Page 2: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Maven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build.

Prerequisites

This tutorial assumes that you're familiar with the basics of Maven. If that isn't thecase, you should first read the "Getting started" guide on the Maven Web site (seeResources). The developerWorks article "Project management: Maven makes iteasy" is also a good starting point.

To complete this tutorial, you need to have the following software installed:

• Maven V1.0.2

• Eclipse V3.1 M5

An online connection is also required because Maven will download a few files whileworking.

Section 2. Handling complex builds with Maven

A Maven overview

Recently, there's been quite a buzz about Maven, and you probably haven't escapedit. Before Maven came on the market in 2001, no real building tool was available.Developers and build managers had to tediously write build scripts that ended upbeing maintenance nightmares.

Maven is a software project management tool that revolves around the concept of aproject object model (POM) that encapsulates project structural and conceptualmetadata, such as identification information, dependencies, and layout description.The declarative representation of important project metadata shortens the amount oftime needed to jump into a project and enhances its global comprehension.

Maven also promotes reusability and simplicity by encouraging you to decoupleconcerns and split projects into smaller entities that you can maintain more easily.But when an application is split into smaller-grain subprojects, you need a way tobuild the whole application at once. For that purpose, Maven provides a means to

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 2 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

build multiple projects as a global project, automatically resolving the processingorder (see Resources).

Structure the project

In this tutorial, you'll create a JavaNCSS plug-in for Eclipse (see Resources).JavaNCSS lets you collect simple metrics from Java sources. Unfortunately, it hasn'tbeen developed with reusability and integration concerns in mind. So, you must firstcreate a tiny layer above it to let you embed it easily. Although JavaNCSS is mainlya command-line tool, it has the ability to save the collected data into an XML file. It'sno surprise that you'll use this feature.

You can already foresee what needs to be done. You need a command-line wrapperand a parser.

For the sake of simplicity and reusability, you'll dissociate those two aspects anddevelop them as separate projects, each producing its own artifact and having itsown life cycle. However, they're part of the same project and, thus, share someproperties, such as a common directory layout. To avoid information duplication,you'll factorize shared properties in an abstract parent project. You'll end up withthree projects:

• metrics-model provides the parser. The parser and the underlyingclasses mapped to XML are generated using maven-modello-plugin(see Resources) from an XML description (you can find it in theos-maveneclsrc.zip file in this tutorial).

• metrics-core encapsulates the command-line wrapper and dependson metrics-model.

• metrics-commons is the parent project that metrics-core andmetrics-model extend.

The following snippet shows the project model for metrics-commons:

<project><pomVersion>3</pomVersion><groupId>dw-metrics</groupId><artifactId>metrics-commons</artifactId><currentVersion>1.0-SNAPSHOT</currentVersion><name>Metrics Parent</name><build>

<sourceDirectory>src/main/java</sourceDirectory><unitTestSourceDirectory>src/test/java</unitTestSourceDirectory><!-- declare resource directories as well -->

</build>

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 29

Page 4: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

</project>

Easy parser generation

Both metrics-core and metrics-model extend metrics-commons, as follows:

1. Create metrics-model and metrics-core POMs

2. Don't forget to add metrics-model to the metrics-coredependencies and maven-modello-plugin to the dependencies list ofmetrics-core, as shown here:

<project><extend>../metrics-commons/project.xml</extend><pomVersion>3</pomVersion><artifactId>metrics-model</artifactId><name>Metrics Model</name><dependencies>

<dependency><groupId>maven</groupId><artifactId>maven-modello-plugin</artifactId><version>1.0-alpha-1-SNAPSHOT</version><type>plugin</type>

</dependency></dependencies><build>

<sourceDirectory>target/generated-sources/modello</sourceDirectory></build>

</project>

You must override the sourceDirectory element in the metrics-model POMfor the maven-java-plugin to work correctly because the only source files thisproject contains are generated. Source generation should happen beforecompilation begins:

1. Create a maven.xml file in metrics-model

2. Add a preGoal to the java:compile goal:

<project xmlns:maven="jelly:maven"><preGoal name="java:compile">

<!-- generate classes with modello first --><attainGoal name="modello:java" /><attainGoal name="modello:xpp3-reader" /><path id="generated.src"

location="${maven.modello.targetDirectory}"/><!-- add generated.src to default src path --><maven:addPath id="maven.compile.src.set" refid="generated.src"/>

</preGoal>

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 4 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

</project>

Polish the build

You also need to create a master project whose sole purpose is to triggermultiproject builds. You do so as follows:

1. Create a maven.xml script file in metrics-master

2. Declare convenient custom goals:

<project xmlns:j="jelly:core"><goal name="metrics:site" prereqs="clean,multiproject:site" /><goal name="metrics:build">

<j:set var="goal" value="clean,jar:install"/><attainGoal name="multiproject:goal"/>

</goal></project>

To build the whole thing, open a shell and run the following command: mavenmetrics:build.

Figure 1 describes in a UML-like notation the project structure you have created sofar.

Figure 1. Metrics project's structure and dependencies

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 29

Page 6: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

You can now begin coding the core classes (you may also find it easier to get thesources for the projects described so far from the os-maveneclsrc.zip file).

Reconcile Maven with Eclipse

It's no secret that you can't get any productivity from Notepad, and today's projectsare far too complex to avoid using an IDE. So, the problem is simple: How do youreconcile Maven and the IDE? And how do you code and develop within Eclipse andbuild with Maven?

Eclipse has its own project representation, so you need a bridge to translate Mavenmetadata into a form Eclipse can comprehend. Fortunately, Maven comes out the

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 6 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

box with a plug-in, maven-eclipse-plugin, that lets you automatically generateEclipse project files from the POM (see Resources).

Import projects into Eclipse

Depending on the information in the POM, maven-eclipse-plugin creates the.classpath file with source directory and test source directory entries, dependenciesand dependent project entries, and output directory entries. It even adds zip sourceattachments whenever possible. Follow these steps:

1. To specify that the metrics-model dependency in metrics-core isbound to an Eclipse project, add the following property to themetrics-model dependency:

<properties><eclipse.dependency>true</eclipse.dependency>

</properties>

2. To generate a .classpath file for every subproject, run the followingcommand from metrics-master:

maven -Dgoal=eclipse:generate-classpath multiproject:goal

Import the projects into Eclipse before you begin coding, as follows:

1. Launch Eclipse

2. Browse to File > Import

3. Select Existing Project into workspace and click Next

4. In the root directory text box, input the parent folder of metrics-master

5. Click Select All, then click Finish

Last bits of configuration

At this point, your projects won't compile. maven-eclipse-plugin generates.classpath using a special classpath variable, MAVEN_REPO, pointing to the localMaven repository where all dependencies are locally stored, thus allowing better

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 29

Page 8: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

cooperative development. You need to declare it as follows:

1. Open the Preferences window

2. Go to the Classpath Variables page, located under the Java > Build Pathnode

3. Click New

4. Set the name to MAVEN_REPO and the value to the location of your localMaven repository (see Figure 2)Figure 2. Adding MAVEN_REPO in the Classpath Variables window

You're now ready to start coding.

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 8 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Multiproject concerns

As you've seen previously, Maven is useful when you're dealing with complexprojects involving many subprojects. If you look more closely at the recommendedMaven multiproject layout, you'll notice that it's structured in a hierarchical way: Theroot of the structure contains shared metadata, such as the parent POM, sharedproperties, and common goal definitions. In some way, this structure looks similar toan Eclipse workspace, which includes a top-level ..metadata folder containing theconfiguration of the current workspace.

However, Eclipse workspace metadata isn't intended to be manually edited by theuser, whereas you should be able to add and manually edit Maven metadata (andeventually add folders to structure it). You can't import the Maven project root as anEclipse project because it would overlap with existing subprojects, and Eclipsedoesn't yet support overlapping projects.

About non-Eclipse-friendly projects

A natural conflict exists between the typical Maven project layout (hierarchicallystructured, with the parent files at the root of the hierarchy) and the Eclipse projectstructure. That's why the only practical way to make Maven and Eclipse collaboratesmoothly is to flatten the hierarchy so shared metadata is contained in a subproject.

But that's not always possible. For instance, suppose you check out a project that ishierarchically structured and that you have no control over. How will you makeEclipse play nicely with the project? In such cases, a few workarounds -- each withits own drawbacks -- let you deal with the issue:

• Use one big Eclipse project -- The main disadvantage is a loss ofdependency visibility; you're almost unable to tell which module dependson which libraries. This also promotes cycles that increase entropy morequickly and makes maintenance more difficult.

• Edit root files outside of Eclipse -- This is the safest workaroundpresented here. However, this solution isn't convenient because itrequires switching between tools and is also error-prone.

• Create a virtual project that only contains links to root files andfolders -- Although convenient, this solution has two disadvantages: Itdoesn't support variable expansion (and, thus, is troublesome in a teamenvironment), and it must be manually configured.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 29

Page 10: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

These are just tips, not recommendations. Whenever possible, you should avoidthem. Eventually, you should try to refactor your build instead of relying onworkarounds that will make things harder.

Section 3. Integrating Maven into Eclipse

Rationale

Even though Maven is a powerful tool by itself, it needs to be integrated into themost popular IDEs. Doing so simplifies the use of Maven, reduces its learning curve,and drastically increases productivity. For instance, some important and desirablefeatures include the ability to selectively synchronize metadata of the IDE andMaven, and to completely embed Maven by being able to run it from within the IDE.

Eclipse, as a language-neutral general tool and application integration platform, fitsthese needs perfectly. However, a smooth integration is also about collaboration, asdiscussed in "Exploiting Maven in Eclipse." At first glance, you may think that thesetools overlap in the build area. Even experienced Java developers and architectsdon't always consider them complementary, which is natural because they don'ttarget the same phase of the build process. However, this conflict only appears to bethe case.

An ideal plug-in should try to close this gap by acting as a bridge between Mavenand Eclipse, thus enabling bidirectional information flow and making developmentmore fluid.

Mevenide overview

Mevenide is a first step in that direction. Mevenide is a project hosted at theCodehaus (see Resources) that aims to make the Maven user's life easier bybringing Maven's power close to hand and providing a consistent set of tools, thushiding complexity and letting you get started rapidly with Maven. Mevenide hassupported multiple IDEs from the beginning, including Eclipse. A few Eclipseplug-ins with similar goals exist, but Mevenide is the most ambitious and mostmature.

In this section, you'll create an Eclipse plug-in from the JavaNCSS wrapper you

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 10 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

created previously. To keep the later artifact as generic as possible, you'll leave ituntouched and add a few new Plug-in Development Environment (PDE)-orientedprojects.

Install Mevenide

Before you use Mevenide, you must install and configure it. Mevenide is distributedthrough the standard Eclipse update mechanism. If you're not familiar with it, you'llfind that this mechanism makes software updates easy and straightforward. Itrevolves around the concept of features: sets of correlated individual plug-ins. Afeature is generally defined in the context of a site, which you can view as arepository of features.

To install Mevenide, follow these steps:

1. Browse to Help > Software Updates > Find & Install

2. Select Search for new features to install

3. Define a New Remote Site pointing tohttp://mevenide.codehaus.org/release/eclipse/update

4. Click Finish

At this point, Eclipse searches for features declared in the update site. When it'sfinished, you're asked which features to install. Select Maven 1.0.2 and Mevenide0.3.1, as shown in Figure 3, and click Finish.

Figure 3. Choosing the appropriate features in the Updates window

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 29

Page 12: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Although Mevenide features aren't signed, you can safely install them. After that, youmust restart the platform.

A few more steps are required to correctly configure Mevenide:

1. In the Preferences window, find the new entry for Maven

2. Locate the Locations page under this entry, and set the values accordingto your configuration

Default proposed values are retrieved from the user preferences defined in~/build.properties and Maven defaults. You might first object that these values seemto be duplicated. However, they're required because Mevenide doesn't launch

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 12 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Maven through the shell script. Instead, it spawns a new Virtual Machine (VM)process. This lets you easily take advantage of Eclipse features, such as traceredirection and automatic coloring, and associate different values with differentworkspaces.

Project creation options

If you've followed every step described in this tutorial, you should have a projectstructure similar to this one:

+- metrics-commons|_ project.properties|_ project.xml

+- metrics-core|_ project.xml

+- metrics-master|_ maven.xml|_ project.properties|_ project.xml

+- metrics-model|_ maven.xml|_ project.properties|_ project.xml

If not, you can catch up by using the sources available in the os-maveneclsrc.zip file.

It's time to create the Eclipse plug-in that uses the JavaNCSS wrapper exposed bymetrics-core. When you're creating a new Maven project inside Eclipse, youhave two options: use the Java Project Wizard, then Mavenize the newly createdproject, or use the Maven Project Wizard, and optionally specify a POM template.

if the project doesn't yet exist, the second option is the simplest way to get started.However, the latest Eclipse versions introduce incompatibilities, and the MavenProject Wizard is partly broken at the time I'm writing this tutorial.

Using templates to promote uniformity

In a corporate environment where elements such as company information, siteinformation, and repository locations are predefined and invariant, templates are animportant piece in the software development puzzle because they promotefactorization and uniformity. A template as intended here is a POM that can be usedas a base when creating other POMs. So, create a new file in metrics-commonscalled pom-template.xml, which defines the following element:

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 29

Page 14: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

<project><extend>../metrics-commons/project.xml</extend><pomVersion>3</pomVersion><artifactId>metrics-template</artifactId><name>dw-metrics template</name><groupId>dw-metrics</groupId>

</project>

then, add a template definition. POM templates can be defined under the MavenPreferences window:

1. Launch the Preferences window

2. Open the Templates preference page, located under the Maven node

3. Click Add template

4. Browse and select pom-template.xml (see Figure 4)Figure 4. Adding a new Maven POM template to be used later

5. Click Finish

The template is now available in Mevenide wizards.

Create a new POM file

Create a new Java project, and call it metrics-ui. Then, create a new POM usingthe POM Wizard:

1. Browse to File > New > Other

2. Expand the Maven group, and select Project Object Model

This option pops up a wizard that lets you specify basic project identificationelements. Set the name, artifactId, and version elements to Metrics UI,metrics-ui, and 1.0, respectively. Set groupId to dw-metrics to work arounda known issue (it can be left empty because it will be inherited, but you can safelyleave it as is). You're now ready to develop the plug-in as a dw-metricssubproject.

Overview of the Metrics plug-in

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 14 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

In the context of this didactic example, the plug-in you're creating won't be tooambitious and, thus, will remain simple. Here are few related use cases:

• Generate metrics for any Eclipse IContainer

• Generate metrics for any Java file

• Display the metrics

Those use cases are trivial. Suffice to say that the plug-in contributes to the contextmenus of the aforementioned elements and that the results are displayed in adedicated view.

You've probably noticed that the plugin project isn't yet a real plug-in projectbecause it doesn't have the PDE nature. In this case, you won't take the usual PDEpath. Instead, you'll use the MEP plug-in, maven-eclipse-plugin-plugin (seeResources), which lets you build Eclipse artifacts -- plug-ins, features, and sites. Themaven-eclipse-plugin-plugin Maven plug-in aims to simplify themanagement of Eclipse plug-in artifacts' interdependency.

Building Eclipse plug-ins with Maven

When you're developing Eclipse plug-ins with Maven, you face a troublesome issue:The plug-in descriptor (plugin.xml) and the project descriptor (project.xml) containduplicate information. For instance, required libraries are declared in both files,under the runtime and dependencies elements, respectively. And although it's ina slightly different form, identification information (such as version and name) is alsopresent in both files. You need a tool to make overall maintenance easier andprevent information from being duplicated and scattered. From the Maven point ofview, the solution is simple: You can use the POM as an authoritative metadatasource.

for that purpose, you'll rely on a plug-in descriptor template that mainly contains theplug-in contributions. At build time, the MEP plug-in generates the definitive plug-indescriptor, updating the plug-in version with the current project version and addingthe required dependencies, as declared in the POM.

Once the plug-in descriptor has been generated, unless the dependencies or theplug-in template have changed, you can safely develop as usual, using Eclipse's fastincremental compilation and debugging facilities, such as source stepping and hotreplace. The proposed method provides more flexibility and makes maintenanceeasier without adding any complexity in the development cycle.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 29

Page 16: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Section 4. Using Maven to build Eclipse plug-ins

Prepare the plug-in project

You'll now create the template processed by the MEP plug-in. The MEP plug-inexpects this template to be located in a special directory referenced in theproject.properties:

1. Create a new source folder with the path src/eclipse/resources

2. Add the following line to metrics-commons/project.properties:maven.eclipse.plugin.src.dir=${basedir}/src/eclipse/resourcesThis instructs the MEP plug-in to look in this directory for the plugin.xmltemplate.

3. Create a plugin.xml file inside this folder, with the following identificationinformation:

<?eclipse version="3.0"?><pluginid="@maven.eclipse.plugin.artifact.id@"

name="Metrics UI"version="@maven.eclipse.plugin.artifact.version@"

provider-name="The Codehaus"class="org.codehaus.metrics.ui.MetricsPlugin">

<runtime><library

name="@maven.eclipse.plugin.artifact.internal.id@[email protected].\[email protected]">

<export name="*"/><packages

prefixes="org.codehaus.metrics.ui"/></library>

</runtime>[...]

</plugin>

Take special care with the id and version elements, as well as thename attribute of the library element. At build time, the MEP plug-inreplaces them with their respective values extracted from the projectmetadata, thus keeping the plug-in and the project descriptorssynchronized.

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 16 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Also notice that the runtime section remains simple. It's populated atbuild time with POM dependencies. However, the requires section can'tyet be generated. So, you still need to declare the imports. This feature iscruelly missing from the MEP plug-in. Making it even worse, you alsohave to add the imports to the POM (as you'll see later).

4. Add the requires section:

<requires><import plugin="org.eclipse.jface"/><!-- add swt, resources, runtime, and workbench as well -->

</requires>

Declare the plug-in contributions

The plugin.xml template holds plug-in contributions as usual. You need to declarethe three contributions described previously. Toward that end, you can use theplug-in descriptor multipart editor or manually edit the file, depending on yourpreference:

<extension point="org.eclipse.ui.popupMenus"><objectContribution

adaptable="true"objectClass="org.eclipse.core.resources.IContainer"id="org.codehaus.metrics.container">

<menu label="%Metrics.Generate"path="additions"id="metrics.menu">

<separator name="MetricsType" /></menu><action enablesFor="1"

label="%Metrics.AllMetrics"class="org.codehaus.metrics.ui.actions.AllMetricsAction"menubarPath="metrics.menu/MetricsType" id="metrics.container" />

</objectContribution><!--

add another objectContribution for *.java IFiles :- declare it adaptable- set nameFilter to *.java

--></extension><extension point="org.eclipse.ui.views">

<category name="Metrics" id="org.codehaus.metrics.views" /><view name="Metrics Report View" category="org.codehaus.metrics.views"

class="org.codehaus.metrics.ui.views.MetricsReportView"id="org.codehaus.metrics.view.report" />

</extension>

You're almost ready to begin coding the plug-in. But first, you need to configure itsbuild.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 29

Page 18: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Declare the project's dependencies

An Eclipse plug-in often depends on several other plug-ins, including core Eclipseplug-ins. In particular, the plug-in under development depends on the followingplug-ins: resources, runtime, workbench, jface, and swt. For each of thosedependencies, you have to add an entry to the POM dependencies section.Mevenide provides a multipart editor to help you edit POM files. Follow these stepsto add the jface dependency to the POM:

1. Open project.xml with the Project Object Model Editor

2. Select the Dependencies page (see Figure 5)Figure 5. The Mevenide POM editor lets you edit projectdependencies

3. Click the Add button

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 18 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

4. Fill the groupId, artifactId, and version fields with these values,respectively: eclipse, jface, 3.1.0.

5. Click Finish

The actual file is updated only when you save it. Repeat these steps for the otherEclipse dependencies listed earlier. You can also manually edit the file in the Sourcepage of the editor. (If you're comfortable enough with the POM structure, you mightfind it easier not to use the editor.)

Eclipse dependencies issue

When building the project, Maven tries to download the dependencies and add themto the classpath. But unless you've set an internal repository, Maven can't find thejust-added JARs because most of them aren't in the default Maven remoterepository. You might want to install them manually into your local repository, but thisis a tedious operation -- and whenever a new version of Eclipse is released, you'llhave to repeat it.

A better solution is to use Maven's JAR override feature. To override the jfacedependency, add the following lines to project.properties:

maven.jar.override = onmaven.jar.jface = ${eclipse.home}/org.eclipse.jface_3.1.0/jface.jar# override other eclipse dependencies

You also need to declare that metrics-ui depends on metrics-core:

1. Add a new POM dependency for metrics-core, as shown earlier, andselect it

2. Click the Add button next to the Properties table

3. Double-click the newly added item in the Properties table. Doing so popsup the standard Properties view (see Figure 6).Figure 6. Setting metrics-code dependency properties

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 29

Page 20: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

4. Set name to eclipse.dependency and value to true

5. Add another property, eclipse.plugin.bundle and set its value totrue

6. Don't forget to save the file

As you saw earlier, the first property is used by maven-eclipse-plugin when it'sgenerating Eclipse ..classpath and is also reused by Mevenide when synchronizingthe POM and ..classpath files. It lets you declare a dependency as being bound toan Eclipse project.

The second property instructs the MEP plug-in to treat the dependency as a plug-inlibrary. The dependency is then included in the distribution, and an entry is added tothe runtime section of the plug-in descriptor.

Your POM should now contain a new dependency entry like this one:

<dependency><groupId>dw-metrics</groupId><artifactId>metrics-core</artifactId><version>1.0</version><type>jar</type><properties>

<eclipse.dependency>true</eclipse.dependency><eclipse.plugin.bundle>true</eclipse.plugin.bundle>

</properties></dependency>

Synchronize the Eclipse classpath

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 20 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Your build is almost Mavenized. All that's left is to synchronize Eclipse and Mavenmetadata, and add a custom goal to build the whole plug-in at once, including allsubprojects.

To synchronize the Eclipse project with the POM, right-click the project node orproject.xml and select Maven > Synchronize. This option opens the Mevenidesynchronization view. If you opened the view through project.xml, only the selectedPOM is compared to the current Eclipse project configuration. Otherwise, Mevenidescans the primary POM and all of its ancestors.

The synchronization view presents the differences between .classpath and structuralinformation (dependencies and source, resource, and target folders) contained in thePOM file (see Figure 7). They're classified as incoming and outgoing differences.while working in incoming mode, the view only displays elements declared in thePOM, but not in .classpath, and vice versa. You can modify both files on the fly byright-clicking any node.

Figure 7. Eclipse classpath synchronization window

In this case, you want to update the .classpath:

1. Right-click the metrics-ui project node

2. Select Menu > Synchronize

3. Select Incoming mode

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 29

Page 22: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

4. For each library and folder node, bring up the contextual menu andchoose Add to .classpath

Your Eclipse project is now correctly configured, and you can safely begin codingthe plug-in. If you prefer, you can also import the sources in the os-maveneclsrc.zipfile.

Build the JavaNCSS plug-in

Last, you need to create a goal in the metrics-master project to build the wholeplug-in:

<goal name="metrics:eclipse" prereqs="clean"><j:set var="goal"

value="clean,eclipse-plugin:create-artifact-dist"/><j:set var="maven.multiproject.includes"

value="metrics-ui/project.xml"/><attainGoal name="multiproject:goal"/>

</goal>

This example uses the multiproject semantic to easily evolve toward a more complexproject composed of various Eclipse plug-ins. The code builds two Eclipse plug-ins;metrics-core is also a plug-in, which doesn't contribute to the platform, but doesexpose the artifact.

Of course, for this to work, you also need to add the MEP plug-in as a dependencyin the master project, since it's the provider ofeclipse-plugin:create-artifact-dist:

<dependency><groupId>mevenide</groupId><artifactId>maven-eclipse-plugin-plugin</artifactId><version>0.3.3</version><type>plugin</type>

</dependency>

Run Maven

When your project is configured, you can run Maven to build it. Mevenide integratesa Maven Runner available through the External Tools standard interface. Goals torun, as well as VM parameters and Maven options, are passed through the Runnerwindow, which you open via the metrics-master contextual menu:

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 22 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

1. Right-click the metrics-master project

2. Select Maven > Run Maven to open the Maven Runner window (seeFigure 8)Figure 8. Maven Runner window

The window is initialized with convenient default values, such asbasedir, default goal, and name; basedir defaults to the location ofthe current project, and the goal section is initialized with test. Thewindow only presents options relevant in this context (for instance, itdoesn't propose the -f option), and the table allows you to input VMparameters as key/value pairs.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 29

Page 24: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

3. You can manually edit the Goal textbox or click the Choose button tochoose from the list of all available goals (defined in plug-in or local toyour project). Set the Goal value to metrics:eclipse (see Figure 9).Figure 9. Goal choice window

4. Click Run

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 24 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

The goal you wrote earlier now executes. The execution output is displayed in thestandard Eclipse console. Maven doesn't use the Maven shell script, but insteadspawns a new VM; so, you benefit from automatic coloring that helps you quicklydistinguish the various streams (err, out, in).

Test your plug-in

After the project has been built, refresh the workspace -- if you haven't enabledAutomatic Refresh in the Runner configuration window -- and launch a new run-timeworkspace to exercise your freshly created plug-in. Figure 10 shows the result ofyour work.

Figure 10. The resulting plug-in in action

Section 5. Summary

In this tutorial, you've seen how to build with Maven while developing under Eclipse.Using Mevenide, you created a complex Maven project comprising severalsubprojects and learned how to overcome the apparent conflicts between thestructure of Eclipse projects and Maven's recommended layout. With the POM editorand the Runner, you quickly created Maven-enabled projects and built them fromwithin Eclipse, without relying on the shell console.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 29

Page 26: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

However, you haven't taken a complete tour of Mevenide's features. See theMevenide Web site for a thorough presentation of the capabilities of Mevenide andmaven-eclipse-plugin-plugin. In particular,maven-eclipse-plugin-plugin can generate Eclipse feature and site artifactsthat are ready to be deployed.

Although maven-eclipse-plugin-plugin is flexible, this flexibility can be adrawback: It might sometimes add unneeded complexity if it isn't used correctly.That's why this plug-in is being rewritten with simplicity in mind -- meaning, forinstance, the ability to avoid declaring Eclipse dependencies in the POM, focusingespecially on Eclipse versions greater than 3.1M6. This Eclipse version introducesthe single JAR'd plug-in, which is a closer representation of a Maven artifact than theprevious folder view and will help to further integrate both tools.

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 26 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Downloads

Description Name Size Download method

Source code os-maveneclsrc.zip8MB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 29

Page 28: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

Resources

Learn

• Maven provides many references and lots of information about getting started. Italso presents some best practices.

• Eclipse hosts the Eclipse platform project, as well as other technology projects.

• "Exploiting Maven in Eclipse" compares Maven to other technologies andexplains how you can make Maven and Eclipse collaborate.

• Check out the "Recommended Eclipse reading list."

• Browse all the Eclipse content on developerWorks.

• New to Eclipse? Read the developerWorks article "Get started with EclipsePlatform" to learn its origin and architecture, and how to extend Eclipse withplug-ins.

• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse projectresources.

• To listen to interesting interviews and discussions for software developers, checkout check out developerWorks podcasts.

• For an introduction to the Eclipse platform, see "Getting started with the EclipsePlatform."

• Stay current with developerWorks' Technical events and webcasts.

• Watch and learn about IBM and open source technologies and product functionswith the no-cost developerWorks On demand demos.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologies anduse them with IBM's products.

Get products and technologies

• Download the Mevenide Eclipse plug-in and other related Maven plug-ins fromthe Mevenide Codehaus Web site.

• Get JavaNCSS from the JavaNCSS Web site. The site also provides morein-depth explanation of the metrics generated.

• Download modello sources from the modello repository, hosted at the Codehaus.

developerWorks® ibm.com/developerWorks

When Maven encounters EclipsePage 28 of 29 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: When Maven encounters Eclipse - IBM Software · PDF fileMaven's features via Eclipse, through the creation of an Eclipse JavaNCSS plug-in --from the initial planning to the final build

• The maven-eclipse-plugin provides the ability to generate Eclipse project files.

• The maven-eclipse-plugin-plugin aims to simplify management of Eclipse plug-inartifacts interdependency, and generates Eclipse plug-ins, features, and sites.

• Check out the latest Eclipse technology downloads at IBM alphaWorks.

• Download Eclipse Platform and other projects from the Eclipse Foundation.

• Download IBM product evaluation versions, and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• The Eclipse Platform newsgroups should be your first stop to discuss questionsregarding Eclipse. (Selecting this will launch your default Usenet news readerapplication and open eclipse.platform.)

• The Eclipse newsgroups has many resources for people interested in using andextending Eclipse.

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Gilles DodinetGilles Dodinet has worked for several years as a Java™ 2 Platform, Enterprise Edition(J2EE) consultant. Since 2004, he has worked on a .NET component-assembling toolas an R&D engineer for KarmicSoft. He's an experienced Eclipse developer and aMevenide committer.

ibm.com/developerWorks developerWorks®

When Maven encounters Eclipse© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 29