List of usage examples for org.apache.commons.csv CSVPrinter CSVPrinter
public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException
From source file:org.thingsboard.server.service.install.sql.SqlDbHelper.java
public static Path dumpTableIfExists(Connection conn, String tableName, String[] columns, String[] defaultValues, String dumpPrefix, boolean printHeader) throws Exception { if (tableExists(conn, tableName)) { Path dumpFile = Files.createTempFile(dumpPrefix, null); Files.deleteIfExists(dumpFile); CSVFormat csvFormat = CSV_DUMP_FORMAT; if (printHeader) { csvFormat = csvFormat.withHeader(columns); }//from ww w .j a v a2 s . c o m try (CSVPrinter csvPrinter = new CSVPrinter(Files.newBufferedWriter(dumpFile), csvFormat)) { try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM " + tableName)) { try (ResultSet tableRes = stmt.executeQuery()) { ResultSetMetaData resMetaData = tableRes.getMetaData(); Map<String, Integer> columnIndexMap = new HashMap<>(); for (int i = 1; i <= resMetaData.getColumnCount(); i++) { String columnName = resMetaData.getColumnName(i); columnIndexMap.put(columnName.toUpperCase(), i); } while (tableRes.next()) { dumpRow(tableRes, columnIndexMap, columns, defaultValues, csvPrinter); } } } } return dumpFile; } else { return null; } }
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. ja v a 2 s . c om 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 ww. ja v a 2s.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 w w w .j av a 2 s . 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.utils.TableExportAction.java
@Override public void actionPerformed(ActionEvent e) { WritableFileChooser chooser = new WritableFileChooser( Model.getSingleton().getOptionsParam().getUserDirectory()) { private static final long serialVersionUID = 1L; @Override/* ww w. ja va2s . c o 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:password.pwm.util.Helper.java
public static CSVPrinter makeCsvPrinter(final OutputStream outputStream) throws IOException { return new CSVPrinter(new OutputStreamWriter(outputStream, PwmConstants.DEFAULT_CHARSET), PwmConstants.DEFAULT_CSV_FORMAT); }
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 .ja v a2 s . co 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;/* w w w . j a v a 2 s . 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;/*from w ww. j av a 2 s . com*/ // 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.fortsoft.kempes.demo.EvomagEventHandler.java
private void writeToCsv(Product product) throws IOException { // TODO improve if (csvPrinter == null) { CSVFormat csvFormat = CSVFormat.RFC4180.withHeader().withDelimiter(','); csvPrinter = new CSVPrinter(new FileWriter(CSV_FILE), csvFormat.withDelimiter('#')); csvPrinter.printRecord("Name", "Price"); }//from w w w. j a v a2s . c om List<String> data = new ArrayList<String>(); data.add(product.getName()); data.add(String.valueOf(product.getPrice())); csvPrinter.printRecord(data); csvPrinter.flush(); // TODO // csvPrinter.close(); }