Example usage for org.apache.commons.csv CSVFormat DEFAULT

List of usage examples for org.apache.commons.csv CSVFormat DEFAULT

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat DEFAULT.

Prototype

CSVFormat DEFAULT

To view the source code for org.apache.commons.csv CSVFormat DEFAULT.

Click Source Link

Document

Standard comma separated format, as for #RFC4180 but allowing empty lines.

Usage

From source file:org.zanata.client.commands.stats.CsvStatisticsOutput.java

@Override
@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public void write(ContainerTranslationStatistics statistics) {
    try {/*from  w w w .  j a  v a 2  s  . co m*/
        OutputStreamWriter streamWriter = new OutputStreamWriter(System.out);
        try {
            CSVPrinter csvPrinter = new CSVPrinter(streamWriter,
                    CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));

            try {
                writeToCsv(statistics, csvPrinter);
                csvPrinter.flush();
            } finally {
                csvPrinter.close();
            }
        } finally {
            streamWriter.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.zaproxy.zap.extension.fuzz.httpfuzzer.ui.HttpFuzzResultsContentPanel.java

public HttpFuzzResultsContentPanel() {
    super(new BorderLayout());

    tabbedPane = new JTabbedPane();

    toolbar = new JToolBar();
    toolbar.setFloatable(false);//from  w w w .  j a  va 2 s . c  o  m
    toolbar.setRollover(true);

    messageCountLabel = new JLabel(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.messagesSent"));
    messageCountValueLabel = new JLabel("0");

    errorCountLabel = new JLabel(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.errors"));
    errorCountValueLabel = new JLabel("0");

    showErrorsToggleButton = new ZapToggleButton(
            Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.label"));
    showErrorsToggleButton.setEnabled(false);
    showErrorsToggleButton.setToolTipText(
            Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip"));
    showErrorsToggleButton.setSelectedToolTipText(
            Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip.selected"));
    showErrorsToggleButton.setDisabledToolTipText(
            Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.showErrors.tooltip.disabled"));
    showErrorsToggleButton
            .setIcon(new ImageIcon(HttpFuzzResultsContentPanel.class.getResource("/resource/icon/16/050.png")));
    showErrorsToggleButton.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (ItemEvent.SELECTED == e.getStateChange()) {
                showTabs();
            } else {
                hideErrorsTab();
            }
        }
    });

    toolbar.add(Box.createHorizontalStrut(4));
    toolbar.add(messageCountLabel);
    toolbar.add(Box.createHorizontalStrut(4));
    toolbar.add(messageCountValueLabel);
    toolbar.add(Box.createHorizontalStrut(32));

    toolbar.add(errorCountLabel);
    toolbar.add(Box.createHorizontalStrut(4));
    toolbar.add(errorCountValueLabel);

    toolbar.add(Box.createHorizontalStrut(16));
    toolbar.add(showErrorsToggleButton);

    JButton button = new JButton(Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.export"));
    button.setIcon(new ImageIcon(HttpFuzzResultsContentPanel.class.getResource("/resource/icon/16/115.png")));
    button.addActionListener((new AbstractAction() {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            WritableFileChooser chooser = new WritableFileChooser(
                    Model.getSingleton().getOptionsParam().getUserDirectory()) {

                private static final long serialVersionUID = -1660943014924270012L;

                @Override
                public void approveSelection() {
                    File file = getSelectedFile();
                    if (file != null) {
                        String filePath = file.getAbsolutePath();
                        if (!filePath.toLowerCase(Locale.ROOT).endsWith(CSV_EXTENSION)) {
                            setSelectedFile(new File(filePath + CSV_EXTENSION));
                        }
                    }

                    super.approveSelection();
                }
            };
            chooser.setSelectedFile(new File(
                    Constant.messages.getString("fuzz.httpfuzzer.results.toolbar.button.export.defaultName")));
            if (chooser
                    .showSaveDialog(View.getSingleton().getMainFrame()) == WritableFileChooser.APPROVE_OPTION) {

                boolean success = true;
                try (CSVPrinter pw = new CSVPrinter(
                        Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8),
                        CSVFormat.DEFAULT)) {
                    pw.printRecord(currentFuzzer.getMessagesModel().getHeaders());
                    int count = currentFuzzer.getMessagesModel().getRowCount();
                    for (int i = 0; i < count; i++) {
                        List<Object> valueOfRow = currentFuzzer.getMessagesModel().getEntry(i)
                                .getValuesOfHeaders();
                        String customStateValue = fuzzResultTable.getCustomStateValue(
                                currentFuzzer.getMessagesModel().getEntry(i).getCustomStates());
                        valueOfRow.add(13, customStateValue);
                        pw.printRecord(valueOfRow);
                    }
                } catch (Exception ex) {
                    success = false;
                    JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                            Constant.messages
                                    .getString("fuzz.httpfuzzer.results.toolbar.button.export.showMessageError")
                                    + "\n" + ex.getLocalizedMessage());
                    logger.error("Export Failed: " + ex);
                }
                // Delay the presentation of success message, to ensure all the data was
                // already flushed.
                if (success) {
                    JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(), Constant.messages
                            .getString("fuzz.httpfuzzer.results.toolbar.button.export.showMessageSuccessful"));
                }
            }
        }
    }));
    toolbar.add(Box.createHorizontalGlue());
    toolbar.add(button);
    mainPanel = new JPanel(new BorderLayout());

    fuzzResultTable = new HttpFuzzerResultsTable(RESULTS_PANEL_NAME, EMPTY_RESULTS_MODEL);
    errorsTable = new HttpFuzzerErrorsTable(ERRORS_PANEL_NAME, EMPTY_ERRORS_MODEL);

    fuzzResultTableScrollPane = new JScrollPane();
    fuzzResultTableScrollPane.setViewportView(fuzzResultTable);

    errorsTableScrollPane = new JScrollPane();
    errorsTableScrollPane.setViewportView(errorsTable);

    mainPanel.add(fuzzResultTableScrollPane);

    add(toolbar, BorderLayout.PAGE_START);
    add(mainPanel, BorderLayout.CENTER);
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzerContentPanel.java

@Override
public void saveRecords(File f) {
    try (CSVPrinter printer = new CSVPrinter(new FileWriter(f), CSVFormat.DEFAULT);) {
        printer.print(Constant.messages.getString("fuzz.http.csv.head.name"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.custom"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.result"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.payloadSize"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.payload"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.reqHead"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.reqBody"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.respHead"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.respBody"));
        printer.print(Constant.messages.getString("fuzz.http.csv.head.respTime"));
        printer.println();/*from  ww w.  j a v  a  2s .c  o  m*/
        for (HttpFuzzRecord r : getResultsModel().getEntries()) {
            if (r instanceof HttpFuzzRequestRecord) {
                printer.print(r.getName());
                printer.print(r.getCustom());
                printer.print(r.getResult().first);
                printer.print(r.getPayloads().size());
                printer.print(r.getPayloads());
                HttpMessage m = ((HttpFuzzRequestRecord) r).getHistory().getHttpMessage();
                printer.print(m.getRequestHeader().toString());
                printer.print(m.getRequestBody().toString());
                printer.print(m.getResponseHeader().toString());
                printer.print(m.getResponseBody().toString());
                printer.print(m.getTimeElapsedMillis());
                printer.println();
            }
        }
        printer.flush();
    } catch (IOException | SQLException e) {
        logger.debug(e.getMessage());
        JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                Constant.messages.getString("fuzz.http.csv.writeError"));
    }
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzerContentPanel.java

@Override
public void loadRecords(File f) {
    try (CSVParser parser = new CSVParser(new FileReader(f), CSVFormat.DEFAULT);) {
        boolean header = true;
        for (CSVRecord rec : parser) {
            if (!header) {
                String name = rec.get(0);
                String custom = rec.get(1);
                HttpFuzzRequestRecord.State s;
                if (rec.get(2).equals(STATE_SUCCESSFUL_LABEL)) {
                    s = HttpFuzzRequestRecord.State.SUCCESSFUL;
                } else if (rec.get(2).equals(STATE_REFLECTED_LABEL)) {
                    s = HttpFuzzRequestRecord.State.REFLECTED;
                } else if (rec.get(2).equals(STATE_ANTI_CSRF_TOKEN_REQUEST_LABEL)) {
                    s = HttpFuzzRequestRecord.State.ANTI_CRSF_TOKEN;
                } else if (rec.get(2).equals(STATE_ERROR_LABEL)) {
                    s = HttpFuzzRequestRecord.State.ERROR;
                } else {
                    s = HttpFuzzRequestRecord.State.CUSTOM;
                }// www . jav a2s .  c  o  m

                int l = Integer.parseInt(rec.get(3));
                ArrayList<String> pay = new ArrayList<>();
                if (l == 0) {
                    l++;
                } else {
                    for (int i = 4; i < l + 4; i++) {
                        pay.add(rec.get(i).substring(1, rec.get(i).length() - 1));
                    }
                }
                HttpMessage m = new HttpMessage();
                m.setRequestHeader(rec.get(l + 4));
                m.setRequestBody(rec.get(l + 5));
                m.setResponseHeader(rec.get(l + 6));
                m.setResponseBody(rec.get(l + 7));
                m.setTimeElapsedMillis(Integer.parseInt(rec.get(l + 8)));
                addFuzzResult(name, custom, s, pay, m);
            } else {
                header = false;
            }
        }
    } catch (IOException e) {
        logger.debug(e.getMessage());
        JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                Constant.messages.getString("fuzz.http.csv.readError"));
    }
}

From source file:org.zaproxy.zap.utils.TableExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    WritableFileChooser chooser = new WritableFileChooser(
            Model.getSingleton().getOptionsParam().getUserDirectory()) {

        private static final long serialVersionUID = 1L;

        @Override//from   w  w w  .  j a  v  a  2 s. co  m
        public void approveSelection() {
            File file = getSelectedFile();
            if (file != null) {
                String filePath = file.getAbsolutePath();
                if (!filePath.toLowerCase(Locale.ROOT).endsWith(CSV_EXTENSION)) {
                    setSelectedFile(new File(filePath + CSV_EXTENSION));
                }
            }

            super.approveSelection();
        }
    };

    chooser.setSelectedFile(new File(Constant.messages.getString("export.button.default.filename")));
    if (chooser.showSaveDialog(View.getSingleton().getMainFrame()) == WritableFileChooser.APPROVE_OPTION) {
        boolean success = true;
        try (CSVPrinter pw = new CSVPrinter(
                Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8),
                CSVFormat.DEFAULT)) {
            pw.printRecord(getColumnNames());
            int rowCount = getTable().getRowCount();
            for (int row = 0; row < rowCount; row++) {
                pw.printRecord(getRowCells(row));
            }
        } catch (Exception ex) {
            success = false;
            JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                    Constant.messages.getString("export.button.error") + "\n" + ex.getMessage());
            LOGGER.error("Export Failed: " + ex.getMessage(), ex);
        }

        // Delay the presentation of success message, to ensure all the data was already flushed.
        if (success) {
            JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                    Constant.messages.getString("export.button.success"));
        }
    }
}

From source file:permafrost.tundra.data.IDataCSVParser.java

/**
 * Returns an IData representation of the CSV data in the given input stream.
 *
 * @param inputStream The input stream to be decoded.
 * @param charset     The character set to use.
 * @return An IData representation of the given input stream data.
 * @throws IOException If there is a problem reading from the stream.
 *///www .j  av a2s.c  om
@Override
public IData decode(InputStream inputStream, Charset charset) throws IOException {
    if (inputStream == null)
        return null;

    Reader reader = new InputStreamReader(inputStream, CharsetHelper.normalize(charset));
    CSVFormat format = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter).withNullString("");
    CSVParser parser = format.parse(reader);

    Set<String> keys = parser.getHeaderMap().keySet();
    List<IData> list = new ArrayList<IData>();

    for (CSVRecord record : parser) {
        IData document = IDataFactory.create();
        IDataCursor cursor = document.getCursor();
        for (String key : keys) {
            if (record.isSet(key)) {
                String value = record.get(key);
                if (value != null)
                    IDataUtil.put(cursor, key, value);
            }
        }
        cursor.destroy();
        list.add(document);
    }

    IData output = IDataFactory.create();
    IDataCursor cursor = output.getCursor();
    IDataUtil.put(cursor, "recordWithNoID", list.toArray(new IData[list.size()]));

    return output;
}

From source file:permafrost.tundra.data.IDataCSVParser.java

/**
 * Returns a CSV representation of the given IData object.
 *
 * @param document The IData to convert to CSV.
 * @return The CSV representation of the IData.
 */// www .j  a v a2 s.  c  o m
@Override
public String encodeToString(IData document) throws IOException {
    if (document == null)
        return null;

    IDataCursor cursor = document.getCursor();
    IData[] records = IDataUtil.getIDataArray(cursor, "recordWithNoID");
    cursor.destroy();

    if (records == null)
        return null;
    if (records.length == 0)
        return "";

    StringBuilder builder = new StringBuilder();
    CSVFormat format = CSVFormat.DEFAULT.withHeader(IDataHelper.getKeys(records)).withDelimiter(delimiter)
            .withNullString("");
    CSVPrinter printer = new CSVPrinter(builder, format);

    for (IData record : records) {
        if (record != null)
            printer.printRecord(IDataHelper.getValues(record));
    }

    return builder.toString();
}

From source file:persistencia.ArchivoCSV.java

public void create() throws IOException {
    CSVPrinter csvFilePrinter = null;//from  w  ww.j  a v  a2s . c o  m

    try {

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);

        csvFilePrinter = new CSVPrinter(file, csvFileFormat);

        csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(csv);

        System.out.println("CSV CORRECTAMENTE ESCRITO");

    } catch (Exception e) {
        System.out.println("Error en escritura");
    } finally {
        try {

            cerrarArchivo();
            csvFilePrinter.close();

        } catch (Exception e) {

            System.out.println("Error al cerrar archivo");
        }
    }

}

From source file:resources.TitleTag.java

public static boolean writeAsCsvTitleTagList(String fileName, List<TitleTag> titleTagList) {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;/* w  w  w  .  j ava  2s .c  om*/

    //        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(DELIMITER);
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withDelimiter('\t');

    boolean err = false;
    try {
        fileWriter = new FileWriter(fileName);// Open File with fileWriter
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);// get Printer
        csvFilePrinter.printRecord(FILE_HEADER); // Write Header 

        for (TitleTag tag : titleTagList) {
            List tagRecord = new ArrayList();
            tagRecord.add(tag.getDbID());
            tagRecord.add(tag.getTitle());
            tagRecord.add(tag.getTag());
            csvFilePrinter.printRecord(tagRecord);
        }
        System.out.println("CSV File Recorded Successfylly");
    } catch (Exception ex) {
        err = true;
        System.out.println("Error in CSV File Writer ! Writing TItle - Tag table");
        ex.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            err = true;
            System.out.println("Error while flushing/closing fileWriter /csvPrinter !!");
            e.printStackTrace();
        } finally {
            return err;
        }
    }

}

From source file:ro.dabuno.office.integration.Data.java

private void readCSVFile(File csvFile) throws IOException {
    // open file/*from  w  ww .  ja  va  2 s .c  o  m*/
    // List<String> lines = FileUtils.readLines(file, null);
    try (Reader reader = new FileReader(csvFile)) {
        CSVFormat strategy = CSVFormat.DEFAULT.withHeader().withDelimiter(',').withQuote('"')
                .withCommentMarker((char) 0).withIgnoreEmptyLines().withIgnoreSurroundingSpaces();

        try (CSVParser parser = new CSVParser(reader, strategy)) {
            Map<String, Integer> headerMap = parser.getHeaderMap();
            for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
                headers.add(entry.getKey());
                log.info("Had header '" + entry.getKey() + "' for column " + entry.getValue());
            }

            List<CSVRecord> lines = parser.getRecords();
            log.info("Found " + lines.size() + " lines");
            for (CSVRecord line : lines) {
                List<String> data = new ArrayList<>();
                for (int pos = 0; pos < headerMap.size(); pos++) {
                    if (line.size() <= pos) {
                        data.add(null);
                    } else {
                        data.add(line.get(pos));
                    }
                }

                values.add(data);
            }
        }
    }
}