FileDocCategorySizeDatePackage
ContextBookServiceServantData.javaAPI DocExample3483Fri Oct 18 15:10:52 BST 2002ora.jwsnut.chapter6.contextbookservice

ContextBookServiceServantData

public class ContextBookServiceServantData extends Object
A class that loads the data for the context-handling book service

Fields Summary
private static HashMap
bookAuthorMap
The author data in the form of a HashMap, created when it is first requested.
private static String[]
bookTitles
List of book titles.
private static byte[]
buffer
Buffer used when reading image data
private static ByteArrayOutputStream
os
Stream used when reading image data
private static boolean
sorted
Records whether book data should be sorted.
Constructors Summary
Methods Summary
public static java.lang.StringgetBookAuthor(java.lang.String title)
Gets the author name for a book with a given title.

        loadData();
        return (String)bookAuthorMap.get(title.trim().toUpperCase());
    
public static java.lang.String[]getBookTitles()
Gets a list of all known books.

        loadData();
        return bookTitles;
    
private static voidloadData()
Loads the book data from information contained in the booklist.txt file.

        if (bookAuthorMap == null) {
            
            // First request - create the data
            bookAuthorMap = new HashMap();
            ArrayList list = new ArrayList();

            try {
                buffer = new byte[1024];
                os = new ByteArrayOutputStream();                
                InputStream is = 
                    ContextBookServiceServantData.class.getResourceAsStream("booklist.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    StringTokenizer st = new StringTokenizer(line, "!");
                    if (st.countTokens() == 2) {
                        String title = st.nextToken();
                        String canonicalTitle = title.trim().toUpperCase();
                        String author = st.nextToken();
                        
                        // Store the author name
                        bookAuthorMap.put(canonicalTitle, author);
                        
                        // Add a new book title
                        list.add(title);
                    }
                }
                
                bookTitles = new String[list.size()];
                list.toArray(bookTitles);
                if (sorted) {
                    Arrays.sort(bookTitles);
                }
            } catch (Exception ex) {
                // Just return an empty or partial list                
                ex.printStackTrace();
            }
        }
    
public static voidsetSorted(boolean cond)
Enables sorting of book titles.

        if (cond != sorted) {
            sorted = cond;
            bookTitles = null;  // Force reload of data
        }