12.07.2015 Views

Download - NetBeans

Download - NetBeans

Download - NetBeans

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>NetBeans</strong>PlatformMavenDevelopment with2Creating a Module Suitewith Apache Maven andMevenide – from basicPlatform API features toJavaHelp support andbrandingEmilian Bold


<strong>NetBeans</strong> Platform Development with Maven 2Apache Maven, you allknow, is widely used as abuild system and for manyother activities. A greatthing about Maven is thatits “build script” is actually no script atall but a completely declarative configurationfile called a POM (Project ObjectModel). Maven’s design will look familiarto <strong>NetBeans</strong> Platform developers: it’s basicallyconstructed from a core “platform”supporting versioned plugins that can beautomatically downloaded from a centralrepository.This article will show that <strong>NetBeans</strong> isstarting to have excellent Maven support,and how to use this as an alternative tothe IDE’s built-in Ant integration – for everyaspect of <strong>NetBeans</strong> Platform development.We start from simple issues likedependency declaration and go allthe way to the building of modulesuites, branding, and help moduleconstruction.Meet Mevenide<strong>NetBeans</strong> does not yetsupport Maven 2 projectsout of the box.Luckily though, we have Mevenide, a certified <strong>NetBeans</strong> pluginthat provides extensive Maven integration. You can use existingMaven projects directly from the IDE as Mevenide provides executionand debugging support, auto-completion for many Mavenspecificfiles, and more. All projects created with Mevenide willbe standard Maven 2 projects that can also be built with the command-linemvn command.But if your projects will be standard Maven 2 projects, there’snothing actually forcing you to use the <strong>NetBeans</strong> IDE; so what’sto gain as a Platform developer? Well, by standardizing on Maven,members of your team could use different IDEs or even plain texteditors to do the development. In particular, you can build Net-Beans Platform applications with whatever tools you prefer.The downside to using Mevenide and Maven 2 projects is that,while you do get independence from the IDE and an arguably betterbuild system than Ant, you lose some IDE integration. Forexample, some of the wizards are gone regardless of the projecttype. For Platform development in particular, you’ll have to handeditsome of the properties or XML files (the layer.xml file beingthe prime candidate). In some cases the loss of integration ispartial; for example, the form editor will work but you won’t beable to edit the layer using drag and drop.CAll that said, keep an eye on the update center as the missing wizards areslowly coming to Maven-based projects.Mevenide can be easily installed by selecting Tools|Plugin,choosing “Maven” from the list of plugins (see Figure 1), andgoing through the normal installation steps.A 1mojo.codehaus.org/nbm-maven-plugin/descriptor.htmlSample NBMMaven PlugindescriptorsAFigure 1.The Pluginswindow aftermanual selectionIssue 4 N 39


Module DevelopmentAFigure 2.Selecting aMaven ArchetypeThe first moduleLet’s start creating a Maven-based <strong>NetBeans</strong> module. The firststeps are the same for any Maven project: select File>New Project,open the Maven category and choose Maven Project. We’ll usethe Quickstart Archetype (see Figure 2) for this module.CAn Archetype is basically a project generator in the Maven world. It produces theinitial folder layout and the files to build upon.In the final step, we define the Group Id, Artifact Id, and Version,as well as the project name (see Figure 3). These piecesof information together identify each artifact generated andmanipulated by Maven (including the project itself), and will go intothe project’s POM. The Group Id is basically a namespace – it’scommon practice to use company, domain or application namesA 2here. The Artifact Id is the name for thisparticular module. The Version is used forexample for configuration management.As a result, we have a new project in Net-Beans, shown as “tutorial (jar)”. You willalso notice a package under the SourcePackages node and another under TestPackages (see Figure 4). Additionally,you’ll have a simple example class and atest, JUnit as a test library (a dependency),and the pom.xml file under Project Files.The first strange thing you’ll notice ifyou’ve never used Maven before is thatthe project seems to have some errors.The reason in this case is that Mavendoesn’t come by default with JUnit. JUnitis treated like any other dependencyand will need to be downloaded from arepository. Maven takes care of this andany all other dependencies the first timeyou build the project. It will download theneeded artifacts and cache them locally(the default repository being repo1.maven.org).AFigure 3.Artifact id, Groupid and VersiondefinitionA 3The POMLet’s now open the Project Files/pom.xmlfile, through which you can control all aspectsof the project. Changes in the POMwill be reflected in the project in the IDE.For example, by changing the element and saving the file, you’ll noticethat the name of the project changes.Next we need to change the element (whose value isshown in parentheses to the right of theproject name). That’s because, of course,a <strong>NetBeans</strong> module isn’t distributed as asimple JAR file but as a NBM. So changethe packaging to nbm and try to build theproject. You’ll see that it fails miserably.40 N <strong>NetBeans</strong> Magazine


<strong>NetBeans</strong> Platform Development with Maven 2The reason is that no default Maven pluginknows how to handle the nbm packaging.We need to add the nbm-maven-plugin(which I’ll call “NBM Plugin” from now on)inside the element in the POM.See Listing 1.Now the project will build successfully.After the build, switch to the Files tab andyou’ll notice in the target folder all the extraartifacts, including the generated NBMfile (see Figure 5). At this point we havea working module project; by clicking Runyou’ll get a new IDE running, which shouldinclude our module among many others.CYou might get errors related to Windows pathswhile trying to run the project. Make sure you don’thave spaces in these paths, as these are usuallythe culprits.A 4tion class. It also changes the layer file and adds thecorresponding dependency to the POM.At this point, any build using Platform APIs will fail,as the Maven project doesn’t have a dependency onthe needed Platform-specific artifacts. First we needto declare the repository where the <strong>NetBeans</strong> artifactsare located; see Listing 2. Next we include adependency on org-openide-util, which is the moduleproviding the Platform’s Actions API. See Listing 3.This is equivalent to a dependency added to a normalPlatform module. The NBM Plugin will detect that this artifactis a module and configure the proper dependency in the generatedbuild artifact. As before, the project won’t initially compilewithout the dependency; this will be resolved when the files aredownloaded on the first build.CRegarding Listing 3, if the version RELEASE60 doesn’t work for you, tryRELEASE60-BETA2 as the new bits might not yet have reached the Mavenrepository when you read this.BListing 1. Build configuration for the NBM Plugin...org.codehaus.mojonbm-maven-pluginRELEASEtrue...AFigure 4.New Maven project,with errors that willbe solved with thefirst buildAdding an ActionWe will now create a newPlatform Action using theNew Action wizard. Thepurpose of this Action willbe just to inspect that agiven service exists andshow a dialog. The wizardautomatically generatesthe Bundle.properties filein the proper Maven-friendlyfolder, as well as the Ac-BListing 2. Declaring a default repository for <strong>NetBeans</strong> artifacts...netbeansRepository for hosting <strong>NetBeans</strong> API artifactshttp://deadlock.netbeans.org/maven2/truefalseIssue 4 N 41


Module DevelopmentBleeding edge<strong>NetBeans</strong> APIdocsbits.netbeans.org/dev/javadocNow right click on the project node and create an Action withdefault options. Upon building the project, you might get a warningabout Java sources being 1.4 due to some @Override annotationswhich are 1.5 specific. You can just delete the annotations.CAll the basic Platform modules have the groupId org.netbeans.api and theJAR name as the artifactId. If you don’t know the groupId/artifactId for a module,you can try finding it in the repository at http://deadlock.netbeans.org/maven2.Other <strong>NetBeans</strong>Platform specific settingsSo far our module does little to interact with the <strong>NetBeans</strong> Platform.Sure, by adding a dependency on org-openide-util we can alreadyuse the lookup service for example, but we can’t yet declarea service in the global lookup.The standard <strong>NetBeans</strong> way in this case is to place a textfile under META-INF/services. Luckily this is almost the sameunder Maven, with a twist: while the Java source files sit undersrc/main/java, all resources must be under src/main/resources.Cof the file under META-INF/services arethe same as usual. Respectively: theservice base class or interface; and thefully qualified name of the implementingclasses, each in its own line.The layer fileNow, in order to have menu items ortoolbars we need a layer file. The necessaryconfiguration task is letting thebuild plugin know which is your layer file.In order to do this, you need to create aplugin configuration file (an NBM descriptor),which defines the module metadatayou’d expect: cluster name, module type,update center URL, codebase, manifest,resources folder). In the new folder, cre-This Maven-specific separation of resource files from Java source files means ate a file called module.xml with contentsextra work if you plan to migrate an existing project to Maven. You’ll have to similar to Listing 4.write a script that splits the files that were together in the older project (or doit by hand).BListing 3. Adding openide-util as a dependencyetc.First, create the src/main/nbm folder.This is where you’ll put the descriptor asa special configuration file (and not in theThe resources folder may be createdoutside the IDE, or inside it from the Filestab (under src/main). It will also be automaticallycreated by the Actions wizard.After this, you should see anothernode in the Projects window called OtherSources, containing your resource files(see Figure 6).CThe resources folder onlyholds resources that belong tothe artifact. It does not containfor example the POM file orother Maven configuration files.The contents and name......org.netbeans.apiorg-openide-utilRELEASE60...BListing 4. NBM Plugin descriptor file: module.xmlnormalro.emilianbold.nbmagazine.tutorial/1nbmagazinesrc/main/nbm/manifest.mfhttp://emilianbold.ro/nbmagazine/GNU GPL 3src/main/nbm/license.txt42 N <strong>NetBeans</strong> Magazine


<strong>NetBeans</strong> Platform Development with Maven 2EThe NBM descriptor is capable of holdinga lot more data. Please see the NBM Plugindocumentation for the full schema.A5AFigure 5.NBM artifact intarget folderNext we have to edit the manifest fileand declare the layer in the OpenIDE-Module-Layer section. While the NBMPlugin lets you declare some modulemetadata, it currently supports only themanifest file but not the layer. Thus, thesrc/main/nbm/MANIFEST.MF file definedin module.xml should be created with thisline content (in a single line):OpenIDE-Module-Layer:ro/emilianbold/nbmagazine/tutorial/layer.xmlWe know that anything that isn’t a Javasource class must be placed in the resourcesfolder; the layer file is no exceptionas it will also be part of the final buildartifact. Now it’s time to rebuild and re-runthe project. You’ll be happy to notice thatthe layer is properly registered, that ourAction is working, and also that we candeclare services in META-INF/services.With the configuration done so far, themanifest, layer and NBM descriptor files,plus some dependencies, we have coveredabout 90% of the Platform developmentcases. Next we’ll talk about Java-Help modules, branding and suites, whichshould bring us to 100%.Help modulesThe <strong>NetBeans</strong> Platformhas excellent Java-Help support viaNetBean’s standardbuild harness; theNBM Plugin alsosupportsbuildingBListing 6. helpset.xmlmodules with JavaHelp documentation.First, you’ll need a new empty Maven project configured like theprevious one (but without the Action), containing a NBM descriptorand an empty layer file. I’ll assume “ro.emilianbold.nbmagazine.tutorial” as groupId and “help” as artifactId. Also, the layer mustdeclare the reference to the JavaHelp docs (see Listing 5).The helpset.xml file (see Listing 6) just contains a reference tothe location of the helpset configuration. The reason for doingthis is that the documentation won’t actually be in the main JARartifact but in a separate JAR (the kind of JAR you see in the docsfolder in the cluster).Now we get to the actual JavaHelp files. First we need to create anew folder: src/main/javahelp/${groupId}/${artifactId}/docs (withour groupId/artifactId, that would be src/main/javahelp/ro/emil-BListing 5. layer.xmlmevenide.codehaus.org/m2-site/index.htmlMevenide<strong>NetBeans</strong>integrationmodulesIssue 4 N 43


Module DevelopmentAFigure 6.Other SourcesnodeA6ianbold/nbmagazine/tutorial/help/docs.) Then createthe various JavaHelp files (see Listing 7). Compile andrun the project, and you’ll see that the help works (seeFigure 7).COK, remember you shouldn’t copy-and-paste? This is exactlywhat I did to bootstrap this module and get the JavaHelp files. Afteryou obtain the base files, you just need to add the new HTML filesand entries to the map.BListing 7. JavaHelp filesMap (map.xml)Table of contents (toc.xml)...Index (idx.xml)...Helpset (hs.xml)...HelpaboutTOCTable of Contentsjavax.help.TOCViewtoc.xmlIndexIndexjavax.help.IndexViewidx.xmlSearchSearchjavax.help.SearchViewJavaHelpSearchLibrary wrappersSo far we’ve seen how to declare a normal moduleand add dependencies. However,a module may also “wrap”an existing JAR and export partor all of its packages. Let’s seehow to do this.Adding a dependency to a thirdpartyJAR can be done the normalMaven 2 way (see Listing 8). Youjust need to remember to have arepository declared in the POMif the JAR is not in the standardrepository.The NBM Plugin will automaticallyadd the JAR to the NBM, but therewill be no public packages so far, soit can only be used internally. Sadly,the public packages will have to bemanually added to the manifest (seeListing 9), which is quite painful butshould be a one-time job.Remember that the manifest file isquite finicky with line lengths, so youmight need to break it into multiplelines (each one starting with a singlespace).ENormally leaving an empty OpenIDE-Module-Public-Packages means that44 N <strong>NetBeans</strong> Magazine


<strong>NetBeans</strong> Platform Development with Maven 2all packages will be public. Note that thoughthis is good for normal modules, it won’t workfor library wrappers.The module suiteWe’ve already seen how to create individualmodules, module wrappers anddocumentation modules, but we still needto put them somehow in a suite. The solutionis to rely on Maven again and use anaggregating project. This must have thePOM packaging and list each of the containedsub-modules (see Listing 10).While the NBM Plugin is able to generatethe whole suite cluster with the clustergoal, you still have to configure it to runduring the build project (see Listing 11).Note that the elements pointto the actual disk folders, as opposed tothe normal way of using groupId:artifactId:version for dependencies.In the configuration file in Listing 11,I first register the NBM Plugin as a buildplugin extension. Then I define the enabledclusters, as well as the brandingToken(needed for branding) and keystorealias.All this information is used by the clustergoal, which is responsible for generatingthe Platform-compatible cluster. Next,with the element, I registerthe plugin to run during the build andexecute the cluster goal.This way, the plugin will run each timeI build the aggregating project and generatethe proper cluster. You can run theapplication now and notice that it’s quitesimple (it only uses the Platform cluster),has the help working, and even our littleAction which uses the Lookup serviceworks (see Figure 8).BListing 8. A non-NBM (plain JAR) dependency...net.java.dev.swing-layoutswing-layout1.0...BListing 9. MANIFEST.MF for holding the public packagesManifest-Version: 1.0...OpenIDE-Module-Public-Packages: org.jdesktop.layout.*...BListing 10. Aggregating project4.0.0ro.emilianbold.nbmagazinesuitepom1.0-SNAPSHOTsuite../help../tutorial...BListing 11. NBM Plugin configuration...org.codehaus.mojonbm-maven-pluginLATESTtruefalsenbmagazinenbmagazineplatform7nbmagazineclusterprocess-resourcesclusterwww.emilianbold.roThe author’shomepageIssue 4 N 45


Module DevelopmentAFigure 7.Our help contentregistered in themain PlatformhelpAFigure 8.Module suitewith HelpBrandingThe last piece of the puzzle is branding. Support via actual wizardsis totally missing to this date, so it’s back to manual workor copy-pasting from another project. You’ll need a src/main/nbm-branding folder where all the brandingsources will reside. The folder’s struc-A 8ture should be the same as the one usedby the Ant-based build harness. Also, theA 7POM must be changed to configure thenbm:branding goal as in Listing 12. Theend result is a branded application asAFigure 9.The brandedsplash screenseen in Figure 9.ConclusionsUsing Maven to build <strong>NetBeans</strong> Platform applicationsis no longer an obscure task. The currentA 9integration makes Maven-based projects almoston par with standard IDE projects and the gap isnarrowing. So, if you like Maven but couldn’t useit before with <strong>NetBeans</strong> IDE, or you do <strong>NetBeans</strong>Platform development but can’t use the IDE forsome reason, rest assured that there’s a goodand rapidly improving solution now.CEmilian Bold(emilian.bold.public@gmail.com) is a Javaand <strong>NetBeans</strong> Platformconsultant fromTimisoara, Romania, aswell as member of the<strong>NetBeans</strong> Dream Team.He has been workingwith the <strong>NetBeans</strong>Platform since version3.6, starting witha project at AlcatelRomania (now Alcatel-Lucent) and owns a<strong>NetBeans</strong> Platformfocusedconsultingcompany.BListing 12. Running the branding goal in the process-resources phaseorg.codehaus.mojonbm-maven-pluginRELEASEtrue${basedir}/src/main/nbm-brandingnbmagazinenbmagazine${project.build.directory}/nbmbrandingprocess-resourcesbranding.../plugins>...46 N <strong>NetBeans</strong> Magazine


In-depth, no-fluffarticles for the fullgamut of <strong>NetBeans</strong>developers Platform APIs Java SE development Profiling Mobility Dynamic languages Modules Visual Web Web Services Matisse C/C++ SOA Java EE development Ruby UML CommunityyourCheck out previous issues atnetbeans.org/community/magazineModules . Visual Library . Maven 2 . Ruby . Profiling . Web Services . Localization . SchliemannThe Best Ruby IDEDynamic web development andthe IDE’s Ruby featuresFluent in <strong>NetBeans</strong>How global localization efforts areexpanding the IDE’s reachCreative uses of Creating RESTfulthe Visual LibraryWeb ServicesExplore the graph handling andvisualization Platform APIA comprehensive tutorial onextensions for REST developmentmagazineDecember . 2007magazineAdvanced ProfilingReal-world explorations withthe <strong>NetBeans</strong> ProfilerSchliemann in the FieldExpand your developmentHorizonPeople and projects working tomultiply language supportHorizonswith <strong>NetBeans</strong> 6.0Release 6.0 . JSF . Matisse . C/C++ . Mobility . <strong>NetBeans</strong> Platform . Scripting LanguagesProject SchliemannOpening the IDE to other languagesMobility Pack in PracticeLearn the basics and reduce device fragmentationNew UI Design FeaturesUpgrade your desktop productivity with <strong>NetBeans</strong> 6.0Visual Web DevelopmentRapid web application design and implementationModule Developmentwith MavenA powerful alternative for building<strong>NetBeans</strong> extensionsMay . 2007magazineCore <strong>NetBeans</strong> 6.0 FeaturesKnow in depth what’s coming in the new releaseIntroducing C/C++ PackLeverage <strong>NetBeans</strong> for native developmentThe blueMarine Project<strong>NetBeans</strong> Platform development in the real worldOpenOffice.org IntegrationCreate add-ons and components to interface with OOoReach Outwith the IDE and Platform

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!