Example usage for org.apache.commons.csv QuoteMode ALL

List of usage examples for org.apache.commons.csv QuoteMode ALL

Introduction

In this page you can find the example usage for org.apache.commons.csv QuoteMode ALL.

Prototype

QuoteMode ALL

To view the source code for org.apache.commons.csv QuoteMode ALL.

Click Source Link

Document

Quotes all fields.

Usage

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".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)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();//from ww  w  .  j a  v a2  s .c om

        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);
    }
}

From source file:ch.silviowangler.i18n.ResourceBundler.java

public void generateResourceBundle() throws IOException {

    CSVParser records = CSVFormat.RFC4180.withDelimiter(separator.charAt(0)).withFirstRecordAsHeader()
            .withQuoteMode(QuoteMode.ALL)
            .parse(new InputStreamReader(new FileInputStream(this.csvFile), this.inputEncoding));

    final Map<String, Integer> headers = records.getHeaderMap();

    processHeader(headers.keySet());//  w w  w  .j  a  v a2s  . co  m

    for (CSVRecord record : records) {
        processData(record);
    }

    final int propertiesFilesAmount = this.propertiesStore.size();
    LOGGER.info("Will generate {} properties files with {} records each", propertiesFilesAmount,
            records.getRecordNumber());

    // Properties Dateien schreiben
    for (int i = 0; i < propertiesFilesAmount; i++) {
        Map<String, String> properties = this.propertiesStore.get(i);
        File outputFile = new File(this.outputDir,
                this.bundleBaseName + "_" + this.languages.get(i) + ".properties");

        LOGGER.info("Writing {} to {}", outputFile.getName(), outputFile.getParentFile().getAbsolutePath());

        FileOutputStream outputStream = new FileOutputStream(outputFile);

        try (OutputStreamWriter writer = new OutputStreamWriter(outputStream,
                this.native2ascii ? Consts.ASCII : this.outputEncoding)) {
            properties.forEach((key, value) -> {
                try {
                    writer.append(key).append("=").append(value).append("\n");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            writer.flush();
        }
    }
}

From source file:com.lithium.flow.util.CsvFormats.java

@Nullable
private static QuoteMode getQuoteMode(@Nonnull Config config, @Nonnull String key) {
    switch (config.getString(key, "default")) {
    case "default":
        return null;
    case "all":
        return QuoteMode.ALL;
    case "minimal":
        return QuoteMode.MINIMAL;
    case "non_numeric":
        return QuoteMode.NON_NUMERIC;
    case "none":
        return QuoteMode.NONE;
    default://  w w  w .  ja v a 2 s .  c o  m
        return null;
    }
}

From source file:de.upb.wdqa.wdvd.processors.statistics.ActionStatisticsProcessor.java

private void logResults() {
    logger.info("Action frequency distribution:\n" + FrequencyUtils.formatFrequency(actionDistribution));
    logger.info("Action frequency distribution of rollback-reverted revisions:\n"
            + FrequencyUtils.formatFrequency(rollbackRevertedActionDistribution));
    logger.info("Action frequency distribution of non-rollback-reverted revisions:\n"
            + FrequencyUtils.formatFrequency(nonRollbackRevertedActionDistribution));

    try {//from   w  w  w  . j  a  v  a 2s.co m
        Writer writer = new PrintWriter(path, "UTF-8");
        CSVPrinter csvWriter = CSVFormat.RFC4180.withQuoteMode(QuoteMode.ALL)
                .withHeader("month", "action", "count").print(writer);

        for (Entry<String, HashMap<String, Integer>> entry : getSortedList(monthlyActionDistribution)) {
            String month = entry.getKey();

            for (Entry<String, Integer> entry2 : getSortedList2(entry.getValue())) {
                String action = entry2.getKey();
                Integer value = entry2.getValue();

                csvWriter.printRecord(month, action, value);
            }
        }
        csvWriter.close();
    } catch (IOException e) {
        logger.error("", e);
    }
}

From source file:edu.harvard.mcz.imagecapture.RunnableJobReportDialog.java

protected void serializeTableModel() {
    PrintWriter out = null;/*from   w  ww. jav  a 2  s  . com*/
    CSVPrinter writer = null;
    try {
        int cols = jTable.getModel().getColumnCount();
        CSVFormat csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                .withHeaderComments(jTextArea.getText());
        TableModel model = jTable.getModel();
        switch (cols) {
        case 9:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4), model.getColumnName(5),
                            model.getColumnName(6), model.getColumnName(7), model.getColumnName(8))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 6:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4), model.getColumnName(5))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 5:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3), model.getColumnName(4))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        case 4:
            csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL)
                    .withHeader(model.getColumnName(0), model.getColumnName(1), model.getColumnName(2),
                            model.getColumnName(3))
                    .withCommentMarker('*').withHeaderComments(jTextArea.getText());
            break;
        }

        log.debug(jTextArea.getText());
        log.debug(csvFormat.getHeaderComments());

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd_HHmmss");
        String time = dateFormat.format(now);
        String filename = "jobreport_" + time + ".csv";
        out = new PrintWriter(filename);

        writer = new CSVPrinter(out, csvFormat);
        writer.flush();

        int rows = jTable.getModel().getRowCount();
        for (int i = 0; i < rows; i++) {
            ArrayList<String> values = new ArrayList<String>();
            for (int col = 0; col < cols; col++) {
                values.add((String) jTable.getModel().getValueAt(i, col));
            }

            writer.printRecord(values);
        }
        writer.flush();
        writer.close();
        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                "Saved report to file: " + filename, "Report to CSV file", JOptionPane.OK_OPTION);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
        try {
            writer.close();
        } catch (Exception e) {
        }

    }
}

From source file:org.apache.camel.dataformat.csv.CsvDataFormatTest.java

@Test
public void shouldOverrideQuoteMode() {
    CsvDataFormat dataFormat = new CsvDataFormat().setQuoteMode(QuoteMode.ALL);

    // Properly saved
    assertSame(CSVFormat.DEFAULT, dataFormat.getFormat());
    assertEquals(QuoteMode.ALL, dataFormat.getQuoteMode());

    // Properly used
    assertEquals(QuoteMode.ALL, dataFormat.getActiveFormat().getQuoteMode());
}

From source file:org.apache.nifi.csv.TestWriteCSVResult.java

@Test
public void testDataTypes() throws IOException {
    final CSVFormat csvFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL).withRecordSeparator("\n");

    final StringBuilder headerBuilder = new StringBuilder();
    final List<RecordField> fields = new ArrayList<>();
    for (final RecordFieldType fieldType : RecordFieldType.values()) {
        if (fieldType == RecordFieldType.CHOICE) {
            final List<DataType> possibleTypes = new ArrayList<>();
            possibleTypes.add(RecordFieldType.INT.getDataType());
            possibleTypes.add(RecordFieldType.LONG.getDataType());

            fields.add(new RecordField(fieldType.name().toLowerCase(),
                    fieldType.getChoiceDataType(possibleTypes)));
        } else {/*from  w  w  w.j  av a2 s . c o  m*/
            fields.add(new RecordField(fieldType.name().toLowerCase(), fieldType.getDataType()));
        }

        headerBuilder.append('"').append(fieldType.name().toLowerCase()).append('"').append(",");
    }
    final RecordSchema schema = new SimpleRecordSchema(fields);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final long now = System.currentTimeMillis();

    try (final WriteCSVResult result = new WriteCSVResult(csvFormat, schema, new SchemaNameAsAttribute(), baos,
            RecordFieldType.DATE.getDefaultFormat(), RecordFieldType.TIME.getDefaultFormat(),
            RecordFieldType.TIMESTAMP.getDefaultFormat(), true, "UTF-8")) {

        final Map<String, Object> valueMap = new HashMap<>();
        valueMap.put("string", "abc?123");
        valueMap.put("boolean", true);
        valueMap.put("byte", (byte) 1);
        valueMap.put("char", 'c');
        valueMap.put("short", (short) 8);
        valueMap.put("int", 9);
        valueMap.put("bigint", BigInteger.valueOf(8L));
        valueMap.put("long", 8L);
        valueMap.put("float", 8.0F);
        valueMap.put("double", 8.0D);
        valueMap.put("date", new Date(now));
        valueMap.put("time", new Time(now));
        valueMap.put("timestamp", new Timestamp(now));
        valueMap.put("record", null);
        valueMap.put("choice", 48L);
        valueMap.put("array", null);

        final Record record = new MapRecord(schema, valueMap);
        final RecordSet rs = RecordSet.of(schema, record);

        result.write(rs);
    }

    final String output = new String(baos.toByteArray(), StandardCharsets.UTF_8);

    headerBuilder.deleteCharAt(headerBuilder.length() - 1);
    final String headerLine = headerBuilder.toString();

    final String[] splits = output.split("\n");
    assertEquals(2, splits.length);
    assertEquals(headerLine, splits[0]);

    final String values = splits[1];
    final StringBuilder expectedBuilder = new StringBuilder();
    expectedBuilder.append("\"abc?123\",\"true\",\"1\",\"c\",\"8\",\"9\",\"8\",\"8\",\"8.0\",\"8.0\",");

    final String dateValue = getDateFormat(RecordFieldType.DATE.getDefaultFormat()).format(now);
    final String timeValue = getDateFormat(RecordFieldType.TIME.getDefaultFormat()).format(now);
    final String timestampValue = getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat()).format(now);

    expectedBuilder.append('"').append(dateValue).append('"').append(',');
    expectedBuilder.append('"').append(timeValue).append('"').append(',');
    expectedBuilder.append('"').append(timestampValue).append('"').append(',');
    expectedBuilder.append(",\"48\",,");
    final String expectedValues = expectedBuilder.toString();

    assertEquals(expectedValues, values);
}

From source file:org.easybatch.extensions.apache.common.csv.ApacheCommonCsvRecordMarshaller.java

/**
 * Create a record marshaller.//from  w  ww . j  a va  2  s . c o m
 *
 * @param fieldExtractor the field extractor
 * @param delimiter      the field delimiter
 * @param qualifier      the field qualifier
 * @throws IntrospectionException If the object to marshal cannot be introspected
 */
public ApacheCommonCsvRecordMarshaller(RecordFieldExtractor fieldExtractor, final char delimiter,
        final char qualifier) throws IntrospectionException {
    this.fieldExtractor = fieldExtractor;
    this.csvFormat = CSVFormat.newFormat(delimiter).withQuote(qualifier).withQuoteMode(QuoteMode.ALL)
            .withRecordSeparator(null);// recordSeparator is forced to null to avoid CSVPrinter to print new lines. New lines are written later by EasyBatch RecordWriter
}

From source file:org.nuxeo.theme.Utils.java

public static String listToCsv(List<String> list) {
    StringWriter sw = new StringWriter();
    try (CSVPrinter writer = new CSVPrinter(sw,
            CSVFormat.DEFAULT.withDelimiter(',').withQuoteMode(QuoteMode.ALL))) {
        writer.printRecord(list);/*from   w  ww.  j a va 2 s.c  o m*/
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return sw.toString();
}

From source file:org.schedoscope.export.ftp.outputformat.CSVRecordWriter.java

/**
 * The constructor to initialize the CSV Record Writer.
 *
 * @param out       A data output stream.
 * @param header    A flag to print a header or not.
 * @param delimiter The delimiter to use.
 * @throws IOException Is thrown if an error occurs.
 *///from   w ww . jav a2  s .c  o m
public CSVRecordWriter(DataOutputStream out, String[] header, char delimiter) throws IOException {

    this.out = out;
    csvFormat = CSVFormat.DEFAULT.withTrim(true).withQuoteMode(QuoteMode.ALL).withHeader(header)
            .withDelimiter(delimiter);

    buffer = new StringBuilder();
    csvPrinter = csvFormat.print(buffer);
}