package com.ilegra.core;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import au.com.bytecode.opencsv.CSVReader;
import com.ilegra.domain.DomainDataFile;
import com.ilegra.domain.DomainResults;
public class ImportFile {
/**
* Dir of file.
*/
private String dir;
private ArrayList<DomainDataFile> lastDataFiles;
private static ArrayList<String> extensions = new ArrayList<String>();
/**
* Start extensions available to read.
*/
{
extensions.add("dat");
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
/**
* Extension validate.
*
* @param fileDir File directory
* @return {@link Boolean} TRUE if extension is ok
*/
public boolean checkExtension(String fileDir) {
if (fileDir == null) {
return false;
}
String extension = fileDir.replaceAll("^.*\\.([^.]+)$", "$1");
if (extension == null) {
return false;
}
if ( ! extensions.contains(extension)) {
return false;
}
return true;
}
/**
* Import file.
* @throws IOException
*/
public DomainResults importFile() throws IOException {
ArrayList<DomainDataFile> domains = new ArrayList<DomainDataFile>();
CSVReader csvReader = getCSVReader(getDir());
String[] row = null;
DomainResults result = new DomainResults();
while ((row = csvReader.readNext()) != null) {
DomainDataFile domain = FactoryDataFile.getInstance().getDomain(row);
domain.parse(row);
domains.add(domain);
/**
* Results
*/
result.done(domain);
}
csvReader.close();
lastDataFiles = domains;
return result;
}
/**
* Returna a reader CSV
*
* @param file directory
* @return {@link CSVReader} reader de CSV
* @throws FileNotFoundException
*/
public static CSVReader getCSVReader(String file) throws FileNotFoundException {
return getCSVReader(file, DomainDataFile.DELIMETER);
}
/**
* Returna a reader CSV
*
* @param file directory
* @return {@link CSVReader} reader de CSV
* @throws FileNotFoundException
*/
public static CSVReader getCSVReader(String file, char delimeter) throws FileNotFoundException {
FileReader reader = new FileReader(file);
return new CSVReader(reader, delimeter);
}
public ArrayList<DomainDataFile> getLastDataFiles() {
return lastDataFiles;
}
}