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

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

Introduction

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

Prototype

public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException 

Source Link

Document

Creates a printer that will print values to the given stream following the CSVFormat.

Usage

From source file:org.cloudsimulator.controller.PlacementSimulatorTestRunner.java

protected void exportSimulationResults(String dcName, String testCase,
        ArrayList<SimulationResultWrapper> simulationResultWrappers) {

    Path resultPath = Paths.get(this.autoExportResultPath, dcName);

    if (!Files.exists(resultPath)) {
        File resultFile = new File(resultPath.toString());
        resultFile.mkdirs();/*  w  w  w .  j  av a2 s .  c om*/
    }

    ArrayList<PlacementResultExt> resultExts = new ArrayList<PlacementResultExt>();

    Path resultFilePath = Paths.get(resultPath.toString(), testCase + ".csv");

    CSVFormat csvFormat = CSVFormat.EXCEL.withDelimiter(';');

    Object[] header = { "Id", "Reserved OS resource", "Max risk", "Max overprov time", "N runs for GRASP",
            "N simulation", "N VM", "N VM used for keep test consistency", "Iteration time", "Euristic method",
            "Euristic coefficient", "N Used host", "CPU Avg", "Mem Avg", "Overall Avg", "Cpu in range",
            "Mem in range", "Overall in range" };

    FileWriter buffer;
    try {
        buffer = new FileWriter(resultFilePath.toString());
        CSVPrinter csvPrinter = new CSVPrinter(buffer, csvFormat);

        csvPrinter.printRecord(header);
        for (SimulationResultWrapper simulationResultWrapper : simulationResultWrappers) {

            for (PlacementResult result : simulationResultWrapper.getPlacementResults()) {
                List record = new ArrayList();
                record.add(result.getId());
                record.add(simulationResultWrapper.getReservedOsHostResource());
                record.add(simulationResultWrapper.getHostMaxRisk());
                record.add(simulationResultWrapper.getMaxOverprovisioningTime());
                record.add(simulationResultWrapper.getN_runs());
                record.add(simulationResultWrapper.getN_simulation());
                record.add(simulationResultWrapper.getOriginalMachines().size());
                record.add(simulationResultWrapper.getUsedForSimulationMachines().size());
                record.add(result.getIterationTime());
                record.add(simulationResultWrapper.getEuristicMethod());
                record.add(simulationResultWrapper.getEuristicCoeffBuilderMethod());
                record.add(result.getUsedHost().size());
                record.add((float) result.getDataCenterMachinePlacement().getCpu_avg_usage());
                record.add((float) result.getDataCenterMachinePlacement().getMemory_avg_usage());
                record.add((float) result.getDataCenterMachinePlacement().getOverall_avg_usage());
                record.add((float) result.getDataCenterMachinePlacement().getCpu_in_range());
                record.add((float) result.getDataCenterMachinePlacement().getMemory_in_range());
                record.add((float) result.getDataCenterMachinePlacement().getOverall_in_range());

                csvPrinter.printRecord(record);
                csvPrinter.flush();

                //            resultExts.add(new PlacementResultExt(result.getId(),
                //                    simulationResultWrapper.getReservedOsHostResource(),
                //                    simulationResultWrapper.getHostMaxRisk(),
                //                    simulationResultWrapper.getMaxOverprovisioningTime(),
                //                    simulationResultWrapper.getN_runs(),
                //                    simulationResultWrapper.getN_simulation(),
                //                    simulationResultWrapper.getOriginalMachines().size(),
                //                    simulationResultWrapper.getUsedForSimulationMachines().size(),
                //                    result.getIterationTime(),
                //                    simulationResultWrapper.getEuristicMethod(),
                //                    simulationResultWrapper.getEuristicCoeffBuilderMethod(),
                //                    result.getUsedHost().size(),
                //                    (float)result.getDataCenterMachinePlacement().getCpu_avg_usage(),
                //                    (float)result.getDataCenterMachinePlacement().getMemory_avg_usage(),
                //                    (float)result.getDataCenterMachinePlacement().getOverall_avg_usage(),
                //                    (float)result.getDataCenterMachinePlacement().getCpu_in_range(),
                //                    (float)result.getDataCenterMachinePlacement().getMemory_in_range(),
                //                    (float)result.getDataCenterMachinePlacement().getOverall_in_range()));
            }
        }
        csvPrinter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    //            for (PlacementResultExt res : resultExts) {
    //                csvPrinter.printRecords(res);    
    //            }
    //            

}

From source file:org.cricketmsf.in.http.CsvFormatter.java

public String format(List list) {
    StringBuilder sb = new StringBuilder();
    try {/*from   w w w.ja  v  a2 s .c  o m*/
        CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT);
        if (list.size() > 0) {
            printer.printRecord((List) list.get(0));
            for (int i = 1; i < list.size(); i++) {
                printer.printRecord((List) list.get(i));
            }
        }
    } catch (IOException e) {
        sb.append(e.getMessage());
    }
    return sb.toString();
}

From source file:org.cricketmsf.in.http.CsvFormatter.java

public String format(Map data) {
    StringBuilder sb = new StringBuilder();
    try {/*  w  ww .  j  a v a 2 s .c  o  m*/
        CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT);
        printer.printRecord(data.keySet());
        printer.printRecord(data.values());
    } catch (IOException e) {
        sb.append(e.getMessage());
    }
    return sb.toString();
}

From source file:org.easybatch.extensions.apache.common.csv.ApacheCommonCsvRecordMarshaller.java

@Override
public StringRecord processRecord(final GenericRecord record) throws RecordMarshallingException {
    try {/*from  ww  w.  j  a v  a2  s.c  o  m*/
        StringWriter stringWriter = new StringWriter();
        CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
        Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload());
        csvPrinter.printRecord(iterable);
        csvPrinter.flush();
        return new StringRecord(record.getHeader(), stringWriter.toString());
    } catch (Exception e) {
        throw new RecordMarshallingException(e);
    }
}

From source file:org.eclipse.sw360.portal.portlets.admin.UserPortlet.java

public void backUpUsers(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException, SystemException, PortalException {
    List<User> liferayUsers;
    try {//from  w w  w .  j a  v  a 2  s .com
        liferayUsers = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
    } catch (SystemException e) {
        log.error("Could not get user List from liferay", e);
        liferayUsers = Collections.emptyList();
    }

    final ByteArrayOutputStream outB = new ByteArrayOutputStream();
    Writer out = new BufferedWriter(new OutputStreamWriter(outB));

    CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat);

    csvPrinter.printRecord("GivenName", "Lastname", "Email", "Department", "UserGroup", "GID", "isMale",
            "PasswdHash", "wantsMailNotification");
    for (User liferayUser : liferayUsers) {

        String firstName = liferayUser.getFirstName();
        String lastName = liferayUser.getLastName();
        String emailAddress = liferayUser.getEmailAddress();
        List<Organization> organizations = liferayUser.getOrganizations();

        String department = "";

        if (organizations != null && organizations.size() > 0) {
            department = organizations.get(0).getName();
        }

        String gid = liferayUser.getOpenId();
        boolean isMale = liferayUser.isMale();
        String passwordHash = liferayUser.getPassword();
        if (isNullOrEmpty(emailAddress) || isNullOrEmpty(department)) {
            continue;
        }
        org.eclipse.sw360.datahandler.thrift.users.User sw360user = UserCacheHolder
                .getUserFromEmail(emailAddress);
        boolean wantsMailNotification = sw360user.isSetWantsMailNotification() ? sw360user.wantsMailNotification
                : true;
        String userGroup = sw360user.getUserGroup().toString();

        csvPrinter.printRecord(firstName, lastName, emailAddress, department, userGroup, gid, isMale,
                passwordHash, wantsMailNotification);
    }

    csvPrinter.flush();
    csvPrinter.close();

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outB.toByteArray());
    PortletResponseUtil.sendFile(request, response, "Users.csv", byteArrayInputStream, "text/csv");
}

From source file:org.gephi.io.exporter.plugin.ExporterSpreadsheet.java

private void exportData(Graph graph) throws Exception {
    final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(fieldDelimiter);

    try (CSVPrinter csvWriter = new CSVPrinter(writer, format)) {
        boolean isEdgeTable = tableToExport != ExportTable.NODES;
        Table table = isEdgeTable ? graph.getModel().getEdgeTable() : graph.getModel().getNodeTable();

        ElementIterable<? extends Element> rows;

        Object[] edgeLabels = graph.getModel().getEdgeTypeLabels();
        boolean includeEdgeKindColumn = false;
        for (Object edgeLabel : edgeLabels) {
            if (edgeLabel != null && !edgeLabel.toString().isEmpty()) {
                includeEdgeKindColumn = true;
            }/* w  w  w  .  j  a v  a 2s. c o m*/
        }

        TimeFormat timeFormat = graph.getModel().getTimeFormat();
        DateTimeZone timeZone = graph.getModel().getTimeZone();
        List<Column> columns = new ArrayList<>();

        if (columnIdsToExport != null) {
            for (String columnId : columnIdsToExport) {
                Column column = table.getColumn(columnId);
                if (column != null) {
                    columns.add(column);
                }
            }
        } else {
            for (Column column : table) {
                columns.add(column);
            }
        }

        //Write column headers:
        if (isEdgeTable) {
            csvWriter.print("Source");
            csvWriter.print("Target");
            csvWriter.print("Type");
            if (includeEdgeKindColumn) {
                csvWriter.print("Kind");
            }
        }

        for (Column column : columns) {
            //Use the title only if it's the same as the id (case insensitive):
            String columnId = column.getId();
            String columnTitle = column.getTitle();
            String columnHeader = columnId.equalsIgnoreCase(columnTitle) ? columnTitle : columnId;
            csvWriter.print(columnHeader);
        }
        csvWriter.println();

        //Write rows:
        if (isEdgeTable) {
            rows = graph.getEdges();
        } else {
            rows = graph.getNodes();
        }

        for (Element row : rows) {
            if (isEdgeTable) {
                Edge edge = (Edge) row;

                csvWriter.print(edge.getSource().getId());
                csvWriter.print(edge.getTarget().getId());
                csvWriter.print(edge.isDirected() ? "Directed" : "Undirected");
                if (includeEdgeKindColumn) {
                    csvWriter.print(edge.getTypeLabel().toString());
                }
            }

            for (Column column : columns) {
                Object value = row.getAttribute(column);
                String text;

                if (value != null) {
                    if (value instanceof Number) {
                        text = NUMBER_FORMAT.format(value);
                    } else {
                        text = AttributeUtils.print(value, timeFormat, timeZone);
                    }
                } else {
                    text = "";
                }
                csvWriter.print(text);
            }

            csvWriter.println();
        }
    }
}

From source file:org.gitia.jdataanalysis.JDataAnalysis.java

public void save(String[][] data, String[] headers, String folder, String fileName) {
    String NEW_LINE_SEPARATOR = "\n";

    FileWriter fileWriter = null;

    CSVPrinter csvFilePrinter = null;//  w w  w . ja  va2  s  .c  o  m

    //Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
    try {
        //initialize FileWriter object
        File file = new File(folder + "/" + fileName);
        fileWriter = new FileWriter(file);

        //initialize CSVPrinter object 
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        //Create CSV file header
        csvFilePrinter.printRecord(headers);

        //Write a new student object list to the CSV file
        for (int i = 0; i < data.length; i++) {
            //List studentDataRecord = new ArrayList();
            csvFilePrinter.printRecord(data[i]);
        }
        System.out.println("CSV file was created successfully !!!");
        System.out.println(folder + "/" + fileName);

    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            e.printStackTrace();
        }
    }
}

From source file:org.gitia.jdataanalysis.JDataAnalysis.java

/**
 *
 * @param list//from www .j a va  2  s . c om
 * @param folder
 * @param fileName
 */
public void save(List<String> list, String folder, String fileName) {
    String NEW_LINE_SEPARATOR = "\n";

    FileWriter fileWriter = null;

    CSVPrinter csvFilePrinter = null;

    //Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
    try {
        //initialize FileWriter object
        File file = new File(folder + "/" + fileName);
        fileWriter = new FileWriter(file);

        //initialize CSVPrinter object 
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        //Create CSV file header
        //csvFilePrinter.printRecord(headers);
        //Write a new student object list to the CSV file
        for (int i = 0; i < list.size(); i++) {
            //List studentDataRecord = new ArrayList();
            csvFilePrinter.printRecord(list.get(i));
        }
        System.out.println("CSV file was created successfully !!!");
        System.out.println(folder + "/" + fileName);

    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
    } finally {
        try {
            fileWriter.flush();
            fileWriter.close();
            csvFilePrinter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
            e.printStackTrace();
        }
    }
}

From source file:org.jboss.jbossset.JiraReporter.java

public static void main(String[] args) {
    CommandLineParser parser = new CommandLineParser(args);
    try {/*from w  w  w. j  ava 2s .  c o m*/
        parser.parse();
    } catch (ParseException e) {
        System.err.println("Error parsing command line arguments: " + e);
        new HelpFormatter().printHelp(JiraReporter.class.getSimpleName(), parser.getOptions());
        System.exit(-1);
        return;
    }

    Map<String, String> domains = parser.getDomains();
    String queryBody = String.format(QUERY_TEMPLATE, parser.getStartDate(), parser.getEndDate(),
            parser.getIssueOrder());
    String lineBreak = "---------------------------------------------------------------------";
    System.out.println("JiraReporter");
    System.out.println(lineBreak);
    for (String user : parser.getUsernames()) {
        System.out.println("Starting to search for JIRA issues associated with user " + user);
        try (FileWriter fileWriter = new FileWriter(Paths.get("", user + ".csv").toFile());
                CSVPrinter printer = new CSVPrinter(fileWriter, parser.getCSVFormat())) {
            for (Map.Entry<String, String> domain : domains.entrySet()) {
                System.out.println("Searching domain " + domain.getKey() + " at url " + domain.getValue());

                String jqlQuery = String.format(USER_QUERY_TEMPLATE, user) + queryBody;
                JiraClient jira = new JiraClient(domain.getValue());
                Issue.SearchResult sr;
                try {
                    sr = jira.searchIssues(jqlQuery, parser.getIssueLimit());
                } catch (JiraException e) {
                    System.err.println("Exception while searching domain " + domain.getKey() + ": " + e + ": "
                            + e.getCause());
                    continue;
                }

                printer.printRecord(domain.getKey() + " Issues");
                printer.printRecord(IssueProcessor.CSV_HEADERS);
                for (Issue i : sr.issues) {
                    IssueProcessor processor = new IssueProcessor(user, i);
                    printer.printRecord(processor.getPrintableRecord());
                }
                printer.println();
            }
        } catch (IOException e) {
            System.err.println("Error writing to " + user + ".csv: " + e);
            continue;
        }
        System.out.println("All domains searched and results have been output to " + user + ".csv");
        System.out.println(lineBreak);
    }
    System.out.println("Searching Complete");
}

From source file:org.kuali.test.runner.execution.TestExecutionContext.java

private void writePerformanceDataFile(File f) {
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;//w w w  .java 2s .c  o m

    //Create the CSVFormat object with "\n" as a record delimiter
    CSVFormat csvFileFormat = CSVFormat.EXCEL.withRecordSeparator("\n");

    try {
        //initialize FileWriter object
        fileWriter = new FileWriter(f);

        //initialize CSVPrinter object
        csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

        //Create CSV file header
        csvFilePrinter.printRecord(Arrays.asList(PERFORMANCE_DATA_HEADER));

        //Write a new student object list to the CSV file
        for (String[] rec : performanceData) {
            csvFilePrinter.printRecord(Arrays.asList(rec));
        }
    }

    catch (Exception ex) {
        LOG.error(ex.toString(), ex);
    }

    finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
        }

        catch (Exception e) {
        }

        try {
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        }

        catch (Exception e) {
        }
    }
}