Example usage for org.apache.commons.csv CSVPrinter print

List of usage examples for org.apache.commons.csv CSVPrinter print

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter print.

Prototype

public void print(final Object value) throws IOException 

Source Link

Document

Prints the string as the next value on the line.

Usage

From source file:biz.webgate.dominoext.poi.component.kernel.CSVProcessor.java

public ByteArrayOutputStream generateCSV(UICSV csvDef, FacesContext context) throws IOException, POIException {
    ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream();
    OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS);
    CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT);

    List<CSVColumn> lstColumns = csvDef.getColumns();
    Collections.sort(lstColumns, new Comparator<CSVColumn>() {

        public int compare(CSVColumn o1, CSVColumn o2) {
            Integer p1 = Integer.valueOf(o1.getPosition());
            Integer p2 = Integer.valueOf(o2.getPosition());
            return p1.compareTo(p2);
        }//ww  w.j a v  a  2 s .c  om

    });
    if (csvDef.isIncludeHeader()) {
        for (CSVColumn cl : lstColumns) {
            csvPrinter.print(cl.getTitle());
        }
        csvPrinter.println();
    }

    // DATASOURCE holen und verarbeiten.
    if (csvDef.getDataSource() != null) {
        EmbeddedDataSourceExportProcessor.getInstance().process(lstColumns, csvDef, csvPrinter, context);
    } else {
        XPagesDataSourceExportProcessor.getInstance().process(lstColumns, csvDef, csvPrinter, context);
    }

    csvPrinter.flush();
    return csvBAOS;
}

From source file:com.rcv.ResultsWriter.java

private void addActionRows(CSVPrinter csvPrinter) throws IOException {
    // print eliminated candidates in first action row
    csvPrinter.print("Eliminated");
    // for each round print any candidates who were eliminated
    for (int round = 1; round <= numRounds; round++) {
        // list of all candidates eliminated in this round
        List<String> eliminated = roundToEliminatedCandidates.get(round);
        if (eliminated != null && eliminated.size() > 0) {
            addActionRowCandidates(eliminated, csvPrinter);
        } else {//from w  ww.j  a  v  a  2s  .  co  m
            csvPrinter.print("");
        }
    }
    csvPrinter.println();

    // print elected candidates in second action row
    csvPrinter.print("Elected");
    // for each round print any candidates who were elected
    for (int round = 1; round <= numRounds; round++) {
        // list of all candidates eliminated in this round
        List<String> winners = roundToWinningCandidates.get(round);
        if (winners != null && winners.size() > 0) {
            addActionRowCandidates(winners, csvPrinter);
        } else {
            csvPrinter.print("");
        }
    }
    csvPrinter.println();
}

From source file:biz.webgate.dominoext.poi.component.kernel.csv.EmbeddedDataSourceExportProcessor.java

public void process(List<CSVColumn> lstColumns, UICSV csvDef, CSVPrinter csvPrinter, FacesContext context)
        throws POIException {
    try {//from ww w.  j a v  a2 s . c om
        IExportSource is = csvDef.getDataSource();
        int nAccess = is.accessSource();
        if (nAccess < 1) {
            throw new POIException("Error accessing Source: " + is.getClass() + " Error: " + nAccess);
        }
        int nCount = 0;
        while (is.accessNextRow() == 1) {
            nCount++;
            for (CSVColumn cl : lstColumns) {
                Object objCurrent = is.getValue(cl, csvDef.getVar(), csvDef.getIndex(), nCount, context);
                csvPrinter.print(objCurrent);
            }
            csvPrinter.println();
        }
        is.closeSource();
    } catch (Exception e) {
        throw new POIException("Error in processExportRow", e);
    }

}

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/** write the resources.
 * @throws IOException *//*from   ww w .ja v a  2s  .  c o  m*/
private void writeResources(CSVPrinter writer) throws IOException {
    writeResourceHeaders(writer);
    // parse all resources
    for (HumanResource p : myProject.getHumanResourceManager().getResources()) {
        // ID
        if (csvOptions.bExportResourceID) {
            writer.print(String.valueOf(p.getId()));
        }
        // Name
        if (csvOptions.bExportResourceName) {
            writer.print(p.getName());
        }
        // Mail
        if (csvOptions.bExportResourceMail) {
            writer.print(p.getMail());
        }
        // Phone
        if (csvOptions.bExportResourcePhone) {
            writer.print(p.getPhone());
        }
        // Role
        if (csvOptions.bExportResourceRole) {
            Role role = p.getRole();
            String sRoleID = role == null ? "0" : role.getPersistentID();
            writer.print(sRoleID);
        }
        List<CustomProperty> customProps = p.getCustomProperties();
        for (int j = 0; j < customProps.size(); j++) {
            CustomProperty nextProperty = customProps.get(j);
            writer.print(nextProperty.getValueAsString());
        }
        writer.println();
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcLoadRecordWriter.java

@Override
public List<OnRecordErrorException> writeBatch(Iterator<Record> recordIterator) throws StageException {
    final List<OnRecordErrorException> errorRecords = new LinkedList<>();
    if (!recordIterator.hasNext()) {
        return errorRecords;
    }//  www  .j av a 2 s  . c  om

    // Assume all records have the same columns.
    final Record first = recordIterator.next();
    SortedMap<String, String> columnsToParameters = recordReader.getColumnsToParameters(first,
            OperationType.LOAD_CODE, getColumnsToParameters(), getColumnsToFields());
    if (columnsToParameters.isEmpty()) {
        throw new StageException(JdbcErrors.JDBC_22);
    }

    final Set<String> columnNames = columnsToParameters.keySet();
    final String loadSql = "LOAD DATA LOCAL INFILE '' " + duplicateKeyAction.getKeyword() + " INTO TABLE "
            + getTableName() + " (" + Joiner.on(", ").join(columnNames) + ")";
    try (Connection connection = getDataSource().getConnection()) {
        Connection conn = connection.unwrap(Connection.class);
        try (PreparedStatement statement = conn.prepareStatement(loadSql)) {
            PipedInputStream is = new PipedInputStream();
            PipedOutputStream os = new PipedOutputStream(is);
            statement.getClass().getMethod("setLocalInfileInputStream", InputStream.class).invoke(statement,
                    is);

            Future<?> future = loadOutputExecutor.submit(() -> {
                try (OutputStreamWriter writer = new OutputStreamWriter(os)) {
                    CSVPrinter printer = new CSVPrinter(writer, CSVFormat.MYSQL);
                    Record record = first;
                    while (record != null) {
                        int opCode = getOperationCode(record, errorRecords);
                        if (opCode == OperationType.LOAD_CODE) {
                            for (String column : columnNames) {
                                Field field = record.get(getColumnsToFields().get(column));
                                printer.print(field.getValue());
                            }
                            printer.println();
                        } else if (opCode > 0) {
                            LOG.debug("Sending record to error due to unsupported operation {}", opCode);
                            errorRecords.add(new OnRecordErrorException(record, JdbcErrors.JDBC_70, opCode));
                        } else {
                            // It should be added to the error records.
                        }
                        record = recordIterator.hasNext() ? recordIterator.next() : null;
                    }
                    ;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing query: {}", statement.toString());
            }
            statement.execute();
            future.get();
        }
        connection.commit();
    } catch (SQLException e) {
        handleSqlException(e);
    } catch (Exception e) {
        throw new StageException(JdbcErrors.JDBC_14, e.getMessage(), e);
    }
    return errorRecords;
}

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/** Write all tasks.
 * @throws IOException *///www . j av  a2s .  c  o  m
private void writeTasks(CSVPrinter writer) throws IOException {
    writeTaskHeaders(writer);
    List<CustomPropertyDefinition> customFields = myProject.getTaskCustomColumnManager().getDefinitions();
    for (Task task : myProject.getTaskManager().getTasks()) {
        // ID
        if (csvOptions.bExportTaskID) {
            writer.print(String.valueOf(task.getTaskID()));
        }
        // Name
        if (csvOptions.bExportTaskName) {
            writer.print(getName(task));
        }
        // Start Date
        if (csvOptions.bExportTaskStartDate) {
            writer.print(task.getStart().toString());
        }
        // End Date
        if (csvOptions.bExportTaskEndDate) {
            writer.print(task.getEnd().getDisplayValue().toString());
        }
        // Duration
        if (csvOptions.bExportTaskDuration) {
            writer.print(String.valueOf(task.getDuration().getLength()));
        }
        // Percent complete
        if (csvOptions.bExportTaskPercent) {
            writer.print(String.valueOf(task.getCompletionPercentage()));
        }
        // Web Link
        if (csvOptions.bExportTaskWebLink) {
            writer.print(getWebLink((GanttTask) task));
        }
        // associated resources
        if (csvOptions.bExportTaskResources) {
            writer.print(getAssignments(task));
        }
        // Notes
        if (csvOptions.bExportTaskNotes) {
            writer.print(task.getNotes());
        }
        writer.print(
                Joiner.on(';').join(Lists.transform(Arrays.asList(task.getDependenciesAsDependant().toArray()),
                        new Function<TaskDependency, String>() {
                            @Override
                            public String apply(TaskDependency input) {
                                return "" + input.getDependee().getTaskID();
                            }
                        })));
        CustomColumnsValues customValues = task.getCustomValues();
        for (int j = 0; j < customFields.size(); j++) {
            Object nextCustomFieldValue = customValues.getValue(customFields.get(j));
            writer.print(String.valueOf(nextCustomFieldValue));
        }
        writer.println();
    }
}

From source file:com.quanticate.opensource.datalistdownload.DataListDownloadWebScript.java

@Override
protected void populateBody(Object resource, CSVPrinter csv, List<QName> properties) throws IOException {
    NodeRef list = (NodeRef) resource;/*from www .j av  a2  s  . c o  m*/
    List<NodeRef> items = getItems(list);

    for (NodeRef item : items) {
        for (QName prop : properties) {
            Pair<Object, String> valAndLink = identifyValueAndLink(item, prop);

            if (valAndLink == null) {
                // This property isn't set
                csv.print("");
            } else {
                Object val = valAndLink.getFirst();

                // Multi-line property?
                if (val instanceof String[]) {
                    String[] lines = (String[]) val;
                    StringBuffer text = new StringBuffer();

                    for (String line : lines) {
                        if (text.length() > 0) {
                            text.append('\n');
                        }
                        text.append(line);
                    }

                    csv.print(text.toString());
                }

                // Regular properties
                else if (val instanceof String) {
                    csv.print((String) val);
                } else if (val instanceof Date) {
                    csv.print(ISO8601DateFormat.format((Date) val));
                } else if (val instanceof Integer || val instanceof Long) {
                    csv.print(val.toString());
                } else if (val instanceof Float || val instanceof Double) {
                    csv.print(val.toString());
                } else {
                    System.err.println("TODO: Handle CSV output of " + val.getClass().getName() + " - " + val);
                }
            }
        }
        csv.println();
    }
}

From source file:com.rcv.ResultsWriter.java

private void addActionRowCandidates(List<String> candidates, CSVPrinter csvPrinter) throws IOException {
    List<String> candidateDisplayNames = new ArrayList<>();
    // build list of display names
    for (String candidate : candidates) {
        candidateDisplayNames.add(config.getNameForCandidateID(candidate));
    }//from  ww w .j  a v  a2s  .  co  m
    // concatenate them using semi-colon for display in a single cell
    String candidateCellText = String.join("; ", candidateDisplayNames);
    // print the candidate name list
    csvPrinter.print(candidateCellText);
}

From source file:biz.webgate.dominoext.poi.component.kernel.csv.XPagesDataSourceExportProcessor.java

public void process(List<CSVColumn> lstColumns, UICSV csvDef, CSVPrinter csvPrinter, FacesContext context)
        throws POIException {
    DataSource ds = csvDef.getPageDataSource();

    if (ds != null) {
        try {/*from   w ww. j  a va 2  s .c om*/
            TabularDataModel tdm = getTDM(ds, context);
            for (int nCount = 0; nCount < tdm.getRowCount(); nCount++) {
                nCount++;
                for (CSVColumn cl : lstColumns) {
                    String strTitle = cl.getColumnTitle();
                    Object objCurrent = null;
                    if (strTitle != null && !"".equals(strTitle)) {
                        objCurrent = getColumnValue(cl.getColumnTitle(), tdm, context);
                    } else {
                        objCurrent = cl.executeComputeValue(context, tdm.getRowData(), nCount, csvDef.getVar(),
                                csvDef.getIndex());
                    }
                    csvPrinter.print(objCurrent);
                }
                csvPrinter.println();
            }
        } catch (Exception e) {
            throw new POIException("Error in process", e);
        }
    } else {
        throw new POIException("No DataSource found", null);
    }

}

From source file:com.rodaxsoft.mailgun.CampaignManager.java

/**
 * Saves campaign events to a CSV file with the following format:
 * <code>&lt;campaign name&gt;_(&lt;campaign id&gt;)_&lt;timestamp&gt;.csv</code>
 * @param campaignId The campaign ID// w ww  . j  ava  2 s  . c  o m
 * @throws ContextedException if a processing error occurs
 * @throws IOException if an I/O error occurs
 */
void saveCampaignEventsToCSV(String campaignId) throws ContextedException, IOException {

    Campaign campaign = getCampaign(campaignId);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    String dateTime = format.format(new Date());
    String fileName;

    if (campaign != null) {

        String name = StringUtils.replace(campaign.getName(), " ", "_");
        fileName = new StringBuilder(name).append("_(").append(campaignId).append(")_").append(dateTime)
                .append(".csv").toString();
    } else {
        fileName = campaignId + "_" + dateTime + ".csv";
    }

    CSVPrinter csvPrinter = null;
    PrintWriter pw = null;
    CSVFormat csvFormat = null;
    try {

        pw = new PrintWriter(fileName);
        final List<Map<String, Object>> events = getEvents(campaignId);

        for (Map<String, Object> map : events) {

            if (null == csvPrinter) {
                final Set<String> keySet = map.keySet();
                int size = keySet.size();
                String[] keys = keySet.toArray(new String[size]);
                csvFormat = CSVFormat.DEFAULT.withHeader(keys);
                csvPrinter = new CSVPrinter(pw, csvFormat);
            }
            //            city   domain   tags   timestamp   region   ip   country   recipient   event   user_vars

            String[] headers = csvFormat.getHeader();
            for (String key : headers) {
                csvPrinter.print(map.get(key));
            }

            csvPrinter.println();
        }

    } finally {

        if (csvPrinter != null) {
            csvPrinter.flush();
        }

        IOUtils.closeQuietly(csvPrinter);
    }

}