import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class AddressService {
protected static Logger logger = LogManager.getLogger();
@Value("${jp.esoro.master.address}")
String csvPath;
@Cacheable("AddressInfo")
public Map<String,Address> getAll() {
BufferedReader in = null;
Map<String,Address> list = new HashMap<String,Address>();
logger.info("readCSV");
try{
in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(csvPath)),"MS932"));
CSVParser parser = CSVFormat
.EXCEL // ExcelのCSV形式を指定
.withIgnoreEmptyLines(true) // 空行を無視する
.withSkipHeaderRecord() // 最初の行をヘッダーとして読み飛ばす
.withIgnoreSurroundingSpaces(false) // 値をtrimして取得する
.withRecordSeparator(System.getProperty("line.separator"))
.withDelimiter(',')
.withQuote('"')
.parse(in);
// CSVのレコードを取得
List<CSVRecord> pList = parser.getRecords();
for(int i = 0 ; i < pList.size() ; i++ ){
CSVRecord rec = pList.get(i);
Address inf = new Address();
inf.setPrefid(rec.get(1));
inf.setZipCode(rec.get(4));
inf.setPrefName(rec.get(7));
inf.setAddressName(rec.get(9)+rec.get(11)+rec.get(13));
list.put(rec.get(0), inf);
}
} catch (Exception e) {
logger.error("csv read error", e);
} finally{
if (in != null){
try {
in.close();
} catch (IOException e) {
}
}
}
return list;
}
}