// create a writer
try {
File tmpFile = File.createTempFile("trialData", "csv");
FileOutputStream fos = new FileOutputStream(tmpFile, false);
CSVWriter writer = new CSVWriter(new OutputStreamWriter(fos,"ISO-8859-1"), separator);
// write the csv file header
List<String> headers = new ArrayList<String>(baseProperties);
// try to use shorthand headers if unique
HashSet<String> trialPropertiesShort = new HashSet<String>();
for (String name : trialProperties) {
String newName = "trial.";
String[] nameParts = name.split("\\.");
if (nameParts.length > 1) {
newName += nameParts[nameParts.length - 2] + ".";
}
newName += nameParts[nameParts.length - 1];
trialPropertiesShort.add(newName);
}
if (trialPropertiesShort.size() == trialProperties.size()) {
useTrialShortNames = true;
trialProperties.clear();
trialProperties.addAll(trialPropertiesShort);
Collections.sort(trialProperties, String.CASE_INSENSITIVE_ORDER);
headers.addAll(trialProperties);
} else {
Collections.sort(trialProperties, String.CASE_INSENSITIVE_ORDER);
headers.addAll(trialProperties);
}
writer.writeNext(headers.toArray(new String[headers.size()]));
// fetch each session and trial, write one line for each trial
List<ModuleSession> sessions = dataService.getSessions(module);
for (ModuleSession session : sessions) {
// skip if we only export some of the session
if (fromSessionIndex >= 0 && session.getIndex() < fromSessionIndex) {
continue;
}
// export all trials for this session
List<Trial> trials = dataService.getTrials(session);
for (Trial trial : trials) {
List<String[]> trialData = getDataForTrial(session, trial);
writer.writeAll(trialData);
}
}
// close the writer and return the file
writer.close();
return tmpFile;
} catch (IOException ioe) {
logger.error("Unable to write csv file", ioe);
return null;
}