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

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

Introduction

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

Prototype

public void printRecord(final Object... values) throws IOException 

Source Link

Document

Prints the given values a single record of delimiter separated values followed by the record separator.

Usage

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.ExportUsageServlet.java

private String csvExport(String sessionId, String user, Date startDate, Date endDate)
        throws ServiceException, RestServerException, IOException {
    Object[] header = { "Owner", "Project", "Job Id", "Job Name", "Job Duration", "Task Id", "Task Name",
            "Task Node Number", "Task Start Time", "Task Finished Time", "Task Duration" };
    List<JobUsage> jobUsages = ((SchedulerServiceImpl) Service.get()).getUsage(sessionId, user, startDate,
            endDate);/*w w  w  . jav a  2  s. co m*/
    StringBuilder sb = new StringBuilder();
    CSVPrinter csvFilePrinter = null;
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(LINE_SEPARATOR);
    csvFilePrinter = new CSVPrinter(sb, csvFileFormat);
    csvFilePrinter.printRecord(header);
    for (JobUsage jobUsage : jobUsages) {
        for (TaskUsage taskUsage : jobUsage.getTaskUsages()) {
            csvFilePrinter.printRecord(jobUsage.getOwner(), jobUsage.getProject(), jobUsage.getJobId(),
                    jobUsage.getJobName(), jobUsage.getJobDuration(), taskUsage.getTaskId(),
                    taskUsage.getTaskName(), taskUsage.getTaskNodeNumber(), taskUsage.getTaskStartTime(),
                    taskUsage.getTaskFinishedTime(), taskUsage.getTaskExecutionDuration());
        }
    }
    csvFilePrinter.close();
    return sb.toString();
}

From source file:org.roda.wui.api.v1.utils.ResultsCSVOutputStream.java

@Override
public void consumeOutputStream(final OutputStream out) throws IOException {
    final OutputStreamWriter writer = new OutputStreamWriter(out);
    CSVPrinter printer = null;
    boolean isFirst = true;
    for (final T result : this.results) {
        if (isFirst) {
            printer = getFormat().withHeader(result.toCsvHeaders().toArray(new String[0])).print(writer);
            isFirst = false;/* w  w w  .  j a v  a  2 s . c  o m*/
        }
        printer.printRecord(result.toCsvValues());
    }
    writer.flush();
}

From source file:org.shareok.data.documentProcessor.CsvHandler.java

/**
 * Output the data into a new CSV file//from ww w  .  jav a2  s .  com
 * <p>Uses "\n" as the line separator</P>
 * 
 * @param newFileName : String. 
 * If the newFileName is not specified, a "-copy" will be attached to the old file name for the new CSV file
 * 
 * @return the path of the new CSV file
 */
public String outputData(String newFileName) {
    if (null == data) {
        readData();
    }

    if (null != data) {
        FileWriter fileWriter = null;
        CSVPrinter csvFilePrinter = null;
        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
        try {
            if (null == newFileName || newFileName.equals("")) {
                newFileName = fileName.substring(0, fileName.indexOf(".csv")) + "-copy.csv";
            }
            fileWriter = new FileWriter(newFileName);

            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            csvFilePrinter.printRecord(Arrays.asList(fileHeadMapping));
            Map<String, String[]> records = new HashMap<>();
            List<String> headingList = Arrays.asList(fileHeadMapping);

            Iterator it = data.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = (String) data.get(key);
                String[] keyInfo = key.split("-");
                String row = keyInfo[keyInfo.length - 1];
                String column = key.replace("-" + row, "");

                if (null == records.get(row)) {
                    String[] dataRecord = new String[fileHeadMapping.length];
                    dataRecord[headingList.indexOf(column)] = value;
                    records.put(row, dataRecord);
                } else {
                    String[] dataRecord = records.get(row);
                    dataRecord[headingList.indexOf(column)] = value;
                }
            }

            Iterator it2 = records.keySet().iterator();
            while (it2.hasNext()) {
                String key = (String) it2.next();
                String[] value = (String[]) records.get(key);
                csvFilePrinter.printRecord(Arrays.asList(value));
            }
        } catch (Exception e) {
            System.out.println("Error in CsvFileWriter!\n");
            e.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                System.out.println("Error while flushing/closing fileWriter/csvPrinter\n");
                e.printStackTrace();
            }
        }
    }
    return newFileName;
}

From source file:org.thingsboard.server.service.install.cql.CassandraDbHelper.java

private static void dumpRow(Row row, String[] columns, String[] defaultValues, CSVPrinter csvPrinter)
        throws Exception {
    List<String> record = new ArrayList<>();
    for (int i = 0; i < columns.length; i++) {
        String column = columns[i];
        String defaultValue;//  ww  w  .j  av  a 2  s . co  m
        if (defaultValues != null && i < defaultValues.length) {
            defaultValue = defaultValues[i];
        } else {
            defaultValue = "";
        }
        record.add(getColumnValue(column, defaultValue, row));
    }
    csvPrinter.printRecord(record);
}

From source file:org.thingsboard.server.service.install.sql.SqlDbHelper.java

private static void dumpRow(ResultSet res, Map<String, Integer> columnIndexMap, String[] columns,
        String[] defaultValues, CSVPrinter csvPrinter) throws Exception {
    List<String> record = new ArrayList<>();
    for (int i = 0; i < columns.length; i++) {
        String column = columns[i];
        String defaultValue;/*from  w w w.  ja  va2  s.  c o m*/
        if (defaultValues != null && i < defaultValues.length) {
            defaultValue = defaultValues[i];
        } else {
            defaultValue = "";
        }
        record.add(getColumnValue(column, defaultValue, columnIndexMap, res));
    }
    csvPrinter.printRecord(record);
}

From source file:org.zanata.client.commands.stats.CsvStatisticsOutput.java

private void writeToCsv(ContainerTranslationStatistics statistics, CSVPrinter writer) throws IOException {

    writer.printRecord(Lists.newArrayList());

    // Display headers
    Link sourceRef = statistics.getRefs().findLinkByRel("statSource");
    if (sourceRef.getType().equals("PROJ_ITER")) {
        writer.printRecord(Lists.newArrayList("Project Version: ", statistics.getId()));
    } else if (sourceRef.getType().equals("DOC")) {
        writer.printRecord(Lists.newArrayList("Document: ", statistics.getId()));
    }/*from ww w.  j a  v a  2 s  .  c o m*/

    // Write headers
    writer.printRecord(Lists.newArrayList("Locale", "Unit", "Total", "Translated", "Need Review",
            "Untranslated", "Last Translated"));

    // Write stats
    if (statistics.getStats() != null) {
        for (TranslationStatistics transStats : statistics.getStats()) {
            writer.printRecord(Lists.newArrayList(transStats.getLocale(), transStats.getUnit().toString(),
                    Long.toString(transStats.getTotal()), Long.toString(transStats.getTranslatedAndApproved()),
                    Long.toString(transStats.getDraft()), Long.toString(transStats.getUntranslated()),
                    transStats.getLastTranslated()));
        }
    }

    writer.printRecord(Lists.newArrayList());

    try {
        writer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Detailed stats
    if (statistics.getDetailedStats() != null) {
        for (ContainerTranslationStatistics detailedStats : statistics.getDetailedStats()) {
            writeToCsv(detailedStats, writer);
        }
    }
}

From source file:password.pwm.event.AuditManager.java

public int outputVaultToCsv(OutputStream outputStream, final Locale locale, final boolean includeHeader)
        throws IOException {
    final Configuration config = null;

    final CSVPrinter csvPrinter = Helper.makeCsvPrinter(outputStream);

    csvPrinter.printComment(" " + PwmConstants.PWM_APP_NAME + " audit record output ");
    csvPrinter.printComment(" " + PwmConstants.DEFAULT_DATETIME_FORMAT.format(new Date()));

    if (includeHeader) {
        final List<String> headers = new ArrayList<>();
        headers.add("Type");
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_EventCode", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Timestamp", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_GUID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Message", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Instance", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_PerpetratorID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_PerpetratorDN", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_TargetID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_TargetDN", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_SourceAddress", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_SourceHost", config,
                password.pwm.i18n.Admin.class));
        csvPrinter.printRecord(headers);
    }/*from w ww  .  j a  v a 2 s.c o  m*/

    int counter = 0;
    for (final Iterator<AuditRecord> recordIterator = readVault(); recordIterator.hasNext();) {
        final AuditRecord loopRecord = recordIterator.next();
        counter++;

        final List<String> lineOutput = new ArrayList<>();
        lineOutput.add(loopRecord.getEventCode().getType().toString());
        lineOutput.add(loopRecord.getEventCode().toString());
        lineOutput.add(PwmConstants.DEFAULT_DATETIME_FORMAT.format(loopRecord.getTimestamp()));
        lineOutput.add(loopRecord.getGuid());
        lineOutput.add(loopRecord.getMessage() == null ? "" : loopRecord.getMessage());
        if (loopRecord instanceof SystemAuditRecord) {
            lineOutput.add(((SystemAuditRecord) loopRecord).getInstance());
        }
        if (loopRecord instanceof UserAuditRecord) {
            lineOutput.add(((UserAuditRecord) loopRecord).getPerpetratorID());
            lineOutput.add(((UserAuditRecord) loopRecord).getPerpetratorDN());
            lineOutput.add("");
            lineOutput.add("");
            lineOutput.add(((UserAuditRecord) loopRecord).getSourceAddress());
            lineOutput.add(((UserAuditRecord) loopRecord).getSourceHost());
        }
        if (loopRecord instanceof HelpdeskAuditRecord) {
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getPerpetratorID());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getPerpetratorDN());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getTargetID());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getTargetDN());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getSourceAddress());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getSourceHost());
        }
        csvPrinter.printRecord(lineOutput);
    }
    csvPrinter.flush();

    return counter;
}

From source file:password.pwm.svc.event.AuditService.java

public int outputVaultToCsv(final OutputStream outputStream, final Locale locale, final boolean includeHeader)
        throws IOException {
    final Configuration config = null;

    final CSVPrinter csvPrinter = JavaHelper.makeCsvPrinter(outputStream);

    csvPrinter.printComment(" " + PwmConstants.PWM_APP_NAME + " audit record output ");
    csvPrinter.printComment(" " + JavaHelper.toIsoDate(Instant.now()));

    if (includeHeader) {
        final List<String> headers = new ArrayList<>();
        headers.add("Type");
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_EventCode", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Timestamp", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_GUID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Message", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_Instance", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_PerpetratorID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_PerpetratorDN", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_TargetID", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_TargetDN", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_SourceAddress", config,
                password.pwm.i18n.Admin.class));
        headers.add(LocaleHelper.getLocalizedMessage(locale, "Field_Audit_SourceHost", config,
                password.pwm.i18n.Admin.class));
        csvPrinter.printRecord(headers);
    }/*from   w w w  .j a v  a2 s  .  c o m*/

    int counter = 0;
    for (final Iterator<AuditRecord> recordIterator = readVault(); recordIterator.hasNext();) {
        final AuditRecord loopRecord = recordIterator.next();
        counter++;

        final List<String> lineOutput = new ArrayList<>();
        lineOutput.add(loopRecord.getEventCode().getType().toString());
        lineOutput.add(loopRecord.getEventCode().toString());
        lineOutput.add(JavaHelper.toIsoDate(loopRecord.getTimestamp()));
        lineOutput.add(loopRecord.getGuid());
        lineOutput.add(loopRecord.getMessage() == null ? "" : loopRecord.getMessage());
        if (loopRecord instanceof SystemAuditRecord) {
            lineOutput.add(((SystemAuditRecord) loopRecord).getInstance());
        }
        if (loopRecord instanceof UserAuditRecord) {
            lineOutput.add(((UserAuditRecord) loopRecord).getPerpetratorID());
            lineOutput.add(((UserAuditRecord) loopRecord).getPerpetratorDN());
            lineOutput.add("");
            lineOutput.add("");
            lineOutput.add(((UserAuditRecord) loopRecord).getSourceAddress());
            lineOutput.add(((UserAuditRecord) loopRecord).getSourceHost());
        }
        if (loopRecord instanceof HelpdeskAuditRecord) {
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getPerpetratorID());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getPerpetratorDN());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getTargetID());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getTargetDN());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getSourceAddress());
            lineOutput.add(((HelpdeskAuditRecord) loopRecord).getSourceHost());
        }
        csvPrinter.printRecord(lineOutput);
    }
    csvPrinter.flush();

    return counter;
}

From source file:password.pwm.svc.report.ReportCsvUtility.java

public void outputSummaryToCsv(final OutputStream outputStream, final Locale locale) throws IOException {
    final List<ReportSummaryData.PresentationRow> outputList = reportService.getSummaryData()
            .asPresentableCollection(pwmApplication.getConfig(), locale);
    final CSVPrinter csvPrinter = JavaHelper.makeCsvPrinter(outputStream);

    for (final ReportSummaryData.PresentationRow presentationRow : outputList) {
        final List<String> headerRow = new ArrayList<>();
        headerRow.add(presentationRow.getLabel());
        headerRow.add(presentationRow.getCount());
        headerRow.add(presentationRow.getPct());
        csvPrinter.printRecord(headerRow);
    }/*from  w w w.  j  a v a 2s . c  o m*/

    csvPrinter.close();
}

From source file:password.pwm.svc.report.ReportCsvUtility.java

public void outputToCsv(final OutputStream outputStream, final boolean includeHeader, final Locale locale,
        final Configuration config, final ReportColumnFilter columnFilter) throws IOException,
        ChaiUnavailableException, ChaiOperationException, PwmUnrecoverableException, PwmOperationalException {
    final CSVPrinter csvPrinter = JavaHelper.makeCsvPrinter(outputStream);
    final Class localeClass = password.pwm.i18n.Admin.class;
    if (includeHeader) {
        final List<String> headerRow = new ArrayList<>();

        if (columnFilter.isUsernameVisible()) {
            headerRow.add(/*from   www.  j ava2  s  .c om*/
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_Username", config, localeClass));
        }
        if (columnFilter.isUserDnVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_UserDN", config, localeClass));
        }
        if (columnFilter.isLdapProfileVisible()) {
            headerRow.add(
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_LDAP_Profile", config, localeClass));
        }
        if (columnFilter.isEmailVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_Email", config, localeClass));
        }
        if (columnFilter.isUserGuidVisible()) {
            headerRow.add(
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_UserGuid", config, localeClass));
        }
        if (columnFilter.isAccountExpirationTimeVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_AccountExpireTime", config,
                    localeClass));
        }
        if (columnFilter.isPasswordExpirationTimeVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdExpireTime", config,
                    localeClass));
        }
        if (columnFilter.isPasswordChangeTimeVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdChangeTime", config,
                    localeClass));
        }
        if (columnFilter.isResponseSetTimeVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_ResponseSaveTime", config,
                    localeClass));
        }
        if (columnFilter.isLastLoginTimeVisible()) {
            headerRow.add(
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_LastLogin", config, localeClass));
        }
        if (columnFilter.isHasResponsesVisible()) {
            headerRow.add(
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_HasResponses", config, localeClass));
        }
        if (columnFilter.isHasHelpdeskResponsesVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_HasHelpdeskResponses", config,
                    localeClass));
        }
        if (columnFilter.isResponseStorageMethodVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_ResponseStorageMethod", config,
                    localeClass));
        }
        if (columnFilter.isResponseFormatTypeVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_ResponseFormatType", config,
                    localeClass));
        }
        if (columnFilter.isPasswordStatusExpiredVisible()) {
            headerRow.add(
                    LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdExpired", config, localeClass));
        }
        if (columnFilter.isPasswordStatusPreExpiredVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdPreExpired", config,
                    localeClass));
        }
        if (columnFilter.isPasswordStatusViolatesPolicyVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdViolatesPolicy", config,
                    localeClass));
        }
        if (columnFilter.isPasswordStatusWarnPeriodVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_PwdWarnPeriod", config,
                    localeClass));
        }
        if (columnFilter.isRequiresPasswordUpdateVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_RequiresPasswordUpdate",
                    config, localeClass));
        }
        if (columnFilter.isRequiresResponseUpdateVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_RequiresResponseUpdate",
                    config, localeClass));
        }
        if (columnFilter.isRequiresProfileUpdateVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_RequiresProfileUpdate", config,
                    localeClass));
        }
        if (columnFilter.isCacheTimestampVisible()) {
            headerRow.add(LocaleHelper.getLocalizedMessage(locale, "Field_Report_RecordCacheTime", config,
                    localeClass));
        }

        csvPrinter.printRecord(headerRow);
    }

    ClosableIterator<UserCacheRecord> cacheBeanIterator = null;
    try {
        cacheBeanIterator = iterator();
        while (cacheBeanIterator.hasNext()) {
            final UserCacheRecord userCacheRecord = cacheBeanIterator.next();
            outputRecordRow(config, locale, userCacheRecord, csvPrinter, columnFilter);
        }
    } finally {
        if (cacheBeanIterator != null) {
            cacheBeanIterator.close();
        }
    }

    csvPrinter.flush();
}