27.7.10

Using Lookup & ServiceProvider Mechanism in NetBeans Platform

http://platform.netbeans.org/tutorials/nbm-quick-start.html

Part of the tutorial, only focus on Lookup & serviceProvider

 


  1. Create a third module in your application, name it "MyFilter", with "org.demo.myfilter" as the code name base.
  2. Add a dependency in the Project Properties dialog of the newly created "MyFilter" module to the "TextFilter" module:

  3. In the same way as shown in the previous step, set a dependency on the Lookup API module, which provides the ServiceProvider annotation that you will use in the next step.
  4. Because of the dependency you defined above, you can now implement the interface defined in the second module:
    package org.demo.myfilter;

    import org.demo.textfilter.TextFilter;

    @ServiceProvider(service=TextFilter.class)
    public class UpperCaseFilter implements TextFilter {

    public String process(String s) {
    return s.toUpperCase();
    }

    }

    At compile time, the @ServiceProvider annotation will create a META-INF/services folder with a file that registers your implementation of the TextFilter interface, following the JDK 6 ServiceLoader mechanism.


  5. The code that handles a click on the filter button now needs to be changed, so that an implementor of the interface "TextFilter" is located and loaded. When such an implementor is found, it is invoked to filter the text.

    Before we can do this, we need to add a dependency in the Project Properties dialog of the "WordEngine" module to the "TextFilter" module:


    Now, you can load implementations of the "TextFilter" class, as shown below:

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    String s = text.getText();
    TextFilter filter = Lookup.getDefault().lookup(TextFilter.class);
    if (filter != null) {
    s = filter.process(s);
    }
    text.setText(s);
    }

    The above could be done via the JDK 6 "ServiceLoader" class, except that the "Lookup" class can be used in JDK's prior to JDK 6. Aside from that, the "Lookup" class has a number of additional features, as the next section will illustrate.


Now you are ready to run the code and check that everything works just as before. While the functionality is the same, the new modular design offers a clear separation between the graphical user interface and the implementation of the filter. The new application can also be extended quite easily, simply by adding new service providers to the application's classpath.

As an exercise, you could change the code, so that ALL found text filters (use the method "lookupAll") are applied consecutively on the text. For example, add a text filter implementation that removes all whitespaces and then test the resulting application.

No comments: