package org.simantics.excel.poi.parser; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; public class ColumnResolver { private enum Type {SINGLE,MULTI}; private Map values = new HashMap(); private Map types = new HashMap(); private Set optional = new HashSet(); private Set resolved = new HashSet(); public void addSingleColumn(String id) { addSingleColumn(id, true); } public void addSingleColumn(String id, boolean required) { types.put(id, Type.SINGLE); if (!required) this.optional.add(id); } public void addMultiColumn(String id) { addMultiColumn(id, true); } public void addMultiColumn(String id, boolean required) { types.put(id, Type.MULTI); if (!required) this.optional.add(id); } public int getSingleColumn(String id) { int[] val = values.get(id); if (val == null) return -1; if (val.length == 0) return -1; return val[0]; } public int[] getMultiColumn(String id) { return values.get(id); } public boolean resolve(Row row) { return resolve(row, true); } public boolean resolve(Row row, boolean ignoreCase) { values.clear(); resolved.clear(); if (row == null) { return false; } for (int i = 0; i <= row.getLastCellNum(); i++) { Cell cell = row.getCell(i); if (cell == null) continue; int colIndex = cell.getColumnIndex(); String value = cell.getStringCellValue(); for (Entry col : types.entrySet()) { String id = col.getKey(); if (id.equals(value) || ignoreCase && id.equalsIgnoreCase(value)) { if (col.getValue() == Type.SINGLE) { values.put(id, new int[]{colIndex}); } else { int curr[] = values.get(id); if (curr == null) { values.put(id, new int[]{colIndex}); } else { int n[] = new int[curr.length+1]; System.arraycopy(curr, 0, n, 0, curr.length); n[curr.length] = colIndex; values.put(id, n); } } resolved.add(id); break; } } } // check that required columns have been resolved for (Entry col : types.entrySet()) { if (!optional.contains(col.getKey())) { if (!resolved.contains(col.getKey())) return false; } } return true; } }