package ora.jwsnut.chapter6.headerbookservice;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* A class that loads the data for the header book service
*/
class HeaderBookServiceServantData {
/**
* The author data in the form of a HashMap, created when it is
* first requested.
*/
private static HashMap bookAuthorMap;
/**
* List of book titles.
*/
private static String[] bookTitles;
/**
* Buffer used when reading image data
*/
private static byte[] buffer;
/**
* Stream used when reading image data
*/
private static ByteArrayOutputStream os;
/**
* Gets a list of all known books.
*/
public static String[] getBookTitles() {
loadData();
return bookTitles;
}
/**
* Gets the author name for a book with a given title.
*/
public static String getBookAuthor(String title) {
loadData();
return (String)bookAuthorMap.get(title.trim().toUpperCase());
}
/**
* Loads the book data from information contained
* in the booklist.txt file.
*/
private static void loadData() {
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 =
HeaderBookServiceServantData.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);
} catch (Exception ex) {
// Just return an empty or partial list
ex.printStackTrace();
}
}
}
} |