package dk.hansen; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class SimpleCDManager implements CDManagerIF { private static HashMap cds = new HashMap(); static { System.out.println("SimpleCDManager created - static code"); // Create some CDs for testing CD cd; String id; String title; String author; int year; id = "ID88"; title = "Who knows this CD?"; author = "The Singer"; year = 1988; cd = new CD(id, title, author, year); cds.put(id, cd); id = "ID89"; title = "I know this CD!"; author = "The Listener"; year = 1998; cd = new CD(id, title, author, year); cds.put(id, cd); } public void createCD(String id, String title, String author, int year) throws DAOException { CD cd = (CD)cds.get(id); if (cd != null) throw new DAOException("Id " + id + " is already used"); cd = new CD(id, title, author, year); cds.put(id, cd); } public void updateCD(String id, String title, String author, int year) throws DAOException { CD cd = (CD)cds.get(id); if (cd == null) throw new DAOException("Id " + id + " was not found"); cd.setTitle(title); cd.setAuthor(author); cd.setYear(year); } public void deleteCD(String id) throws DAOException { CD cd = (CD)cds.get(id); if (cd == null) throw new DAOException("Id " + id + " was not found"); cds.remove(id); } public CD getCD(String id) throws DAOException { CD cd = (CD)cds.get(id); return cd; } public Collection getAll() { return cds.values(); } public Collection findCDTitle(String title) { Collection hits = new ArrayList(); Collection c = cds.values(); for (Iterator it = c.iterator(); it.hasNext();) { CD cd = (CD)it.next(); if (cd.getTitle().toUpperCase().indexOf(title.toUpperCase()) > -1) { hits.add(cd); } } return hits; } public Collection findCDAuthor(String author) { Collection hits = new ArrayList(); Collection c = cds.values(); for (Iterator it = c.iterator(); it.hasNext();) { CD cd = (CD)it.next(); if (cd.getAuthor().toUpperCase().indexOf(author.toUpperCase()) > -1) { hits.add(cd); } } return hits; } public Collection findCDYear(int year) { Collection hits = new ArrayList(); Collection c = cds.values(); for (Iterator it = c.iterator(); it.hasNext();) { CD cd = (CD)it.next(); if (cd.getYear() == year) { hits.add(cd); } } return hits; } }