Search in sources :

Example 1 with ICSVWriter

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;
    }
}
Also used : ICSVWriter(com.opencsv.ICSVWriter) StringWriter(java.io.StringWriter) CSVWriterBuilder(com.opencsv.CSVWriterBuilder) StringWriter(java.io.StringWriter) Writer(java.io.Writer) CSVWriter(com.opencsv.CSVWriter) ICSVWriter(com.opencsv.ICSVWriter)

Example 2 with ICSVWriter

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);
    }
}
Also used : CSVWriterBuilder(com.opencsv.CSVWriterBuilder) ArchiveUnitCsv(fr.gouv.vitamui.archives.search.common.dto.ArchiveUnitCsv) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayResource(org.springframework.core.io.ByteArrayResource) IOException(java.io.IOException) ICSVWriter(com.opencsv.ICSVWriter) BadRequestException(fr.gouv.vitamui.commons.api.exception.BadRequestException) OutputStreamWriter(java.io.OutputStreamWriter) ParseException(java.text.ParseException) DateTimeParseException(java.time.format.DateTimeParseException) SimpleDateFormat(java.text.SimpleDateFormat) Writer(java.io.Writer) ICSVWriter(com.opencsv.ICSVWriter) OutputStreamWriter(java.io.OutputStreamWriter)

Example 3 with ICSVWriter

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);
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ICSVWriter(com.opencsv.ICSVWriter) CSVWriterBuilder(com.opencsv.CSVWriterBuilder) BotTest(com.faendir.zachtronics.bot.BotTest) Test(org.junit.jupiter.api.Test)

Example 4 with ICSVWriter

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);
        }
    }
}
Also used : HashMap(java.util.HashMap) RFC4180ParserBuilder(com.opencsv.RFC4180ParserBuilder) ICSVWriter(com.opencsv.ICSVWriter) ImmutableFeatureMap(org.tribuo.ImmutableFeatureMap) CSVParserWriter(com.opencsv.CSVParserWriter)

Example 5 with ICSVWriter

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;
}
Also used : ICSVWriter(com.opencsv.ICSVWriter) CSVWriterBuilder(com.opencsv.CSVWriterBuilder) OutputStreamWriter(java.io.OutputStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

ICSVWriter (com.opencsv.ICSVWriter)7 CSVWriterBuilder (com.opencsv.CSVWriterBuilder)5 IOException (java.io.IOException)3 OutputStreamWriter (java.io.OutputStreamWriter)3 BotTest (com.faendir.zachtronics.bot.BotTest)2 CSVParserWriter (com.opencsv.CSVParserWriter)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Writer (java.io.Writer)2 Path (java.nio.file.Path)2 Test (org.junit.jupiter.api.Test)2 DisplayContext (com.faendir.zachtronics.bot.model.DisplayContext)1 RedditService (com.faendir.zachtronics.bot.reddit.RedditService)1 Subreddit (com.faendir.zachtronics.bot.reddit.Subreddit)1 CategoryRecord (com.faendir.zachtronics.bot.repository.CategoryRecord)1 com.faendir.zachtronics.bot.sz.model (com.faendir.zachtronics.bot.sz.model)1 CSVWriter (com.opencsv.CSVWriter)1 RFC4180Parser (com.opencsv.RFC4180Parser)1 RFC4180ParserBuilder (com.opencsv.RFC4180ParserBuilder)1 ConfigurationManager (com.oracle.labs.mlrg.olcut.config.ConfigurationManager)1 UsageException (com.oracle.labs.mlrg.olcut.config.UsageException)1