This accepts information about a new item and adds it to the
internal file-based catalog, using JAXB.
PrintWriter out = res.getWriter();
res.setContentType("text/html");
// Get input parameters
String id = req.getParameterValues("id")[0];
String levelString = req.getParameterValues("level")[0];
String title = req.getParameterValues("title")[0];
String teacher = req.getParameterValues("teacher")[0];
String[] guests = req.getParameterValues("guest");
String description = req.getParameterValues("description")[0];
// Create new item
Item item = new Item();
item.setId(id);
item.setLevel(LevelType.valueOf(levelString));
item.setTitle(title);
item.setTeacher(teacher);
if (guests != null) {
for (int i=0; i<guests.length; i++) {
if (!guests[i].trim().equals("")) {
item.addGuest(guests[i]);
}
}
}
item.setDescription(description);
try {
// Load current catalog
File catalogFile = new File(CATALOG_FILE);
FileReader reader = new FileReader(catalogFile);
Catalog catalog =
(Catalog)Unmarshaller.unmarshal(Catalog.class, reader);
// Add item
catalog.addItem(item);
// Write back out modified catalog
FileWriter writer = new FileWriter(catalogFile);
Marshaller.marshal(catalog, writer);
out.println("Item added.");
} catch (Exception e) {
out.println("Error loading/writing catalog: " + e.getMessage());
} finally {
out.close();
}