package dk.daoas.adressevedligehold; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.fileupload.FileItem; import com.google.common.base.Splitter; import dk.daoas.adressevedligehold.AddressSourceEntry.EntryType; import dk.daoas.adressevedligehold.util.DeduplicateHelper; public class AddressSourceFD implements AddressSource { DeduplicateHelper dirigeringsCache = new DeduplicateHelper(); FileItem file; InputStream is; InputStreamReader isr; BufferedReader br; int lineCount = 0; String filenameFirst2; public AddressSourceFD(FileItem file) throws Exception { this.file = file; filenameFirst2 = file.getName().substring(0, 2).toUpperCase(); } @Override public String getFilename() { return file.getName(); } @Override public void validate() throws IOException { try { is = file.getInputStream(); isr = new InputStreamReader(is, Charset.forName("ISO-8859-1") ); br = new BufferedReader(isr); String line = br.readLine(); String[] parts = line.split(";"); int numFields = parts.length; if (numFields != 9) { throw new IOException("Not enough fields in CSV file. Found " + numFields + ", expected 9"); } } catch (Exception e) { try { br.close(); isr.close(); is.close(); } catch (Exception e2) { System.out.println("Error cleaning up resources"); } throw e; // Re-throw } } //TODO: Skal csv parsning klares med Apache Commons CSV ? @Override public AddressSourceEntry getNextEntry() throws IOException { String line = br.readLine(); if (line == null) // end of file return null; if (line.trim().equals("")) return null; //System.out.println(line); AddressSourceEntry entry = new AddressSourceEntry( EntryType.TypeSingleAddress); entry.distributor = "FD"; List parts = Splitter.on(';').splitToList(line); if (parts.size() != 9) { throw new IOException("Not enough fields in line " + line); } entry.postnr = Short.parseShort( parts.get(0) ); entry.vejnavn = parts.get(1); entry.husnr = Short.parseShort( parts.get(2) ); entry.litra = parts.get(3); entry.vejkode = Short.parseShort( parts.get(4) ); entry.kommunekode = Short.parseShort( parts.get(5) ); entry.gadeid = Integer.parseInt( parts.get(6) ); entry.rute = dirigeringsCache.getInstance( parts.get(7) ); entry.koreliste = dirigeringsCache.getInstance( parts.get(8) ); switch(filenameFirst2) { case "HV": entry.ugedage = EntryUgedage.MAN_FRE; break; case "LO": entry.ugedage = EntryUgedage.LOR; break; case "SO": entry.ugedage = EntryUgedage.SON; break; default: throw new IOException("Ukendt ugedage " + filenameFirst2); } lineCount++; return entry; } @Override public String getDistributor() { return "FD"; } @Override //AutoCloseable public void close() throws Exception { System.out.println("Closing FD after lines " + lineCount); try { br.close(); isr.close(); is.close(); file.delete(); } catch (Exception e) { System.out.println("Error on closing " + e.getMessage() ); } } }