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:com.team3637.service.TeamServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Team> data = getTeams();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;/*from   w ww .  jav  a  2s  .co  m*/
    try {
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Team team : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Team.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(team);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.csv.CSVFileReader.java

public int readFile(BufferedReader csvReader, DataTable dataTable, PrintWriter finalOut) throws IOException {

    List<DataVariable> variableList = new ArrayList<>();
    CSVParser parser = new CSVParser(csvReader, inFormat.withHeader());
    Map<String, Integer> headers = parser.getHeaderMap();

    int i = 0;/*w  ww  .ja v a  2  s  .c  o  m*/
    for (String varName : headers.keySet()) {
        if (varName == null || varName.isEmpty()) {
            // TODO:
            // Add a sensible variable name validation algorithm.
            // -- L.A. 4.0 alpha 1
            throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.invalidHeader"));
        }

        DataVariable dv = new DataVariable();
        dv.setName(varName);
        dv.setLabel(varName);
        dv.setInvalidRanges(new ArrayList<>());
        dv.setSummaryStatistics(new ArrayList<>());
        dv.setUnf("UNF:6:NOTCALCULATED");
        dv.setCategories(new ArrayList<>());
        variableList.add(dv);

        dv.setTypeCharacter();
        dv.setIntervalDiscrete();
        dv.setFileOrder(i);
        dv.setDataTable(dataTable);
        i++;
    }

    dataTable.setVarQuantity((long) variableList.size());
    dataTable.setDataVariables(variableList);

    boolean[] isNumericVariable = new boolean[headers.size()];
    boolean[] isIntegerVariable = new boolean[headers.size()];
    boolean[] isTimeVariable = new boolean[headers.size()];
    boolean[] isDateVariable = new boolean[headers.size()];

    for (i = 0; i < headers.size(); i++) {
        // OK, let's assume that every variable is numeric;
        // but we'll go through the file and examine every value; the
        // moment we find a value that's not a legit numeric one, we'll
        // assume that it is in fact a String.
        isNumericVariable[i] = true;
        isIntegerVariable[i] = true;
        isDateVariable[i] = true;
        isTimeVariable[i] = true;
    }

    // First, "learning" pass.
    // (we'll save the incoming stream in another temp file:)
    SimpleDateFormat[] selectedDateTimeFormat = new SimpleDateFormat[headers.size()];
    SimpleDateFormat[] selectedDateFormat = new SimpleDateFormat[headers.size()];

    File firstPassTempFile = File.createTempFile("firstpass-", ".csv");

    try (CSVPrinter csvFilePrinter = new CSVPrinter(
            // TODO allow other parsers of tabular data to use this parser by changin inFormat
            new FileWriter(firstPassTempFile.getAbsolutePath()), inFormat)) {
        //Write  headers
        csvFilePrinter.printRecord(headers.keySet());
        for (CSVRecord record : parser.getRecords()) {
            // Checks if #records = #columns in header
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                isIntegerVariable[i] = isIntegerVariable[i] && varString != null
                        && (varString.isEmpty() || varString.equals("null")
                                || (firstNumCharSet.contains(varString.charAt(0))
                                        && StringUtils.isNumeric(varString.substring(1))));
                if (isNumericVariable[i]) {
                    // If variable might be "numeric" test to see if this value is a parsable number:
                    if (varString != null && !varString.isEmpty()) {

                        boolean isNumeric = false;
                        boolean isInteger = false;

                        if (varString.equalsIgnoreCase("NaN") || varString.equalsIgnoreCase("NA")
                                || varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")
                                || varString.equalsIgnoreCase("-Inf") || varString.equalsIgnoreCase("null")) {
                            continue;
                        } else {
                            try {
                                Double testDoubleValue = new Double(varString);
                                continue;
                            } catch (NumberFormatException ex) {
                                // the token failed to parse as a double
                                // so the column is a string variable.
                            }
                        }
                        isNumericVariable[i] = false;
                    }
                }

                // If this is not a numeric column, see if it is a date collumn
                // by parsing the cell as a date or date-time value:
                if (!isNumericVariable[i]) {

                    Date dateResult = null;

                    if (isTimeVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isTime = false;

                            if (selectedDateTimeFormat[i] != null) {
                                ParsePosition pos = new ParsePosition(0);
                                dateResult = selectedDateTimeFormat[i].parse(varString, pos);

                                if (dateResult != null && pos.getIndex() == varString.length()) {
                                    // OK, successfully parsed a value!
                                    isTime = true;
                                }
                            } else {
                                for (SimpleDateFormat format : TIME_FORMATS) {
                                    ParsePosition pos = new ParsePosition(0);
                                    dateResult = format.parse(varString, pos);
                                    if (dateResult != null && pos.getIndex() == varString.length()) {
                                        // OK, successfully parsed a value!
                                        isTime = true;
                                        selectedDateTimeFormat[i] = format;
                                        break;
                                    }
                                }
                            }
                            if (!isTime) {
                                isTimeVariable[i] = false;
                                // if the token didn't parse as a time value,
                                // we will still try to parse it as a date, below.
                                // unless this column is NOT a date.
                            } else {
                                // And if it is a time value, we are going to assume it's
                                // NOT a date.
                                isDateVariable[i] = false;
                            }
                        }
                    }

                    if (isDateVariable[i]) {
                        if (varString != null && !varString.isEmpty()) {
                            boolean isDate = false;

                            // TODO:
                            // Strictly speaking, we should be doing the same thing
                            // here as with the time formats above; select the
                            // first one that works, then insist that all the
                            // other values in this column match it... but we
                            // only have one, as of now, so it should be ok.
                            // -- L.A. 4.0 beta
                            for (SimpleDateFormat format : DATE_FORMATS) {
                                // Strict parsing - it will throw an
                                // exception if it doesn't parse!
                                format.setLenient(false);
                                try {
                                    format.parse(varString);
                                    isDate = true;
                                    selectedDateFormat[i] = format;
                                    break;
                                } catch (ParseException ex) {
                                    //Do nothing
                                }
                            }
                            isDateVariable[i] = isDate;
                        }
                    }
                }
            }

            csvFilePrinter.printRecord(record);
        }
    }
    dataTable.setCaseQuantity(parser.getRecordNumber());
    parser.close();
    csvReader.close();

    // Re-type the variables that we've determined are numerics:
    for (i = 0; i < headers.size(); i++) {
        if (isNumericVariable[i]) {
            dataTable.getDataVariables().get(i).setTypeNumeric();

            if (isIntegerVariable[i]) {
                dataTable.getDataVariables().get(i).setIntervalDiscrete();
            } else {
                dataTable.getDataVariables().get(i).setIntervalContinuous();
            }
        } else if (isDateVariable[i] && selectedDateFormat[i] != null) {
            // Dates are still Strings, i.e., they are "character" and "discrete";
            // But we add special format values for them:
            dataTable.getDataVariables().get(i).setFormat(DATE_FORMATS[0].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("date");
        } else if (isTimeVariable[i] && selectedDateTimeFormat[i] != null) {
            // Same for time values:
            dataTable.getDataVariables().get(i).setFormat(selectedDateTimeFormat[i].toPattern());
            dataTable.getDataVariables().get(i).setFormatCategory("time");
        }
    }
    // Second, final pass.
    try (BufferedReader secondPassReader = new BufferedReader(new FileReader(firstPassTempFile))) {
        parser = new CSVParser(secondPassReader, inFormat.withHeader());
        String[] caseRow = new String[headers.size()];

        for (CSVRecord record : parser) {
            if (!record.isConsistent()) {
                List<String> args = Arrays.asList(new String[] { "" + (parser.getCurrentLineNumber() - 1),
                        "" + headers.size(), "" + record.size() });
                throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.recordMismatch", args));
            }

            for (i = 0; i < headers.size(); i++) {
                String varString = record.get(i);
                if (isNumericVariable[i]) {
                    if (varString == null || varString.isEmpty() || varString.equalsIgnoreCase("NA")) {
                        // Missing value - represented as an empty string in
                        // the final tab file
                        caseRow[i] = "";
                    } else if (varString.equalsIgnoreCase("NaN")) {
                        // "Not a Number" special value:
                        caseRow[i] = "NaN";
                    } else if (varString.equalsIgnoreCase("Inf") || varString.equalsIgnoreCase("+Inf")) {
                        // Positive infinity:
                        caseRow[i] = "Inf";
                    } else if (varString.equalsIgnoreCase("-Inf")) {
                        // Negative infinity:
                        caseRow[i] = "-Inf";
                    } else if (varString.equalsIgnoreCase("null")) {
                        // By request from Gus - "NULL" is recognized as a
                        // numeric zero:
                        caseRow[i] = isIntegerVariable[i] ? "0" : "0.0";
                    } else {
                        /* No re-formatting is done on any other numeric values.
                         * We'll save them as they were, for archival purposes.
                         * The alternative solution - formatting in sci. notation
                         * is commented-out below.
                         */
                        caseRow[i] = varString;
                        /*
                         if (isIntegerVariable[i]) {
                        try {
                            Integer testIntegerValue = new Integer(varString);
                            caseRow[i] = testIntegerValue.toString();
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as an integer in the first pass! (?)");
                        }
                        } else {
                        try {
                            Double testDoubleValue = new Double(varString);
                            if (testDoubleValue.equals(0.0)) {
                                caseRow[i] = "0.0";
                            } else {
                                                                    // One possible implementation:
                                //
                                // Round our fractional values to 15 digits
                                // (minimum number of digits of precision guaranteed by
                                // type Double) and format the resulting representations
                                // in a IEEE 754-like "scientific notation" - for ex.,
                                // 753.24 will be encoded as 7.5324e2
                                BigDecimal testBigDecimal = new BigDecimal(varString, doubleMathContext);
                                caseRow[i] = String.format(FORMAT_IEEE754, testBigDecimal);
                                
                                // Strip meaningless zeros and extra + signs:
                                caseRow[i] = caseRow[i].replaceFirst("00*e", "e");
                                caseRow[i] = caseRow[i].replaceFirst("\\.e", ".0e");
                                caseRow[i] = caseRow[i].replaceFirst("e\\+00", "");
                                caseRow[i] = caseRow[i].replaceFirst("^\\+", "");
                            }
                        } catch (NumberFormatException ex) {
                            throw new IOException("Failed to parse a value recognized as numeric in the first pass! (?)");
                        }
                        }
                         */
                    }
                } else if (isTimeVariable[i] || isDateVariable[i]) {
                    // Time and Dates are stored NOT quoted (don't ask).
                    if (varString != null) {
                        // Dealing with quotes:
                        // remove the leading and trailing quotes, if present:
                        varString = varString.replaceFirst("^\"*", "");
                        varString = varString.replaceFirst("\"*$", "");
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "";
                    }
                } else {
                    // Treat as a String:
                    // Strings are stored in tab files quoted;
                    // Missing values are stored as an empty string
                    // between two tabs (or one tab and the new line);
                    // Empty strings stored as "" (quoted empty string).
                    // For the purposes  of this CSV ingest reader, we are going
                    // to assume that all the empty strings in the file are
                    // indeed empty strings, and NOT missing values:
                    if (varString != null) {
                        // escape the quotes, newlines, and tabs:
                        varString = varString.replace("\"", "\\\"");
                        varString = varString.replace("\n", "\\n");
                        varString = varString.replace("\t", "\\t");
                        // final pair of quotes:
                        varString = "\"" + varString + "\"";
                        caseRow[i] = varString;
                    } else {
                        caseRow[i] = "\"\"";
                    }
                }
            }
            finalOut.println(StringUtils.join(caseRow, "\t"));
        }
    }
    long linecount = parser.getRecordNumber();
    finalOut.close();
    parser.close();
    dbglog.fine("Tmp File: " + firstPassTempFile);
    // Firstpass file is deleted to prevent tmp from filling up.
    firstPassTempFile.delete();
    if (dataTable.getCaseQuantity().intValue() != linecount) {
        List<String> args = Arrays
                .asList(new String[] { "" + dataTable.getCaseQuantity().intValue(), "" + linecount });
        throw new IOException(BundleUtil.getStringFromBundle("ingest.csv.line_mismatch", args));
    }
    return (int) linecount;
}

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

/**
 * Generates the spreadsheet, based on the properties in the header
 *  and a callback for the body./*  ww  w  . j ava 2  s . c om*/
 */
public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status,
        Map<String, Object> model) throws IOException {
    Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)");

    // Build up the details of the header
    List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req);
    String[] headings = new String[propertyDetails.size()];
    String[] descriptions = new String[propertyDetails.size()];
    boolean[] required = new boolean[propertyDetails.size()];
    for (int i = 0; i < headings.length; i++) {
        Pair<QName, Boolean> property = propertyDetails.get(i);
        if (property == null || property.getFirst() == null) {
            headings[i] = "";
            required[i] = false;
        } else {
            QName column = property.getFirst();
            required[i] = property.getSecond();

            // Ask the dictionary service nicely for the details
            PropertyDefinition pd = dictionaryService.getProperty(column);
            if (pd != null && pd.getTitle(dictionaryService) != null) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle(dictionaryService);
                descriptions[i] = pd.getDescription(dictionaryService);
            } else {
                // Nothing friendly found, try to munge the raw qname into
                //  something we can show to a user...
                String raw = column.getLocalName();
                raw = raw.substring(0, 1).toUpperCase() + raw.substring(1);

                Matcher m = qnameMunger.matcher(raw);
                if (m.matches()) {
                    headings[i] = m.group(1) + " " + m.group(2);
                } else {
                    headings[i] = raw;
                }
            }
        }
    }

    // Build a list of just the properties
    List<QName> properties = new ArrayList<QName>(propertyDetails.size());
    for (Pair<QName, Boolean> p : propertyDetails) {
        QName qn = null;
        if (p != null) {
            qn = p.getFirst();
        }
        properties.add(qn);
    }

    // Output
    if ("csv".equals(format)) {
        StringWriter sw = new StringWriter();
        CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY);
        csv.println(headings);

        populateBody(resource, csv, properties);

        model.put(MODEL_CSV, sw.toString());
    } else if ("odf".equals(format) || "ods".equals(format)) {
        try {
            SpreadsheetDocument odf = SpreadsheetDocument.newSpreadsheetDocument();

            // Add the header row
            Table sheet = odf.appendSheet("Export");
            org.odftoolkit.simple.table.Row hr = sheet.appendRow();

            // TODO

            // Have the contents populated
            // TODO

            // Save it for the template
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            odf.save(baos);
            model.put(MODEL_ODF, baos.toByteArray());
        } catch (Exception e) {
            throw new WebScriptException("Error creating ODF file", e);
        }
    } else {
        Workbook wb;
        if ("xlsx".equals(format)) {
            wb = new XSSFWorkbook();
            // TODO Properties
        } else {
            wb = new HSSFWorkbook();
            // TODO Properties
        }

        // Add our header row
        Sheet sheet = wb.createSheet("Export");
        Row hr = sheet.createRow(0);
        sheet.createFreezePane(0, 1);

        Font fb = wb.createFont();
        fb.setBoldweight(Font.BOLDWEIGHT_BOLD);
        Font fi = wb.createFont();
        fi.setBoldweight(Font.BOLDWEIGHT_BOLD);
        fi.setItalic(true);

        CellStyle csReq = wb.createCellStyle();
        csReq.setFont(fb);
        CellStyle csOpt = wb.createCellStyle();
        csOpt.setFont(fi);

        // Populate the header
        Drawing draw = null;
        for (int i = 0; i < headings.length; i++) {
            Cell c = hr.createCell(i);
            c.setCellValue(headings[i]);

            if (required[i]) {
                c.setCellStyle(csReq);
            } else {
                c.setCellStyle(csOpt);
            }

            if (headings[i].length() == 0) {
                sheet.setColumnWidth(i, 3 * 250);
            } else {
                sheet.setColumnWidth(i, 18 * 250);
            }

            if (descriptions[i] != null && descriptions[i].length() > 0) {
                // Add a description for it too
                if (draw == null) {
                    draw = sheet.createDrawingPatriarch();
                }
                ClientAnchor ca = wb.getCreationHelper().createClientAnchor();
                ca.setCol1(c.getColumnIndex());
                ca.setCol2(c.getColumnIndex() + 1);
                ca.setRow1(hr.getRowNum());
                ca.setRow2(hr.getRowNum() + 2);

                Comment cmt = draw.createCellComment(ca);
                cmt.setAuthor("");
                cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i]));
                cmt.setVisible(false);
                c.setCellComment(cmt);
            }
        }

        // Have the contents populated
        populateBody(resource, wb, sheet, properties);

        // Save it for the template
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        model.put(MODEL_EXCEL, baos.toByteArray());
    }
}

From source file:de.fme.alfresco.repo.web.scripts.DeclarativeSpreadsheetWebScript.java

/**
 * Generates the spreadsheet, based on the properties in the header
 *  and a callback for the body./*from   ww w .  ja v  a  2s .c o  m*/
 */
public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status,
        Map<String, Object> model) throws IOException {
    Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)");

    // Build up the details of the header
    List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req);
    String[] headings = new String[propertyDetails.size()];
    String[] descriptions = new String[propertyDetails.size()];
    boolean[] required = new boolean[propertyDetails.size()];
    for (int i = 0; i < headings.length; i++) {
        Pair<QName, Boolean> property = propertyDetails.get(i);
        if (property == null || property.getFirst() == null) {
            headings[i] = "";
            required[i] = false;
        } else {
            QName column = property.getFirst();
            required[i] = property.getSecond();

            // Ask the dictionary service nicely for the details
            PropertyDefinition pd = dictionaryService.getProperty(column);
            if ((pd != null) && (pd.getTitle(messageLookup) != null)) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle(messageLookup);
                descriptions[i] = pd.getDescription(messageLookup);
            } else {
                // Nothing friendly found, try to munge the raw qname into
                //  something we can show to a user...
                String raw = column.getLocalName();
                raw = raw.substring(0, 1).toUpperCase() + raw.substring(1);

                Matcher m = qnameMunger.matcher(raw);
                if (m.matches()) {
                    headings[i] = m.group(1) + " " + m.group(2);
                } else {
                    headings[i] = raw;
                }
            }
        }
    }

    // Build a list of just the properties
    List<QName> properties = new ArrayList<QName>(propertyDetails.size());
    for (Pair<QName, Boolean> p : propertyDetails) {
        QName qn = null;
        if (p != null) {
            qn = p.getFirst();
        }
        properties.add(qn);
    }

    // Output
    if ("csv".equals(format)) {
        StringWriter sw = new StringWriter();
        CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY);
        csv.println(headings);

        populateBody(resource, csv, properties);

        model.put(MODEL_CSV, sw.toString());
    } else {
        Workbook wb;
        if ("xlsx".equals(format)) {
            wb = new XSSFWorkbook();
            // TODO Properties
        } else {
            wb = new HSSFWorkbook();
            // TODO Properties
        }

        // Add our header row
        Sheet sheet = wb.createSheet("Export");
        Row hr = sheet.createRow(0);
        try {
            sheet.createFreezePane(0, 1);
        } catch (IndexOutOfBoundsException e) {
            //https://issues.apache.org/bugzilla/show_bug.cgi?id=51431 & http://stackoverflow.com/questions/6469693/apache-poi-clearing-freeze-split-panes
        }
        Font fb = wb.createFont();
        fb.setBoldweight(Font.BOLDWEIGHT_BOLD);
        Font fi = wb.createFont();
        fi.setBoldweight(Font.BOLDWEIGHT_BOLD);
        fi.setItalic(true);

        CellStyle csReq = wb.createCellStyle();
        csReq.setFont(fb);
        CellStyle csOpt = wb.createCellStyle();
        csOpt.setFont(fi);

        // Populate the header
        Drawing draw = null;
        for (int i = 0; i < headings.length; i++) {
            Cell c = hr.createCell(i);
            c.setCellValue(headings[i]);

            if (required[i]) {
                c.setCellStyle(csReq);
            } else {
                c.setCellStyle(csOpt);
            }

            if (headings[i].length() == 0) {
                sheet.setColumnWidth(i, 3 * 250);
            } else {
                sheet.setColumnWidth(i, 18 * 250);
            }

            if (descriptions[i] != null && descriptions[i].length() > 0) {
                // Add a description for it too
                if (draw == null) {
                    draw = sheet.createDrawingPatriarch();
                }
                ClientAnchor ca = wb.getCreationHelper().createClientAnchor();
                ca.setCol1(c.getColumnIndex());
                ca.setCol2(c.getColumnIndex() + 1);
                ca.setRow1(hr.getRowNum());
                ca.setRow2(hr.getRowNum() + 2);

                Comment cmt = draw.createCellComment(ca);
                cmt.setAuthor("");
                cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i]));
                cmt.setVisible(false);
                c.setCellComment(cmt);
            }
        }

        // Have the contents populated
        populateBody(resource, wb, sheet, properties);

        // Save it for the template
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        model.put(MODEL_EXCEL, baos.toByteArray());
    }
}

From source file:gov.usda.DataCatalogClient.Catalog.java

/**
 * Outputs a Catalog into tab delimited format.
 * <p>//from w ww .java 2  s .c o  m
 * Begins the process by listing out the header and calling all datasets to create
 * tab delimitted lines.
 * @param filePath String The output file for the catalog tab delimitted file.
 * @param dataListCode DataListingCode This will either print the Public Data Listing or the Enterprise 
 * Data Inventory
 */
public void toCSV(String filePath, DataListingCode dataListingCode) throws IOException {
    Collections.sort(dataSetList);
    if (filePath == null) {
        throw (new NullPointerException("filepath cannot be null"));
    }
    PrintWriter out = null;
    CSVPrinter csvPrinter = null;
    CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    List<String> catalogString = new ArrayList<String>();
    catalogString.add("Agency Name");
    catalogString.add("Title");
    catalogString.add("Description");
    catalogString.add("MediaType");
    catalogString.add("Download URL");
    catalogString.add("Frequency");
    catalogString.add("Bureau Code");
    catalogString.add("Contact Email");
    catalogString.add("Contact Name");
    catalogString.add("Landing Page");
    catalogString.add("Program Code");
    catalogString.add("Publisher");
    catalogString.add("Public Access Level");
    catalogString.add("Access Level Comment");
    catalogString.add("Tags");
    catalogString.add("Last Update");
    catalogString.add("Release Date");
    catalogString.add("Unique Identifier");
    catalogString.add("Data Dictionary");
    catalogString.add("License");
    catalogString.add("Spatial");
    catalogString.add("Temporal");
    catalogString.add("System of Records");
    catalogString.add("Data Quality");
    catalogString.add("Language");
    catalogString.add("Theme");
    catalogString.add("Reference");
    catalogString.add("CKAN Create Date");
    catalogString.add("CKAN Modified Date");
    catalogString.add("CKAN Revision Timestamp");
    catalogString.add("Is Part Of");

    try {
        out = new PrintWriter(filePath);
        csvPrinter = new CSVPrinter(out, csvFormat);
        csvPrinter.printRecord(catalogString);
        for (Dataset ds : dataSetList) {
            if (dataListingCode.equals(DataListingCode.ENTERPRISE_DATA_INVENTORY)) {
                csvPrinter.printRecord(ds.datasetToListString());
            } else if (dataListingCode.equals(DataListingCode.PUBLIC_DATA_LISTING)) {
                if (ds.getAccessLevel().equals(Dataset.AccessLevel.PUBLIC.toString())
                        || ds.getAccessLevel().equals(Dataset.AccessLevel.RESTRICTED)) {
                    csvPrinter.printRecord(ds.datasetToListString());
                }
            }
        }
    } catch (IOException e) {
        throw (e);
    } finally {
        out.close();
        csvPrinter.close();
    }
}

From source file:com.team3637.service.MatchServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Match> data = getMatches();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;//w ww  .j  av a 2  s . c  om
    try {
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Match match : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Match.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(match);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.itemanalysis.jmetrik.file.JmetrikFileImporter.java

private void convertFile() {
    CSVParser parser = null;/*from  w  w w.  j  a v a2s  . c o  m*/
    Reader reader = null;
    CSVPrinter printer = null;
    Writer writer = null;

    try {
        if (outputFile.exists()) {
            if (!overwrite) {
                theException = new IOException("File already exists and overwrite==false");
                return;
            }
        } else {
            outputFile.createNewFile();
        }

        //For debugging
        //            System.out.println("CREATED: " + outputFile.getAbsolutePath());

        //Writer header to file
        writer = new OutputStreamWriter(new FileOutputStream(outputFile));
        printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#'));

        printer.printComment("VERSION");
        printer.printRecord(new String[] { "jmetrik1" });
        printer.printComment("METADATA");
        printer.printRecord(new String[] { Integer.valueOf(nrow).toString() });
        printer.printComment("ATTRIBUTES");
        for (VariableName v : variableAttributeMap.keySet()) {
            printer.printRecord(variableAttributeMap.get(v).getAttributeArray());
        }
        printer.printComment("DATA");

        //Write data to file
        reader = new InputStreamReader(new BOMInputStream(new FileInputStream(dataFile)), "UTF-8");
        parser = new CSVParser(reader, dataFileFormat);

        if (hasHeader) {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames).withSkipHeaderRecord(true));
        } else {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames));
        }

        Iterator<CSVRecord> iter = parser.iterator();
        CSVRecord csvRecord = null;
        VariableAttributes variableAttributes = null;
        DataType dataType = null;
        String temp = "";

        while (iter.hasNext()) {
            csvRecord = iter.next();

            for (VariableName v : variableAttributeMap.keySet()) {
                temp = csvRecord.get(v.toString());
                variableAttributes = variableAttributeMap.get(v);
                dataType = variableAttributes.getDataType();
                if (!variableAttributes.isMissing(temp)) {
                    if (DataType.INTEGER == dataType) {
                        printer.print(Double.valueOf(Double.parseDouble(temp)).intValue());
                    } else if (DataType.DOUBLE == dataType) {
                        printer.print(Double.parseDouble(temp));
                    } else {
                        printer.print(temp);
                    }
                } else {
                    printer.print(temp);
                }

            }
            printer.println();
        }

    } catch (IOException ex) {
        theException = ex;
    } finally {
        try {
            if (parser != null)
                parser.close();
            if (reader != null)
                reader.close();
            if (printer != null)
                printer.close();
            if (writer != null)
                writer.close();
        } catch (IOException ex) {
            theException = ex;
            logger.fatal(ex);
        }
    }
}

From source file:com.siemens.sw360.portal.portlets.admin.UserPortlet.java

public void backUpUsers(ResourceRequest request, ResourceResponse response)
        throws PortletException, IOException, SystemException, PortalException {
    List<User> liferayUsers;
    try {//from   w ww  .  ja va2 s  . c o  m
        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");
    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 userGroup = "";

        List<Role> roles = liferayUser.getRoles();
        List<String> roleNames = new ArrayList<>();

        for (Role role : roles) {
            roleNames.add(role.getName());
        }

        for (UserGroup group : UserGroup.values()) {
            String roleConstantFromUserGroup = getRoleConstantFromUserGroup(group);
            if (roleNames.contains(roleConstantFromUserGroup)) {
                userGroup = group.toString();
                break;
            }
        }

        String gid = liferayUser.getOpenId();
        boolean isMale = liferayUser.isMale();
        String passwordHash = liferayUser.getPassword();
        if (isNullOrEmpty(emailAddress) || isNullOrEmpty(department))
            continue;
        csvPrinter.printRecord(firstName, lastName, emailAddress, department, userGroup, gid, isMale,
                passwordHash);
    }

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

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

From source file:com.mycompany.twitterapp.TwitterApp.java

public void saveToFile(long id, String tweet, String user, Orientation orientation) {
    OutputStreamWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;// w  ww.j  a v  a  2 s  . c  o m
    CSVFormat csvFileFormat = CSVFormat.DEFAULT;

    if (tweet != null) {
        try {
            fileWriter = new OutputStreamWriter(new FileOutputStream(tweetFileName, true), "UTF-8");

            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            csvFilePrinter.printRecord(id, orientation.name().toLowerCase(), tweet);

        } catch (IOException ex) {
            Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
                csvFilePrinter.close();
            } catch (IOException e) {
                System.out.println("Error while flushing/closing fileWriter/csvPrinter !!!");
                e.printStackTrace();
            }

        }
    } else {
        try {
            fileWriter = new OutputStreamWriter(new FileOutputStream(userFileName, true), "UTF-8");
            csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
            csvFilePrinter.printRecord(id, user, orientation.name().toLowerCase());

        } catch (IOException ex) {
            Logger.getLogger(TwitterApp.class.getName()).log(Level.SEVERE, null, ex);
        } 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:com.blackducksoftware.integration.hubdiff.HubDiff.java

public String writeDiffAsCSV(File file) throws IOException {
    if (!file.exists()) {
        file.createNewFile();//w w w .  ja v  a2 s.co  m
    }

    CSVPrinter printer = new CSVPrinter(new PrintStream(file), CSVFormat.EXCEL);

    printer.printRecord("HubVersions", swaggerDoc1.getVersion(), " -> ", swaggerDoc2.getVersion());
    printer.printRecord("Operation", "Expected", "Actual", "Field");

    // Log all additions to the API
    for (FieldComparisonFailure added : results.getFieldUnexpected()) {
        printer.printRecord("ADDED", added.getExpected(), added.getActual(), added.getField());
    }
    // Log all changes made to the API
    for (FieldComparisonFailure changed : results.getFieldFailures()) {
        printer.printRecord("CHANGED", changed.getExpected(), changed.getActual(), changed.getField());
    }
    // Log all deletions made to the API
    for (FieldComparisonFailure removed : results.getFieldMissing()) {
        printer.printRecord("REMOVED", removed.getExpected(), removed.getActual(), removed.getField());
    }

    printer.close();
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}