Scanner scanner;
int rowCount = 0;
int previewRowCounter = 0;
// Hold the updateContainer JSON
JSONStringer jsonStr = new JSONStringer();
try {
logger.info("CSVFileImportPreview: Got encoding: " + encoding);
if (encoding == null) {
encoding = EncodingDetector.detect(csvFile);
}
scanner = new Scanner(csvFile, encoding);
JSONWriter writer = jsonStr.object().key(JsonKeys.commandId.name())
.value(commandId).key(GenericJsonKeys.updateType.name())
.value("ImportCSVPreview").key(JsonKeys.fileName.name())
.value(csvFile.getName()).key("encoding").value(encoding)
.key("maxNumLines").value(maxNumLines);
JSONArray dataRows = new JSONArray();
while (scanner.hasNextLine()) {
// Check for the header row
if (rowCount + 1 == headerRowIndex) {
String line = scanner.nextLine();
CSVReader reader = new CSVReader(new StringReader(line),
delimiter, quoteCharacter, escapeCharacter);
String[] rowValues = reader.readNext();
List<String> headers = new ArrayList<String>();
if (rowValues == null || rowValues.length == 0) {
logger.error("No data found in the Header row!");
rowCount++;
scanner.nextLine();
continue;
}
for (int i = 0; i < rowValues.length; i++) {
headers.add(rowValues[i]);
}
// Add the row index
headers.add(0, Integer.toString(rowCount + 1));
// Add to the output JSON
JSONArray arr = new JSONArray(headers);
writer.key(JsonKeys.headers.name()).value(arr);
rowCount++;
reader.close();
continue;
}
// Check for the data rows. We choose the first five for preview
if (rowCount + 1 >= dataStartRowIndex
&& rowCount + 1 < dataStartRowIndex + 5) {
if (previewRowCounter++ > 5) {
break;
}
String line = scanner.nextLine();
CSVReader reader = new CSVReader(new StringReader(line),
delimiter, quoteCharacter, escapeCharacter);
String[] rowValues = reader.readNext();
List<String> vals = new ArrayList<String>();
if (rowValues != null) {
for (int i = 0; i < rowValues.length; i++) {
vals.add(rowValues[i]);
}
} else
vals.add("");
// Add the row index
vals.add(0, Integer.toString(rowCount + 1));
reader.close();
// Add to the data rows JSON
dataRows.put(vals);
rowCount++;
continue;
}
rowCount++;
scanner.nextLine();
}
writer.key(JsonKeys.rows.name()).value(dataRows);
writer.endObject();
pw.println(jsonStr.toString());
} catch (FileNotFoundException e) {
logger.error("File not found!", e);
} catch (IOException e) {
logger.error("Error occured while reading the file!", e);
} catch (JSONException e) {