import java.util.SortedSet; import java.io.OutputStream; import java.io.File; import java.util.TreeSet; import java.io.OutputStreamWriter; import java.io.IOException; import java.io.FileWriter; /** * @author Tomas Sedmik, xsedmik@fi.muni.cz * @version 06 01 2010 */ public class BarImpl implements Bar { private SortedSet drinks = new TreeSet(); /** * Adds a new drink. * * @param drink Drink to add, must not be null * @return false if the drink is already present at the bar, true otherwise * @throws NullPointerException if drink param. is null */ public boolean addDrink(Drink drink) { return drinks.add(drink); } /** * @return all drinks at the bar sorted by the NATURAL ORDERING of drinks */ public SortedSet getDrinks() { return drinks; } /** * @return drinks SORTED BY THEIR PRICE, i.e. by the PriceComparator */ public SortedSet getPriceList() { SortedSet tmp = new TreeSet(new PriceComparator()); tmp.addAll(drinks); return tmp; } /** * Writes names of drinks to given output stream. Drinks are writen * in the order defined by the PriceComparator. * * @param os Output stream to write drinks to * @throws BarException on any I/O failure */ public void printPriceList(OutputStream os) throws BarException { OutputStreamWriter osw = new OutputStreamWriter(os); SortedSet tmp = getPriceList(); try { for (Drink drink : tmp) { osw.write(drink.getName() + '\n'); } osw.flush(); } catch (IOException e) { throw new BarException("Output error",e); } } /** * Writes names of drinks to given file. Drinks are writen * in the order defined by the PriceComparator. * * @param file File to write drinks to * @throws BarException on any I/O failure */ public void printPriceList(File file) throws BarException { try { FileWriter fw = new FileWriter(file); SortedSet tmp = getPriceList(); for (Drink drink : tmp) { fw.write(drink.getName() + '\n'); } fw.flush(); } catch (IOException e) { throw new BarException("File output error",e); } } }