Java Code Examples for org.apache.commons.csv.CSVPrinter#close()

The following examples show how to use org.apache.commons.csv.CSVPrinter#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InformationExtraction2Postgres.java    From newsleak with GNU Affero General Public License v3.0 8 votes vote down vote up
private void mappingIdsInMetadata(String mappedMetadataFile) throws Exception {
	// read mappings file
	FileInputStream fis = new FileInputStream(this.dataDirectory + File.separator + this.metadataFile + ".id-map");
	ObjectInputStream ois = new ObjectInputStream(fis);
	HashMap<Integer, ArrayList<Integer>> documentIdMapping = (HashMap<Integer, ArrayList<Integer>>) ois
			.readObject();
	ois.close();

	// open metadata file, replace ids, write to temporary metadata file
	BufferedWriter writer = new BufferedWriter(new FileWriter(mappedMetadataFile));
	CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.RFC4180);

	BufferedReader reader = new BufferedReader(new FileReader(this.dataDirectory + File.separator + this.metadataFile));
	Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);
	for (CSVRecord record : records) {
		Integer tmpDocId = Integer.parseInt(record.get(0));
		if (documentIdMapping.containsKey(tmpDocId)) { 
			ArrayList<Integer> mappedIds = documentIdMapping.get(tmpDocId);
			int nParts = mappedIds.size();
			int partCounter = 0;
			for (Integer newsleakDocId : mappedIds) {
				String key = StringUtils.capitalize(record.get(1));
				String value = record.get(2);
				if (nParts > 1 && key.equals("Subject")) {
					partCounter++;
					value += " (" + partCounter + "/" + nParts + ")";
				}
				ArrayList<String> meta = new ArrayList<String>();
				meta.add(newsleakDocId.toString());
				meta.add(key);
				meta.add(value);
				meta.add(record.get(3));
				csvPrinter.printRecord(meta);
			}
		}
	}
	csvPrinter.close();
	reader.close();
}
 
Example 2
Source File: ClassDupRiskWriter.java    From Decca with MIT License 6 votes vote down vote up
public void writeRchNum(String outPath, boolean append) {
	try {
		CSVPrinter printer = new CSVPrinter(new FileWriter(outPath, append), CSVFormat.DEFAULT);
		DepJarCgs jarCgs = new DepJarCgs();
		for (DupClsJarPair jarPair : getJarPairs().getAllJarPair()) {
			FourRow fourRow = jarPair.getPairRisk(jarCgs).getFourRow();
			printer.printRecord(fourRow.mthdRow);
			printer.printRecord(fourRow.mthdNameRow);
			printer.printRecord(fourRow.serviceRow);
			printer.printRecord(fourRow.serviceNameRow);
		}
		printer.close();
	} catch (Exception e) {
		MavenUtil.i().getLog().error("can't write reach class number:", e);
	}
}
 
Example 3
Source File: JarRchedWriter.java    From Decca with MIT License 6 votes vote down vote up
public void writeCsv(String outPath, boolean append) {
	try {
		// final String[] header = { "projectId", "conflictId", "type", "origin",
		// "load", "other" };
		// CSVFormat format = CSVFormat.DEFAULT.withHeader(header);

		CSVPrinter printer = new CSVPrinter(new FileWriter(outPath, append), CSVFormat.DEFAULT);
		for (NodeConflict conflict : NodeConflicts.i().getConflicts()) {
			FourRow fourRow = conflict.getRiskAna().getFourRow();
			printer.printRecord(fourRow.mthdRow);
			printer.printRecord(fourRow.mthdNameRow);
			printer.printRecord(fourRow.serviceRow);
			printer.printRecord(fourRow.serviceNameRow);
			printer.flush();
		}
		printer.close();
	} catch (Exception e) {
		MavenUtil.i().getLog().error("can't write risk result:", e);
	}
}
 
Example 4
Source File: CSVUtil.java    From searoute with European Union Public License 1.2 6 votes vote down vote up
public static void save(Collection<Map<String, String>> data, String outFile, CSVFormat cf) {
	try {
		FileWriter out = new FileWriter(outFile);
		String[] header = cf.getHeader(); int nb = header.length;
		CSVPrinter printer = new CSVPrinter(out, cf);
		for(Map<String, String> raw : data) {
			String[] values = new String[nb];
			for(int i=0; i<nb; i++) values[i]=raw.get(header[i]);
			printer.printRecord(values);
		}
		printer.close();
		out.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: CSVGenerator.java    From janusgraph-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Create csv files for a VertexType
 * @param type a vertex type
 * @param outputDirectory the output folder to write the csv file
 */
void writeVertexCSV(VertexTypeBean type, String outputDirectory ){
    String csvFile = outputDirectory + "/" + type.name + ".csv";
    ArrayList<String> header = new ArrayList<String>();
    header.add("node_id");
    header.addAll(type.columns.keySet());
    int botId = idFactory.getMinId(type.name);
    int topId = idFactory.getMaxId(type.name);
    try {
        CSVPrinter csvFilePrinter = new CSVPrinter(new FileWriter(csvFile), csvFileFormat);
        csvFilePrinter.printRecord(header);
        for (int i = botId; i<=topId; i++){
            ArrayList<Object> record = new ArrayList<Object>();
            record.add(i);
            record.addAll(generateOneRecord(type.columns));
            csvFilePrinter.printRecord(record);
        }
        csvFilePrinter.close();
        System.out.println("Generated vertex file: "+ csvFile);
    } catch (Exception e) {
        throw new RuntimeException(e.toString());
    }
}
 
Example 6
Source File: ToCsvPragmaTransform.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute() {
	try {
		StringBuffer sb = new StringBuffer();
		CSVPrinter printer = new CSVPrinter(sb, ToCsvPragmaInstance.getFormat(options1));
		int srcId = (int) options1.getOrDefault(AqlOption.start_ids_at);
		int dstId = (int) options2.getOrDefault(AqlOption.start_ids_at);

		Pair<TObjectIntMap<X1>, TIntObjectMap<X1>> a = h.src().algebra().intifyX(srcId);
		Pair<TObjectIntMap<X2>, TIntObjectMap<X2>> b = h.dst().algebra().intifyX(dstId);

		for (En en : h.src().schema().ens) {
			for (X1 x1 : h.src().algebra().en(en)) {
				List<String> row = new LinkedList<>();
				row.add(Integer.toString(a.first.get(x1)));
				X2 x2 = h.repr(en, x1);
				row.add(Integer.toString(b.first.get(x2)));
				printer.printRecord(row);
			}
		}

		printer.close();
		delete();
		if (!file.createNewFile()) {
			throw new RuntimeException("Could not create new file: " + file);
		}
		FileWriter out = new FileWriter(file);
		out.write(sb.toString());
		out.close();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Source File: DebugMojo.java    From Decca with MIT License 5 votes vote down vote up
public void writeDepNum(String outPath) {
	try {
		CSVPrinter printer = new CSVPrinter(new FileWriter(outPath, true), CSVFormat.DEFAULT);
		List<String> record = new ArrayList<String>();
		int directDep = 0;
		int allNode = -1 + NodeAdapters.i().getAllNodeAdapter().size();
		int allJar = -1 + DepJars.i().getAllDepJar().size();
		int allUsedJar = -1;
		for (NodeAdapter node : NodeAdapters.i().getAllNodeAdapter()) {
			if (node.getNodeDepth() == 2) {
				directDep++;
			}
			if (node.isNodeSelected()) {
				allUsedJar++;
			}
		}
		record.add(MavenUtil.i().getProjectInfo());
		record.add("" + directDep);
		record.add("" + allNode);
		record.add("" + allJar);
		record.add("" + allUsedJar);
		printer.printRecord(record);
		printer.close();
	} catch (Exception e) {
		MavenUtil.i().getLog().error("can't write debug:", e);
	}
}
 
Example 8
Source File: TableUtils.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Guava table to a CSV table
 *
 * @param table                   table
 * @param csvFormat               CSV format
 * @param missingValuePlaceholder print if a value is missing (empty string by default)
 * @param <T>                     object type (string)
 * @return table
 * @throws IOException exception
 */
public static <T> String tableToCsv(Table<String, String, T> table, CSVFormat csvFormat,
        String missingValuePlaceholder)
        throws IOException
{
    StringWriter sw = new StringWriter();
    CSVPrinter printer = new CSVPrinter(sw, csvFormat);

    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()) {
            T value = table.get(rowKey, columnKey);

            if (value == null) {
                printer.print(missingValuePlaceholder);
            }
            else {
                printer.print(value);
            }
        }
        printer.println();
    }

    printer.close();

    return sw.toString();
}
 
Example 9
Source File: PatientTumorLocation.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
public static void writeRecords(@NotNull String outputPath, @NotNull List<PatientTumorLocation> patientTumorLocations)
        throws IOException {
    CSVFormat format = CSVFormat.DEFAULT.withNullString(Strings.EMPTY).withHeader(Header.class);
    CSVPrinter printer = new CSVPrinter(new FileWriter(outputPath), format);
    printer.printRecords(patientTumorLocations.stream().map(PatientTumorLocation::csvRecord).collect(Collectors.toList()));
    printer.close();
}
 
Example 10
Source File: MetadataResource.java    From newsleak with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Append a list of metadata entries for one document to the temporary metadata
 * file.
 *
 * @param metadata
 *            the metadata
 */
public synchronized void appendMetadata(List<List<String>> metadata) {
	try {
		BufferedWriter writer = new BufferedWriter(new FileWriter(metadataFile, true));
		CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.RFC4180);
		csvPrinter.printRecords(metadata);
		csvPrinter.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 11
Source File: GetSubscriptionUsage.java    From development with Apache License 2.0 5 votes vote down vote up
private StringBuffer toCSV(VOSubscriptionUsageEntry entry) throws IOException {
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator());
    StringBuffer appendable = new StringBuffer();
    CSVPrinter csvFilePrinter = new CSVPrinter(appendable, csvFileFormat);
    List<String> columns = toList(entry);
    csvFilePrinter.printRecord(columns);
    csvFilePrinter.close();
    return appendable;
}
 
Example 12
Source File: OperatorServiceBeanIT.java    From development with Apache License 2.0 5 votes vote down vote up
private StringBuffer toCSV(VOSubscriptionUsageEntry entry) throws IOException {
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator());
    StringBuffer appendable = new StringBuffer();
    CSVPrinter csvFilePrinter = new CSVPrinter(appendable, csvFileFormat);
    List<String> columns = toList(entry);
    csvFilePrinter.printRecord(columns);
    csvFilePrinter.close();
    return appendable;
}
 
Example 13
Source File: CSVUtils.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public String toCsv(String ...strings) throws IOException {
	StringWriter writer = new StringWriter();
	CSVPrinter printer = new CSVPrinter(writer, csvFormat);
	printer.printRecord(Arrays.asList(strings));
	printer.flush();
	printer.close();
	
	String string = writer.toString();
	return string;
}
 
Example 14
Source File: FileIndexerPipeline.java    From dataflow-opinion-analysis with Apache License 2.0 4 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext c) {
	
	ContentIndexSummary summary = c.element();

	if (summary.sentiments == null) 
		return;
	
	try {
	
		StringWriter stringWriter = new StringWriter();
		CSVPrinter csvPrinter = new CSVPrinter(stringWriter,CSVFormat.DEFAULT);
			
		for (int i=0; i < summary.sentiments.length; i++)
		{
			
			ArrayList<String> linefields = new ArrayList<String>();
			
			addField(linefields,"RecordID",summary.doc.collectionItemId);
	
			ArrayList<String> sttags = new ArrayList<>();
			if (summary.sentiments[i].tags != null) 
				for (int j=0; j < summary.sentiments[i].tags.length; j++)
					sttags.add(summary.sentiments[i].tags[j].tag);
			
			addField(linefields,"Tags",sttags.toString()); // will write as [a,b,c]
			
			addField(linefields,"SentimentHash", summary.sentiments[i].sentimentHash);
			addField(linefields,"Text", summary.sentiments[i].text);
			addField(linefields,"LabelledPositions", summary.sentiments[i].labelledPositions);
			addField(linefields,"AnnotatedText", summary.sentiments[i].annotatedText);
			addField(linefields,"AnnotatedHtml", summary.sentiments[i].annotatedHtmlText);
			addField(linefields,"SentimentTotalScore", summary.sentiments[i].sentimentTotalScore);
			addField(linefields,"DominantValence", summary.sentiments[i].dominantValence.ordinal());
			addField(linefields,"StAcceptance", summary.sentiments[i].stAcceptance);
			addField(linefields,"StAnger", summary.sentiments[i].stAnger);
			addField(linefields,"StAnticipation", summary.sentiments[i].stAnticipation);
			addField(linefields,"StAmbiguous", summary.sentiments[i].stAmbiguous);
			addField(linefields,"StDisgust", summary.sentiments[i].stDisgust);
			addField(linefields,"StFear", summary.sentiments[i].stFear);
			addField(linefields,"StGuilt", summary.sentiments[i].stGuilt);
			addField(linefields,"StInterest", summary.sentiments[i].stInterest);
			addField(linefields,"StJoy", summary.sentiments[i].stJoy);
			addField(linefields,"StSadness", summary.sentiments[i].stSadness);
			addField(linefields,"StShame", summary.sentiments[i].stShame);
			addField(linefields,"StSurprise", summary.sentiments[i].stSurprise);
			addField(linefields,"StPositive", summary.sentiments[i].stPositive);
			addField(linefields,"StNegative", summary.sentiments[i].stNegative);
			addField(linefields,"StSentiment", summary.sentiments[i].stSentiment);
			addField(linefields,"StProfane", summary.sentiments[i].stProfane);
			addField(linefields,"StUnsafe", summary.sentiments[i].stUnsafe);
			
			ArrayList<String> signalsarray = new ArrayList<>();
			if (summary.sentiments[i].signals != null) 
				for (int j=0; j < summary.sentiments[i].signals.length; j++)
					signalsarray.add(summary.sentiments[i].signals[j]);
			
			addField(linefields,"Signals",signalsarray.toString());
			
			csvPrinter.printRecord(linefields);
			
			String output = stringWriter.toString().trim(); // need to trim, because printRecord will add the record separator, as will the TextIO.write method at the end of the pipeline
			csvPrinter.flush(); // will also flush the stringWriter
			
			c.output(output);
			
			
		}
		
		csvPrinter.close();
	} catch (IOException e) {
		LOG.warn(e.getMessage());
	}
}