List of usage examples for org.apache.commons.csv CSVPrinter printRecord
public void printRecord(final Object... values) throws IOException
From source file:com.coverity.report.analysis.ProtecodeSCToolProcessor.java
@Override public void readData() throws ToolProcessorException { componentsDataList = restService.getComponentsInfo(config.productId); vulnerabilitiesDataList = restService.getVulnerabilitiesInfo(config.productId); systemInfo = restService.getSystemInfo(); productScan = restService.getProductScanResult(config.productId); try {/*from w w w.ja v a 2 s . com*/ File componentsTempFile = File.createTempFile(Personality.getInstance().tempFileNameBase(), ".csv"); File vulnerabilitiesTempFile = File.createTempFile(Personality.getInstance().tempFileNameBase(), ".csv"); String[] componentsHeadings = new String[] { "component name", "version", "license", "license type", "vulnerability count", "object" }; try (FileWriter writer = new FileWriter(componentsTempFile)) { CSVPrinter printer = new CSVPrinter(writer, CSVFormat.EXCEL); printer.printRecord(componentsHeadings); componentsDataList.stream().forEach(info -> { String[] componentsRecord = new String[componentsHeadings.length]; componentsRecord[0] = info.getComponent(); componentsRecord[1] = info.getVersion(); componentsRecord[2] = info.getLicense(); componentsRecord[3] = info.getLicenseType(); componentsRecord[4] = String.valueOf(info.getVulnerabilityCount()); componentsRecord[5] = info.getObject(); try { printer.printRecord(componentsRecord); } catch (Exception ignored) { } }); dataFiles.add(new DataFile("protecode-components.csv", componentsTempFile)); } catch (IOException e) { throw makeException("Could not write protecode components data to CSV file " + componentsTempFile.getAbsolutePath(), e); } String[] vulnerabilitiesHeadings = new String[] { "component", "version", "CVE", "CVSS" }; try (FileWriter writer = new FileWriter(vulnerabilitiesTempFile)) { CSVPrinter printer = new CSVPrinter(writer, CSVFormat.EXCEL); printer.printRecord(vulnerabilitiesHeadings); vulnerabilitiesDataList.stream().forEach(info -> { String[] vulnerabilitiesRecord = new String[vulnerabilitiesHeadings.length]; vulnerabilitiesRecord[0] = info.getComponent(); vulnerabilitiesRecord[1] = info.getVersion(); vulnerabilitiesRecord[2] = info.getCve(); vulnerabilitiesRecord[3] = String.valueOf(info.getCvss()); try { printer.printRecord(vulnerabilitiesRecord); } catch (Exception ignored) { } }); dataFiles.add(new DataFile("protecode-vulnerabilities.csv", vulnerabilitiesTempFile)); } catch (IOException e) { throw makeException("Could not write protecode vulnerabilities to CSV file " + vulnerabilitiesTempFile.getAbsolutePath(), e); } } catch (IOException e) { throw makeException("Cannot create temporary file", e); } }
From source file:edu.harvard.hms.dbmi.bd2k.irct.ws.rs.resultconverter.CSVTabularDataConverter.java
@Override public StreamingOutput createStream(final Result result) { StreamingOutput stream = new StreamingOutput() { @Override/* ww w . j a v a 2 s . c o m*/ public void write(OutputStream outputStream) throws IOException, WebApplicationException { ResultSet rs = null; CSVPrinter printer = null; try { rs = (ResultSet) result.getData(); rs.load(result.getResultSetLocation()); printer = new CSVPrinter(new OutputStreamWriter(outputStream), CSVFormat.DEFAULT); String[] columnHeaders = new String[rs.getColumnSize()]; for (int i = 0; i < rs.getColumnSize(); i++) { columnHeaders[i] = rs.getColumn(i).getName(); } printer.printRecord((Object[]) columnHeaders); rs.beforeFirst(); while (rs.next()) { String[] row = new String[rs.getColumnSize()]; for (int i = 0; i < rs.getColumnSize(); i++) { row[i] = rs.getString(i); } printer.printRecord((Object[]) row); } printer.flush(); } catch (ResultSetException | PersistableException e) { log.info("Error creating CSV Stream: " + e.getMessage()); } finally { if (printer != null) { printer.close(); } if (rs != null && !rs.isClosed()) { try { rs.close(); } catch (ResultSetException e) { e.printStackTrace(); } } if (outputStream != null) { outputStream.close(); } } } }; return stream; }
From source file:com.awesheet.managers.CSVManager.java
/** * Exports the given Sheet to a CSV file in the specified path. * @param sheet the Sheet to export.//from w w w .ja va2s . c om * @param path the target path of the CSV file. * @return whether the export was successful */ public boolean exportSheet(Sheet sheet, String path) { FileWriter writer = null; CSVPrinter printer = null; try { writer = new FileWriter(path); printer = new CSVPrinter(writer, CSVFormat.RFC4180); // Write records. for (int y = 0; y < sheet.getMaxRow(); ++y) { List<String> values = new ArrayList<String>(); for (int x = 0; x < sheet.getMaxColumn(); ++x) { Cell cell = sheet.getCell(x, y); values.add(cell == null ? "" : cell.getDisplayValue()); } printer.printRecord(values); } } catch (Exception e) { return false; } finally { try { if (writer != null) { writer.flush(); writer.close(); } if (printer != null) { printer.close(); } } catch (Exception ignored) { } } return true; }
From source file:de.speexx.csv.table.app.Application.java
void exportResult(final Configuration conf, final RowReader rows) throws Exception { assert Objects.nonNull(rows) : "Rows are null"; assert Objects.nonNull(conf) : "configuration is null"; final CSVPrinter printer = createCsvPrinter(rows, conf); for (final Row row : rows) { final List<String> recordEntries = new ArrayList<>(); for (final Entry entry : row) { final EntryDescriptor.Type type = entry.getDescriptor().getType(); final TypeTransformer transformer = TypeTransformer.of(type, EntryDescriptor.Type.STRING); final Optional<String> opt = transformer.transform(entry.getValue()); recordEntries.add(opt.orElseGet(() -> "")); }/*from w w w . j a v a 2 s.c om*/ printer.printRecord(recordEntries); } }
From source file:com.bigtester.ate.tcg.controller.TrainingFileDB.java
/** * Write cache csv file.//from ww w . j av a 2 s.c om * * @param absoluteCacheFilePath * the absolute cache file path * @param beginningComments * the beginning comments * @param endingComments * the ending comments * @param trainedRecords * the trained records * @param append * the append * @throws IOException */ public static void writeCacheCsvFile(String absoluteCacheFilePath, String beginningComments, String endingComments, List<UserInputTrainingRecord> trainedRecords, boolean append) throws IOException { // Create new students objects FileWriter fileWriter = null;// NOPMD CSVPrinter csvFilePrinter = null;// NOPMD // Create the CSVFormat object with "\n" as a record delimiter CSVFormat csvFileFormat = getCSVFormat(); try { if (trainedRecords.isEmpty()) { fileWriter = new FileWriter(absoluteCacheFilePath, append); // initialize CSVPrinter object csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); // Write a new student object list to the CSV file csvFilePrinter.printComment(beginningComments); csvFilePrinter.printComment(endingComments); fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); return; } // initialize FileWriter object fileWriter = new FileWriter(absoluteCacheFilePath, append); // initialize CSVPrinter object csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); // Write a new student object list to the CSV file csvFilePrinter.printComment(beginningComments); for (UserInputTrainingRecord student : trainedRecords) { List<String> studentDataRecord = new ArrayList<String>(); studentDataRecord.add(student.getInputLabelName()); studentDataRecord.add(student.getInputMLHtmlCode()); csvFilePrinter.printRecord(studentDataRecord); } csvFilePrinter.printComment(endingComments); // System.out.println("CSV file was created successfully !!!"); } catch (Exception e) {// NOPMD throw new IOException("Error in CsvFileWriter !!!");// NOPMD // e.printStackTrace(); } finally { //NOPMD try { if (null != fileWriter) { fileWriter.flush(); fileWriter.close(); } if (null != csvFilePrinter) csvFilePrinter.close(); } catch (IOException e) {//NOPMD //System.out throw new IOException("Error while flushing/closing fileWriter/csvPrinter !!!");//NOPMD //e.printStackTrace(); } } }
From source file:de.speexx.jira.jan.command.transition.IssueTransitionFetcher.java
void exportAsCsv(final List<IssueInfo> issues, final AtomicBoolean doHeader) { try {//from w w w . j a v a 2s. com final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), RFC4180); final String[] header = new String[] { "issue-key", "type", "issue-creation-datetime", "priority", "resolution", "from-stage", "stage", "stage-enter-datetime", "stage-duration" }; if (!doHeader.get()) { csvPrinter.printRecord((Object[]) header); doHeader.set(true); } issues.forEach(info -> { info.stageInfoAsDuration().forEach(stageDuration -> { final String[] values = new String[header.length]; values[0] = info.key; values[1] = info.issueType; values[2] = DateTimeFormatter.ISO_DATE_TIME.format(info.created); values[3] = info.priority; values[4] = resolutionAdjustment(info); values[5] = stageDuration.fromStageName != null ? "" + stageDuration.fromStageName : ""; values[6] = "" + stageDuration.stageName; values[7] = DateTimeFormatter.ISO_DATE_TIME.format(stageDuration.stageStart); values[8] = "" + stageDuration.getDurationSeconds(); try { csvPrinter.printRecord((Object[]) values); } catch (final IOException e) { throw new JiraAnalyzeException(e); } }); }); csvPrinter.flush(); } catch (final IOException e) { throw new JiraAnalyzeException(e); } }
From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java
void printIssueData(final IssueData issueData, final List<FieldNamePath> currentFieldNames, final List<FieldName> historyFieldNames, final TemporalChangeOutput temporalOutput) { assert !Objects.isNull(issueData); assert !Objects.isNull(currentFieldNames); assert !Objects.isNull(historyFieldNames); assert !Objects.isNull(temporalOutput); final List<String> currentFieldEntries = fetchCurrentFieldEntries(issueData, currentFieldNames); try {/*from w w w. j av a 2s.com*/ final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), RFC4180); if (issueData.getHistoricalCount() == 0) { final int fieldsPerChangeEntry = calculateHistoricalFieldSize(temporalOutput); final int max = historyFieldNames.size() * fieldsPerChangeEntry; final List<String> out = new ArrayList(currentFieldEntries); addEmptyChangeData(out, max); csvPrinter.printRecord(out); } else { final int fieldsPerChangeEntry = calculateHistoricalFieldSize(temporalOutput); final int historyFieldNamesSize = historyFieldNames.size(); for (int idx = 0; idx < historyFieldNamesSize; idx++) { final FieldName fieldName = historyFieldNames.get(idx); final List<HistoricalDataEntry> historicalData = issueData.getHistoricalIssueData(fieldName); LocalDateTime lastChangeDate = issueData.getCreatedDate() .orElseThrow(() -> new IllegalStateException("No createdDate available")); for (final HistoricalDataEntry entry : historicalData) { final List<String> out = new ArrayList(); for (int i = 0; i < historyFieldNamesSize; i++) { if (i != idx) { addEmptyChangeData(out, fieldsPerChangeEntry); } else { lastChangeDate = addChangeData(out, entry, temporalOutput, lastChangeDate); } } final List<String> outList = new ArrayList<>(currentFieldEntries); outList.addAll(out); csvPrinter.printRecord(outList.toArray()); } } } csvPrinter.flush(); } catch (final IOException e) { throw new JiraAnalyzeException(e); } }
From source file:com.denkbares.semanticcore.utils.ResultTableModel.java
public String toCSV() throws IOException { StringWriter out = new StringWriter(); CSVPrinter printer = CSVFormat.DEFAULT.withHeader(variables.toArray(new String[variables.size()])) .print(out);/* www.j av a 2 s . c o m*/ for (TableRow row : rows) { List<Object> values = new ArrayList<>(variables.size()); for (String variable : variables) { Value value = row.getValue(variable); values.add(value == null ? null : value.stringValue()); } printer.printRecord(values); } return out.toString(); }
From source file:com.team3637.service.ScheduleServiceMySQLImpl.java
@Override public void exportCSV(String outputFile) { List<Schedule> data = getSchedule(); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try {// w ww.j av a 2s . c om fileWriter = new FileWriter(outputFile); csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n")); for (int i = 0; i < data.size(); i++) { List<Object> line = new ArrayList<>(); for (Field field : Schedule.class.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(data.get(i)); line.add(value); } csvFilePrinter.printRecord(line); } } catch (IOException | IllegalAccessException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.flush(); fileWriter.close(); } if (csvFilePrinter != null) { csvFilePrinter.close(); } } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.team3637.service.TeamServiceMySQLImpl.java
@Override public void exportCSV(String outputFile) { List<Team> data = getTeams(); FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; try {// w w w .ja va 2 s . c o m fileWriter = new FileWriter(outputFile); csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n")); for (Team team : data) { List<Object> line = new ArrayList<>(); for (Field field : Team.class.getDeclaredFields()) { field.setAccessible(true); Object value = field.get(team); line.add(value); } csvFilePrinter.printRecord(line); } } catch (IOException | IllegalAccessException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.flush(); fileWriter.close(); } if (csvFilePrinter != null) { csvFilePrinter.close(); } } catch (IOException e) { e.printStackTrace(); } } }