How to use certain NetBeans APIs

This page contains extracted usecases for some of the NetBeans modules that offer an API.

How to use Progress API?

The progress API is good for tracking progress of long lasting tasks in the IDE.

Basic usage

There are 3 types of progress indication:

The default location of the progress indication is the status bar which aggregates all tasks running in the IDE that show progress. However it's possible to exclude the task from the default location and show the progress in one's custom dialog component. In such a case the same task should not appear in the status line component as well.

It's possible to request cancelling the task from status line progress aggregator if the task allows cancelling.

Progress tasks that get started as a result of explicit user action takes precedence in the status line docked component over tasks that are triggered by the system. (say filesystem refresh for example)

The most common usecase of the API looks like this:

ProgressHandle handle = ProgressHandleFactory.creatHandle("My custom task");
...
// we have 100 workunits
// at this point the task appears in status bar.
handle.start(100);
...
handle.progress(10);
...
handle.progress("half way through", 50);
...
handle.progress(99);
// at this point the task is finished and removed from status bar
// it's not realy necessary to count all the way to the limit, finish can be called earlier.
// however it has to be called at the end of the processing.
handle.finish();

Advanced Usage

In case your usage of the API

then you should consider using the aggregating version of APIs which is similar to the simple APIs but has distinctive differences and additions that allow for more complex scenarios.

It allows to compose the progress bar from 1+ independent sources, all sharing proportional piece of the progress bar. Additionally you can monitor the task's overall progress from one central place and possibly add more contributing sources of the progress during processing.

        // let's have a factory for client code that performs some part of the job to be done..
        Lookup.Result res = Lookup.getDefault().lookup(new LookupTemplate(MyWorkerFactory.class));
        Iterator it = res.allInstances().iterator();
        ProgressContributor[] contribs = new ProgressContributor[res.allInstances().size()];
        int i = 0;
        while (it.hasNext()) {
            MyWorkerFactory prov = (MyWorkerFactory)it.next();
            contribs[i] = AggregateProgressFactory.createProgressContributor("Module X contribution");
            MyWorker worker = prov.createWorker(contribs[i]);
            //... snip ... do something with the worker..
            i = i + 1;
        }
        AggregateProgressHandle handle = AggregateProgressFactory.createHandle("My Task", contribs, null, null);
        // non-cancellable and with out output link.
        
        // calling start() at the time when the actual long running task starts processing
        handle.start("here we go");
        // ...snip...
        // now the individual MyWorker instances log their progress.
        // possibly in other threads too..
        // ... snip...
        // 
        if (myConditionThatSpawnsAnotherContributor()) {
            ProgressContributor cont = AggregateProgressFactory.createProgressContributor("Additional exceptional contribution");
            handle.addContributor(cont);
            // ... snip ...
        }
        
        // the task is finished when all the ProgressContributors finish..

How to use MIME Lookup API?

Each editor provides an EditorKit which controls the policy of specific MIME content type. The policy of content type should be easily registered and found via some lookup mechanism, that will provide convenient way of using it either for kit provider or base editor infrastructure. In addition to this, the policy can be inherited, (e.g. in case of embeded kits like JSP) and the content types need to be merged in this case. MIME Lookup API should provide all mentioned requierements via easy lookup query, so content type policy user need not to solve this searching and merging on its own side.

Per mime-type operation

Operation of the editor module must be parametrized by the type of the file being edited. In the past the operation was parametrized by the class of the editor kit but that did not show up as being useful enough.
It is more practical to use a string-based parametrization concretely the mime-type. Anyone can then easily register an additional functionality for the editor because it's just enough to know the right mime-type and the type of the functionality class to be implemented and the xml layer folder where the class should be registered.

Provide list of instances as lookup result

On the modules' implementation side the registered functionality must be retrieved somehow. It's necessary to instantiate the registered objects and react to module enabling/disabling which can affect validity of the registered objects.
As the most convenient solution appears to use org.openide.util.Lookup allowing to provide the registered instances as a Lookup.Result allowing to listen for changes (e.g. caused by the module enabling/disabling).
This resulted into creation of class MimeLookup extends Lookup containing static MimeLookup getMimeLookup(String mimeType).

Nested mime-types

On the lexical level the document can contain nested languages.
For example JSP document can contain pieces of java code which can further contain javadoc comment tokens with nested javadoc language.
The nested languages should allow for special settings such as fonts and colors of nested syntax coloring but even things like actions that would be active in the nested document section.
This resulted into creation of static Lookup getLookup(MimePath mimePath) method in MimeLookup.

Known clients summary

Fold Manager Factories
The editor/fold module expects to find the registered fold manager factories (org.netbeans.spi.editor.fold.FoldManagerFactory classes).

Completion Providers
The editor/completion module expects to find the registered completion providers (org.netbeans.spi.editor.completion.CompletionProvider classes).

Editor Context Menu Actions
The editor module expects to find the registered popup menu actions (javax.swing.Action classes or names of actions (i.e. value of Action.NAME attribute) present in editor kit e.g. "goto-source").

Side Bars
The editor/lib module expects to find factories for components to be placed on the sides of the editor component (org.netbeans.editor.SideBarFactory classes).

Hyperlink Providers
The editor/lib module expects to find hyperlink providers that allow connecting an open document with some other documents (org.netbeans.lib.editor.hyperlink.spi.HyperlinkProvider classes).

Code Template Processors
The editor/codetemplates module expects to find factories for code template processors (org.netbeans.lib.editor.codetemplates.spi.CodeTemplateProcessorFactory classes).

Hints Providers
The editor/hints module expects to find editor hints providers (org.netbeans.modules.editor.hints.spi.HintsProvider classes).


API Use Cases

Find class instances for the given mime-type

An API method

MimeLookup lookup = MimeLookup.getMimeLookup("text/x-java");

can be used for getting the mime specific lookup. Having this we can lookup class or template:

Object obj = lookup.lookup(LookedUpClass.class);

or

Lookup.Result result = lookup.lookup(new Lookup.Template(LookedUpClass.class));

Getting embeded mime-type specific Lookup

As an example a jsp scriptlet is used. Scriptlet in fact consists of parent "text/x-jsp" mime-type and embeded "text/x-java" mime-type. To obtain a scriptlet lookup firstly we need to get a MimePath and then get appropriate lookup:

    MimePath scriptletPath = MimePath.parse("text/x-jsp/text/x-java");
    Lookup lookup = MimeLookup.getLookup(scriptletPath);

SPI Use Cases

Providing implemented MimeLookupInitializer

It is the general way of adding mime specific object into the MimeLookup. Implementation of MimeLookupInitializer should be created and registered to default lookup via META-INF/services registration. For details, please look at the simplified TestMimeLookupInitializer in mimelookup/test/unit or LayerMimeLookupInitializer. Usage of MimeLookupInitializer is deprecated, please use MimeDataProvider instead in similar way

How to use Options Dialog and SPI?

This module contains implementation of Options Panel and simple SPI.

Register top level Options Panel

Client can install new panel to Options Dialog - see JavaDoc for OptionsCategory class.

Register panel to Advanced Options Panel

Client can install new panel to Advanced Options Panel - see JavaDoc for AdvancedOption class.


How to use General Queries API?

General kinds of queries between modules. Queries are one way of solving the intermodule communication problem when it is necessary for some modules to obtain basic information about the system (e.g. whether a particular file is intended for version control) without needing direct dependencies on the module providing the answer (e.g. the project type which controls the file). Details are covered in the Javadoc.

Particular use cases are enumerated in the Javadoc for each query API. Usage consists of simple static method calls. Potentially a wide variety of modules could use these queries; implementations are typically registered by project type providers, though also by Java library and platform implementations.


How to use Command Line Parsing API?

GetOpts like infrastructure to parse command line arguments with the cooperative participation of various modules.

Just Parse the Command Line

There needs to be a simple API for someone who has an array of strings and wants to parse them. One does not need to search for providers, just ask the infrastructure to do the parse and get the result.

The correct way to achieve this is to call CommandLine.getDefault().process(args).

Short and Long options with or without an argument

The standard getopts supports short form of options - e.g. a dash followed with one letter - or long form using two dashes followed with a word. Moreover the long form is optimized for abbrevations. If there are no conflicts between multiple options, then one can only use double dash followed with a prefix of a long option.

One can create an Option by calling any of its factory methods (like withoutArgument) and provider char for the one letter option and/or string for the long getopts option.

Options with or without an argument

There are three types of options. Those without an argument, those with a required one and those with optional one. Each one can be created by appropriate factory method in the Option class.

Support for --

The getopts compliant command line parsers support --. If these characters do appear on the command line, the rest of it is treated as extra arguments and not processed. The sendopts infrastructure supports this as well.

Multiple Independent CLI Handlers

The handlers for the options need not know about each other and still have to be able to process the command line successfully. Any module which wishes to provide its own options can register its OptionProcessor into a file META-INF/services/org.netbeans.spi.sendopts.OptionProcessor in its JAR file.

Extensible Options Set

Q: How shall one write an OptionProcessor that recognizes set of basic options, however contains one open slot? The processor wants other modules to provide recognizers for that slot and wants to communicate with them. For example, by default the processor recognizes option --channel <name_of_the_channel> which describes a source of data, and stores such data into a sink. There can be multiple sinks - discard the output, save it to file, show it on stdout, stream it to network. The processor itself can handle the copying of data, but does not itself know all the possible sink types.

To implement OptionProcessor like this one shall define an additional interface to communicate with the sink providers:

   package my.module;
   public interface SinkProvider {
     /** gets the option (even composite) that this sink needs on command line */
     public Option getOption();

     /** processes the options and creates a "sink" */
     public OutputStream createSink(Env env, Map<Option,String[]> values) throws CommandException;
   }
       

Other modules would then registered implementations of this interface in the META-INF/services/my.module.SinkProvider files. The OptionProcessor itself would just look all the implementations up, queried for the sinks, and then did the copying:

   class CopyingProvider extends OptionProvider {
     public Option getOption() {
        List<Option> l = ...;
        for (SinkProvider sp : Lookup.getDefault().lookupAll(SinkProvider.class)) {
          l.add(sp.getOption());
        }

        // we need only one provider to be present
        Option oneOfSinks = OptionGroups.oneOf(l.toArray(new Option[0]));

        // our channel option
        Option channel = ...;

        // the channel option needs to be present as well as a sink
        return OptionGroups.allOf(channel, oneOfSinks);
     }

     public void process(Env env, Map<Option,String[]> values) throws CommandException {
        OutputStream os = null;
        for (SinkProvider sp : Lookup.getDefault().lookupAll(SinkProvider.class)) {
          if (values.containsKey(sp.getOption())) {
            os = sp.createSink(env, values);
            break;
          }
        }
        if (os == null) {
          throw CommandException.exitCode(2);
        }

        // process the channel option and
        // handle the copying to the sink os
     }
   }
       

Another possible approach how to allow sharing of one option between multiple modules is to expose the option definition and its handling code as an interface to other modules, and then let the modules to write their own OptionProcessors. Necessary condition is that each of the processor is uniquely identified by some additional option, so when the shared option appears the infrastructure knows which processor to delegate to. This is demonstrated in the SharedOptionTest which basically does the following:

   /** the shared option, part of an interface of some module */
   public static final Option SHARED = ...;
   /** finds value(s) associated with the SHARED option and 
   * creates a JPanel based on them */
   public static JPanel getSharedPanel(Map<Option,String[]> args) { ... }
       

Then each module who wishes to reuse the SHARED option and the factory method that knows how to process their values for their own processing can just:

  public static final class ShowDialog extends OptionProcessor {
    private static final Option DIALOG = Option.withoutArgument('d', "dialog");

    protected Set<Option> getOptions() {
        // the following says that this processor should be invoked
        // everytime --dialog appears on command line, if the SHARED
        // option is there, then this processor wants to consume it 
        // as well...
        return Collections.singleton(Option.allOf(DIALOG, Option.anyOf(SHARED)));
    }

    protected void process(Env env, Map<Option, String[]> optionValues) throws CommandException {
        JPanel p = getSharedPanel(optionvalues);
        if (p == null) {
           // show empty dialog
        } else {
           // show some dialog containing the panel p
        }
    }
  }
       

The other modules are then free to write other processors refering to SHARED, for example one can write ShowFrame that does the same, just shows the panel in a frame, etc. The infrastructure guarantees that the exactly one provider which matches the command line options is called.

Printing Full Help Text

Althrough the handlers are provided by independent parties, it must be possible to generate resonable and consistent help description from all of them, so for the end user it appears as well formated and easily understandable. That is why every option can be associated with a short description providing info about what it is useful for using Option.shortDescription method. To get the description for all available options one can use CommandLine.getDefault().usage(java.io.PrintWriter).

Finding and Reporting when Options Are Not Correct

In case the command line cannot be processed a clean error for programmatic consumation and also one that can be shown to the end user of the command line must be given. This is handled by throwing CommandException with appropriate message description and exit code.

Processing Extra Command Line Arguments

There can be non-option arguments in the command line and they can freely mix with the option ones. For example the getopts would treat the following command line arguments as the same:
       --open X.java Y.java Z.txt
       X.java Y.java --open Z.txt
       
if the option open handles extra arguments. The sendopts infrastructure must distinquish between them and pass the non-option ones to the only one handler (active because it processed an option) that knowns how to parse them. It is an error if more than one or no handler expresses an interest in extra arguments and those are given. One can register such option by using the Option.additionalArgument factory method.

Handling Input and Output

Handler's shall not use the input and output streams directly for their execution, they should rely on the framework provided ones. This allows NetBeans based application to transfer the I/O from second started instance to the master one which is already running. From the client side there is the CommandLine.getDefault().parse methods taking additional arguments like input and output streams. This gets transfered to providers as an Env argument of their methods.

Returning Exit Code

When Handler's get execute (in the order defined by the order of options on the command line), each of them can either execute successfully, or fail. If a handler succeeds, next one is executed, if it fails, the execution is terminated and its return code is returned to the caller. The error can be notified by creating and throwing CommandException.exitCode(int errorCode).

Processing Only Extra Command Line Arguments

Sometimes it is desirable to process non-option arguments like file names without providing any option. Handlers can declare interest in such arguments. It is an error if such non-options are provided and no or more than one handler is around to handle them. One can create such option by using Option.defaultArguments factory method.

Only those processor need to process the options are created

For purposes of usage in NetBeans, it is needed to non initialize those handlers that are not really needed to process certain command line. The infrastracture decides which of them are going to be needed and instantiates only those. Given the amount of providers in current NetBeans IDE, this is not supported yet.

Complex Option Relations

Certain CLI processors may need more than one option before they can process the input. For example it is necesary to tune the radio and then also tell what to do with the output. It is unconvenient to process that as one option with argument(s), that is why one can use the OptionGroups.allOf, OptionGroups.someOf, for example like:
class PP extends OptionProcessor {
    private static Option tune = Option.requiredArgument(Option.NO_SHORT_NAME, "tune");
    private static Option stream = Option.requiredArgument(Option.NO_SHORT_NAME, "stream");
    
    public Set<Option> getOptions() {
      return Collections.singleton(
        OptionGroups.allOf(tune, stream)
      );
    }
    
    public void process(Env env, Map>Option,String[]> values) throws CommandException {
        String freq = values.get(tune)[0];
        String output = values.get(stream)[0];

        // XXX handle what is needed here
    }
}
When the two options are registered and command line like --tune 91.9 --stream radio1.mp3 is being processed, the PP's process method is going to get called with values 91.9 and radio1.mp3.

Alternative Options

Sometimes there may different ways to specify the same option and just one of them or none of them can be provided at given time. For example is there is a way to tune the radio with direct frequency or with name of the station. Just one can be provided and one is needed. This can be specified by using OptionGroups.oneOf factory methods:
Option freq = Option.requiredArgument(Option.NO_SHORT_NAME, "tune");
Option station = Option.requiredArgument(Option.NO_SHORT_NAME, "station");
Option tune = OptionGroups.oneOf(freq, station);    
The option tune then signals that just one of the station or freq options can appear and that they both are replaceable.


How to use Actions APIs?

Actions provides system of support and utility classes for 'actions' usage in NetBeans.

First see the API description. Here is just a list of frequently asked or interesting questions slowly expanding as people ask them:

Actions faq:

How to define configurable Shortcut for Component based shortcut?

Q: The usual Swing way of defining Actions for your component is to create an Action instance and put it into the Input and Action maps of your component. However how to make this Action's shortcut configurable from the Tools/Keyboard Shortcuts dialog?

In order for the action to show up in Keyboards Shortcut dialog you need the action defined in the layer file under "Actions" folder and have the shortcut defined there under "Keymaps/<Profile Name>" linking to your action.

    <folder name="Actions" >
        <folder name="Window">
            <file name="org-netbeans-core-actions-PreviousViewCallbackAction.instance"/>
        </folder>
    </folder>

    <folder name="Keymaps">
        <folder name="NetBeans">
            <file name="S-A-Left.shadow">
                <attr name="originalFile" stringvalue="Actions/Window/org-netbeans-core-actions-PreviousViewCallbackAction.instance"/>
            </file>
        </folder>
    </folder>

The mentioned Action has to be a subclass of org.openide.util.actions.CallbackSystemAction. It does not necessarily has to perform the action, it's just a placeholder for linking the shortcut. You might want to override it's getActionMapKey() and give it a reasonable key.

The actual action that does the work in your component (preferably a simple Swing javax.swing.Action) is to be put into your TopComponent's ActionMap. The key for the ActionMap has to match the key defined in the global action's getActionMapKey() method.

        getActionMap().put("PreviousViewAction", new MyPreviousTabAction());

This way even actions from multiple TopComponents with the same gesture (eg. "switch to next tab") can share the same configurable shortcut.

Note: Don't define your action's shortcut and don't put it into any of the TopComponent's javax.swing.InputMap. Otherwise the component would not pick up the changed shortcut from the global context.


How to use UI Utilities API?

The org.openide.awt provides API/SPI for UI related aspects of application.

XXX no answer for arch-usecases


How to use Dialogs API?

The DialogsAPI allows creating a user notification, a dialog's description and also permits it to be displayed. The wizard framework allows create a sequence of panels which leads a user through the steps to complete any task. This API is part of package org.openide.

There is a Wizard Guide Book providing the introductionary information, moreover here is a list of frequently asked questions and their answers:

How to change the title of a wizard?

Q: Although none of my panels have names set (using setName() method) and the method name() in the WizardDescriptor.Iterator returns an empty string, I'm getting "wizard ( )" as the title of each panel in my wizard. When I set the name of the panel and return a string from the method name() I get: "panelName wizard (myName)". The wizard steps are labeled correctly, it just the panel title/name that looks like it adds "wizard ()" to any of my panels. I don't mind the "( )", but I would like to rid of the word "wizard".

A: You can change the format of your wizard's title by WizardDescriptor.setTitleFormat(MessageFormat format) and rid of 'wizard' word in the default wizard's title.


How to use File System API?

The Filesystems API provides a common API to access files in a uniform manner. It is available as standalone library and also is bundled together with other parts of the openide. Specification

Many of the usecases are described at the overall documentation, in a way how to register a mime type. Some of the additional usecases are covered here.

How to change menus, etc. after login?

Since version 7.1 there is a way to change the content of system file system in a dynamic way. As system file systems contains various definitions (in NetBeans Platform menus, toolbars, layout of windows, etc.) it de-facto allows global change to these settings for example when user logs into some system.

First thing to do is to create an implementation of filesystem. It can be created either from scratch, or by subclassing AbstractFileSystem, or MultiFileSystem. In this example we will subclass the MultiFileSystem:

public class LoginFileSystem extends MultiFileSystem {
    private static LoginFileSystem INSTANCE;
    public LoginFileSystem() {
        // let's create the filesystem empty, because the user
        // is not yet logged in
        INSTANCE = this;
    }
    public static void assignURL(URL u) throws SAXException {
        INSTANCE.setDelegates(new XMLFileSystem(u));
    }
}
      

It is necessary to register this instance in lookup by creating the file:

with a single line containing the full name of your filesystem - e.g. your.module.LoginFileSystem. When done, the system will find out your registration of the filesystem on startup and will merge the content of the filesystem into the default system file system. You can show a dialog letting the user to log in to some system anytime later, and when the user is successfully in, just call LoginFileSystem.assignURL(url) where the URL is an XML file in the same format as used for regular layer files inside of many NetBeans modules. The system will notice the change in the content and notify all the config file listeners accordingly.

Of course, instead of XMLFileSystem you can use for example memory file system, or any other you write yourself.


How to use I/O APIs?

The Input/Output API is a small API module which contains InputOutput and related interfaces used in driving the Output Window. The normal implementation is org.netbeans.core.output2.

There is an SPI but additional implementations are not expected. The API is most important.

Simple usage example:


InputOutput io = IOProvider.getDefault().getIO("My Window", true);
io.select();
OutputWriter w = io.getOut();
w.println("Line of plain text.");
OutputListener listener = new OutputListener() {
    public void outputLineAction(OutputEvent ev) {
        StatusDisplayer.getDefault().setStatusText("Hyperlink clicked!");
    }
    public void outputLineSelected(OutputEvent ev) {
        // Let's not do anything special.
    }
    public void outputLineCleared(OutputEvent ev) {
        // Leave it blank, no state to remove.
    }
};
w.println("Line of hyperlinked text.", listener, true);

How to use Datasystems API?

In summary, the LoadersAPI is responsible for scanning files in a directory on disk, weeding out irrelevant files of no interest to the IDE, and grouping the rest into logical chunks, or just determining what type of data each represents. It does this scanning by asking each registered data loader whether or not the given file(s) should be handled. The first loader to recognize a file takes ownership of it, and creates a matching data object to represent it to the rest of the IDE.

A lot of usecases is described in the javadoc. Here is the list of some faqs:

Using Scripting and Templating Languages

Often many people require ability to create a "clever" template - e.g. write piece of simple text and at the time of its processing do some advanced changes to it using either scripting or templating languages.

This traditionally used to be a bit complicated task, however since version 6.1 there are new interfaces can be registered as a services in a lookup and it is reponsible for handling the whole copy of the template file(s) to the destination folder. and can be registered as a services in a lookup and it is reponsible for providing "hints" - e.g. map mapping strings to various objects. and these interfaces allow anyone to extend the behaviour during creation of new files without writing new DataLoader and co.

Smart Templating Quick How-To
First of all create a file in your module layer located somewhere under the Templates/ folder. Make it a template by adding <attr name="template" boolvalue="true"/>. Associate this template with a scripting language, for example by <attr name="javax.script.ScriptEngine" stringvalue="freemarker"/>. Now make sure that the scripting language integration is also available by requesting a token in standard format, for freemarker just put OpenIDE-Module-Needs: javax.script.ScriptEngine.freemarker in your manifest. Also create a runtime dependency on org.netbeans.modules.templates - the module providing the templates/scripting languages integration. the module providing the templates/scripting languages integration. This tells the NetBeans module system that a module providing integration with such scripting engine has to be enabled. Now you can use regular script language tags inside of your template file. When you write your instantiate method in your wizard, you can create a Map<String,Object> and fill it with parameters collected from your wizard and then pass it to createFromTemplate(targetFolder, targetName, mapWithParameters) . This will invoke the scripting language and make the mapWithParameters values available to it. Beyond this there is few standard parameters predefined including name, user, date, time, etc. and also additional parameters are collected from all registered CreateFromTemplateAttributesProviders.

Moreover there is a built in support for scripting languages in the standard NetBeans IDE. If a template is annotated with a property that can be associated to templates that either should return real instance of ScriptEngine interface or a String name of the engine that is then used to search for it in the javax.script.ScriptEngineManager. Usually the freemarker engine is the one that is supported by the NetBeans IDE - if your module wants to use it then include a token dependency OpenIDE-Module-Needs: javax.script.ScriptEngine.freemarker in your manifest file (also accessible through project customizer GUI) to indicate to the system that you need it. then the scripting engine is then used to process the template and generate the output file. While running the engine one can rely on few predefined properties:

Other properties can indeed be provided by CreateFromTemplateAttributesProviders. After processing, the output is also sent to appropriate org.openide.text.IndentEngine associated with the mime type of the template, for formating.

How to add action to folder's popup menu?

The actions that the default folder loader shows in its popup menu are read from a layer folder Loaders/folder/any/Actions so if any module wishes to extend, hide or reorder some of them it can just register its actions there. As code like this does:
    <folder name="Loaders" >
        <folder name="folder" >
            <folder name="any" >
                <folder name="Actions" >
                    <file name="org-mymodule-MyAction.instance" >
                        <attr name="instanceCreate" stringvalue="org.mymodule.MyAction" />
                    </file>
                </folder>
            </folder>
        </folder>
    </folder>
    
As described in general actions registration tutorial.

This functionality is available since version 5.0 of the loaders module. Please use OpenIDE-Module-Module-Dependencies: org.openide.loaders > 5.0 in your module dependencies.

In version 5.8 all the standard loaders were changed to read actions from layer:

How to allow others to enhance actions of your loader?

If you want other modules to enhance or modify actions that are visible on DataObjects produced by your DataLoader and you are either using DataNode or its subclass, you can just override protected String actionsContext() method to return non-null location of context in layers from where to read the actions.

The usual value should match Loaders/mime/type/Actions scheme, for example java is using Loaders/text/x-java/Actions, but the name can be arbitrary.

This functionality is available since version 5.0 of the loaders module. Please use OpenIDE-Module-Module-Dependencies: org.openide.loaders > 5.0 in your module dependencies.

How to use Module System API?

The Modules API lies at the core of NetBeans and describes how plug-in modules are added and managed. ModulesAPI

How a classpath of my module is constructed?

The NetBeans is defacto a container that manages individual module's lifecycle and other runtime aspects. One of the important things is that it creates a runtime classpath for provided modules based on dependencies they specify in their manifests. The overview of the runtime infrastructure is a good starting place for everyone who wishes to learn more about the NetBeans runtime container behaviour.

How to use Settings Options API?

org.openide.options

N/A


How to use Utilities API?

Described in the overall answer.

There is a great introduction to Lookup and its usage in its javadoc. Here is just a list of frequently asked or interesting questions slowly expanding as people ask them:

Lookup faq:

How to specify that a service in Lookup should be available only on Windows?

Q: Most of the time I specify interfaces that I want to add to the Lookup class in the layer.xml file. But, let's say I have a platform-specific interface (something on Windows only, for instance).

How can I specify (in the xml, or programmatically) that this service should only be added to the Lookup if the platform is Windows? >

In general there are three ways to achieve this.

How shall I write an extension point for my module?

Q: I have more modules one of them providing the core functionality and few more that wish to extend it. What is the right way to do it? How does the Netbeans platform declare such extension point?

Start with declaring an extension interface in your core module and put it into the module's public packages. Imagine for example that the core module is in JAR file org-my-netbeans-coremodule.jar and already contains in manifests line like OpenIDE-Module: org.my.netbeans.coremodule/1 and wants to display various tips of the day provided by other modules and thus defines:

 

package org.my.netbeans.coremodule;

public interface TipsOfTheDayProvider {
    public String provideTipOfTheDay ();
}

And in its manifest adds line OpenIDE-Module-Public-Packages: org.my.netbeans.coremodule.* to specify that this package contains exported API and shall be accessible to other modules.

When the core module is about to display the tip of the day it can ask the system for all registered instances of the TipsOfTheDayProvider, randomly select one of them:


import java.util.Collection;
import java.util.Collections;
import org.openide.util.Lookup;

Lookup.Result result = Lookup.getDefault ().lookup (new Lookup.Template (TipsOfTheDayProvider.class));
Collection c = result.allInstances ();
Collections.shuffle (c);
TipsOfTheDayProvider selected = (TipsOfTheDayProvider)c.iterator ().next ();

and then display the tip. Simple, trivial, just by the usage of Lookup interface once creates a registry that other modules can enhance. But such enhancing of course requires work on the other side. Each module that would like to register its TipsOfTheDayProvider needs to depend on the core module - add OpenIDE-Module-Module-Dependencies: org.my.netbeans.coremodule/1 into its manifest and write a class with its own implementation of the provider:


package org.my.netbeans.extramodule;

class ExtraTip implements TipsOfTheDayProvider {
    public String provideTipOfTheDay () {
        return "Do you know that in order to write extension point you should use Lookup?";
    }
}

Then, the only necessary thing is to register such class by using the J2SE standard into plain text file META-INF/services/org.my.netbeans.coremodule.TipsOfTheDayProvider in the module JAR containing just one line:

org.my.netbeans.extramodule.ExtraTip

and your modules are now ready to communicate using your own extension point.

How shall I do or influence logging in NetBeans?

If you are interested in logging from inside your module, or in writing your own log handler or in configuring the whole system, then best place to start is the NetBeans logging guide.


How to use Window System API?

Window System API is used to display and control application GUI: Main window, frames, components.

General Use cases can be read on the external page. Here is a small howto for simple things that may be found useful:

How to create a '.settings' file for a TopComponent?

Either write it by hand (not that hard if you copy other file and tweak it to match your TC), or start the IDE, instantiate the TC somehow (You have a "Window->Show My TC", right? ), copy the file that gets created in $userdir/config/Windows2Local/Component and cleanup the serialdata section - replace it with proper "<instance class='..." /> tag.

How to make a TopComponentGroup?

Q: I'm trying to make a TopComponentGroup. I've just read http://ui.netbeans.org/docs/ui/ws/ws_spec.html#3.9 I want to make a group that uses the first invocation strategy. That is, I want the group to open/close when I activate a certain subclass of TopComponent. Say, for example, I have a FooTopComponent, and when it's active, I want to open a FooPropertySheetComponent, docked in a mode on the right-hand side. I know I have to:
  1. declare the group in the layer file (Windows2/Groups)
  2. have code for opening the group
  3. have code for closing the group
I think I do #2 in FooTopComponent.componentActivated() and #3 in FooTopComponent.componentDeactivated(). Is that right?

A:Yes it is correct way. You can check simple test module. First you must get TopComponentGroup instance using find method then call TopComponentGroup.open()/close(). Here is the code in your componentDeactivated method:
   protected void componentDeactivated ()
   {
       // close window group containing propsheet, but only if we're
       // selecting a different kind of TC in the same mode
       boolean closeGroup = true;
       Mode curMode = WindowManager.getDefault().findMode(this);
       TopComponent selected = curMode.getSelectedTopComponent();
       if (selected != null && selected instanceof FooTopComponent)
           closeGroup = false;
             if (closeGroup)
       {
           TopComponentGroup group = WindowManager.getDefault().findTopComponentGroup(TC_GROUP);
           if (group != null)
           {
               group.close();
           }
       }
   }