4.3. Retrieving Resources from within the Bundle

A bundle can carry not only code, but also data. Packaging classes and required resources together make the bundle a self-contained deployment unit.

In our dictionary bundle, it is apparent that inserting individual word definition entries into the data structure is awkward. Unless we add tens of thousands of put statements to our implementation code, our dictionary service won't be of much use.

Let's create a property file containing the dictionary entries, pack the file into the bundle, and write code to retrieve the entries in the dictionary service.

Here's a segment of the text file webster.properties:

# The word definitions from Webster's Dictionary
...
accuse=to charge with fault or offense
admire=to marvel at or esteem highly
...
calamity=a state of deep distress or misery caused by major
misfortune or loss
kill=to deprive of life
...

Save the property file in the directory in which the implementation classes reside and create the bundle JAR file. Its contents will look like this:

META-INF/
META-INF/MANIFEST.MF
com/acme/service/dictionary/DictionaryService.class
com/acme/impl/dictionary/Devil.class
com/acme/impl/dictionary/Webster.class
com/acme/impl/dictionary/Activator.class
com/acme/impl/dictionary/webster.properties
				

We modify the constructor of Webster class to retrieve the properties:

import java.io.*;
class Webster implements DictionaryService {
   private Properties defs;
   Webster() {
      try {
         String resourceName =
            "/com/acme/impl/dictionary/webster.properties";
         InputStream in =
            this.getClass().getResourceAsStream(resourceName);
         if (in != null)
            defs.load(in);
      } catch (IOException e) {
      }
   }
   ...
}

A class loader is created for each bundle for loading classes and resources from the bundle. When you call the getResourceAsStream or the getResource methods, the class loader associated with the bundle is called to duty to retrieve the resources. That's why you can use any class object inside the bundle and call getResourceAsStream on it. The resource name should be the full path to the resource internal to the bundle JAR file. This technique works for any type of data files, be they GIF or JPEG images, HTML pages, or configuration properties.

You may also call getResource and get a URL pointing to the desired resource. We discuss the use of the URL in more detail when we discuss the HTTP service in Chapter 7.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.228