package com.mindprod.welcome; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.HashSet; /** * A persistent cache people who have been sent a message, any newsgroup. * @since 2002-05-3 */ public class Informed { /** * constructor * * @param group name of newsgroup collection e.g. * comp.lang.java to handle comp.lang.java.help * and comp.lang.java.programmer. */ public Informed( String group ) { this.group = group; fireup(); } /** * name of newsgroup collection e.g. * comp.lang.java to handle comp.lang.java.help * and comp.lang.java.programmer. */ private String group; /** * Get list of everyone who has ever posted. * * @return */ public String[] getAllPeople() { String[] result = (String[])(cache.toArray(new String[cache.size()])); Arrays.sort(result); return result; } /** * collection of people who been informed already. * cleaned up email address, unlike Poster class. */ private HashSet cache; /** * Has this person posted before? * * @param email email address cleaned up * * @return true if person has been informed before. */ public boolean wasInformed(String email) { return cache.contains(email); } /** * Record the fact this person has posted to this newsgroup * It is ok to call hasPosted even if he hasPostedBefore, * though doing so is pointless. * * @param email email address cleaned up * * @return true if has posted in that newsgroup before. */ public void markInformed(String email) { if ( ! cache.contains(email) ) { cache.add(email); } } /** * Called when class is loaded to reconstitute the * serialised cache. */ private void fireup() { try { // O P E N FileInputStream fis = new FileInputStream(group+".group.ser"); ObjectInputStream ois = new ObjectInputStream(fis); // R E A D cache = (HashSet) ois.readObject(); // C L O S E ois.close(); } catch ( Exception e ) { System.out.println("Troubles restoring the group.ser file. Not to worry, starting afresh."); e.printStackTrace(); cache = new HashSet(2053, 0.75f); } } // end fireup /** * Called to save the cache * in serialised form * so you won't lose what you have so fare */ public void flush() { try { // O P E N FileOutputStream fos = new FileOutputStream(group+".group.ser", false /* append */); ObjectOutputStream oos = new ObjectOutputStream(fos); // W R I T E oos.writeObject(cache); // C L O S E oos.close(); } catch ( IOException e ) { System.out.println("Troubles writing out the group.ser file"); e.printStackTrace(); } } /** * Called when class is shut down to save the cache * in serialised form. */ public void close() { flush(); } // end close }