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

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

Introduction

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

Prototype

@Override
    public void close() throws IOException 

Source Link

Usage

From source file:com.chargebee.CSV.RemovingDuplicateEntries.java

public static void main(String[] args) throws IOException, Exception {
    String source = System.getProperty("user.home") + "/input.csv";
    String output = System.getProperty("user.home") + "/output.csv";

    RemovingDuplicateEntries rde = new RemovingDuplicateEntries();

    CSVParser parser = MethodBank.parserInitializer(source);
    CSVPrinter printer = MethodBank.printerInitializer(output);

    rde.remove(parser, printer);/*  w  ww .j a v  a 2  s  .co m*/
    parser.close();
    printer.close();

}

From source file:com.chargebee.Application.DateFormat.java

public static void main(String[] args) throws IOException, Exception {
    Scanner sc = new Scanner(System.in);
    System.out.println("Input CSV File: ");
    String source = sc.nextLine();

    System.out.println("Input JSON File: ");
    String requirements = sc.nextLine();

    System.out.println("Output CSV File: ");
    String output = sc.nextLine();

    DateFormat df = new DateFormat();
    JSONObject jobj = MethodBank.readJsonObjectData(requirements);
    CSVParser parser = MethodBank.parserInitializer(source);
    CSVPrinter printer = MethodBank.printerInitializer(output);

    df.formatter(parser, printer, jobj);
    parser.close();//from   www.  ja  v  a  2s .c  o  m
    printer.close();

}

From source file:com.chargebee.Application.Amountediting.java

public static void main(String[] args) throws IOException, Exception {
    Scanner sc = new Scanner(System.in);
    System.out.println("Input CSV File: ");
    String source = sc.nextLine();

    System.out.println("Input JSON File: ");
    String requirements = sc.nextLine();

    System.out.println("Output CSV File: ");
    String output = sc.nextLine();

    Amountediting ae = new Amountediting();
    JSONObject jobj = MethodBank.readJsonObjectData(requirements);
    CSVParser parser = MethodBank.parserInitializer(source);
    CSVPrinter printer = MethodBank.printerInitializer(output);

    ae.formatter(parser, printer, jobj);
    parser.close();/*from  ww  w .  j  a  v a2 s.  c  om*/
    printer.close();

}

From source file:com.chargebee.Application.MappingHeaders.java

public static void main(String[] args) throws Exception {
    String source1 = System.getProperty("user.home") + "/Output-3.csv"; // Source CSV file containing the customer details 
    String source2 = System.getProperty("user.home") + "/header.json";//Json file containing the customer id and token
    String output = System.getProperty("user.home") + "/Output-4.csv";// The destination CSV file.
    //        Scanner sc = new Scanner(System.in);
    //        System.out.println("Input CSV File: ");
    //        String source1 = sc.nextLine();
    ////from   w ww. j  ava  2 s.  c  om
    //        System.out.println("config File: ");
    //        String source2 = sc.nextLine();
    //
    //        System.out.println("Output CSV File: ");
    //        String output = sc.nextLine();
    //        

    MappingHeaders objHm = new MappingHeaders();
    JSONObject jobj = objHm.readJsonData(source2);
    CSVPrinter printer = new CSVPrinter(new FileWriter(output),
            CSVFormat.EXCEL.withRecordSeparator("\n").withDelimiter(','));
    CSVParser parser = new CSVParser(new FileReader(source1), CSVFormat.EXCEL.withHeader());
    objHm.extractJsonData(jobj, printer, parser);
    parser.close();
    printer.close();

}

From source file:com.act.lcms.db.analysis.StandardIonAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from   w  w  w  .j  a  v a2 s. com
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);
        StandardIonAnalysis analysis = new StandardIonAnalysis();
        HashMap<Integer, Plate> plateCache = new HashMap<>();

        String plateBarcode = cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE);
        String inputChemicals = cl.getOptionValue(OPTION_STANDARD_CHEMICAL);
        String medium = cl.getOptionValue(OPTION_MEDIUM);

        // If standard chemical is specified, do standard LCMS ion selection analysis
        if (inputChemicals != null && !inputChemicals.equals("")) {
            String[] chemicals;
            if (!inputChemicals.contains(",")) {
                chemicals = new String[1];
                chemicals[0] = inputChemicals;
            } else {
                chemicals = inputChemicals.split(",");
            }

            String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + CSV_FORMAT;
            String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);
            String[] headerStrings = { "Molecule", "Plate Bar Code", "LCMS Detection Results" };
            CSVPrinter printer = new CSVPrinter(new FileWriter(outAnalysis),
                    CSVFormat.DEFAULT.withHeader(headerStrings));

            for (String inputChemical : chemicals) {
                List<StandardWell> standardWells;

                Plate queryPlate = Plate.getPlateByBarcode(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                if (plateBarcode != null && medium != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlateAndMedium(db,
                            inputChemical, queryPlate.getId(), medium);
                } else if (plateBarcode != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db, inputChemical,
                            queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, inputChemical);
                }

                if (standardWells.size() == 0) {
                    throw new RuntimeException("Found no LCMS wells for " + inputChemical);
                }

                // Sort in descending order of media where MeOH and Water related media are promoted to the top and
                // anything derived from yeast media are demoted.
                Collections.sort(standardWells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                                && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                });

                Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                        .getBestMetlinIonsForChemical(inputChemical, lcmsDir, db, standardWells,
                                plottingDirectory);

                if (wellToIonRanking.size() != standardWells.size()
                        && !cl.hasOption(OPTION_OVERRIDE_NO_SCAN_FILE_FOUND)) {
                    throw new Exception("Could not find a scan file associated with one of the standard wells");
                }

                for (StandardWell well : wellToIonRanking.keySet()) {
                    LinkedHashMap<String, XZ> snrResults = wellToIonRanking.get(well).getAnalysisResults();

                    String snrRankingResults = "";
                    int numResultsToShow = 0;

                    Plate plateForWellToAnalyze = Plate.getPlateById(db, well.getPlateId());

                    for (Map.Entry<String, XZ> ionToSnrAndTime : snrResults.entrySet()) {
                        if (numResultsToShow > 3) {
                            break;
                        }

                        String ion = ionToSnrAndTime.getKey();
                        XZ snrAndTime = ionToSnrAndTime.getValue();

                        snrRankingResults += String.format(ion + " (%.2f SNR at %.2fs); ",
                                snrAndTime.getIntensity(), snrAndTime.getTime());
                        numResultsToShow++;
                    }

                    String[] resultSet = { inputChemical,
                            plateForWellToAnalyze.getBarcode() + " " + well.getCoordinatesString() + " "
                                    + well.getMedia() + " " + well.getConcentration(),
                            snrRankingResults };

                    printer.printRecord(resultSet);
                }
            }

            try {
                printer.flush();
                printer.close();
            } catch (IOException e) {
                System.err.println("Error while flushing/closing csv writer.");
                e.printStackTrace();
            }
        } else {
            // Get the set of chemicals that includes the construct and all it's intermediates
            Pair<ConstructEntry, List<ChemicalAssociatedWithPathway>> constructAndPathwayChems = analysis
                    .getChemicalsForConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
            System.out.format("Construct: %s\n", constructAndPathwayChems.getLeft().getCompositionId());

            for (ChemicalAssociatedWithPathway pathwayChem : constructAndPathwayChems.getRight()) {
                System.out.format("  Pathway chem %s\n", pathwayChem.getChemical());

                // Get all the standard wells for the pathway chemicals. These wells contain only the
                // the chemical added with controlled solutions (ie no organism or other chemicals in the
                // solution)

                List<StandardWell> standardWells;

                if (plateBarcode != null) {
                    Plate queryPlate = Plate.getPlateByBarcode(db,
                            cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db,
                            pathwayChem.getChemical(), queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, pathwayChem.getChemical());
                }

                for (StandardWell wellToAnalyze : standardWells) {
                    List<StandardWell> negativeControls = analysis.getViableNegativeControlsForStandardWell(db,
                            wellToAnalyze);
                    Map<StandardWell, List<ScanFile>> allViableScanFiles = analysis
                            .getViableScanFilesForStandardWells(db, wellToAnalyze, negativeControls);

                    List<String> primaryStandardScanFileNames = new ArrayList<>();
                    for (ScanFile scanFile : allViableScanFiles.get(wellToAnalyze)) {
                        primaryStandardScanFileNames.add(scanFile.getFilename());
                    }
                    Plate plate = plateCache.get(wellToAnalyze.getPlateId());
                    if (plate == null) {
                        plate = Plate.getPlateById(db, wellToAnalyze.getPlateId());
                        plateCache.put(plate.getId(), plate);
                    }

                    System.out.format("    Standard well: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                            wellToAnalyze.getCoordinatesString(), wellToAnalyze.getChemical(),
                            wellToAnalyze.getMedia() == null ? ""
                                    : String.format(" in %s", wellToAnalyze.getMedia()),
                            wellToAnalyze.getConcentration() == null ? ""
                                    : String.format(" @ %s", wellToAnalyze.getConcentration()));
                    System.out.format("      Scan files: %s\n",
                            StringUtils.join(primaryStandardScanFileNames, ", "));

                    for (StandardWell negCtrlWell : negativeControls) {
                        plate = plateCache.get(negCtrlWell.getPlateId());
                        if (plate == null) {
                            plate = Plate.getPlateById(db, negCtrlWell.getPlateId());
                            plateCache.put(plate.getId(), plate);
                        }
                        List<String> negativeControlScanFileNames = new ArrayList<>();
                        for (ScanFile scanFile : allViableScanFiles.get(negCtrlWell)) {
                            negativeControlScanFileNames.add(scanFile.getFilename());
                        }

                        System.out.format("      Viable negative: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                                negCtrlWell.getCoordinatesString(), negCtrlWell.getChemical(),
                                negCtrlWell.getMedia() == null ? ""
                                        : String.format(" in %s", negCtrlWell.getMedia()),
                                negCtrlWell.getConcentration() == null ? ""
                                        : String.format(" @ %s", negCtrlWell.getConcentration()));
                        System.out.format("        Scan files: %s\n",
                                StringUtils.join(negativeControlScanFileNames, ", "));
                        // TODO: do something useful with the standard wells and their scan files, and then stop all the printing.
                    }
                }
            }
        }
    }
}

From source file:com.streamsets.pipeline.lib.util.CsvUtil.java

public static String csvRecordToString(Record r, CSVFormat csvFormat) throws IOException {
    StringWriter stringWriter = new StringWriter();
    CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
    csvPrinter.printRecord(CsvUtil.fieldToCsv(r.get()));
    csvPrinter.flush();//from w  ww.jav a2s . c o m
    csvPrinter.close();
    return stringWriter.toString();
}

From source file:com.siemens.sw360.exporter.CSVExport.java

@NotNull
private static ByteArrayOutputStream getCSVOutputStream(Iterable<String> csvHeaderIterable,
        Iterable<Iterable<String>> inputIterable) throws IOException {
    final ByteArrayOutputStream outB = new ByteArrayOutputStream();
    try (Writer out = new BufferedWriter(new OutputStreamWriter(outB));) {
        CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat);
        csvPrinter.printRecord(csvHeaderIterable);
        csvPrinter.printRecords(inputIterable);
        csvPrinter.flush();/* w w  w. j av  a  2  s  . c o  m*/
        csvPrinter.close();
    } catch (Exception e) {
        outB.close();
        throw e;
    }

    return outB;

}

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.significance.SignificanceMain.java

/**
 * Prints table to output string as CSV//from ww  w  . j  a  v a  2s .  com
 *
 * @param out   output
 * @param <T>   value type
 * @param table table
 * @throws IOException
 */
public static <T> String tableToCsv(Table<String, String, Boolean> table) throws IOException {
    StringWriter sw = new StringWriter();
    CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);

    List<String> firstRow = new ArrayList<>();
    firstRow.add(" ");
    firstRow.addAll(table.columnKeySet());
    printer.printRecord(firstRow);

    for (String rowKey : table.rowKeySet()) {
        printer.print(rowKey);
        for (String columnKey : table.columnKeySet()) {
            printer.print(table.get(rowKey, columnKey));
        }
        printer.println();
    }

    printer.close();

    return sw.toString();
}

From source file:com.streamsets.pipeline.kafka.common.KafkaTestUtil.java

public static List<KeyedMessage<String, String>> produceCsvMessages(String topic, String partition,
        CSVFormat csvFormat, File csvFile) throws IOException {
    List<KeyedMessage<String, String>> messages = new ArrayList<>();
    String line;// www. j av a  2  s  . c o m
    BufferedReader bufferedReader = new BufferedReader(
            new FileReader(KafkaTestUtil.class.getClassLoader().getResource("testKafkaTarget.csv").getFile()));
    while ((line = bufferedReader.readLine()) != null) {
        String[] strings = line.split(",");
        StringWriter stringWriter = new StringWriter();
        CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
        csvPrinter.printRecord(strings);
        csvPrinter.flush();
        csvPrinter.close();
        messages.add(new KeyedMessage<>(topic, partition, stringWriter.toString()));
    }
    return messages;
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.evaluation.helpers.FinalTableExtractor.java

public static <T> String tableToCsv(Table<String, String, T> table) throws IOException {
    StringWriter sw = new StringWriter();
    CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);

    List<String> firstRow = new ArrayList<>();
    firstRow.add(" ");
    firstRow.addAll(table.columnKeySet());
    printer.printRecord(firstRow);//  w  ww  .j  a  v a  2s  .  c om

    for (String rowKey : table.rowKeySet()) {
        printer.print(rowKey);
        for (String columnKey : table.columnKeySet()) {
            printer.print(table.get(rowKey, columnKey));
        }
        printer.println();
    }

    printer.close();

    return sw.toString();
}