Search in sources :

Example 56 with CSVPrinter

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);
    }
}
Also used : CSVPrinter(org.apache.commons.csv.CSVPrinter) StoryBookLearningEvent(ai.elimu.model.analytics.StoryBookLearningEvent) StringWriter(java.io.StringWriter) CSVFormat(org.apache.commons.csv.CSVFormat) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 57 with CSVPrinter

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);
    }
}
Also used : CSVPrinter(org.apache.commons.csv.CSVPrinter) Word(ai.elimu.model.content.Word) StringWriter(java.io.StringWriter) JSONArray(org.json.JSONArray) Emoji(ai.elimu.model.content.Emoji) CSVFormat(org.apache.commons.csv.CSVFormat) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 58 with CSVPrinter

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);
    }
}
Also used : FieldGroup(io.atlasmap.v2.FieldGroup) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) AtlasException(io.atlasmap.api.AtlasException) CSVPrinter(org.apache.commons.csv.CSVPrinter) CsvField(io.atlasmap.csv.v2.CsvField) Field(io.atlasmap.v2.Field) CsvField(io.atlasmap.csv.v2.CsvField) CSVFormat(org.apache.commons.csv.CSVFormat) OutputStreamWriter(java.io.OutputStreamWriter)

Example 59 with CSVPrinter

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);
    }
}
Also used : CSVPrinter(org.apache.commons.csv.CSVPrinter) Transaction(jgnash.engine.Transaction) CSVFormat(org.apache.commons.csv.CSVFormat) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) DateTimeFormatter(java.time.format.DateTimeFormatter) BufferedWriter(java.io.BufferedWriter)

Example 60 with CSVPrinter

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);
}
Also used : CSVPrinter(org.apache.commons.csv.CSVPrinter) SimulationRunMetadata(org.drools.scenariosimulation.api.model.SimulationRunMetadata) HashMap(java.util.HashMap) Map(java.util.Map) AuditLog(org.drools.scenariosimulation.api.model.AuditLog) Test(org.junit.Test)

Aggregations

CSVPrinter (org.apache.commons.csv.CSVPrinter)71 IOException (java.io.IOException)25 CSVFormat (org.apache.commons.csv.CSVFormat)20 OutputStreamWriter (java.io.OutputStreamWriter)17 StringWriter (java.io.StringWriter)14 Writer (java.io.Writer)13 ArrayList (java.util.ArrayList)12 FileOutputStream (java.io.FileOutputStream)11 Test (org.junit.Test)11 FileWriter (java.io.FileWriter)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)8 BufferedWriter (java.io.BufferedWriter)6 File (java.io.File)5 PrintWriter (java.io.PrintWriter)5 JSONArray (org.json.JSONArray)5 Map (java.util.Map)4 Word (ai.elimu.model.content.Word)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Letter (ai.elimu.model.content.Letter)2 LetterSoundCorrespondence (ai.elimu.model.content.LetterSoundCorrespondence)2