Java Code Examples for au.com.bytecode.opencsv.CSVWriter.flush()

The following are Jave code examples for showing how to use flush() of the au.com.bytecode.opencsv.CSVWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: fancy-chart   File: CsvDao.java   Source Code and License Vote up 7 votes
public static void exportCsv(SortedMap<Number, Number> data, String filePath) {
	try {
		writer = new CSVWriter(new FileWriter(filePath), ',', '\0');

		List<String[]> entries = new ArrayList<>(data.size());
		for (Number x : data.keySet()) {
			String xString = String.valueOf(x);
			String yString = String.valueOf(data.get(x));
			entries.add(new String[] { xString, yString });
		}

		writer.writeAll(entries);
		writer.flush();
		writer.close();
	} catch (IOException e) {
		System.err.println(e.getMessage());
	}
}
 
Example 2
Project: geeCommerce-Java-Shop-Software-and-PIM   File: CustomerResource.java   Source Code and License Vote up 6 votes
@GET
@Path("export/emails")
// @Produces("text/plain")
public Response getCustomerExportEmails(@FilterParam Filter filter, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"customer-emails.csv\"");
    PrintWriter printWriter = response.getWriter();
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(new String[] { "E-mail" });

    List<Customer> customers = service.get(Customer.class);
    for (Customer customer : customers) {
        if (customer.getEmail() != null && !customer.getEmail().isEmpty()) {
            writer.writeNext(new String[] { customer.getEmail() });
        }
    }
    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 3
Project: ICDClassifier   File: ExperimentalCipeClassifier.java   Source Code and License Vote up 6 votes
/**
 * Print config and stats as a CSV line.
 */
public void printStatsAsCsvLine(CSVWriter writer, String id,
		Instances dataset, ExtendedEvaluation eval) {
	int n = dataset.numInstances();
	double p = eval.microAveragedPrecision();
	double r = eval.microAveragedRecall();
	double macroF1 = eval.macroAveragedFMeasure(1);
	double microF1 = eval.microAveragedFMeasure(1);
	double a = eval.accuracy();

	String[] line = { id, String.valueOf(n), String.valueOf(a), String.valueOf(p),
			String.valueOf(r), String.valueOf(macroF1), String.valueOf(microF1),
			 };
	writer.writeNext(line);
	try {
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Project: IDRT-Import-and-Mapping-Tool   File: RegexWizard.java   Source Code and License Vote up 6 votes
@Override
	public boolean performFinish() {

		try {
			CSVWriter writer = new CSVWriter(new FileWriter(new File(FileHandler.getCFGFilePath("regex.csv"))), ';');
			writer.writeNext(new String[] {"Name","Regex"});
			for (Regex r : CombineNodesCommand.getRegex()) {
				if (!r.getName().isEmpty())
					writer.writeNext(new String[] {r.getName(),r.getRegex().replaceAll("\\\\", "\\\\\\\\"), r.getTable()});
			}
			writer.flush();
			writer.close();
//			MyOntologyTrees.createRegexMenu();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
 
Example 5
Project: phon   File: CSVTableDataWriter.java   Source Code and License Vote up 6 votes
public void writeTableToFile(JTable table, File file) 
	throws IOException {
	final CSVWriter writer = 
			new CSVWriter(new PrintWriter(file, charEncoding), ',', '\"', 
					(OSInfo.isWindows() ? "\r\n" : "\n"));
	// output column names
	final String[] colnames = new String[table.getColumnCount()];
	for(int i = 0; i < table.getColumnCount(); i++) {
		colnames[i] = table.getColumnName(i);
	}
	writer.writeNext(colnames);
	
	final String[] currentRow = new String[table.getColumnCount()];
	for(int row = 0; row < table.getRowCount(); row++) {
		for(int col = 0; col < table.getColumnCount(); col++) {
			final Object cellVal = table.getValueAt(row, col);
			currentRow[col] = (cellVal == null ? "" : cellVal.toString());
		}
		writer.writeNext(currentRow);
	}
	writer.flush();
	writer.close();
}
 
Example 6
Project: streaminggraphpartitioning   File: AllGraphDetails.java   Source Code and License Vote up 5 votes
private void printHeader(CSVWriter wr) throws IOException {
	String[] header = {
		"Nome",
		"Numero di nodi",
		"Numero di archi",
		"Coefficiente di clustering",
		"Densita'",
		"Grado massimo",
		"Grado minimo",
		"Grado medio",
		"Componenti connesse"
	};
	wr.writeNext(header);
	wr.flush();
}
 
Example 7
Project: geeCommerce-Java-Shop-Software-and-PIM   File: DiscountPromotionResource.java   Source Code and License Vote up 5 votes
@GET
@Path("{id}/export/expired")
public Response getEmailExportExpired(@PathParam("id") Id id, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"expired-emails.csv\"");
    PrintWriter printWriter = response.getWriter();
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(new String[] { "E-mail", "From", "To", "Used", "Code" });
    // rom/to dates, used and coupon code
    DiscountPromotion p = checked(service.get(DiscountPromotion.class, id));
    if (p != null) {
        Coupon c = p.getCoupon();
        if (c != null) {
            List<CouponCode> couponCodes = c.getCodes();
            if (couponCodes != null) {
                for (CouponCode couponCode : couponCodes) {
                    if (couponCode.getEmail() != null) {
                        String email = couponCode.getEmail();
                        if (couponCode.getCouponUsages() == null || couponCode.getCouponUsages().size() == 0) {
                            Date now = new Date();
                            Date fromDate = DateTimes.maxOfDates(c.getFromDate(), couponCode.getFromDate());
                            Date toDate = DateTimes.minOfDates(c.getToDate(), couponCode.getToDate());
                            if (toDate != null && toDate.before(now)) {
                                writer.writeNext(
                                    new String[] { email, fromDate == null ? "" : csvDate.format(fromDate),
                                        csvDate.format(toDate), "", couponCode.getCode() });
                            }
                        }
                    }
                }
            }
        }
    }

    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 8
Project: geeCommerce-Java-Shop-Software-and-PIM   File: DiscountPromotionResource.java   Source Code and License Vote up 5 votes
@GET
@Path("{id}/export/all")
public Response getEmailExportAll(@PathParam("id") Id id, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"all.csv\"");
    PrintWriter printWriter = response.getWriter();
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(new String[] { "E-mail", "From", "To", "Used", "Code" });

    DiscountPromotion p = checked(service.get(DiscountPromotion.class, id));
    if (p != null) {
        Coupon c = p.getCoupon();
        if (c != null) {
            List<CouponCode> couponCodes = this.couponCodes.thatBelongTo(c);
            if (couponCodes != null) {
                for (CouponCode couponCode : couponCodes) {
                    String code = couponCode.getCode();
                    String email = couponCode.getEmail() == null ? Str.EMPTY : couponCode.getEmail();
                    String used = couponCode.getCouponUsages() != null && couponCode.getCouponUsages().size() > 0
                        ? (couponCode.getCouponUsages().get(0).getUsageDate() != null
                            ? csvDate.format(couponCode.getCouponUsages().get(0).getUsageDate()) : "---")
                        : "";
                    String exported = couponCode.getExportedDate() != null
                        ? csvDate.format(couponCode.getExportedDate()) : "";
                    Date fromDate = DateTimes.maxOfDates(c.getFromDate(), couponCode.getFromDate());
                    Date toDate = DateTimes.minOfDates(c.getToDate(), couponCode.getToDate());

                    writer.writeNext(new String[] { email, fromDate == null ? "" : csvDate.format(fromDate),
                        toDate == null ? "" : csvDate.format(toDate), used, code });
                }
            }
        }
    }

    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 9
Project: ICDClassifier   File: ExperimentalCipeClassifier.java   Source Code and License Vote up 5 votes
public void printBaseline(CSVWriter writer) {
	String[] baseline = { "0", "0", "0", "0", "0", "0", "0" };
	writer.writeNext(baseline);
	try {
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 10
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillDistributionsCSV(CSVWriter writer) throws IOException {
    writer.writeNext(DISTRIBUTIONS_HEADER);
    SortedSet<Long> times = new TreeSet<>(blockchainInfo.getTimeInfos().keySet());
    for (Long time : times) {
        SortedSet<Integer> sizes = new TreeSet<>(blockchainInfo.getTimeInfos().get(time).keySet());
        for (Integer size : sizes) {
            TimeInfo t = blockchainInfo.getTimeInfos().get(time).get(size);
            String[] entry = {String.valueOf(time), String.valueOf(t.getTimeAndSize().getSizeSpan().getBlockSizeMin()),
                    String.valueOf(t.getTimeAndSize().getSizeSpan().getBlockSizeMax()),
                    String.valueOf(t.getMediumDstrbTime95()), String.valueOf(t.getMediumDstrbTime100())};
            writer.writeNext(entry);
            writer.flush();
        }
    }
}
 
Example 11
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillNumberOfNodesCSV(CSVWriter writer) throws IOException {
    writer.writeNext(NUMBER_OF_NODES_HEADER);
    SortedSet<Long> times = new TreeSet<>(blockchainInfo.getTimeToNumNodes().keySet());
    for (Long time : times) {
        String[] entry = {String.valueOf(time), String.valueOf(blockchainInfo.getTimeToNumNodes().get(time))};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 12
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillIntensitiesCSV(CSVWriter writer) throws IOException {
    writer.writeNext(INTENSIIES_HEADER);
    SortedSet<Long> times = new TreeSet<>(blockchainInfo.getTimeToIntensities().keySet());
    for (Long time : times) {
        String[] entry = {String.valueOf(time), String.valueOf(blockchainInfo.getTimeToIntensities().get(time))};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 13
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillTransactionsCSV(CSVWriter writer) throws IOException {
    writer.writeNext(TRANSACTIONS_HEADER);
    for (TransactionInfo transactionInfo : blockchainInfo.getTransactions().values()) {
        String[] entry = {String.valueOf(transactionInfo.getTransactionId()),
                String.valueOf(transactionInfo.getBlockId()),
                String.valueOf(transactionInfo.getTransactionSize()),
                String.valueOf(transactionInfo.getTime()),
                String.valueOf(transactionInfo.getNodeId())};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 14
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillBlocksCSV(CSVWriter writer) throws IOException {
    writer.writeNext(BLOCKS_HEADER);
    for (BlockInfo blockDistributionInfo : blockchainInfo.getBlocks().values()) {
        String[] entry = {String.valueOf(blockDistributionInfo.getBlockId()),
                String.valueOf(blockDistributionInfo.getCreationTime()),
                String.valueOf(blockDistributionInfo.getDistributionTime95()),
                String.valueOf(blockDistributionInfo.getDistributionTime100()),
                String.valueOf(blockDistributionInfo.getVerificationTime())};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 15
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillUnverifiedTransactionsCSV(CSVWriter writer) throws IOException {
    writer.writeNext(UNVERIFIED_HEADER);
    SortedSet<Long> times = new TreeSet<>(blockchainInfo.getTimeToUnverifiedTransactions().keySet());
    for (Long time : times) {
        String[] entry = {String.valueOf(time), String.valueOf(blockchainInfo.getTimeToUnverifiedTransactions().get(time))};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 16
Project: liferaylms-portlet   File: CourseStats.java   Source Code and License Vote up 5 votes
private void endCsv(ResourceResponse resourceResponse, CSVWriter writer)
		throws IOException {
	writer.flush();
	writer.close();
	resourceResponse.getPortletOutputStream().flush();
	resourceResponse.getPortletOutputStream().close();
}
 
Example 17
Project: gatk-protected   File: DecomposeSingularValues.java   Source Code and License Vote up 5 votes
private void writeMatrix(final RealMatrix m, final File outputFilename) throws IOException {
    final List<String []> textTable = new ArrayList<>();
    for (int i = 0; i < m.getRowDimension(); i ++){
        textTable.add(Arrays.stream(m.getRow(i)).mapToObj(Double::toString).toArray(String[]::new));
    }
    final FileWriter fw = new FileWriter(outputFilename);
    CSVWriter csvWriter = new CSVWriter(fw, '\t', CSVWriter.NO_QUOTE_CHARACTER);
    csvWriter.writeAll(textTable);
    csvWriter.flush();
    csvWriter.close();
}
 
Example 18
Project: spring-usc   File: Data2Features.java   Source Code and License Vote up 5 votes
public static void Testdata2CSV(Vector<String> tests, String fpath,
		RecordFeatureSet rf) {
	try {
		CSVWriter writer = new CSVWriter(new FileWriter(new File(fpath)));
		// get attribute names
		// get attribute names
		Collection<String> attrStrings = rf.getFeatureNames();
		String[] attr_names = attrStrings.toArray(new String[attrStrings
				.size() + 1]);
		attr_names[attr_names.length - 1] = "label";
		writer.writeNext(attr_names);
		for (String Record : tests) {
			Vector<String> row = new Vector<String>();
			Collection<Feature> cf = rf.computeFeatures(Record, "");
			Feature[] x = cf.toArray(new Feature[cf.size()]);
			// row.add(f.getName());
			for (int k = 0; k < cf.size(); k++) {
				row.add(String.valueOf(x[k].getScore()));
			}
			row.add("");
			String[] dataEntry = row.toArray(new String[row.size()]);
			writer.writeNext(dataEntry);
		}
		writer.flush();
		writer.close();
	} catch (Exception ex) {
		ex.printStackTrace();
	}
}
 
Example 19
Project: spring-usc   File: Data2Features.java   Source Code and License Vote up 5 votes
public static void Traindata2CSV(
		HashMap<String, Vector<String>> class2Records, String fpath,
		RecordFeatureSet rf) {
	try {
		CSVWriter writer = new CSVWriter(new FileWriter(new File(fpath)));
		Vector<String> vsStrings = new Vector<String>();
		for (Vector<String> vecs : class2Records.values()) {
			vsStrings.addAll(vecs);
		}
		// get attribute names
		Collection<String> attrStrings = rf.getFeatureNames();
		String[] attr_names = attrStrings.toArray(new String[attrStrings
				.size() + 1]);
		attr_names[attr_names.length - 1] = "label";
		writer.writeNext(attr_names);
		for (String label : class2Records.keySet()) {

			for (String Record : class2Records.get(label)) {
				Vector<String> row = new Vector<String>();
				Collection<Feature> cf = rf.computeFeatures(Record, label);
				Feature[] x = cf.toArray(new Feature[cf.size()]);
				// row.add(f.getName());
				for (int k = 0; k < cf.size(); k++) {
					row.add(String.valueOf(x[k].getScore()));
				}
				row.add(label); // change this according to the dataset.
				String[] dataEntry = row.toArray(new String[row.size()]);
				writer.writeNext(dataEntry);
			}

		}
		writer.flush();
		writer.close();
	} catch (Exception ex) {
		logger.error("" + Arrays.toString(ex.getStackTrace()));
	}
}
 
Example 20
Project: springfield   File: CsvView.java   Source Code and License Vote up 5 votes
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	
	response.setContentType(CONTENT_TYPE);
	response.setCharacterEncoding("euc-kr");


	Object rootObject = filterModel(model);
	if(modelFilter != null){
		rootObject = modelFilter.extractOutputModel(model);
	}
	
	String url = (String)model.get("springfield.response.viewName");
	String name = guessFileName(rootObject);
	if(name == null){
		name = url != null ? StringUtils.getFilename(url) : "CsvView";
	}
	
	
	String encodedFilename = new String(name.getBytes("euc-kr") , "8859_1"); 
	response.setHeader("Content-Disposition", "attachment; filename=\""+encodedFilename+".csv\"");
	logger.warn("Dowloading CSV name is " + encodedFilename);

	
	PrintWriter out = response.getWriter();
	CSVWriter writer = new CSVWriter(out);
	buildEmptyCSVDocument(writer, rootObject);
	writer.flush();
	writer.close();

}
 
Example 21
Project: DF14_Demo   File: FileProcessor.java   Source Code and License Vote up 5 votes
public static File generateMonthlyUsageData(File inputFile, String fieldName, File outputFile) throws IOException {
	CSVReader reader = new CSVReader(new FileReader(inputFile));
	String[] cols;
	int fieldIndex = -1;
	CSVWriter writer = new CSVWriter(new FileWriter(outputFile), ',', '"', '\\', "\n");
	cols = reader.readNext(); 
	System.out.println(cols.length);
	writer.writeNext(cols);
	writer.flush();
	for(String str : cols) {
		System.out.println(str);
	}
	//TO find the index position of field for which we are going to add Monthly Date Diff.
	for(int i = 0; i < cols.length; i++) {
		if(cols[i].trim().equalsIgnoreCase(fieldName)) {
			fieldIndex	= i;
			cols = reader.readNext();
			break;
		}
	}
	
	if(fieldIndex > -1) {
	
		while(cols != null) {
			int monthDiff = Integer.parseInt(cols[fieldIndex]);
			cols[fieldIndex] = DateUtil.addMonths(new Date(), monthDiff, "yyyy-MM-dd");
			writer.writeNext(cols);
			writer.flush();
			cols = reader.readNext();
		}
		
	}
	else
		throw new RuntimeException("The input file : " + inputFile.getAbsolutePath() + " did not have the required field name : " + fieldName);
	
	return outputFile;
}
 
Example 22
Project: DF14_Demo   File: FileProcessor.java   Source Code and License Vote up 5 votes
public static File generateWeeklyUsageData(File inputFile, String fieldName, File outputFile) throws IOException {
	CSVReader reader = new CSVReader(new FileReader(inputFile));
	String[] cols;
	int fieldIndex = -1;
	CSVWriter writer = new CSVWriter(new FileWriter(outputFile), ',', '"', '\\', "\n");
	cols = reader.readNext(); 
	System.out.println(cols.length);
	writer.writeNext(cols);
	writer.flush();
	for(String str : cols) {
		System.out.println(str);
	}
	//TO find the index position of field for which we are going to add Monthly Date Diff.
	for(int i = 0; i < cols.length; i++) {
		if(cols[i].trim().equalsIgnoreCase(fieldName)) {
			fieldIndex	= i;
			cols = reader.readNext();
			break;
		}
	}
	
	if(fieldIndex > -1) {
	
		while(cols != null) {
			int weekDiff = Integer.parseInt(cols[fieldIndex]);
			cols[fieldIndex] = DateUtil.addWeeks(new Date(), weekDiff, "yyyy-MM-dd");
			writer.writeNext(cols);
			writer.flush();
			cols = reader.readNext();
		}
		
	}
	else
		throw new RuntimeException("The input file : " + inputFile.getAbsolutePath() + " did not have the required field name : " + fieldName);
	
	return outputFile;
}
 
Example 23
Project: DF14_Demo   File: FileProcessor.java   Source Code and License Vote up 5 votes
public static File generateResponseSubmissionDate(File inputFile, String fieldName, File outputFile) throws IOException {
	CSVReader reader = new CSVReader(new FileReader(inputFile));
	String[] cols;
	int fieldIndex = -1;
	CSVWriter writer = new CSVWriter(new FileWriter(outputFile), ',', '"', '\\', "\n");
	cols = reader.readNext(); 
	System.out.println(cols.length);
	writer.writeNext(cols);
	writer.flush();
	for(String str : cols) {
		System.out.println(str);
	}
	//TO find the index position of field for which we are going to add Monthly Date Diff.
	for(int i = 0; i < cols.length; i++) {
		if(cols[i].trim().equalsIgnoreCase(fieldName)) {
			fieldIndex	= i;
			cols = reader.readNext();
			break;
		}
	}
	
	if(fieldIndex > -1) {
		while(cols != null) {
			int daysDiff = Integer.parseInt(cols[fieldIndex]);
			cols[fieldIndex] = DateUtil.addDays(new Date(),daysDiff, "yyyy-MM-dd'T'HH:mm:ss");
			writer.writeNext(cols);
			writer.flush();
			cols = reader.readNext();
		}
	}
	else
		throw new RuntimeException("The input file : " + inputFile.getAbsolutePath() + " did not have the required field name : " + fieldName);
	
	return outputFile;
}
 
Example 24
Project: streaminggraphpartitioning   File: NormalizedVariables.java   Source Code and License Vote up 4 votes
@Test
public void test() throws FileNotFoundException, IOException {
	File fold = new File(FOLDER);
	for (File f : fold.listFiles(p -> p.getName().endsWith(".graph"))) {
		log.info("Test for : " + f.getName());
		writer = new CSVWriter(new FileWriter(new File(f.getName() + ".csv")));
		writer.writeNext(header);
		for (int k = 2; k < MAX_PARTS; k*=2) 
			for (double A = 0.1; A < 10.0; A+=STEP) {
				for (double B = 0.1; B < 10.0; B+= STEP) {
					for (double C = 0.1; C < 10.0; C+=STEP) {
						log.info("Testing for A: " + A + ", B: " + B + " , C: " + C);
						for (int i = 0; i < ITER_TIME; i++) {
							SGPHeuristic heuristic = new LinearAbsoluteWeightedDispersionBased(A, B,C, true);
							GraphLoader gl = new TraversingGraphLoader(new FileInputStream(f), new FileOutputStream(f+"-r"),
									k, heuristic, -1, false, new BFSTraversing());
							gl.runPartition();
							QualityChecker qc = new ParallelQualityChecker();
							String[] res = {
									f.getName(),
									Integer.toString(gl.getNodeNumbers()),
									Integer.toString(gl.getEdgeNumbers()),
									Integer.toString(k),
									Double.toString(A),
									Double.toString(B),
									Double.toString(C),
									qc.getCuttingEdgesCount(gl.getGraphPartitionator().getGraph()).toString(),
									qc.getCuttingEdgeRatio(gl.getGraphPartitionator().getGraph()).toString(),
									ITER_TIME.toString()
							};
							writer.writeNext(res);
							writer.flush();
						}
					}
				}
			}
			writer.close();
		
	}

}
 
Example 25
Project: geeCommerce-Java-Shop-Software-and-PIM   File: DiscountPromotionResource.java   Source Code and License Vote up 4 votes
@GET
@Path("{id}/export/ordered")
public Response getEmailExportOrdered(@PathParam("id") Id id, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"ordered-emails.csv\"");
    PrintWriter printWriter = response.getWriter();
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(new String[] { "E-mail", "From", "To", "Used", "Code" });

    DiscountPromotion p = checked(service.get(DiscountPromotion.class, id));
    if (p != null) {
        Coupon c = p.getCoupon();
        if (c != null) {
            List<CouponCode> couponCodes = c.getCodes();
            if (couponCodes != null) {
                for (CouponCode couponCode : couponCodes) {
                    if (couponCode.getEmail() != null) {
                        String email = couponCode.getEmail();
                        if (couponCode.getCouponUsages() != null && couponCode.getCouponUsages().size() > 0) {
                            Date fromDate = DateTimes.maxOfDates(c.getFromDate(), couponCode.getFromDate());
                            Date toDate = DateTimes.minOfDates(c.getToDate(), couponCode.getToDate());
                            String used = couponCode.getCouponUsages() != null
                                && couponCode.getCouponUsages().size() > 0
                                    ? (couponCode.getCouponUsages().get(0).getUsageDate() != null
                                        ? csvDate.format(
                                            couponCode.getCouponUsages().get(0).getUsageDate())
                                        : "---")
                                    : "";
                            writer.writeNext(new String[] { email, fromDate == null ? "" : csvDate.format(fromDate),
                                toDate == null ? "" : csvDate.format(toDate), used, couponCode.getCode() });
                        }
                    }
                }
            }
        }
    }

    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 26
Project: geeCommerce-Java-Shop-Software-and-PIM   File: DiscountPromotionResource.java   Source Code and License Vote up 4 votes
@GET
@Path("{id}/export/gifts")
public Response getEmailExportGifts(@PathParam("id") Id id, @Context HttpServletResponse response)
    throws IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"gifts.csv\"");
    OutputStream os = response.getOutputStream();
    os.write(239); // 0xEF
    os.write(187); // 0xBB
    os.write(191); // 0xBF
    OutputStreamWriter printWriter = new OutputStreamWriter(os, "UTF-8");
    CSVWriter writer = new CSVWriter(printWriter, ';');
    writer.writeNext(
        new String[] { "Code", "E-mail", "Forename", "Surname", "Address", "ZIP", "City", "Gift-ID", "Gift" });

    DiscountPromotion p = checked(service.get(DiscountPromotion.class, id));
    List<DiscountPromotionSubscription> dpSubscriptions = discountPromotionSubscriptions.subscribedOnPromotion(id);

    if (p != null) {
        Coupon c = p.getCoupon();
        if (c != null) {
            if (dpSubscriptions != null) {
                for (DiscountPromotionSubscription dpSubscription : dpSubscriptions) {
                    String code = dpSubscription.getCouponCode();
                    String email = dpSubscription.getEmail();
                    String firstName = dpSubscription.getForm() == null ? ""
                        : (String) dpSubscription.getForm().get("firstName");
                    String lastName = dpSubscription.getForm() == null ? ""
                        : (String) dpSubscription.getForm().get("lastName");
                    String address = dpSubscription.getForm() == null ? ""
                        : (String) dpSubscription.getForm().get("address");
                    String zip = dpSubscription.getForm() == null ? ""
                        : (String) dpSubscription.getForm().get("zip");
                    String city = dpSubscription.getForm() == null ? ""
                        : (String) dpSubscription.getForm().get("city");
                    String giftId = dpSubscription.getGiftId().toString();
                    String gift = getGift(dpSubscription.getGiftId(), p);

                    writer.writeNext(
                        new String[] { code, email, firstName, lastName, address, zip, city, giftId, gift });
                }

            }
        }
    }

    writer.flush();
    writer.close();

    return Response.ok().build();
}
 
Example 27
Project: liferaylms-portlet   File: OfflineActivity.java   Source Code and License Vote up 4 votes
@Override
public void serveResource(ResourceRequest resourceRequest,
		ResourceResponse resourceResponse) throws IOException,
		PortletException {
	ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
	String action = ParamUtil.getString(resourceRequest, "action");
	long actId = ParamUtil.getLong(resourceRequest, "actId",0);


	if(action.equals("export")){

		try {

			CalificationType ct = new CalificationTypeRegistry().getCalificationType(CourseLocalServiceUtil.getCourseByGroupCreatedId(themeDisplay.getScopeGroupId()).getCalificationType());

			//Necesario para crear el fichero csv.
			resourceResponse.setCharacterEncoding(StringPool.UTF8);
			resourceResponse.setContentType(ContentTypes.TEXT_CSV_UTF8);
			resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=data.csv");
			byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};

			resourceResponse.getPortletOutputStream().write(b);

			CSVWriter writer = new CSVWriter(new OutputStreamWriter(resourceResponse.getPortletOutputStream(),StringPool.UTF8),CharPool.SEMICOLON);
			String[] cabeceras = new String[4];


			//En esta columna vamos a tener el nombre del usuario.
			cabeceras[0]= LanguageUtil.get(getPortletConfig(), themeDisplay.getLocale(), "onlinetaskactivity.export.user");
			cabeceras[1]= LanguageUtil.get(getPortletConfig(), themeDisplay.getLocale(), "onlinetaskactivity.export.date");
			cabeceras[2]= LanguageUtil.get(getPortletConfig(), themeDisplay.getLocale(), "onlinetaskactivity.export.result");
			cabeceras[3]= LanguageUtil.get(getPortletConfig(), themeDisplay.getLocale(), "onlinetaskactivity.export.comment");

			writer.writeNext(cabeceras);
			DynamicQuery dq=DynamicQueryFactoryUtil.forClass(LearningActivityResult.class);
			Criterion criterion=PropertyFactoryUtil.forName("actId").eq(actId);
			dq.add(criterion);

			//Partiremos del usuario para crear el csv para que sea más facil ver los intentos.
			List<LearningActivityResult> listresult = LearningActivityResultLocalServiceUtil.dynamicQuery(dq);
			for(LearningActivityResult learningActivityResult:listresult){
				//Array con los resultados de los intentos.
				String[] resultados = new String[4];
				//En la primera columna del csv introducidos el nombre del estudiante.
				resultados[0] = UserLocalServiceUtil.getUser(learningActivityResult.getUserId()).getScreenName();
				resultados[1] = _dateFormat.format(learningActivityResult.getEndDate());
				resultados[2] = ct.translate(themeDisplay.getLocale(), themeDisplay.getScopeGroupId(), learningActivityResult.getResult());
				resultados[3] = learningActivityResult.getComments()!=null?learningActivityResult.getComments():"";

				//Escribimos las respuestas obtenidas para el intento en el csv.
				writer.writeNext(resultados);
			}
			writer.flush();
			writer.close();
			resourceResponse.getPortletOutputStream().flush();
			resourceResponse.getPortletOutputStream().close();

		} catch (NestableException e) {

		}finally{
			resourceResponse.getPortletOutputStream().flush();
			resourceResponse.getPortletOutputStream().close();
		}
	} 
}
 
Example 28
Project: liferaylms-portlet   File: GeneralStats.java   Source Code and License Vote up 4 votes
@Override
public void serveResource(ResourceRequest resourceRequest,
		ResourceResponse resourceResponse) throws IOException,
		PortletException {
	String action = ParamUtil.getString(resourceRequest, "action");
	long[] courseIds=ParamUtil.getLongValues(resourceRequest, "courseIds");
	ThemeDisplay themeDisplay  =(ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
	if(action.equals("export")){
		try
		{
		String charset = LanguageUtil.getCharset(themeDisplay.getLocale());
		if (Validator.isNull(charset)) {
			charset = LanguageUtil.getCharset(LocaleUtil.getDefault());
		}
		charset = StringPool.UTF8;
		resourceResponse.setCharacterEncoding(charset);
		resourceResponse.setContentType("text/csv;charset="+charset);
		resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=generalstats."+Long.toString(System.currentTimeMillis())+".csv");
		if (StringPool.UTF8.equals(charset)) {
	        byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
	        resourceResponse.getPortletOutputStream().write(b);
		}
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(resourceResponse.getPortletOutputStream(),charset),';');
        String[] linea=new String[8];
        linea[0]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.name");
        linea[1]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.registered");
        linea[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.starts.course");
        linea[3]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.ends.course");
        linea[4]=LanguageUtil.get(themeDisplay.getLocale(),"closed");
        linea[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.marks.average");
        linea[6]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulecounter");
        linea[7]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.activitiescounter");
        writer.writeNext(linea);
        long[] userExcludedIds = null;
        for(long courseId:courseIds)
        {
        	Course course=CourseLocalServiceUtil.getCourse(courseId);
        	userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course);
	        linea=new String[8];
	        linea[0]=course.getTitle(themeDisplay.getLocale());
	        		        
			long registered=CourseLocalServiceUtil.countStudents(courseId, themeDisplay.getCompanyId(), null, null, null, null, false);
			long iniciados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsStarted(courseId, userExcludedIds) : 0;
			long finalizados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFinished(courseId, userExcludedIds) : 0;
			double avgResult=0;
			if(finalizados>0){
				avgResult=CourseResultLocalServiceUtil.avgResultByCourseIdUserExcludedIds(course.getCourseId(), true, userExcludedIds);
			}
			long activitiesCount=LearningActivityLocalServiceUtil.countLearningActivitiesOfGroup(course.getGroupCreatedId());
			long modulesCount=ModuleLocalServiceUtil.countByGroupId(course.getGroupCreatedId());
			String closed=course.getClosed()?LanguageUtil.get(themeDisplay.getLocale(),"yes"):LanguageUtil.get(themeDisplay.getLocale(),"no");
			
			linea[1]=Long.toString(registered);
			linea[2]=Long.toString(iniciados);
			linea[3]=Long.toString(finalizados);
			DecimalFormat df = new DecimalFormat("#.#");
			linea[4]=closed;
			linea[5]=df.format(avgResult);
			linea[6]=Long.toString(modulesCount);
			linea[7]=Long.toString(activitiesCount);
	        writer.writeNext(linea);
	        //resourceResponse.getPortletOutputStream().write(b);
        }
        writer.flush();
		writer.close();
		resourceResponse.getPortletOutputStream().flush();
		resourceResponse.getPortletOutputStream().close();
		
		}
		catch(Exception e)
		{
			
		}
	}
}
 
Example 29
Project: scouter   File: CounterPastLongDateAllView.java   Source Code and License Vote up 4 votes
@Override
protected IStatus run(IProgressMonitor monitor) {
	try {
		TimedSeries<String, Double> sereis = new TimedSeries<String, Double>();
		Range xRange = xyGraph.primaryXAxis.getRange();
		long lower = (long) xRange.getLower();
		long upper = (long) xRange.getUpper();
		List<Trace> traceList = xyGraph.getPlotArea().getTraceList();
		List<String> titleValues = new ArrayList<String>();
		titleValues.add("Time");
		for (Trace t : traceList) {
			titleValues.add(t.getName());
			CircularBufferDataProvider provider = (CircularBufferDataProvider) t.getDataProvider();
			for (int inx = 0; inx < provider.getSize(); inx++) {
				Sample sample = (Sample) provider.getSample(inx);
				double x = sample.getXValue();
				if(x < lower || x > upper) {
					continue;
				}
				double y = sample.getYValue();
				sereis.add(t.getName(), (long)x, y);
			}
		}
		List<String[]> values = new ArrayList<String[]>();
		values.add(titleValues.toArray(new String[titleValues.size()]));
		while (lower < upper) {
			List<String> value = new ArrayList<String>();
			value.add(DateUtil.format(lower, "yyyy-MM-dd HH:mm"));
			for (int i = 1; i < titleValues.size(); i++) {
				String objName = titleValues.get(i);
				Double d = sereis.getInTime(objName, lower, DateUtil.MILLIS_PER_FIVE_MINUTE - 1);
				if (d != null) {
					value.add(FormatUtil.print(d.doubleValue(), "#,###.##"));
				} else {
					value.add("");
				}
			}
			values.add(value.toArray(new String[value.size()]));
			lower += DateUtil.MILLIS_PER_FIVE_MINUTE;
		}
		CSVWriter cw = new CSVWriter(new FileWriter(filePath));
		cw.writeAll(values);
		cw.flush();
		cw.close();
	} catch (Exception e) {
		e.printStackTrace();
		return Status.CANCEL_STATUS;
	}
	return Status.OK_STATUS;
}
 
Example 30
Project: scouter   File: CounterPastTimeAllView.java   Source Code and License Vote up 4 votes
@Override
protected IStatus run(IProgressMonitor monitor) {
	try {
		TimedSeries<String, Double> sereis = new TimedSeries<String, Double>();
		Range xRange = xyGraph.primaryXAxis.getRange();
		long lower = (long) xRange.getLower();
		long upper = (long) xRange.getUpper();
		List<Trace> traceList = xyGraph.getPlotArea().getTraceList();
		List<String> titleValues = new ArrayList<String>();
		titleValues.add("Time");
		for (Trace t : traceList) {
			titleValues.add(t.getName());
			CircularBufferDataProvider provider = (CircularBufferDataProvider) t.getDataProvider();
			for (int inx = 0; inx < provider.getSize(); inx++) {
				Sample sample = (Sample) provider.getSample(inx);
				double x = sample.getXValue();
				if(x < lower || x > upper) {
					continue;
				}
				double y = sample.getYValue();
				sereis.add(t.getName(), (long)x, y);
			}
		}
		List<String[]> values = new ArrayList<String[]>();
		values.add(titleValues.toArray(new String[titleValues.size()]));
		while (lower < upper) {
			List<String> value = new ArrayList<String>();
			value.add(DateUtil.format(lower, "HH:mm:ss"));
			for (int i = 1; i < titleValues.size(); i++) {
				String objName = titleValues.get(i);
				Double d = sereis.getInTime(objName, lower, 3000);
				if (d != null) {
					value.add(FormatUtil.print(d.doubleValue(), "#,###.##"));
				} else {
					value.add("");
				}
			}
			values.add(value.toArray(new String[value.size()]));
			lower += 2000;
		}
		CSVWriter cw = new CSVWriter(new FileWriter(filePath));
		cw.writeAll(values);
		cw.flush();
		cw.close();
	} catch (Exception e) {
		e.printStackTrace();
		return Status.CANCEL_STATUS;
	}
	return Status.OK_STATUS;
}
 
Example 31
Project: appformer   File: DataSetExportServicesImpl.java   Source Code and License Vote up 4 votes
public org.uberfire.backend.vfs.Path exportDataSetCSV(DataSet dataSet) {
    try {
        if (dataSet == null) {
            throw new IllegalArgumentException("Null dataSet specified!");
        }
        int columnCount = dataSet.getColumns().size();
        int rowCount = dataSet.getRowCount();

        List<String[]> lines = new ArrayList<>(rowCount+1);

        String[] line = new String[columnCount];
        for (int cc = 0; cc < columnCount; cc++) {
            DataColumn dc = dataSet.getColumnByIndex(cc);
            line[cc] = dc.getId();
        }
        lines.add(line);

        for (int rc = 0; rc < rowCount; rc++) {
            line = new String[columnCount];
            for (int cc = 0; cc < columnCount; cc++) {
                line[cc] = formatAsString(dataSet.getValueAt(rc, cc));
            }
            lines.add(line);
        }

        String tempCsvFile = uuidGenerator.newUuid() + ".csv";
        Path tempCsvPath = gitStorage.createTempFile(tempCsvFile);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(tempCsvPath)));
        CSVWriter writer = new CSVWriter(bw,
                DEFAULT_SEPARATOR_CHAR.charAt(0),
                DEFAULT_QUOTE_CHAR.charAt(0),
                DEFAULT_ESCAPE_CHAR.charAt(0));
        writer.writeAll(lines);
        writer.close();
        writer.flush();
        writer.close();
        return Paths.convert(tempCsvPath);
    }
    catch (Exception e) {
        throw exceptionManager.handleException(e);
    }
}
 
Example 32
Project: dashbuilder   File: DataSetExportServicesImpl.java   Source Code and License Vote up 4 votes
public org.uberfire.backend.vfs.Path exportDataSetCSV(DataSet dataSet) {
    try {
        if (dataSet == null) {
            throw new IllegalArgumentException("Null dataSet specified!");
        }
        int columnCount = dataSet.getColumns().size();
        int rowCount = dataSet.getRowCount();

        List<String[]> lines = new ArrayList<>(rowCount+1);

        String[] line = new String[columnCount];
        for (int cc = 0; cc < columnCount; cc++) {
            DataColumn dc = dataSet.getColumnByIndex(cc);
            line[cc] = dc.getId();
        }
        lines.add(line);

        for (int rc = 0; rc < rowCount; rc++) {
            line = new String[columnCount];
            for (int cc = 0; cc < columnCount; cc++) {
                line[cc] = formatAsString(dataSet.getValueAt(rc, cc));
            }
            lines.add(line);
        }

        String tempCsvFile = uuidGenerator.newUuid() + ".csv";
        Path tempCsvPath = gitStorage.createTempFile(tempCsvFile);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(tempCsvPath)));
        CSVWriter writer = new CSVWriter(bw,
                DEFAULT_SEPARATOR_CHAR.charAt(0),
                DEFAULT_QUOTE_CHAR.charAt(0),
                DEFAULT_ESCAPE_CHAR.charAt(0));
        writer.writeAll(lines);
        writer.close();
        writer.flush();
        writer.close();
        return Paths.convert(tempCsvPath);
    }
    catch (Exception e) {
        throw exceptionManager.handleException(e);
    }
}