FeaturesPluginsDocs & SupportCommunityPartners

NetBeans UML Custom Code Generation

Built-in code generation mechanism is an important addition to the NetBeans 6.1 release UML feature.

When you create a Java class using the the New Project wizard, the NetBeans IDE uses code generation templates to generate source, substituting token variables with the proper information: author name, creation date, license, class name, constructor name, and other attributes. Before NetBeans 6.1, these code generation templates did not support custom behaviors that you could provide as a developer.

However, NetBeans 6.1 utilizes an open source template engine named Freemarker that assists in custom code generation. The difference between the old NetBeans templates and those employing the Freemarker templates resides in the ability to customize content generation using script code in the templates. While this ability can apply to other NetBeans features, you can now use templates to customize code through the UML module code generation feature, thus providing you with great flexibility in the code you generate using the UML feature.

Contents

Content on this page applies to NetBeans IDE 6.0

Required Software

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE NetBeans 6.1
BankApp Sample Project Bundled with the NetBeans IDE
Java Developer Kit (JDK) version 6 or version 5
Zip file for this article, containing Templates and project information http://www.netbeans.org/files/documents/4/1942/codegenresources.zip

Freemarker Template Files and Model Driven Development

With the NetBeans 6.1 UML feature, a set of Freemarker template files is added to the IDE.(See http://freemarker.org/ for information on Freemarker. See http://plugins.netbeans.org/PluginPortal/faces/PluginDetailPage.jsp?pluginid=3755 for a NetBeans Freemarker Plugin that you can use with your Freemarker source.)

The templates enable the generation of standard Java source files (classes, interfaces and enumerations) from model elements, using standard Java source file templates. The Freemarker templates are accessible for your customization purposes like any other template in NetBeans. See also http://wiki.netbeans.org/FaqFreeMarker .

Model-Driven Development

Most of the power that comes from pairing UML with Freemarker is the ability to do Model Driven Development (MDD). MDD means that you can perform development by mapping element attributes to Freemarker templates, and thus you can create model elements tagged with stereotypes that allow you to generate complex programming design patterns.

For example, you can use a single Class element with the stereotype ejb-stateless to generate the Bean class, the Home interface and Remote interface source files for an EJB application.

You can stereotype individual methods as business to indicate the methods to expose to the client. To be more domain-specific, you can use a stereotype named shopping-cart can represent a full implementation of a shopping cart EJB. Each of these stereotypes can map to specific templates that generate the required code.

Background for Successful Freemarker Template Creation

While this article does not focus on scripting itself, three skills are helpful for writing successful custom scripts and corresponding template creation:

  • Knowledge of Freemarker Scripting
  • Knowledge of your source data model
  • Familiarity with the target output format domain.

Freemarker Scripting

The first skill is reasonable comfort with the Freemarker script language. Freemarker is similar to other scripting languages.You can refer to the Freemarker online manual on the SourceForge web site for information on Freemarker.

Source Data Model

The source data models you use can vary in complexity. In the UML data model, there are two elements, one element in type ClassInfo with classInfo as the name of the model element of type Classifier with modelElement as the name of the model. You will recognize these elements when you look at the scripting available through the templates.

Target Output Format Domain

The output format is the result of your code generation. Targeting programming languages is not a trivial task. You have to think as a language parser would think. For Java, you must ensure you begin what you target with a package declaration, then import statements. The class declaration has many variables you need to consider: scope, class name, extends clause, and implementations.

Comments might also accompany the class declaration. You also need to consider attributes and methods and their signatures and comments. Whitespace needs to be considered as well.

However, if you are dedicated to modeling, and keep aware of what your target output is, you will easily advance in your implementation when you generate the source code, and hence obtain the benefits model driven development.

Using The BankApp Sample Project with Custom Code Generation

Before you proceed, you must ensure you have obtained the zip distribution, as indicated in Required Software. This distribution includes Freeemarker code generation templates and NetBeans projects. You will also use the BankApp Sample Project that comes bundled with the IDE.

This article includes a tutorial on custom code generation. To create a starting point for the custom code generation tutorial, you can use the sample projects bundled with the UML feature in the IDE.

To get started, you need to create a Java and UML Project for the bundled BankApp Sample Project:

  1. From the Main Menu of the IDE, choose File > New Project.
  2. In the Choose Project page, expand the Samples node in the Categories pane and select the UML node. The Projects pane is updated with the available UML sample project.
  3. In the Projects pane, select the UML Bank App Sample and click Next.
  4. In the Name and Location page, leave the default value of UMLBankAppSample for the Java project name, or modify it if the project already exists.
  5. Click Finish. The NetBeans IDE creates two projects: a Java project and a UML project. If you chose the default name, the Java Project will be named UMLBankAppSample and the the UML Project will be named UMLBankAppSample-Model.
  6. Expand the UML project to expose all subnodes of the Model node. There is one package, bankpack, and several Class elements and one Interface element. These elements were reverse engineered from the Java project.
  7. Right click any of these elements and select Navigate to Source and the source file in the Java project is opened in the NetBeans editor.
  8. Make changes to these elements and perform Generate Code -- the source files in the Java project are updated appropriately. (Knowing the relationship between the Java project and the UML project is helpful.) The focus will now be on how the code is generated for each of these elements and, secondly, how you can customize code generation.

Now that you have created the Java and UML Project you will use, you can look at the tools used in the UML code generation process.

NetBeans UML Tools Used in the UML Code Generation Process

Before you begin creating custom templates and mapping them to model elements, it is important to understand the tools in within the NetBeans IDE that you will be using and their relationship.

These tools include panels, customizers and a dialog:

  • NetBeans Template Manager: Use this tool to access the Templates in their folders.
  • NetBeans UML Template Options panel: Use this tool to map template files to model elements.
  • NetBeans UML Project Customizer (for project properties): Use this tool to enable domain templates
  • Generate Code dialog: Use this dialog to create code from the templates.

Each of these tools plays a role in the configuration and usage of templates in the UML code generation process.

Managing Template Files Using the NetBeans Template Manager

All templates in NetBeans 6.1 are based on the Freemarker template engine.

Within the IDE, you can manage Freemarker templates with the NetBeans Templates Manager. To access the templates:

  1. From the main menu of the IDE, choose Tools > Templates. The IDE opens the Template Manager dialog. You will see many folders that serve to categorize templates.
  2. Expand the UML folder and its subfolders.
Image showing the Template Manager Dialog

Template files you add to the IDE are not required to have to contain Freemarker scripting, so there is no expected file format when you add files in the Template Manager. The templates for generating Java code are designed for maximum code reuse.

When you add template files, keep the following in mind:

  • The CompilationUnit.java file serves as the sole template file for generating Java class, interface, and enumeration source files.
  • The additional files (*Declaration.java files and DeclLib.ftl) are linked from within the CompilationUnit.java file.
  • There are many other templates in other folders. Some might contain valuable scripting examples that you can use in your custom templates for UML code generation. However, the UML code generation process uses only the templates that are listed in the UML/Code Generation folder and its subfolders
  • You can create your own custom subfolders under the UML/Code Generation folder to store your templates and they will still be available for use by the UML code generation process.

In this article, you will use very simple Freemarker template scripting that takes advantage of those capabilities that the NetBeans UML code generation process provides by default to the Freemarker template engine.

Mapping Domain Templates with the NetBeans UML Options Panel

Creating custom Freemarker template files was`the first step. Some templates are already available for Java code generation.

However, when using template files, you next need to map these template files to the model elements in your model. You can configure this mapping in the NetBeans UML Options panel, by doing the following:

  1. From the main menu of the IDE, choose Tools > Options.
  2. Click the UML options category.
  3. Click the Templates tab.
  4. Select the Basic Class node in the tree.

The IDE displays the properties for the Java/Basic Class domain template showing that any element in a model that is of type Class and that has no stereotype is mapped to the template file under UML/Code Generation/Java/CompilationUnit.java , and that the output will be a file with the same name as that of the element with .java as the file extension.

Image showing the Domain Template

Using Custom Code Template Files to Generate Code for Domain Objects

The UML feature has several types of elements (such as Class, Interface, Actor). These elements can be stereotyped to identify the element as serving a specific purpose or possessing certain behaviors. A domain object is an object that is specific to a Domain Specific Language (DSL).

For example, in an ATM machine domain (a domain not used in this tutorial), some domain objects might be:

  • Customer
  • Account
  • Deposit
  • Withdrawal
  • Bank

These domain objects might be represented in a UML class diagram as Class elements with the following stereotypes, respectively:

  • customer
  • account
  • deposit
  • withdrawal
  • bank

To generate code for domain objects, you must create custom code template files. Custom code template files contain the necessary attributes and methods that will be generated into the source files.

Once you create the template files, you need to map element/stereotype pairs to the appropriate template files during the code generation process. A domain template provides the mapping of a model element type and stereotype to one or more template files.

With the UML Template Options Panel, you can create category folders as needed and then add domain templates to those categories. The way you organize your categories and domain templates is up to you, but you should follow the layout you create in the NetBeans Template Manager where you access template files.

Enabling Domain Templates for UML Projects with the UML Template Options Panel

Once you have created domain templates, you need to enable or disable them on a per-UML- project basis. The default Java domain templates are automatically enabled for every UML project. However, if you created custom domain templates in the UML Template Options panel, these domain templates are not enabled for any of your UML projects by default.

You use the UML Project Customizer (project properties) to customize your UML projects' enabled templates.

To enable domain templates for UML Projects:

  1. Right-click the UML project node (the default name is UMLBankAppSample-Model).
  2. Select Properties to open the UML Project Customizer.
  3. When the customizer dialog is displayed, select the Code Generation category.
  4. Expand the Java node in the bottom panel.

Understanding and Using the Project Properties Panel

In this example, the Target Project field is blank. This is because you reverse-engineered the UML project from the Java project UMLBankAppSample.

The first time you generate code, the IDE does not configure the target project and the status message at the bottom warns that a valid target project must be selected.

To use the Project Properties Panel:

  1. Click OK to save the properties, without specifying the Target Project.(You see the same user interface later in your workflow in the Generate Code dialog, but at that point in the workflow all mandatory fields including Target Project must be filled in before you click OK to generate code.)
  2. Expand the Java node in the Templates pane at the bottom, to see three default domain templates:
    • Basic Class
    • Basic Interface
    • Basic Enumeration
  3. You can turn off code generation for specific elements on a per-template basis. For example, if you do not want to generate code for Enumeration elements that do not have a stereotype in your model, you could deselect that domain template in the Properties Panel.
  4. If you had added custom domain templates, you could enable them for code generation in this Panel. All these options are also available for on-the-fly configuration when you invoke the code generation process, assuming you have enabled the Prompt Before Generating Code option in the Project Customizer. (By default, the IDE turns this dialog option.)

Generating Code from Your Model

Once you have all your domain templates in place and they are properly enabled for your UML project, you can generate code from your model. To do so,

  1. Right-click the UML project node and select the Generate Code action. The IDE displays the Generate Code dialog for you to confirm that the properties are properly configured. By default, the Templates pane is hidden.
  2. Click the Show Templates button to show the domain templates, as in the image.
  3. Click the OK button to start code generation. Messages will be displayed in the NetBeans Output window in a tab labeled Generate Code Log. The generate code process status is displayed there. Review these messages to confirm that your code was generated properly.

In the next section, you use EJB templates that are created by streamlining the current Java templates. The steps to create those templates are not covered here, but the finished, streamlined templates provide a simpler example than Java templates.

Creating Enterprise Java Bean 3.0 Custom Templates

Once you've configured default Java code templates to generate Java code from your UML projects, you can use custom templates to generate source files for application artifacts, such as a typical stateless session EJB.

Creating robust code generation templates can be a fairly complex task. To facilitate your learning how to use custom templates, the three necessary code generation templates for stateless session EJBs have been created for you and are provided in the zipped distribution. These templates are not complete solutions for generating stateless session EJBs. They only generate the bean class and the home and remote interfaces, if tagged appropriately, with methods from the Class element.

A more complete implementation provides the ability to stereotype each individual operation as local, remote, or both to indicate in which interface the operation should be declared.

Obtaining the Code Generation Templates and Adding them to the IDE

To add the code generation templates to the IDE, download the Templates and use the Template Manager to add them to the IDE:

  1. Make sure you have unzipped the source provided with this article to obtain the following Templates:
    • StatelessBean.flt
    • StatelessRemote.ftl
    • StatelessLocal.ftl
  2. Add the templates to the IDE. From the Main Menu, Select Tools > Templates. The NetBeans Template Manager opens.
  3. Navigate to and select the folder UML/Code Generation.
  4. Click the New Folder button and name the folder EJB 3.0.
  5. Click the Add button.
  6. Navigate to the folder location where you unzipped the template files.
  7. Select one of the files to add to the IDE.
  8. Repeat steps 5-7 for the other two template files.
  9. Select all three templates. Click the Open in Editor button. The IDE opens the new template files in a NetBeans editor window.
  10. Browse the template scripts to understand what is being performed. These three template files were created by combining the three separate template files used to generate Java classes, and are linked together so the scripts can be reused. By combining the scripts into one template, it is easier to follow the flow of the script.

    Again, three of the basic default templates are used. These are:

    • DeclLib.ftl
    • CompilationUnit.java
    • NormalClassDeclaration.java

There are three separate template files because you will be using one single model element in the UML project to generate three separate source files, and there must be at least one template file per generated source file: one model element directly uses one template file to generate one source file.

With standard Java types, each type uses the CompilationUnit.java template file, which references the other template files ( DeclLib.ftl and one of the other three *Declaration.java files) to generate one source file.

Generating Templates for the EJBs

The zip file contains three templates that enable you to generate EJBs. With these templates, one model element will directly use three different template files to generate three source files.

The following image will help you visualize the relationship differences between standard Java class code generation and EJB bean class generation.

In the image below:

  • There are three elements in the model: a Class, an Interface and an Enumeration.
  • Each Class element is mapped to use the Basic Class domain template (any Class element without a stereotype) that in turn uses the CompilationUnit.java template file.
  • The script in the CompilationUnit.java template file determines that this element is of type Class and links into the NormalClassDeclaration.java template to perform Java-Class specific code generation.
  • Similarly, for Interface and Enumeration element types, the script in CompilationUnit.java determines that the element is of a specific type and links into the appropriate template to facilitate Java, Interface or Enumeration-specific code generation.

Mapping Stateless Class Elements

Class elements stereotyped as stateless are mapped to the Stateless domain template, which has three template files.

Each template file generates a separate source file: one Java class and two Java interfaces. See the figure below.

Adding the New Templates

Once you have added the new templates to the IDE, you need to add them as Domain Templates through the Options Panel. To do so:

  1. From the main menu of the IDE, choose Tools -> Options.
  2. Click Categories.
  3. Click Add to add the new category.
  4. Rename default Category to EJB 3.0.
  5. Click the Add button to add a new domain.
  6. Name the default domain to Stateless.
  7. Select Stateless.
  8. Select Class from the Element type drop down menu.
  9. Type stateless in the Stereotype field.
  10. Select Add Templates.
  11. Fill in the dialog with these suggested entries:
    • Filename Format: {name}Bean
    • Extension: .java
    • Folder: leave blank unless you want the file to be generated to somewhere
    • Template File: EJB 3.0/StatelessBean.ftl
  12. Repeat these entries, but supply the names of the other two templates.

Mapping EJB Templates

After you have added the templates to the IDE and have added them through the Options panel, you need to map the Templates the to the model elements in your mode using the UML options panel.

  1. From the main menu of the IDE, choose Tools > Options.
  2. Click the UML options category.
  3. Click the Templates tab.
  4. Expand the EJB 3.0 node in the Options Panel.

The IDE displays the properties for the EJB domain template. As the following illustration shows, under the EJB 3.0 domain template, you will have a Stateless domain template of Element Type Class, with Stereotype stateless.

There are three output parameters, Bean, Local and Remote, each with an extension of .java

Multiple Domain Templates for Single Model Elements

Multiple domain templates might have a single model element mapped to them. For example, the Basic Class domain template in the Java category can be mapped to any element of type Class without a stereotype.

You could create another category called C++ with a domain template that is also named Basic Class (or whatever you want to name it) that also maps to elements of type Class with no stereotype, The template file can generate a C++ class instead of Java.

If both templates are enabled when Generate Code action is invoked, you will obtain two files from one element, one being a Java class and the other being a C++ class. While this latter example might be a corner case, it is still possible.

Creating a Calculator Stateless Session EJB

Once you have properly created the templates in NetBeans and configured the proper domain template, you can create a UML model project that will take advantage of the new template to generate Enterprise Java Bean code for the Enterprise Java Bean.

After you create the UML model project, you create a Calculator element and add methods to it.

The first step is to create the UML project:

  1. From the Main menu, select File > New Project.
  2. Select UML, then select Java Platform Model
  3. Click Next and Finish.
  4. When the Create Diagram dialog appears, select Class Diagram and click Finish. You have created a UML Project with one class diagram.

Next, you will create the Calculator element. To create the Calculator element:

  1. Add one Class element to the diagram and name it Calculator (the templates will ensure the suffixes are properly created: that is, the templates create Bean, Local and Remote for the appropriate source file names).
  2. With the Calculator element selected, edit the Stereotype property and add stateless.

The Generate Code process will now identify the Calculator element, to maps it to the Stateless domain template. However, before you can perform code generation, you need to add some methods to the Calculator element.

Adding Methods to the Calculator Element

Create the three operations listed below in the Calculator element in the UML Diagram Editor. To create an operation, right-click the Calculator element in the Operation compartment area and select Add Operation. Add the following operations:

  • public int add(int a, int b)
  • public int subtract(int a, int b)
  • public int multiply(int a, int b)

You might not want all three of these methods exposed in both of your interfaces. Only public methods can be declared in the interfaces, so if did not want all these methods exposed, you would need to filter out non-public methods.

Also, you might not want all of the public methods to be declared in both interfaces, or either of them. You need a mechanism for the script to determine which methods will be generated in each of the three source files. Again, you can use stereotypes to indicate which methods should be added .

Creating a Java Project

Now that the Calculator element is complete, you need to create a Java project to which you can generate the code. To do so:

  1. From the main menu of the IDE, choose File > New Project.
  2. Select Java, Java Application and click Next.
  3. In the Choose Project page, select Java and Java Application.
  4. Uncheck the Create Main Class option and click Finish.
  5. Right-click the Calculator element and select Generate Code.
  6. Select the newly created Java project as the Target Project.
  7. Click the Show Templates button and expand the EJB 3.0 node in the tree.
  8. Check the Stateless domain template. Click OK to start generating code.

The output window displays messages, informing you that the IDE used three separate template files to generate code for the Calculator element.

When the generate code process is finished running, expand the source folder for the Java project to inspect your new Calculator sources. You will see three generated files:

  • CalculatorBean.java
  • CalculatorLocal.java
  • CalculatorRemote.java

Open each file to verify that you generated all three methods in the class and the two interfaces. You might see compilation or other errors because the standard Java project does automatically include the Java Enterprise library or other classes.. You can ignore these as the goal of this tutorial s neither to compile nor run this project you have created.

Observing Diagram Editor Changes in Generated Code

You can see how the generated code is kept synchronized with the Calculator element as you make changes to the element with the Diagram Editor. Within the Diagram Editor:

  1. Add a new operation:
        public float divide(int a, int b)
        
  2. Delete the multiply operation.
  3. Add a third parameter to the add operation:
        int c
        
  4. Right-click the Calculator element and select Generate Code.

Examine the three source files, as you did previously when you inspected the new sources, and notice that the IDE updated all of them to be synchronized with the changes you made to the Calculator element in the Diagram Editor.

Summary

The Freemarker scripting environment provides a powerful addition to NetBeans UML code generation, enabling you to customize code that you generate. This article provided you the conceptual background and tutorial information to enable you to create, add and customize code generation templates, code generation in general and code generation with specific reference to EJB artifacts. By using code generation templates, you can harness the power of the templates within the framework of NetBeans UML code generation and simply modify a few elements to maintain the source code for many source files. Customized code generation templates provide you with an efficient, easy way to generate code that can be used in your application projects.

Next Steps

  • To send comments and suggestions, obtain support, and stay informed of the latest changes to the NetBeans IDE UML development features, join the mailing list.


top

Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Open ESB - The Open Enterprise Service Bus Powered by