package ora.jwsnut.chapter6.serializerbookservice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* A class that loads the data for the book service
* and provides access to it in the form of an array
* of BookInfo objects.
*/
class SBookServiceServantData {
/**
* The loaded data, created when it is first requested
*/
private static BookInfo[] bookInfo;
/**
* The data in the form of a HashMap, created when it is
* first requested.
*/
private static HashMap bookMap;
/**
* Categorized data in the form of a HashMap.
*/
private static HashMap categorizedBookMap;
/**
* Gets the book info, creating it if necessary.
* @return an array of BookInfo objects with one entry
* for each book.
*/
static BookInfo[] getBookInfo() {
if (bookInfo == null) {
// First request - create the data
ArrayList list = new ArrayList();
try {
InputStream is =
SBookServiceServantData.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() == 4) {
list.add(new BookInfo(st.nextToken(), st.nextToken(),
st.nextToken(), Double.parseDouble(st.nextToken())));
} else if (st.countTokens() == 5) {
list.add(new ElectronicBookInfo(st.nextToken(), st.nextToken(),
st.nextToken(), Double.parseDouble(st.nextToken()),
st.nextToken()));
}
}
} catch (Exception ex) {
// Just return an empty or partial list
ex.printStackTrace();
}
// Convert the list to an array
bookInfo = new BookInfo[list.size()];
list.toArray(bookInfo);
}
return bookInfo;
}
/**
* Returns all of the books known to the book
* service in the form of a <code>HashMap</code> where the
* key to each entry is the book title in upper case
* and the value is a <code>BookInfo</code> object.
*/
static HashMap getBookInfoHashMap() {
if (bookMap == null) {
BookInfo[] info = getBookInfo();
bookMap = new HashMap();
for (int i = 0; i < info.length; i++) {
BookInfo book = info[i];
bookMap.put(book.getTitle().toUpperCase(), book);
}
}
return bookMap;
}
} |