Making your own NetBeans modules

NetBeans 7 is a powerful, free IDE that provides lots of opportunities to customise. If you find yourself continuing to create code that does roughly the same thing (eg. PHP scripts), you may want to make your own intelligent, dynamic template file to make life easier. The technology used to do all this is NetBeans IDE API and FreeMarker - a templating system that provides heaps of functionality, only a small portion of which needs to be used in NetBeans when creating modules.

As an exercise, I decided to make my own PHP template file module that lets you create a new PHP file that connects to a MySQL database and table, and runs a simple query against it. Because I keep forgetting the code (and because most of my PHP scripts do MySQL access), I decided to set up a NetBeans module that allows to you to creates a new PHP file with the shell code for database table access filled in. To use the templated file, it's just a simple right-click to get a panel where you provide a database name, a table name and the fields you want. Out pops a valid PHP script that opens the database, runs a SELECT * FROM xxx etc. query against it, then prints a list of fields you have selected in the panel.

There are some pretty good tutorials to do all this on the NetBeans sites, but a number of gotchas as you utilise version 7 - some of the tutorials are slightly out of date for this version. This posting should hopefully help you resolve those differences, and create your own customised template. Follow the tutorial on the NetBeans site NetBeans File Templates Tutorial while you read this post - I'm really just flagging a few tips to get it going on version 7, with a real-life example.

We'll be using FreeMarker as a template language to link what you put on your 'new file' panel into the actual PHP file you create... this is the timesaving feature.

You'll need the FreeMarker plug in for NetBeans, and I don't believe it's available from the standard plugin sites contained in Tools/Plugins, so you'll need to install the .nbm file manually.

Get the Freemarker Samples .nbm by using the link on NetBeans and FreeMarker Tutorial

You should read this page top-to-bottom to get an understanding of FreeMarker's interface to NetBeans, and can even try out the tutorial to install a standard Java file creator if you wish. If you just want to download and install the .nbm file, get it at NetBeans FreeMarker Sample plug-in

Press download, store it somewhere, then use Tools/Plugin/Downloaded and click 'install' to add it to NetBeans. It comes with a few samples that are immensely useful in understanding this beast.

Unfortunately, it won't compile out of the box unless you remove an unnecessary dependency to org.netbeans.modules.templates. Right click the project (FreeMarkerSupport) and edit the libraries list to remove it.

As the tutorial goes on to say, add in the other required (but missing) dependencies: namely 'Java Project Support', 'Project API', and 'Project UI API'. You should now have a working FreeMarker plug in with a few samples (HTML file, Java file, and even a little form-letter writer).

Now, to create your new module, select New Project, with a type of NetBeans Modules/Module. Give a meaningful name eg. PHPMySQLTemplate, and an appropriate code base name eg. org.yourorganisation.phpmysqltemplate.

Once you've done this, you can create the relevant files, compile and (most importantly), right click the project after compilation to Install/Reload in Development IDE. Create a wizard outline by following instruction 4 on the NetBeans FreeMarker Tutorial.

This will give you most of the files you need namely: Java panels, a java Wizard Iterator, a module description html, and layer.xml. You will be adding your own empty file to use a template (.ftl) file.

Because the purpose is to create our own panel, don't follow instruction 6 - we will customise our panel to collect a couple of fields and use those in the template. (Instruction 6 leaves out panel creation by just substituting the default Java file panels).

Now: on to your own panels. This was a trial-and-error thing for me, but the FreeMarkerSupport Example files were enormously helpful.

For your xxxVisualPanel1.java file, just add the required text boxes/list boxes etc. you need to provide the dynamic data for your eg. PHP file.
There's nothing too complex in here, but two things are important:
1) Add your template variables eg.

static final String DB_NAME = "db_name";
static final String TABLE_NAME = "table_name";
static final Object[] FIELD_NAMES = {"field_names"};


2) Provide accessor methods for your screen text boxes eg.


public String getDBName() {
return jTextField1.getText();
}


Note the Letter example shows you how to get hold of ListBox contents if you need that too.

For your xxxWizardPanel1.java file, you need to provide more accessor functions to get hold of the dynamic variables eg.


public String getDBName() {
return ((PHPMySQLVisualPanel1) component).getDBName();
}

Most importantly, don't forget to update the StoreSettings method with your dynamic screen variables eg.


public void storeSettings(Object settings) {
((WizardDescriptor) settings).putProperty(PHPMySQLVisualPanel1.DB_NAME, getDBName());
((WizardDescriptor) settings).putProperty(PHPMySQLVisualPanel1.TABLE_NAME, getTableName());
((WizardDescriptor) settings).putProperty(PHPMySQLVisualPanel1.FIELD_NAMES.toString(), getFieldNames());
}


This step is the mechanism by which the dynamic screen variables get passed to the template file.

The xxxxWizardIterator.java file links it all together. In the instantiate method, you create a HashMap containing the dynamic variables off the panel. Follow the example file closely so you fill in everything. In particular, note the linkage done by these lines of code:

hashMap.put("db_name", wizard.getProperty(PHPMySQLVisualPanel1.DB_NAME));

This puts DB_NAME off the panel into the HashMap which will be provided to the FreeMarker engine to create a variable you can use in your template like ${db_name}. Sticking to the lower/upper case standards here is helpful ie. make your template variables lower case. All the other code outside instantiate stays as is.

The fun bit is creating your template. I used a PHP file, but of course your new file can be any type you like. The FreeMarker site has a list of all the macro instructions you can provide (eg. #ifs, and <#list). A useful site to explore FreeMarker syntax is at FreeMaker Template Cookbook. Again, follow the example .ftl files to help create a template that should run/compile properly as soon as you add it to your next project.

The layer.xml file is very important. Use an example and modify it from there. Important things here are:
folder xxx - tells NetBeans where the new file can be accessed eg. Templates/PHP
You must also add the following line:


<attr name="javax.script.ScriptEngine" stringvalue="freemarker"/\>


so that NetBeans knows you want to tell FreeMarker to use templating.
You can also make an .html file to describe your wizard file creation, and for completeness, you might want a 16x16 icon to show off your new file. There are two .html files in use: one describes the wizard itself, and the other, some information on the file you are creating.

Lastly, clean/compile and Install/Reload in Development IDE to install your template.

When you compile, be careful of some of the libraries you linked in. The main issue I had was the auto-import fixer brought in javax.tools.FileObject which is NOT the one you want: you want the wizard custom file object version:

import org.openide.filesystems.FileObject;


If all goes to plan, you can now add a new file to any project, filling in a couple of custom items on the panel, then see these correctly inserted at the right places in your new file. As I mentioned, I used all this to create a ready-to-go PHP file that accesses a database table and prints a few fields.

One last gotchya when it comes to using your new template: if you're using the ListBox, you'll need to actually select all the values you want: a list box full of data, but unhighlighted brings in sweet FA!

Given you are controlling the creation of your templated-file with FreeMarker and java code, you have opportunities to do all sorts of exciting things - my next idea is to actually pre-fill the table fields in the list box based on the selected database and table. This MySQL access code will go in xxxVisualPanel1.java file, once the user has chosen a database and table.

In summary, you can use NetBeans to 'intelligently' create new files for you using FreeMarker templating, and using Java code to interact with the NetBeans IDE. Nifty eh?

Comments

  1. Cool stuff dude. The complex NetBeans IDE API model would be a lot more useful if they kept the damn documentation up to date!

    ReplyDelete
    Replies
    1. 8 years later: and I've given up trying to update things like this tutorial when it comes to NetBeans. I still think it's an awesome IDE, but, unlike Eclipse, developing the development environment is a thankless task given a) NetBeans can probably do it, but b) the development documentation is fairly poor. Still, I find Eclipse overly complicated for what I need to do, and consequently, still have a place in my heart for good old NetBeans!

      Delete

Post a Comment

Popular Posts