List of usage examples for org.apache.commons.csv CSVFormat DEFAULT
CSVFormat DEFAULT
To view the source code for org.apache.commons.csv CSVFormat DEFAULT.
Click Source Link
From source file:org.roda.core.plugins.plugins.base.InventoryReportPlugin.java
private CSVPrinter createCSVPrinter() { Path jobCSVTempFolder = getJobCSVTempFolder(); Path csvTempFile = jobCSVTempFolder.resolve(IdUtils.createUUID() + ".csv"); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); try (BufferedWriter fileWriter = Files.newBufferedWriter(csvTempFile)) { return new CSVPrinter(fileWriter, csvFileFormat); } catch (IOException e) { LOGGER.error("Unable to instantiate CSVPrinter", e); return null; }//ww w . jav a 2s. c o m }
From source file:org.roda.core.plugins.plugins.base.InventoryReportPlugin.java
@Override public Report afterAllExecute(IndexService index, ModelService model, StorageService storage) throws PluginException { CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); Path csvTempFolder = getJobCSVTempFolder(); if (csvTempFolder != null) { List<Path> partials = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(csvTempFolder); FileWriter fileWriter = new FileWriter(output.toFile()); CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) { if (enableHeaders) { csvFilePrinter.printRecord(fields); }/*w w w . j a v a 2 s . c om*/ for (Path path : directoryStream) { partials.add(path); } } catch (IOException e) { LOGGER.error("Error while merging partial CSVs", e); } try { InventoryReportPluginUtils.mergeFiles(partials, output); FSUtils.deletePathQuietly(csvTempFolder); } catch (IOException e) { LOGGER.error("Error while merging partial CSVs", e); } } return new Report(); }
From source file:org.roda.wui.api.v1.IndexResource.java
/** * Produces a CSV response with results or facets. * /*from w w w . j a v a 2 s . c om*/ * @param findRequest * the request parameters. * @param user * the current {@link User}. * @param <T> * Type of the resources to return. * @return a {@link Response} with CSV. * @throws RequestNotValidException * it the request is not valid. * @throws AuthorizationDeniedException * if the user is not authorized to perform this operation. * @throws GenericException * if some other error occurs. */ private <T extends IsIndexed> Response csvResponse(final FindRequest findRequest, final User user) throws RequestNotValidException, AuthorizationDeniedException, GenericException { final Class<T> returnClass = getClass(findRequest.classToReturn); final Configuration config = RodaCoreFactory.getRodaConfiguration(); final char delimiter; if (StringUtils.isBlank(config.getString(CONFIG_KEY_CSV_DELIMITER))) { delimiter = CSVFormat.DEFAULT.getDelimiter(); } else { delimiter = config.getString(CONFIG_KEY_CSV_DELIMITER).trim().charAt(0); } if (findRequest.exportFacets) { final IndexResult<T> result = Browser.find(returnClass, findRequest.filter, Sorter.NONE, Sublist.NONE, findRequest.facets, user, findRequest.onlyActive, new ArrayList<>()); return ApiUtils.okResponse(new RodaStreamingOutput( new FacetsCSVOutputStream(result.getFacetResults(), findRequest.filename, delimiter)) .toStreamResponse()); } else { final IterableIndexResult<T> result = Browser.findAll(returnClass, findRequest.filter, findRequest.sorter, findRequest.sublist, findRequest.facets, user, findRequest.onlyActive, new ArrayList<>()); return ApiUtils.okResponse( new RodaStreamingOutput(new ResultsCSVOutputStream<>(result, findRequest.filename, delimiter)) .toStreamResponse()); } }
From source file:org.schedoscope.export.ftp.outputformat.CSVRecordWriter.java
/** * The constructor to initialize the CSV Record Writer. * * @param out A data output stream. * @param header A flag to print a header or not. * @param delimiter The delimiter to use. * @throws IOException Is thrown if an error occurs. *///from w w w.j ava 2 s. co m public CSVRecordWriter(DataOutputStream out, String[] header, char delimiter) throws IOException { this.out = out; csvFormat = CSVFormat.DEFAULT.withTrim(true).withQuoteMode(QuoteMode.ALL).withHeader(header) .withDelimiter(delimiter); buffer = new StringBuilder(); csvPrinter = csvFormat.print(buffer); }
From source file:org.servalproject.maps.export.CsvAsyncTask.java
public CsvAsyncTask(Activity context, ProgressBar progressBar, TextView progressLabel) { // check the parameters if (context == null || progressBar == null || progressLabel == null) { throw new IllegalArgumentException("all parameters are required"); }//from w w w . j a v a2 s . co m this.context = context; this.progressBar = progressBar; this.progressLabel = progressLabel; this.csvFormat = CSVFormat.DEFAULT; csvFormat.withEscape('\\'); csvFormat.withCommentStart('#'); if (V_LOG) { Log.v(TAG, "class instantiated"); } }
From source file:org.shareok.data.documentProcessor.CsvHandler.java
/** * Reads out the data in an excel file and stores data in a hashmap * <p>Also sets the total record number and file heading</p> * //from w w w . j av a2 s. co m * @throws Exception */ @Override public void readData() { FileReader fileReader = null; CSVParser csvFileParser = null; String[] headMapping = null; //CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING); try { //initialize FileReader object fileReader = new FileReader(fileName); //initialize CSVParser object if (null == csvFormat) { csvFormat = CSVFormat.DEFAULT; } csvFileParser = new CSVParser(fileReader, csvFormat); //Get a list of CSV file records List csvRecords = csvFileParser.getRecords(); int size = csvRecords.size(); setRecordCount(size); data = new HashMap(); //Read the CSV file records starting from the second record to skip the header for (int i = 0; i < size; i++) { CSVRecord record = (CSVRecord) csvRecords.get(i); if (null != record) { if (i == 0) { List headMappingList = new ArrayList(); Iterator it = record.iterator(); while (it.hasNext()) { String value = (String) it.next(); headMappingList.add(value); } headMapping = new String[headMappingList.size()]; headMapping = (String[]) headMappingList.toArray(headMapping); setFileHeadMapping(headMapping); } else { for (int j = 0; j < fileHeadMapping.length; j++) { String colName = fileHeadMapping[j].trim(); String key = colName + "-" + i; data.put(key, record.get(j)); } } } } } catch (Exception e) { System.out.println("Error in CsvFileReader !!!"); e.printStackTrace(); } finally { try { fileReader.close(); csvFileParser.close(); } catch (IOException e) { System.out.println("Error while closing fileReader/csvFileParser !!!"); e.printStackTrace(); } } }
From source file:org.shareok.data.documentProcessor.CsvHandler.java
/** * Output the data into a new CSV file/* w ww.j a v a 2 s. c om*/ * <p>Uses "\n" as the line separator</P> * * @param newFileName : String. * If the newFileName is not specified, a "-copy" will be attached to the old file name for the new CSV file * * @return the path of the new CSV file */ public String outputData(String newFileName) { if (null == data) { readData(); } if (null != data) { FileWriter fileWriter = null; CSVPrinter csvFilePrinter = null; CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n"); try { if (null == newFileName || newFileName.equals("")) { newFileName = fileName.substring(0, fileName.indexOf(".csv")) + "-copy.csv"; } fileWriter = new FileWriter(newFileName); csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); csvFilePrinter.printRecord(Arrays.asList(fileHeadMapping)); Map<String, String[]> records = new HashMap<>(); List<String> headingList = Arrays.asList(fileHeadMapping); Iterator it = data.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) data.get(key); String[] keyInfo = key.split("-"); String row = keyInfo[keyInfo.length - 1]; String column = key.replace("-" + row, ""); if (null == records.get(row)) { String[] dataRecord = new String[fileHeadMapping.length]; dataRecord[headingList.indexOf(column)] = value; records.put(row, dataRecord); } else { String[] dataRecord = records.get(row); dataRecord[headingList.indexOf(column)] = value; } } Iterator it2 = records.keySet().iterator(); while (it2.hasNext()) { String key = (String) it2.next(); String[] value = (String[]) records.get(key); csvFilePrinter.printRecord(Arrays.asList(value)); } } catch (Exception e) { System.out.println("Error in CsvFileWriter!\n"); e.printStackTrace(); } finally { try { fileWriter.flush(); fileWriter.close(); csvFilePrinter.close(); } catch (IOException e) { System.out.println("Error while flushing/closing fileWriter/csvPrinter\n"); e.printStackTrace(); } } } return newFileName; }
From source file:org.softinica.maven.jmeter.report.parser.CSVReportParser.java
@Override public Input parseInput(InputDefinition definition) { CSVParser parser = null;/*from w w w. j a va 2 s . co m*/ Input input = new Input(); try { Reader reader = new InputStreamReader(new FileInputStream(definition.getInputFile())); parser = new CSVParser(reader, CSVFormat.DEFAULT); Iterator<CSVRecord> it = parser.iterator(); while (it.hasNext()) { Sample sample = new Sample(); CSVRecord record = it.next(); sample.setTimestamp(Long.valueOf(record.get(0))); sample.setLabel(record.get(2)); sample.setValue(Double.valueOf(record.get(4)) * definition.getScale()); sample.setSuccess(Boolean.parseBoolean(record.get(7))); input.getSamples().add(sample); } } catch (IOException e) { throw new RuntimeException(e); } finally { Utils.close(parser); } return input; }
From source file:org.softinica.maven.jmeter.report.parser.SimpleCSVParser.java
@Override public Input parseInput(InputDefinition definition) { CSVParser parser = null;//from w w w.ja v a 2s . c o m List<String> headers = new LinkedList<String>(); Input input = new Input(); try { Reader reader = new InputStreamReader(new FileInputStream(definition.getInputFile())); parser = new CSVParser(reader, CSVFormat.DEFAULT); Iterator<CSVRecord> it = parser.iterator(); if (it.hasNext()) { CSVRecord header = it.next(); for (String value : header) { headers.add(value); } while (it.hasNext()) { Sample sample = new Sample(); CSVRecord record = it.next(); for (int i = 0; i < record.size(); i++) { sample.put(headers.get(i), record.get(i)); } input.getSamples().add(sample); } } } catch (IOException e) { throw new RuntimeException(e); } finally { Utils.close(parser); } return input; }
From source file:org.sonar.db.version.v51.FeedFileSourcesBinaryData.java
private byte[] toBinary(Long fileSourceId, @Nullable String data) { DbFileSources.Data.Builder dataBuilder = DbFileSources.Data.newBuilder(); CSVParser parser = null;// w w w .j av a 2s .co m try { if (data != null) { parser = CSVParser.parse(data, CSVFormat.DEFAULT); Iterator<CSVRecord> rows = parser.iterator(); int line = 1; while (rows.hasNext()) { CSVRecord row = rows.next(); if (row.size() == 16) { DbFileSources.Line.Builder lineBuilder = dataBuilder.addLinesBuilder(); lineBuilder.setLine(line); String s = row.get(0); if (StringUtils.isNotEmpty(s)) { lineBuilder.setScmRevision(s); } s = row.get(1); if (StringUtils.isNotEmpty(s)) { lineBuilder.setScmAuthor(s); } Date scmDate = DateUtils.parseDateTimeQuietly(row.get(2)); if (scmDate != null) { lineBuilder.setScmDate(scmDate.getTime()); } s = row.get(3); if (StringUtils.isNotEmpty(s)) { lineBuilder.setUtLineHits(Integer.parseInt(s)); } s = row.get(4); if (StringUtils.isNotEmpty(s)) { lineBuilder.setUtConditions(Integer.parseInt(s)); } s = row.get(5); if (StringUtils.isNotEmpty(s)) { lineBuilder.setUtCoveredConditions(Integer.parseInt(s)); } s = row.get(6); if (StringUtils.isNotEmpty(s)) { lineBuilder.setItLineHits(Integer.parseInt(s)); } s = row.get(7); if (StringUtils.isNotEmpty(s)) { lineBuilder.setItConditions(Integer.parseInt(s)); } s = row.get(8); if (StringUtils.isNotEmpty(s)) { lineBuilder.setItCoveredConditions(Integer.parseInt(s)); } s = row.get(9); if (StringUtils.isNotEmpty(s)) { lineBuilder.setOverallLineHits(Integer.parseInt(s)); } s = row.get(10); if (StringUtils.isNotEmpty(s)) { lineBuilder.setOverallConditions(Integer.parseInt(s)); } s = row.get(11); if (StringUtils.isNotEmpty(s)) { lineBuilder.setOverallCoveredConditions(Integer.parseInt(s)); } s = row.get(12); if (StringUtils.isNotEmpty(s)) { lineBuilder.setHighlighting(s); } s = row.get(13); if (StringUtils.isNotEmpty(s)) { lineBuilder.setSymbols(s); } s = row.get(14); if (StringUtils.isNotEmpty(s)) { lineBuilder.addAllDuplication(splitIntegers(s)); } s = row.get(15); if (s != null) { lineBuilder.setSource(s); } } line++; } } return FileSourceDto.encodeSourceData(dataBuilder.build()); } catch (Exception e) { throw new IllegalStateException( "Invalid FILE_SOURCES.DATA on row with ID " + fileSourceId + ": " + data, e); } finally { IOUtils.closeQuietly(parser); } }