Code Generator Integration Tutorial

This tutorial shows you how to write a module that integrates new items into the NetBeans Code Generator feature, which appears when you click Alt-Insert in an editor.

Note: This document uses NetBeans Platform 8.0 and NetBeans IDE 8.0. If you are using an earlier version, see the previous version of this document.

Contents

Content on this page applies to NetBeans IDE 8.0

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

Software or Resource Version Required
NetBeans IDE version 8.0
Java Developer Kit (JDK) version 7 or above

For troubleshooting purposes, you are welcome to download the completed tutorial source code.

Introduction to Code Generator Integration

The Code Generator feature, consisting of a user interface and an API, introduced in NetBeans IDE 6.5, consists of a list of items that appears when you press Alt-Insert. Each item generates code into the editor. In this tutorial, you will create a sample generator, as shown below, which will generate a method into a Java class:

Deployed result

Creating the Module Project

In this section, we use a wizard to create the source structure that every NetBeans module requires. The source structure consists of certain folders in specific places and a set of files that are always needed for Ant-based NetBeans modules. For example, every Ant-based NetBeans module requires a nbproject folder, which holds the project's metadata.

  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select NetBeans Modules. Under Projects, select Module. Click Next.
  2. In the Name and Location panel, type DemoCodeGenerator in Project Name. Change the Project Location to any directory on your computer. Click Next.
  3. In the Basic Module Configuration panel, type org.netbeans.modules.demo as the Code Name Base. Click Finish.

The IDE creates the DemoCodeGenerator project. The project contains all of your sources and project metadata, such as the project's Ant build script. The project opens in the IDE. You can view its logical structure in the Projects window (Ctrl-1) and its file structure in the Files window (Ctrl-2).

Using the Code Generator Provider Wizard

In this section, we use a wizard to create the stub class and registration entries necessary for beginning our integration with the Code Generator feature.

  1. Right-click the project node and choose New > Other. In the New File dialog, choose Module Development > Code Generator, as shown below:


    Code generator wizard.

  2. In the New Code Generator panel, set the following:

    • Class Name. Specifies the class name of the stub that the wizard will generate. Type "DemoCodeGenerator" in this field.
    • Package. Specifies the package where the stub class will be generated. Select "org.netbeans.modules.demo" from the drop-down.
    • MimeType. Specifies the MIME type to which the code generator integration will be applied. Type "text/x-java" in this field.
    • Generate CodeGeneratorContextProvider. Adds additional objects to the code generator's lookup. Leave this checkbox unselected.

    You should see the following:


    Code generator wizard.

  3. Click Finish. The Projects window should now show the following:


    Final Projects window.

The generated class should look like this:

package org.netbeans.modules.demo;

import java.util.Collections;
import java.util.List;
import javax.swing.text.JTextComponent;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.spi.editor.codegen.CodeGenerator;
import org.openide.util.Lookup;

public class DemoCodeGenerator implements CodeGenerator {

    JTextComponent textComp;

    /**
     *
     * @param context containing JTextComponent and possibly other items
     * registered by {@link CodeGeneratorContextProvider}
     */
    // Good practice is not to save Lookup outside ctor
    private DemoCodeGenerator(Lookup context) { 
        textComp = context.lookup(JTextComponent.class);
    }

    @MimeRegistration(mimeType = "text/x-java", service = CodeGenerator.Factory.class)
    public static class Factory implements CodeGenerator.Factory {
        public List<? extends CodeGenerator> create(Lookup context) {
            return Collections.singletonList(new DemoCodeGenerator(context));
        }
    }

    /**
     * The name which will be inserted inside Insert Code dialog
     */
    public String getDisplayName() {
        return "Sample Generator";
    }

    /**
     * This will be invoked when user chooses this Generator from Insert Code
     * dialog
     */
    public void invoke() {
    }
    
}

Coding the Code Generator Integration

Next, we will implement the NetBeans Java Editor APIs introduced in the NetBeans Java Language Infrastructure Tutorial.

Below, we set dependencies on the required modules and then implement them in our own module.

  1. Right-click the project, choose Properties, and add the following dependencies in the Libraries panel:


    • Javac API Wrapper
    • Java Source
  2. Open the generated class and modify the invoke() method as follows:
    public void invoke() {
        try {
            Document doc = textComp.getDocument();
            JavaSource javaSource = JavaSource.forDocument(doc);
            CancellableTask task = new CancellableTask<WorkingCopy>() {
                public void run(WorkingCopy workingCopy) throws IOException {
                    workingCopy.toPhase(Phase.RESOLVED);
                    CompilationUnitTree cut = workingCopy.getCompilationUnit();
                    TreeMaker make = workingCopy.getTreeMaker();
                    for (Tree typeDecl : cut.getTypeDecls()) {
                        if (Tree.Kind.CLASS == typeDecl.getKind()) {
                            ClassTree clazz = (ClassTree) typeDecl;
                            ModifiersTree methodModifiers = 
                                    make.Modifiers(Collections.<Modifier>singleton(Modifier.PUBLIC), 
                                    Collections.<AnnotationTree>emptyList());
                            VariableTree parameter = 
                                    make.Variable(make.Modifiers(Collections.<Modifier>singleton(Modifier.FINAL), 
                                    Collections.<AnnotationTree>emptyList()), 
                                    "arg0", 
                                    make.Identifier("Object"), 
                                    null);
                            TypeElement element = workingCopy.getElements().getTypeElement("java.io.IOException");
                            ExpressionTree throwsClause = make.QualIdent(element);
                            MethodTree newMethod = 
                                    make.Method(methodModifiers, 
                                    "writeExternal", 
                                    make.PrimitiveType(TypeKind.VOID), 
                                    Collections.<TypeParameterTree>emptyList(), 
                                    Collections.singletonList(parameter), 
                                    Collections.<ExpressionTree>singletonList(throwsClause), 
                                    "{ throw new UnsupportedOperationException(\"Not supported yet.\") }", 
                                    null);
                            ClassTree modifiedClazz = make.addClassMember(clazz, newMethod);
                            workingCopy.rewrite(clazz, modifiedClazz);
                        }
                    }
                }
                public void cancel() {
                }
            };
            ModificationResult result = javaSource.runModificationTask(task);
            result.commit();
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
  3. Make sure the following import statements are declared:
    import com.sun.source.tree.AnnotationTree;
    import com.sun.source.tree.ClassTree;
    import com.sun.source.tree.CompilationUnitTree;
    import com.sun.source.tree.ExpressionTree;
    import com.sun.source.tree.MethodTree;
    import com.sun.source.tree.ModifiersTree;
    import com.sun.source.tree.Tree;
    import com.sun.source.tree.TypeParameterTree;
    import com.sun.source.tree.VariableTree;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.List;
    import javax.lang.model.element.Modifier;
    import javax.lang.model.element.TypeElement;
    import javax.lang.model.type.TypeKind;
    import javax.swing.text.Document;
    import javax.swing.text.JTextComponent;
    import org.netbeans.api.editor.mimelookup.MimeRegistration;
    import org.netbeans.api.java.source.CancellableTask;
    import org.netbeans.api.java.source.JavaSource;
    import org.netbeans.api.java.source.JavaSource.Phase;
    import org.netbeans.api.java.source.ModificationResult;
    import org.netbeans.api.java.source.TreeMaker;
    import org.netbeans.api.java.source.WorkingCopy;
    import org.netbeans.spi.editor.codegen.CodeGenerator;
    import org.netbeans.spi.editor.codegen.CodeGeneratorContextProvider;
    import org.openide.util.Lookup;

Installing and Trying Out the Functionality

Let's now install the module and then use the code generator feature integration. The IDE uses an Ant build script to build and install your module. The build script was created for you when you created the project.

  1. In the Projects window, right-click the project and choose Run. A new instance of the IDE starts up and installs the Code Generator integration module.

  2. Create a new Java application and open a Java source file. Press Alt-Insert inside the editor and you will see your new item included:


    Deployed result

  3. Click an item and the code will be inserted:


    Deployed result



Next Steps

For more information about creating and developing NetBeans modules, see the following resources:

Project Features

Project Links

About this Project

Platform was started in November 2009, is owned by Antonin Nebuzelsky, and has 148 members.
By use of this website, you agree to the NetBeans Policies and Terms of Use (revision 20160708.bf2ac18). © 2014, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo
 
 
Close
loading
Please Confirm
Close