use of org.apache.commons.csv.CSVPrinter in project webapp by elimu-ai.
the class StoryBookLearningEventCsvExportController method handleRequest.
@RequestMapping(value = "/storybook-learning-events.csv", method = RequestMethod.GET)
public void handleRequest(HttpServletResponse response, OutputStream outputStream) throws IOException {
logger.info("handleRequest");
List<StoryBookLearningEvent> storyBookLearningEvents = storyBookLearningEventDao.readAll();
logger.info("storyBookLearningEvents.size(): " + storyBookLearningEvents.size());
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(// The Room database ID
"id", "time", "android_id", "package_name", "storybook_id", "storybook_title", "learning_event_type");
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (StoryBookLearningEvent storyBookLearningEvent : storyBookLearningEvents) {
logger.info("storyBookLearningEvent.getId(): " + storyBookLearningEvent.getId());
csvPrinter.printRecord(storyBookLearningEvent.getId(), storyBookLearningEvent.getTime().getTimeInMillis(), storyBookLearningEvent.getAndroidId(), storyBookLearningEvent.getApplication().getPackageName(), storyBookLearningEvent.getStoryBook().getId(), storyBookLearningEvent.getStoryBookTitle(), storyBookLearningEvent.getLearningEventType());
csvPrinter.flush();
}
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
logger.error(ex);
}
}
use of org.apache.commons.csv.CSVPrinter in project webapp by elimu-ai.
the class EmojiCsvExportController method handleRequest.
@RequestMapping(value = "/emojis.csv", method = RequestMethod.GET)
public void handleRequest(HttpServletResponse response, OutputStream outputStream) throws IOException {
logger.info("handleRequest");
List<Emoji> emojis = emojiDao.readAllOrdered();
logger.info("emojis.size(): " + emojis.size());
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("id", "glyph", "unicode_version", "unicode_emoji_version", "word_ids", "word_texts");
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
for (Emoji emoji : emojis) {
logger.info("emoji.getGlyph(): \"" + emoji.getGlyph() + "\"");
JSONArray wordIdsJsonArray = new JSONArray();
int index = 0;
for (Word word : emoji.getWords()) {
wordIdsJsonArray.put(index, word.getId());
index++;
}
JSONArray wordTextsJsonArray = new JSONArray();
index = 0;
for (Word word : emoji.getWords()) {
wordTextsJsonArray.put(index, word.getText());
index++;
}
csvPrinter.printRecord(emoji.getId(), emoji.getGlyph(), emoji.getUnicodeVersion(), emoji.getUnicodeEmojiVersion(), wordIdsJsonArray, wordTextsJsonArray);
csvPrinter.flush();
}
String csvFileContent = stringWriter.toString();
response.setContentType("text/csv");
byte[] bytes = csvFileContent.getBytes();
response.setContentLength(bytes.length);
try {
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException ex) {
logger.error(ex);
}
}
use of org.apache.commons.csv.CSVPrinter in project atlasmap by atlasmap.
the class CsvFieldWriter method toCsv.
/**
* Exports as a CSV.
* @return exported
* @throws AtlasException unexpected error
*/
public String toCsv() throws AtlasException {
CSVFormat csvFormat = csvConfig.newCsvFormat();
String[] headers = csvConfig.getParsedHeaders();
boolean ignoreHeaderCase = Boolean.TRUE.equals(csvConfig.getIgnoreHeaderCase());
if (headers != null && ignoreHeaderCase) {
for (int j = 0; j < headers.length; j++) {
headers[j] = headers[j].toLowerCase();
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
CSVPrinter printer = new CSVPrinter(writer, csvFormat);
List<Field> fields = document.getFields().getField();
if (fields.isEmpty()) {
return "";
}
if (!Boolean.TRUE.equals(csvConfig.getSkipHeaderRecord())) {
if (csvConfig.getHeaders() == null) {
String[] headerRecords = new String[fields.size()];
int i = 0;
for (Field field : fields) {
CsvField csvField;
if (field instanceof FieldGroup) {
FieldGroup fieldGroup = (FieldGroup) field;
csvField = (CsvField) fieldGroup.getField().get(i);
} else {
csvField = (CsvField) field;
}
if (csvField.getColumn() != null) {
headerRecords[csvField.getColumn()] = csvField.getName();
} else {
headerRecords[i] = csvField.getName();
}
i++;
}
printer.printRecord(headerRecords);
}
}
int recordsCount;
if (fields.get(0) instanceof FieldGroup) {
recordsCount = ((FieldGroup) fields.get(0)).getField().size();
} else {
recordsCount = 1;
}
for (int i = 0; i < recordsCount; i++) {
List<String> values = new ArrayList<>();
for (Field field : fields) {
CsvField csvField;
if (field instanceof FieldGroup) {
FieldGroup fieldGroup = (FieldGroup) field;
csvField = (CsvField) fieldGroup.getField().get(i);
} else {
csvField = (CsvField) field;
}
if (csvField.getColumn() != null) {
// Add missing values
for (int j = values.size(); j < csvField.getColumn() + 1; j++) {
values.add(null);
}
values.set(csvField.getColumn(), csvField.getValue().toString());
} else if (headers != null) {
for (int j = values.size(); j < headers.length; j++) {
values.add(null);
}
int column = findColumn(headers, ignoreHeaderCase, csvField);
if (column != -1) {
values.set(column, csvField.getValue().toString());
}
} else {
values.add(csvField.getValue().toString());
}
}
printer.printRecord(values);
}
writer.flush();
String csv = out.toString();
return csv;
} catch (IOException e) {
throw new AtlasException(e);
}
}
use of org.apache.commons.csv.CSVPrinter in project jgnash by ccavanaugh.
the class CsvExport method exportAccount.
public static void exportAccount(@NotNull final Account account, @NotNull final LocalDate startDate, @NotNull final LocalDate endDate, @NotNull final Path path) {
Objects.requireNonNull(account);
Objects.requireNonNull(startDate);
Objects.requireNonNull(endDate);
Objects.requireNonNull(path);
// force a correct file extension
final String fileName = FileUtils.stripFileExtension(path.toString()) + ".csv";
final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);
try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {
// write UTF-8 byte order mark to the file for easier imports
outputStreamWriter.write(BYTE_ORDER_MARK);
writer.printRecord(ResourceUtils.getString("Column.Account"), ResourceUtils.getString("Column.Num"), ResourceUtils.getString("Column.Debit"), ResourceUtils.getString("Column.Credit"), ResourceUtils.getString("Column.Balance"), ResourceUtils.getString("Column.Date"), ResourceUtils.getString("Column.Timestamp"), ResourceUtils.getString("Column.Memo"), ResourceUtils.getString("Column.Payee"), ResourceUtils.getString("Column.Clr"));
// write the transactions
final List<Transaction> transactions = account.getTransactions(startDate, endDate);
final DateTimeFormatter dateTimeFormatter = DateUtils.getExcelDateFormatter();
final DateTimeFormatter timestampFormatter = DateUtils.getExcelTimestampFormatter();
for (final Transaction transaction : transactions) {
final String date = dateTimeFormatter.format(transaction.getLocalDate());
final String timeStamp = timestampFormatter.format(transaction.getTimestamp());
final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? "" : transaction.getAmount(account).abs().toPlainString();
final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? "" : transaction.getAmount(account).abs().toPlainString();
final String balance = account.getBalanceAt(transaction).toPlainString();
final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED ? Boolean.FALSE.toString() : Boolean.TRUE.toString();
writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date, timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
}
} catch (final IOException e) {
Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
use of org.apache.commons.csv.CSVPrinter in project drools-wb by kiegroup.
the class ScenarioCsvDownloadReportTest method printRulesCounterLine.
@Test
public void printRulesCounterLine() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
CSVPrinter printer = getCSVPrinter(stringBuilder);
AuditLog auditLog = new AuditLog();
auditLog.addAuditLogLine(getAuditLogLine());
SimulationRunMetadata simulationRunMetadata = getSimulationRunMetadata(auditLog);
Map.Entry<String, Integer> entry = simulationRunMetadata.getOutputCounter().entrySet().iterator().next();
scenarioCsvDownloadReport.printRulesCounterLine(printer, entry.getKey(), entry.getValue());
String retrieved = stringBuilder.toString();
List<String> data = Arrays.asList("\"" + entry.getKey() + "\"", String.valueOf(entry.getValue()));
commonCheckRetrievedString(retrieved, data);
}
Aggregations