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

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

Introduction

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

Prototype

@Override
public void flush() throws IOException 

Source Link

Document

Flushes the underlying stream.

Usage

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());//  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();
    csvPrinter.close();//  w  w w.  j a v  a  2  s .  c o  m
    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();
        csvPrinter.close();/*ww  w .j  a v  a2s.c  o  m*/
    } catch (Exception e) {
        outB.close();
        throw e;
    }

    return outB;

}

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;//from w w w .  j  a  va2 s .  co 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:javalibs.CSVExtractor.java

/**
 * Write a single CSV record to a CSV file
 * @param path The path to save the CSV file
 * @param rec The record to be written// w ww  . ja  v a  2  s.c om
 * @param headers Headers for the CSV. If this value is null there will be no
 *                headers added to the CSV
 */
public static void writeCSVRecord(String path, CSVRecord rec, String[] headers) {
    BufferedWriter bw = null;
    CSVPrinter printer = null;
    try {
        bw = Files.newBufferedWriter(Paths.get(path));
        if (headers != null)
            printer = new CSVPrinter(bw, CSVFormat.DEFAULT.withHeader(headers));
        else
            printer = new CSVPrinter(bw, CSVFormat.DEFAULT);
    } catch (IOException e) {
        TSL.get().exception(e);
    }

    TSL.get().require(bw != null, "BufferedWriter cannot be null");
    TSL.get().require(printer != null, "CSVPrinter cannot be null");

    try {
        printer.printRecord(rec);
        printer.flush();
    } catch (IOException e) {
        TSL.get().exception(e);
    }
}

From source file:com.ibm.g11n.pipeline.example.CSVFilter.java

@Override
public void write(OutputStream outStream, LanguageBundle languageBundle, FilterOptions options)
        throws IOException, ResourceFilterException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
    CSVPrinter printer = CSVFormat.RFC4180.withHeader("key", "value").print(writer);
    for (ResourceString resString : languageBundle.getSortedResourceStrings()) {
        printer.printRecord(resString.getKey(), resString.getValue());
    }//from  w  w w .j  a v  a  2  s .  c  om
    printer.flush();
}

From source file:de.speexx.jira.jan.command.issuequery.CsvCreator.java

void printHeader(final List<FieldNamePath> currentFieldNames, final List<FieldName> historyFieldNames,
        final TemporalChangeOutput temporalOutput) {
    assert !Objects.isNull(currentFieldNames);
    assert !Objects.isNull(historyFieldNames);
    assert !Objects.isNull(temporalOutput);

    final List<String> headerNames = new ArrayList<>();
    currentFieldNames.stream().map(FieldNamePath::asString)
            .map(name -> name.replaceAll(FieldNamePath.DELIMITER, FIELDNAMEPATH_DELIMITER_REPALCEMENT))
            .forEach(name -> headerNames.add(name));
    historyFieldNames.stream().map(FieldName::asString).forEach(name -> {
        headerNames.add(HOSTORICAL_FROM_PREFIX + name);
        if (temporalOutput != NONE) {
            if (temporalOutput == BOTH || temporalOutput == TIME) {
                headerNames.add(HOSTORICAL_CHANGE_DATETIME_PREFIX + name);
            }/* w ww  .  jav a 2  s.c o m*/
            if (temporalOutput == BOTH || temporalOutput == DURATION) {
                headerNames.add(HOSTORICAL_DURATION_PREFIX + name);
            }
        }
        headerNames.add(HOSTORICAL_TO_PREFIX + name);
    });
    try {
        final CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8),
                RFC4180);
        csvPrinter.printRecord(headerNames.toArray());
        csvPrinter.flush();
    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }
}

From source file:com.ibm.g11n.pipeline.example.CSVFilter.java

@Override
public void merge(InputStream baseStream, OutputStream outStream, LanguageBundle languageBundle,
        FilterOptions options) throws IOException, ResourceFilterException {
    // create key-value map
    Map<String, String> kvMap = new HashMap<String, String>();
    for (ResourceString resString : languageBundle.getResourceStrings()) {
        kvMap.put(resString.getKey(), resString.getValue());
    }//  w  w w  . j  a  v  a  2  s. c  o  m

    CSVParser parser = CSVParser.parse(baseStream, StandardCharsets.UTF_8,
            CSVFormat.RFC4180.withHeader("key", "value").withSkipHeaderRecord(true));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
    CSVPrinter printer = CSVFormat.RFC4180.withHeader("key", "value").print(writer);
    for (CSVRecord record : parser) {
        String key = record.get(0);
        String value = record.get(1);
        String trValue = kvMap.get(key);
        if (trValue != null) {
            value = trValue;
        }
        printer.printRecord(key, value);
    }
    printer.flush();
}

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

public 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.ja v  a2  s . com
    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:com.siemens.sw360.portal.portlets.admin.ComponentUploadPortlet.java

@NotNull
private ByteArrayOutputStream writeCsvStream(List<List<String>> listList) throws TException, IOException {
    final ByteArrayOutputStream riskCategoryCsvStream = new ByteArrayOutputStream();
    Writer out = new BufferedWriter(new OutputStreamWriter(riskCategoryCsvStream));
    CSVPrinter csvPrinter = new CSVPrinter(out, CommonUtils.sw360CsvFormat);
    csvPrinter.printRecords(listList);// w ww  .  j  av a  2  s  . co m
    csvPrinter.flush();
    csvPrinter.close();
    return riskCategoryCsvStream;
}