Skip to content

Commit

Permalink
CSV reader enhancements to validate columns
Browse files Browse the repository at this point in the history
  • Loading branch information
blakemcbride committed Jul 29, 2024
1 parent e2e43ba commit f63fd45
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions src/main/core/org/kissweb/DelimitedFileReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public double getDouble(int i) {
public double getDouble(String fld) {
if (nameMap == null)
return 0.0;
int i = nameMap.get(fld);
int i = nameMap.get(fld.toLowerCase());
try {
return Double.parseDouble(getString(i));
} catch (NumberFormatException e) {
Expand Down Expand Up @@ -180,6 +180,7 @@ public void skipLine() throws IOException, Exception {

/**
* Read the first row and map column title names to indexes.
* Column titles are case-insensitive.
*
*/
public void readHeader() {
Expand All @@ -191,13 +192,43 @@ public void readHeader() {
for (int i = 0; i < lineValues.size(); i++) {
String name = getString(i);
if (name != null && !name.isEmpty())
nameMap.put(name, i);
nameMap.put(name.toLowerCase(), i);
}
} catch (Exception ignored) {

}
}

/**
* Checks if the given column header exists in the delimited file.
* Note that this only works after <code>readHeader()</code> has been called.
*
* @param header the header to check for
* @return true if the header exists, false otherwise
*/
public boolean hasHeader(String header) {
return nameMap.containsKey(header.toLowerCase());
}

/**
* Checks if the given column titles exist in the delimited file.
* Note that this only works after <code>readHeader()</code> has been called.
*
* @param colNames an array of column names to check
* @return a list of column names that do not exist in the nameMap, or null if all column names exist
*/
public ArrayList<String> checkHeaders(String [] colNames) {
ArrayList<String> res = null;
for (String colName : colNames) {
if (!nameMap.containsKey(colName.toLowerCase())) {
if (res == null)
res = new ArrayList<>();
res.add(colName);
}
}
return res;
}

/**
* Return the original row / line last read.
*
Expand Down Expand Up @@ -356,7 +387,7 @@ public String getString(int item) {
public String getString(String fld) {
if (nameMap == null)
return "";
int item = nameMap.get(fld);
int item = nameMap.get(fld.toLowerCase());
if (item >= lineValues.size())
return "";
return lineValues.get(item);
Expand Down Expand Up @@ -415,7 +446,7 @@ public int getInt(int item) {
public int getInt(String fld) {
if (nameMap == null)
return 0;
int item = nameMap.get(fld);
int item = nameMap.get(fld.toLowerCase());
try {
return Integer.parseInt(getString(item));
} catch (NumberFormatException numberFormatException) {
Expand Down

0 comments on commit f63fd45

Please sign in to comment.