use of com.opencsv.ICSVWriter in project JAQU-CAZ-Payments-API by InformedSolutions.
the class CsvWriter method createWriterWithCsvContent.
/**
* Create {@link Writer} with content of csv.
*
* @param accountId ID of Account.
* @param accountUserIds List of account user ids for which we should generate payment history.
* @return {@link Writer}.
*/
public Writer createWriterWithCsvContent(UUID accountId, List<UUID> accountUserIds) throws IOException {
try (Writer writer = new StringWriter();
ICSVWriter csvWriter = new CSVWriterBuilder(writer).withSeparator(CSVWriter.NO_QUOTE_CHARACTER).withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER).build()) {
// Write UTF-8 BOM
writer.write('\ufeff');
List<String[]> csvRows = csvContentGenerator.generateCsvRows(accountId, accountUserIds);
csvWriter.writeAll(csvRows);
return writer;
}
}
use of com.opencsv.ICSVWriter in project vitam-ui by ProgrammeVitam.
the class ArchiveSearchInternalService method exportToCsvSearchArchiveUnitsByCriteriaAndParams.
/**
* export ToCsv Search ArchiveUnits By Criteria And Params by language
*
* @param searchQuery
* @param exportSearchResultParam
* @param vitamContext
* @return
* @throws VitamClientException
*/
private Resource exportToCsvSearchArchiveUnitsByCriteriaAndParams(final SearchCriteriaDto searchQuery, final ExportSearchResultParam exportSearchResultParam, final VitamContext vitamContext) throws VitamClientException {
try {
archiveSearchAgenciesInternalService.mapAgenciesNameToCodes(searchQuery, vitamContext);
List<ArchiveUnitCsv> unitCsvList = exportArchiveUnitsByCriteriaToCsvFile(searchQuery, vitamContext);
// create a write
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8.name());
// header record
String[] headerRecordFr = exportSearchResultParam.getHeaders().toArray(new String[exportSearchResultParam.getHeaders().size()]);
SimpleDateFormat dateFormat = new SimpleDateFormat(exportSearchResultParam.getPatternDate());
// create a csv writer
ICSVWriter csvWriter = new CSVWriterBuilder(writer).withSeparator(exportSearchResultParam.getSeparator()).withQuoteChar(ICSVWriter.NO_QUOTE_CHARACTER).withEscapeChar(ICSVWriter.DEFAULT_ESCAPE_CHARACTER).withLineEnd(ICSVWriter.DEFAULT_LINE_END).build();
// write header record
csvWriter.writeNext(headerRecordFr);
// write data records
unitCsvList.stream().forEach(archiveUnitCsv -> {
String startDt = null;
String endDt = null;
if (archiveUnitCsv.getStartDate() != null) {
try {
startDt = dateFormat.format(LocalDateUtil.getDate(archiveUnitCsv.getStartDate()));
} catch (ParseException e) {
LOGGER.error("Error parsing starting date {} ", archiveUnitCsv.getStartDate());
}
}
if (archiveUnitCsv.getEndDate() != null) {
try {
endDt = dateFormat.format(LocalDateUtil.getDate(archiveUnitCsv.getEndDate()));
} catch (ParseException e) {
LOGGER.error("Error parsing end date {} ", archiveUnitCsv.getEndDate());
}
}
csvWriter.writeNext(new String[] { archiveUnitCsv.getId(), archiveUnitCsv.getArchiveUnitType(), archiveUnitCsv.getOriginatingAgencyName(), exportSearchResultParam.getDescriptionLevelMap().get(archiveUnitCsv.getDescriptionLevel()), archiveUnitCsv.getTitle(), startDt, endDt, archiveUnitCsv.getDescription() });
});
// close writers
csvWriter.close();
writer.close();
return new ByteArrayResource(outputStream.toByteArray());
} catch (IOException ex) {
throw new BadRequestException("Unable to export csv file ", ex);
}
}
use of com.opencsv.ICSVWriter in project zachtronics-leaderboard-bot by F43nd1r.
the class SolRepoManualTest method bootstrapPsv.
@Test
public void bootstrapPsv() throws IOException {
Path repoPath = Paths.get("../spacechem/archive");
for (ScPuzzle puzzle : ScPuzzle.values()) {
Path indexPath = repoPath.resolve(puzzle.getGroup().name()).resolve(puzzle.name()).resolve("solutions.psv");
try (ICSVWriter writer = new CSVWriterBuilder(Files.newBufferedWriter(indexPath)).withSeparator('|').build()) {
for (CategoryRecord<ScRecord, ScCategory> cr : repository.findCategoryHolders(puzzle, true)) {
ScRecord record = cr.getRecord();
String author = record.getAuthor();
String categories = cr.getCategories().stream().map(ScCategory::name).collect(Collectors.joining(","));
String[] csvRecord = { record.getScore().toDisplayString(), author, record.getDisplayLink(), record.getDataPath() == null ? "video" : null, categories };
writer.writeNext(csvRecord, false);
}
}
}
}
use of com.opencsv.ICSVWriter in project tribuo by oracle.
the class CSVSaver method save.
/**
* Saves the dataset to the specified path.
* @param csvPath The path to save to.
* @param dataset The dataset to save.
* @param responseNames The response names set.
* @param <T> The output type.
* @throws IOException If the disk write failed.
*/
public <T extends Output<T>> void save(Path csvPath, Dataset<T> dataset, Set<String> responseNames) throws IOException {
boolean isMultiOutput = responseNames.size() > 1;
ImmutableFeatureMap features = dataset.getFeatureIDMap();
int ncols = features.size() + responseNames.size();
//
// Initialize the CSV header row.
String[] headerLine = new String[ncols];
Map<String, Integer> responseToColumn = new HashMap<>();
int col = 0;
for (String response : responseNames) {
headerLine[col] = response;
responseToColumn.put(response, col);
col++;
}
for (int i = 0; i < features.size(); i++) {
headerLine[col++] = features.get(i).getName();
}
// Write the CSV
try (ICSVWriter writer = new CSVParserWriter(Files.newBufferedWriter(csvPath, StandardCharsets.UTF_8), new RFC4180ParserBuilder().withSeparator(separator).withQuoteChar(quote).build(), "\n")) {
writer.writeNext(headerLine);
for (Example<T> e : dataset) {
String[] denseOutput = (isMultiOutput) ? densifyMultiOutput(e, responseToColumn) : densifySingleOutput(e);
String[] featureArr = generateFeatureArray(e, features);
if (featureArr.length != features.size()) {
throw new IllegalStateException(String.format("Invalid example: had %d features, expected %d.", featureArr.length, features.size()));
}
//
// Copy responses and features into a single array
String[] line = new String[ncols];
System.arraycopy(denseOutput, 0, line, 0, denseOutput.length);
System.arraycopy(featureArr, 0, line, denseOutput.length, featureArr.length);
writer.writeNext(line);
}
}
}
use of com.opencsv.ICSVWriter in project DSpace by DSpace.
the class Dataset method exportAsCSV.
public ByteArrayOutputStream exportAsCSV() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ICSVWriter ecsvp = new CSVWriterBuilder(new OutputStreamWriter(baos, StandardCharsets.UTF_8)).withSeparator(';').build();
// Generate the item row
List<String> colLabels = getColLabels();
colLabels.add(0, "");
ecsvp.writeNext(colLabels.toArray(new String[colLabels.size()]));
List<String> rowLabels = getRowLabels();
String[][] matrix = getMatrix();
for (int i = 0; i < rowLabels.size(); i++) {
String rowLabel = rowLabels.get(i);
ecsvp.writeNext((String[]) ArrayUtils.addAll(new String[] { rowLabel }, matrix[i]));
}
ecsvp.flush();
ecsvp.close();
return baos;
}
Aggregations