001package de.hdm_stuttgart.mi.sd1.htmlformat;
002
003import java.io.BufferedReader;
004import java.io.FileNotFoundException;
005import java.io.FileReader;
006import java.io.IOException;
007import java.io.PrintStream;
008import java.util.ArrayList;
009import java.util.List;
010
011/**
012 * Reading address data from text file data source.
013 */
014public class AddressDataHandler {
015
016  /**
017   * Available address records.
018   */
019  public final List<Address> addresses = new ArrayList<Address>();
020  
021  /**
022   * Parsing text file address data having the following format:
023   * 
024   * <pre>"firstName","lastName","companyName","address","city","county","postal","phone1","phone2","email","web"</pre>
025   * 
026   * The first line is expected to contain the above description and will be ignored.
027   * 
028   * @param filename Address data source.
029   * 
030   * @throws IOException Input file cannot be read
031   * @throws FileNotFoundException File does not exist
032   * @throws AddressParseError Input data file parse error
033   * 
034   */
035  public AddressDataHandler(final String filename) 
036      throws FileNotFoundException, IOException, AddressParseError {
037    
038    final BufferedReader reader = new BufferedReader(new FileReader(filename));
039    int lineNumber = 0; // Needed to supply file positions for error messages
040    for (String lineContent = reader.readLine(); lineContent != null; lineContent = reader.readLine()) {
041      lineNumber ++;
042      addresses.add(new Address(lineContent, lineNumber));
043    }
044    reader.close(); // Freeing OS resources no longer being needed. 
045  }
046  
047  /**
048   * Format the set of address records and write the result
049   * to a stream.
050   * @param out Desired output stream
051   * @param formatter Formatting instance (may e.g. be text, HTML,...)
052   */
053  public void printAddresses(final PrintStream out, final AddressFormatter formatter) {
054    formatter.printHead(out);
055    
056    for (final Address address: addresses) {
057      formatter.printRecord(address, out);
058    }
059    
060    formatter.printTail(out);
061  }
062}