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.util.DeduplicateHelper; public abstract class AbstractAddressSource implements AddressSource { protected DeduplicateHelper dirigeringsCache = new DeduplicateHelper(); protected FileItem file; protected InputStream is; protected InputStreamReader isr; protected BufferedReader br; protected int lineCount = 0; public AbstractAddressSource(FileItem file) { this.file = file; } @Override public String getFilename() { // TODO Auto-generated method stub return file.getName(); } @Override //AutoCloseable public void close() throws Exception { System.out.println("Closing BK after lines " + lineCount); try { if (br != null) br.close(); if (isr != null) isr.close(); if (is != null) is.close(); file.delete(); } catch (Exception e) { System.out.println("Error on closing " + e.getMessage() ); } } protected void validatNoHeaderLine(int exptectedFieldCount, char seperator) throws IOException { try ( InputStream is1 = file.getInputStream(); InputStreamReader isr1 = new InputStreamReader(is1, Charset.forName("ISO-8859-1") ); BufferedReader br1 = new BufferedReader(isr1) ) { String line = br1.readLine(); if (line == null) { throw new IOException("Can't read 1st line - is file empty?"); } List parts = Splitter.on(seperator).splitToList(line); if (parts.size() != exptectedFieldCount) { throw new IOException("Not enough fields in CSV file. Found " + parts.size() + ", expected " + exptectedFieldCount); } } is = file.getInputStream(); isr = new InputStreamReader(is, Charset.forName("ISO-8859-1") ); br = new BufferedReader(isr); } protected void validateWithHeader(int expectedFieldCount, char seperator) throws IOException { try { is = file.getInputStream(); isr = new InputStreamReader(is, Charset.forName("ISO-8859-1") ); br = new BufferedReader(isr); String line = br.readLine(); if (line == null) { throw new IOException("Can't read 1st line - is file empty?"); } List parts = Splitter.on(seperator).splitToList(line); if (parts.size() != expectedFieldCount) { throw new IOException("Not enough fields in CSV file. Found " + parts.size() + ", expected " + expectedFieldCount); } } catch (Exception e) { try { br.close(); isr.close(); is.close(); } catch (Exception e2) { System.out.println("Error cleaning up resources"); } throw e; // Re-throw } } }