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

The following are Jave code examples for showing how to use close() 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: winter   File: CSVDataSetFormatter.java   Source Code and License Vote up 7 votes
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @throws IOException
 */
public void writeCSV(File file, DataSet<RecordType, SchemaElementType> dataset)
		throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

	String[] headers = getHeader(dataset);
	if(headers!=null) {
		writer.writeNext(headers);
	}

	for (RecordType record : dataset.get()) {
		String[] values = format(record, dataset);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 2
Project: three-things-today   File: ThreeThingsDatabase.java   Source Code and License Vote up 6 votes
public synchronized String exportDatabaseToCsvString() {
    StringWriter stringWriter = new StringWriter();
    CSVWriter csvWriter = new CSVWriter(stringWriter);
    csvWriter.writeNext(ThreeThingsEntry.COLUMNS);

    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + ThreeThingsEntry.TABLE_NAME, null);
    while (cursor.moveToNext()) {
        List<String> data = new ArrayList(ThreeThingsEntry.COLUMNS.length);
        for (String column : ThreeThingsEntry.COLUMNS) {
            data.add(cursor.getString(cursor.getColumnIndexOrThrow(column)));
        }
        csvWriter.writeNext(data.toArray(new String[0]));
    }

    try {
        csvWriter.close();
    } catch (IOException e) {
        // Ignore.
    }

    return stringWriter.toString();
}
 
Example 3
Project: incubator-sdap-mudrod   File: DataGenerator.java   Source Code and License Vote up 6 votes
/**
 * Writes newly calculated and equally distributed vector data to user specified CSV file.
 *
 * @param list finalized vector data to write to user specified output file
 */
public static void writeCSVfile(List<List<String>> list) {
  String outputFile = myResultDir;
  boolean alreadyExists = new File(outputFile).exists();

  try {
    CSVWriter csvOutput = new CSVWriter(new FileWriter(outputFile), ','); // Create new instance of CSVWriter to write to file output

    if (!alreadyExists) {
      csvOutput.writeNext(myHeader); // Write the text headers first before data

      for (int i = 0; i < list.size(); i++) // Iterate through all rows in 2D array
      {
        String[] temp = new String[list.get(i).size()]; // Convert row array list in 2D array to regular string array
        temp = list.get(i).toArray(temp);
        csvOutput.writeNext(temp); // Write this array to the file
      }
    }

    csvOutput.close(); // Close csvWriter
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 4
Project: winter   File: CSVFormatter.java   Source Code and License Vote up 6 votes
/**
 * Writes the data set to a CSV file
 * 
 * @param file
 * @param dataset
 * @throws IOException
 */
public void writeCSV(File file, Processable<RecordType> dataset)
		throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

	String[] headers = getHeader();
	if(headers!=null) {
		writer.writeNext(headers);
	}

	for (RecordType record : dataset.get()) {
		String[] values = format(record);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 5
Project: streaminggraphpartitioning   File: AllGraphDetails.java   Source Code and License Vote up 6 votes
public void testDetails() throws IOException, InterruptedException {
	File fold = new File(FOLDER);
	CSVWriter wr = new CSVWriter(new FileWriter(new File(FOLDER + GRAPH_DETAILS)),'&');
	printHeader(wr);
	for (File fpin: fold.listFiles(p -> p.getName().endsWith(".graph"))) { 
		//if (fpin.getName().equals("auto.graph")) continue;
		log.info("Analyzing graph : " + fpin.getName());
		GraphAnalyser ga = new GraphAnalyser(new FileInputStream(fpin), wr, log);
		String grName = fpin.getName().substring(0, fpin.getName().length() - ".graph".length());
		ga.runLoad(grName);
		ga = null;
		System.gc();
	}
	
	wr.close();
}
 
Example 6
Project: mudrod   File: DataGenerator.java   Source Code and License Vote up 6 votes
/**
 * Writes newly calculated and equally distributed vector data to user specified CSV file.
 *
 * @param list finalized vector data to write to user specified output file
 */
public static void writeCSVfile(List<List<String>> list) {
  String outputFile = myResultDir;
  boolean alreadyExists = new File(outputFile).exists();

  try {
    CSVWriter csvOutput = new CSVWriter(new FileWriter(outputFile), ','); // Create new instance of CSVWriter to write to file output

    if (!alreadyExists) {
      csvOutput.writeNext(myHeader); // Write the text headers first before data

      for (int i = 0; i < list.size(); i++) // Iterate through all rows in 2D array
      {
        String[] temp = new String[list.get(i).size()]; // Convert row array list in 2D array to regular string array
        temp = list.get(i).toArray(temp);
        csvOutput.writeNext(temp); // Write this array to the file
      }
    }

    csvOutput.close(); // Close csvWriter
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 7
Project: geoxygene   File: SocialGraph.java   Source Code and License Vote up 6 votes
public static void writeSimpleWeightedGraph2CSV(SimpleWeightedGraph<Long, DefaultWeightedEdge> colocationgraph,
		File file) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[4];
	line[0] = "source";
	line[1] = "target";
	line[2] = "weight";
	line[3] = "type";
	writer.writeNext(line);
	for (DefaultWeightedEdge e : colocationgraph.edgeSet()) {
		line = new String[4];
		line[0] = String.valueOf(colocationgraph.getEdgeSource(e).longValue() + (long) 111);
		line[1] = String.valueOf(colocationgraph.getEdgeTarget(e).longValue() + (long) 111);
		line[2] = String.valueOf(colocationgraph.getEdgeWeight(e));
		line[3] = "undirected";
		writer.writeNext(line);
	}
	writer.close();
}
 
Example 8
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 6 votes
public static void extractRandomConfigs(String inputFile, String outputFile, int nConfigs, int nIterations) throws IOException{
	CSVReader lines = new CSVReader(new FileReader(inputFile), ',');
	List<String[]> content = lines.readAll();
	
	for (int i=0; i<nIterations;i++){
		System.out.println(content.isEmpty());
		// Shuffle list
		Collections.shuffle(content);
		int randomNum = ThreadLocalRandom.current().nextInt(1, content.size() - nConfigs);
		// Write lines
		CSVWriter writer = new CSVWriter(new FileWriter(outputFile+(i+1)+".csv", true),';');
		for(int j=randomNum;j<=randomNum+nConfigs-1;j++){
			writer.writeNext(content.get(j));
		}
		writer.close();
	}
	
	lines.close();
}
 
Example 9
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 10
Project: FinanceAnalytics   File: SecurityFieldMappingTemplateGenerator.java   Source Code and License Vote up 6 votes
@Override
protected void doRun() throws Exception {
  CSVWriter csvWriter = new CSVWriter(new FileWriter(getCommandLine().getArgs()[0]));
  SecurityMaster securityMaster = getToolContext().getSecurityMaster();
  SecurityMetaDataRequest metaRequest = new SecurityMetaDataRequest();
  SecurityMetaDataResult metaData = securityMaster.metaData(metaRequest);
  for (String securityType : metaData.getSecurityTypes()) {
    s_logger.info("Processing security type " + securityType);
    SecuritySearchRequest searchRequest = new SecuritySearchRequest();
    searchRequest.setName("*");
    searchRequest.setSecurityType(securityType);
    searchRequest.setPagingRequest(PagingRequest.ONE);
    SecuritySearchResult search = securityMaster.search(searchRequest);
    s_logger.info("Search returned " + search.getPaging().getTotalItems() + " securities");
    dumpSecurityStructure(csvWriter, securityType, search.getFirstSecurity());
  }
  csvWriter.close();
}
 
Example 11
Project: cloudstreetmarket.com   File: YahooQuoteMessageConverter.java   Source Code and License Vote up 6 votes
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 12
Project: cloudstreetmarket.com   File: YahooHistoMessageConverter.java   Source Code and License Vote up 6 votes
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 13
Project: cloudstreetmarket.com   File: YahooIntraDayHistoMessageConverter.java   Source Code and License Vote up 6 votes
@Override
protected void writeInternal(QuoteWrapper quotes, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(httpOutputMessage.getBody()));
    for (YahooQuote quote : quotes) {
        writer.writeNext(
        		new String[]{	quote.getId(),
        						quote.getName(),
        						String.valueOf(quote.getOpen()),
        						String.valueOf(quote.getPreviousClose()),
                				String.valueOf(quote.getLast()),
                        		String.valueOf(quote.getLastChange()),
                        		String.valueOf(quote.getLastChangePercent()),
                        		String.valueOf(quote.getHigh()),
                        		String.valueOf(quote.getLow()),
                        		String.valueOf(quote.getBid()),
                        		String.valueOf(quote.getAsk()),
                        		String.valueOf(quote.getVolume()),
        						quote.getExchange(),
        						quote.getCurrency()
        		});
    }

    writer.close();
}
 
Example 14
Project: Leboncoin   File: Persistence.java   Source Code and License Vote up 6 votes
private synchronized boolean persist(String id, String hash, boolean append) throws IOException
{
    // Append
    CSVReader reader = new CSVReader(new FileReader(NameFactory.PERSISTENCE_CSV));
    List<String[]> allEntries = reader.readAll();
    for (String[] entry : allEntries)
    {
        if (entry[0].equals(hash))
        {
            reader.close();
            return false;
        }
    }
    reader.close();

    CSVWriter writer = new CSVWriter(new FileWriter(NameFactory.PERSISTENCE_CSV, append));
    String[] entries = new String[2];
    entries[0] = hash;
    entries[1] = id;
    writer.writeNext(entries);
    writer.close();
    return true;
}
 
Example 15
Project: Leboncoin   File: Persistence.java   Source Code and License Vote up 6 votes
public synchronized void flush()
{
    try
    {
        CSVWriter writer = new CSVWriter(new FileWriter(NameFactory.PERSISTENCE_CSV, false));
        writer.close();
    }
    catch (IOException e)
    {
        Logger.traceERROR(e);
    }

    if (getSize() != 0)
    {
        Logger.traceERROR("PERSISTENCE - Persistence flush failed. Program will exit.");
        App.kill();
    }
}
 
Example 16
Project: solrmeter   File: FullQueryStatisticController.java   Source Code and License Vote up 6 votes
public void writeCSV(File file) throws IOException {
   	FileWriter writer = new FileWriter(file);
   	CSVWriter csvWriter = new CSVWriter(writer);
   	
	for (QueryLogValue query : queryLogStatistic.getLastQueries()) {
		String[] cols = new String[] {
				String.valueOf(query.isError()),
				query.getQueryString(),
				query.getFacetQueryString(),
				query.getFilterQueryString(),
				query.getQTime().toString(),
				query.getResults().toString()
		};
		csvWriter.writeNext(cols);
	}
	
	csvWriter.close();
}
 
Example 17
Project: sisob-data-extractor   File: CrawlerTrace.java   Source Code and License Vote up 6 votes
public void close()
{
    for(String key : urls_trace_files.keySet())
    {
        CSVWriter writer = this.urls_trace_files.get(key);
        if(writer != null){
            try {
                writer.close();
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, ex.getMessage(), ex);                    
            }
            urls_trace_files.put(key, null);
        }            
    }
    urls_trace_files.clear();
    urls_trace_files = null;
}
 
Example 18
Project: ScreenSlicer   File: Spreadsheet.java   Source Code and License Vote up 6 votes
public static String csv(List<List<String>> rows) {
  StringWriter sw = new StringWriter();
  CSVWriter writer = new CSVWriter(sw);
  try {
    List<String[]> elements = new ArrayList<String[]>();
    for (List<String> row : rows) {
      elements.add(row.toArray(new String[0]));
    }
    writer.writeAll(elements);
    return sw.toString();
  } finally {
    try {
      writer.close();
    } catch (IOException e) {
      Log.exception(e);
    }
  }
}
 
Example 19
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 20
Project: winter   File: CSVCorrespondenceFormatter.java   Source Code and License Vote up 5 votes
/**
 * Writes the data set to a CSV file
 * @param file
 * @param dataset
 * @throws IOException
 */
public <TypeA extends Matchable, TypeB extends Matchable> void writeCSV(File file, Processable<Correspondence<TypeA, TypeB>> dataset)
		throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(file));

	for (Correspondence<TypeA, TypeB> record : dataset.get()) {
		String[] values = format(record);

		writer.writeNext(values);
	}

	writer.close();
}
 
Example 21
Project: streaminggraphpartitioning   File: SocialGraphTest.java   Source Code and License Vote up 5 votes
public void testStreet() throws HeuristicNotFound, IOException, InterruptedException, IllegalArgumentException, IllegalAccessException {
	File fold = new File(SOCIAL_FOLDER);
	//seq
	File[] files = fold.listFiles(p -> p.getName().endsWith(".graph"));
	for (File fpin: files) {
		String graphName = SOCIAL_FOLDER + fpin.getName();
		
		String[] ords = {".bfs",".dfs",""};
		
		File fpout = new File(SOCIAL_FOLDER + OUTPUT_FILE);
		writer = new CSVWriter(new FileWriter(new File(SOCIAL_FOLDER+ CSV_FOLDER +fpin.getName() + CSV_SUFFIX)),' ');
		Integer C = -1;
		for (int i = 0; i < ITERATION_TIME; i++) {
			File graphNameBfs = new File(graphName + ".bfs." + i);
			File graphNameDfs = new File(graphName + ".dfs." + i);
			
			log.info("Making BSF graph: " + i);
			OrdinatorGraphLoader ogl = new OrdinatorGraphLoader(new FileInputStream(fpin), new FileOutputStream(graphNameBfs),
					new BFSTraversing());
			ogl.runPartition();
			log.info("Making DFS graph: " + i);
			OrdinatorGraphLoader ogld = new OrdinatorGraphLoader(new FileInputStream(fpin), new FileOutputStream(graphNameDfs),
					new DFSTraversing());
			ogld.runPartition();
			
		}
		for (int oi = 0; oi < ords.length; oi++) {
			String ord = ords[oi];
			File graphFile = new File(graphName+ord);
			writer.writeNext(HEADER);
			for (int k = 2; k <= MAX_PARTITION_SIZE; k*=2) {
				log.info("Test for: " + graphFile.getName() + " with "+k+
						"partitions using " + ord +" started");
				socialHeuristicTest(graphFile, fpout, k, C, 
						fpin.getName(), log, true, ord == "" ? "rnd" : ord);
			}
		}
		writer.close();
	}
}
 
Example 22
Project: streaminggraphpartitioning   File: BufferGraphTest.java   Source Code and License Vote up 5 votes
public void testStreet() throws HeuristicNotFound, IOException, InterruptedException, IllegalArgumentException, IllegalAccessException {
	File fold = new File(FOLDER);
	//seq
	for (File fpin: fold.listFiles(p -> p.getName().endsWith(".graph"))) {
		String graphName = FOLDER + fpin.getName();

		String[] ords = {".bfs",".dfs",""};

		File fpout = new File(FOLDER + OUTPUT_FILE);
		writer = new CSVWriter(new FileWriter(new File(FOLDER + CSV_FOLDER +fpin.getName() + CSV_SUFFIX)),' ');
		Integer C = -1;
		for (int i = 0; i < ITERATION_TIME; i++) {
			File graphNameBfs = new File(graphName + ".bfs." + i);
			File graphNameDfs = new File(graphName + ".dfs." + i);

			log.info("Making BSF graph: " + i);
			OrdinatorGraphLoader ogl = new OrdinatorGraphLoader(new FileInputStream(fpin), new FileOutputStream(graphNameBfs),
					new BFSTraversing());
			ogl.runPartition();
			log.info("Making DFS graph: " + i);
			OrdinatorGraphLoader ogld = new OrdinatorGraphLoader(new FileInputStream(fpin), new FileOutputStream(graphNameDfs),
					new DFSTraversing());
			ogld.runPartition();

		}
		for (int oi = 0; oi < ords.length; oi++) {
			String ord = ords[oi];
			File graphFile = new File(graphName+ord);
			writer.writeNext(HEADER);
			for (int k = 2; k <= MAX_PARTITION_SIZE; k*=2) {
				log.info("Test for: " + graphFile.getName() + " with "+k+
						"partitions using " + ord +" started");
				allHeuristicsTestCompareSimple(graphFile, fpout, k, C, 
						fpin.getName(), log, true, ord == "" ? "rnd" : ord);
			}
		}
		writer.close();
	}
}
 
Example 23
Project: murmur   File: RangzenService.java   Source Code and License Vote up 5 votes
/**
 * Logs events to a CSV file on external storage.
 * TODO(lerner): Log to file instead of just to console!
 *
 * @param row String array of column values for the CSV.
 */
private void logEventToCSV(String[] row) {
  try { 
    Log.i(TAG, row.toString());
    String BENCHMARK_FILENAME = "benchmarks.csv";
    FileWriter file = new FileWriter(new File(getBenchmarkDataDir(), BENCHMARK_FILENAME));
    CSVWriter writer = new CSVWriter(file, ',', '\'');
    writer.writeNext(row);

    file.close();
    writer.close();
  } catch (IOException e) {
    Log.e(TAG, "Failed to write to CSV: " + e);
  }
}
 
Example 24
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 25
Project: geoxygene   File: IntrinsicAssessment.java   Source Code and License Vote up 5 votes
public static void writeContributionDetails(File file, Set<OSMResource> myJavaObjects) throws IOException {
	// Create a CSV writer
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[9];
	line[0] = "id";
	line[1] = "version";
	line[2] = "changeset";
	line[3] = "uid";
	line[4] = "contributeur";
	line[5] = "date";
	line[6] = "source";
	line[7] = "nbTags";
	line[8] = "OSMResource.getGeom()";

	writer.writeNext(line);

	for (OSMResource resource : myJavaObjects) {

		// OSMNode node = (OSMNode) resource.getGeom();
		// OSMWay way = (OSMWay) resource.getGeom();
		line = new String[9];
		line[0] = Long.toString(resource.getId());
		line[1] = Integer.toString(resource.getVersion());
		line[2] = Integer.toString(resource.getChangeSet());
		line[3] = Integer.toString(resource.getUid());
		line[4] = resource.getContributeur();
		line[5] = resource.getDate().toString();
		line[6] = resource.getSource();
		line[7] = Integer.toString(resource.getNbTags());
		line[8] = resource.getGeom().getClass().getSimpleName();
		writer.writeNext(line);

	}
	writer.close();
}
 
Example 26
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 5 votes
/**
 * create CSVfile JHipster and heads of the file
 * 
 * @param filename Name of the CSVfile
 * @param List of lines)
 *  
 */
public static void createCSVFileJHipster(String filename) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(filename), ';');
	String[] heads = {"Id","JHipsterRegister","Docker","applicationType","authenticationType","hibernateCache",
			"clusteredHttpSession","websocket","databaseType","devDatabaseType","prodDatabaseType",
			"buildTool","searchEngine","enableSocialSignIn","useSass","enableTranslation","testFrameworks","Generate",
			"Log-Gen","TimeToGenerate","Compile","Log-Compile","TimeToCompile","Build","Log-Build", "TimeToBuildDockerPackage", "TimeToBuild", 
			"ImageDocker","TestsResult", "Cucumber","KarmaJS","Gatling","Protractor","CoverageInstructions","CoverageBranches","JSStatementsCoverage","JSBranchesCoverage"};
	writer.writeNext(heads);
	writer.close();
}
 
Example 27
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 5 votes
/**
 * create CSVfile Coverage and heads of the file
 * 
 * @param filename Name of the CSVfile
 * @param List of lines)
 *  
 */
public static void createCSVFileCoverage(String filename) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(filename), ';');
	String[] heads = {"Id","JHipsterRegister","GROUP","PACKAGE","CLASS","INSTRUCTION_MISSED","INSTRUCTION_COVERED",
			"BRANCH_MISSED","BRANCH_COVERED","LINE_MISSED","LINE_COVERED","COMPLEXITY_MISSED",
			"COMPLEXITY_COVERED","METHOD_MISSED","METHOD_COVERED"};
	writer.writeNext(heads);
	writer.close();
}
 
Example 28
Project: sqlpower-library   File: TableModelCSVFormatter.java   Source Code and License Vote up 5 votes
/**
 * Outputs a table in HTML that represents the TableModel. Only the rows
 * given will be written to the file.
 */
public void formatToStream(TableModel model, PrintWriter writer, int[] selectedRows) {
	try {
		CSVWriter csvWriter = new CSVWriter(writer);
		List<String[]> tableExport = new ArrayList<String[]>();
		int columnCount = model.getColumnCount();
		String[] rowArray = new String[columnCount];
		for (int i = 0; i < columnCount; i++) {
			rowArray[i] = model.getColumnName(i);
		}
		tableExport.add(rowArray);
		for (int row = 0; row < selectedRows.length; row++) {
			rowArray = new String[columnCount];
			for (int col = 0; col < columnCount; col++) {
				Object value = model.getValueAt(selectedRows[row], col);
				if (value != null) {
				    if (columnFormatters.get(col) != null) {
				        rowArray[col] = columnFormatters.get(col).format(value);
				    } else {
				        rowArray[col] = value.toString();
				    }
				} else {
					rowArray[col] = "";
				}
			}
			tableExport.add(rowArray);
		}
		csvWriter.writeAll(tableExport);
		csvWriter.close();

	} catch (IOException ex) {
		throw new RuntimeException("Could not close the CSV Writer", ex);
	}		
}
 
Example 29
Project: fhaes   File: CategoryEditor.java   Source Code and License Vote up 5 votes
/**
 * Writes all category entries to the specified csv file.
 * 
 * @param filePath
 */
private void saveCategoriesToFile(String filePath) {
	
	try
	{
		CSVWriter writer = new CSVWriter(new FileWriter(filePath), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, "\r\n");
		ArrayList<FHCategoryEntry> categoryEntries = getAllCategoryEntries();
		
		String[] headerLine = new String[FHCategoryReader.NUM_COLUMNS_IN_FILE];
		headerLine[FHCategoryReader.INDEX_OF_HEADER] = FHCategoryReader.FHAES_CATEGORY_FILE_HEADER;
		headerLine[FHCategoryReader.INDEX_OF_VERSION] = FHCategoryReader.FHAES_CATEGORY_FILE_VERSION;
		headerLine[FHCategoryReader.INDEX_OF_FILENAME] = workingFile.getFileNameWithoutExtension();
		writer.writeNext(headerLine);
		
		for (int i = 0; i < categoryEntries.size(); i++)
		{
			String[] nextLine = new String[FHCategoryReader.NUM_COLUMNS_IN_FILE];
			nextLine[FHCategoryReader.INDEX_OF_SERIES_TITLE] = categoryEntries.get(i).getSeriesTitle();
			nextLine[FHCategoryReader.INDEX_OF_CATEGORY] = categoryEntries.get(i).getCategory();
			nextLine[FHCategoryReader.INDEX_OF_CONTENT] = categoryEntries.get(i).getContent();
			writer.writeNext(nextLine);
		}
		
		writer.close();
		
		MainWindow.getInstance().getFeedbackMessagePanel().updateFeedbackMessage(FeedbackMessageType.INFO,
				FeedbackDisplayProtocol.AUTO_HIDE, FeedbackDictionary.CATEGORY_FILE_SAVED_MESSAGE.toString());
	}
	catch (IOException ex)
	{
		ex.printStackTrace();
	}
}
 
Example 30
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 31
Project: sakai   File: DownloadEventBean.java   Source Code and License Vote up 5 votes
private void csvSpreadsheet(OutputStream os, List<SignupMeetingWrapper> meetingWrappers) throws IOException {
	
	CSVExport export = new CSVExport(meetingWrappers, getSakaiFacade());
	
	CSVWriter writer = new CSVWriter(new OutputStreamWriter(os), ',');
    
	//header
	List<String> header = export.getHeaderRow();
	
	int cols = header.size(); //total number of columns is based on header row
	
	String[] headerRow = new String[cols];
	headerRow = header.toArray(headerRow);
	writer.writeNext(headerRow);
	
	//data rows
	List<List<String>> data = export.getDataRows();
	Iterator<List<String>> iter = data.iterator();
	while(iter.hasNext()) {
		List<String> row = iter.next();
		String[] dataRow = new String[cols];
		dataRow = row.toArray(dataRow);
		writer.writeNext(dataRow);
	}
	
	writer.close();
	
}
 
Example 32
Project: IDRT-Import-and-Mapping-Tool   File: DBImportWizard.java   Source Code and License Vote up 5 votes
/**
 * Writes the config file for the DBImport
 * 
 * @param itemList
 *            Lists of Items
 * @param tmpTableFile
 *            Output Temp File
 */
private void writeTableConfigFile(List<List<String>> itemList,
		File tmpTableFile) {
	try {
		CSVWriter rotatedOutput = new CSVWriter(
				new FileWriter(tmpTableFile), '\t');
		String[] nextLine = new String[itemList.size() + 1];
		nextLine[0] = "configTmp";
		if (itemList != null) {
			for (int i = 0; i < itemList.size(); i++) {
				nextLine[i + 1] = itemList.get(i).get(HEADERCOLUMN);
			}
			rotatedOutput.writeNext(nextLine);

			for (int i = 0; i < itemList.size(); i++) {
				nextLine[i + 1] = itemList.get(i).get(DATATYPECOLUMN);
			}
			rotatedOutput.writeNext(nextLine);
			for (int i = 0; i < itemList.size(); i++) {
				nextLine[i + 1] = itemList.get(i).get(NAMECOLUMN);
			}
			rotatedOutput.writeNext(nextLine);
			for (int i = 0; i < itemList.size(); i++) {
				nextLine[i + 1] = itemList.get(i).get(TOOLTIPCOLUMN);
			}
			rotatedOutput.writeNext(nextLine);
			for (int i = 0; i < itemList.size(); i++) {
				nextLine[i + 1] = itemList.get(i).get(METADATACOLUMN);
			}
			rotatedOutput.writeNext(nextLine);
		}
		rotatedOutput.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 33
Project: l10n-maven-plugin   File: PropertiesFamilyValidator.java   Source Code and License Vote up 5 votes
private void writeCsv(List<String> entries, File csvFile) {
  try {
    CSVWriter writer = new CSVWriter(new FileWriter(csvFile));
    writer.writeNext(entries.toArray(new String[entries.size()]));
    writer.close();

  } catch (IOException e) {
    throw new L10nValidationException("Could not write csv file", e);
  }
}
 
Example 34
Project: ezid-crawler   File: InclusiveFilter.java   Source Code and License Vote up 5 votes
public static void main(final String[] args) throws IOException {
    final List<String> patterns = new ArrayList<String>();
    final CSVReader iReader = new CSVReader(new FileReader(StringUtils.format("{}_includes.csv", args[0])));
    final CSVReader sReader = new CSVReader(new FileReader(StringUtils.format("{}_ezid.csv", args[0])));
    final CSVWriter writer = new CSVWriter(new FileWriter(StringUtils.format("{}_filtered.csv", args[0])));

    String[] sourceData;
    String[] includes;

    while ((includes = iReader.readNext()) != null) {
        final String include = ".*\\/" + includes[0].replace("*", ".*");

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding an include pattern to the list of includes: {}", include);
        }

        patterns.add(include);
    }

    while ((sourceData = sReader.readNext()) != null) {
        for (int index = 0; index < patterns.size(); index++) {
            if (sourceData[1].matches(patterns.get(index).replace("+", "\\+"))) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Adding file to the list to be ingested: {}", sourceData[0], sourceData[1]);
                }

                writer.writeNext(sourceData);
            }
        }
    }

    iReader.close();
    sReader.close();
    writer.close();
}
 
Example 35
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 36
Project: jeplusplus   File: JEPlusProject.java   Source Code and License Vote up 5 votes
/**
 * Scales the JEPlus results by a multiplicative factor. All columns in the
 * JEPlus output file will be scaled.
 * 
 * @param factor
 *            a scaling factor
 * @throws FileNotFoundException
 *             if unable to find the results file
 * @throw IOException if unable to write the scaled results
 */
public void scaleResults(double factor) throws IOException {

	File rawFile = outdir.resolve("SimResults.csv").toFile();

	if (!rawFile.exists()) {
		throw new FileNotFoundException("Unable to find the results file.");
	}

	// Load the results
	InputStream is = new FileInputStream(rawFile);
	CSVReader reader = new CSVReader(new InputStreamReader(is));
	List<String[]> rawLines = reader.readAll();
	reader.close();

	// Write the results to the new file applying the scaling
	int nHeaderRows = 1;
	File scaledFile = outdir.resolve("SimResults-scaled.csv").toFile();
	Writer output = new BufferedWriter(new FileWriter(scaledFile));
	CSVWriter writer = new CSVWriter(output);
	int lineCount = 0;
	for (String[] s : rawLines) {
		lineCount++;
		if (lineCount <= nHeaderRows) {
			writer.writeNext(s);
		} else {
			for (int i = 3; i < s.length; i++) {
				double val = Double.valueOf(s[i]);
				s[i] = String.valueOf(val * factor);
			}
			writer.writeNext(s);
		}
	}
	writer.close();

}
 
Example 37
Project: edemocracia   File: ExportacaoCSV.java   Source Code and License Vote up 5 votes
public static void getContribuicoesCSV(final Long groupId, final Writer writer) throws SystemException, SQLException, IOException, PortalException {
	final CSVWriter csvWriter = new CSVWriter(writer,';');
	final List<ContribuicaoWrapper> dados = WikiLegisServiceUtil.exportaContribuicoes(groupId);
	exportar(ContribuicaoWrapper.class, dados, csvWriter);
	csvWriter.close();
	writer.close();
}
 
Example 38
Project: edemocracia   File: ExportacaoCSV.java   Source Code and License Vote up 5 votes
public static void getComentariosCSV(final Long groupId, final Writer writer) throws SystemException, SQLException, IOException, PortalException {
	final CSVWriter csvWriter = new CSVWriter(writer,';');
	final List<ComentarioWrapper> dados = WikiLegisServiceUtil.exportaComentarios(groupId);
	exportar(ComentarioWrapper.class, dados, csvWriter);
	csvWriter.close();
	writer.close();
}
 
Example 39
Project: hhmi-exp   File: EdgelMatching.java   Source Code and License Vote up 5 votes
public void computeAndWriteEdgelMatches(String fn, Edgel testEdgel) throws IOException{
	logger.info(" saving edgels to " + fn);
	CSVWriter csvWriter = new CSVWriter(new FileWriter(fn),',');
	 
	ArrayList<Edgel> matches = candidateEdgels( testEdgel );
	filterEdgelsByNormal(testEdgel, matches);
	String[] row = null;
	
	matches.add( testEdgel );
	
	int k = 0;
	for ( Edgel e : matches ){
		
		k = 0;
       	if( row == null){
       		row = new String[ 1 + 2*( e.numDimensions()) ];
       	}
       	
       	for(int i=0; i<e.numDimensions(); i++){
       		row[k++] = Double.toString( e.getDoublePosition(i) );
       	}
       	for(int i=0; i<e.numDimensions(); i++){
       		row[k++] = Double.toString( e.getGradient()[i] );
       	}
       	row[k++] = Double.toString( e.getMagnitude() );
		
       	csvWriter.writeNext(row);
	}
	
	csvWriter.close();
}
 
Example 40
Project: lens   File: CSVSerde.java   Source Code and License Vote up 5 votes
@Override
public Writable serialize(Object obj, ObjectInspector objInspector) throws SerDeException {
  final StructObjectInspector outputRowOI = (StructObjectInspector) objInspector;
  final List<? extends StructField> outputFieldRefs = outputRowOI.getAllStructFieldRefs();

  if (outputFieldRefs.size() != numCols) {
    throw new SerDeException("Cannot serialize the object because there are " + outputFieldRefs.size()
      + " fields but the table has " + numCols + " columns.");
  }

  try {
    // Get all data out.
    for (int c = 0; c < numCols; c++) {
      final Object field = outputRowOI.getStructFieldData(obj, outputFieldRefs.get(c));
      // Get the field objectInspector and the field object.
      ObjectInspector fieldOI = outputFieldRefs.get(c).getFieldObjectInspector();

      outputFields[c] = serializeField(field, fieldOI);
    }

    final StringWriter writer = new StringWriter();
    final CSVWriter csv = newWriter(writer, separatorChar, quoteChar, escapeChar);

    csv.writeNext(outputFields);
    csv.close();

    return new Text(writer.toString());
  } catch (final IOException ioe) {
    throw new SerDeException(ioe);
  }
}
 
Example 41
Project: axelor-business-suite   File: AddressServiceImpl.java   Source Code and License Vote up 5 votes
public int export(String path) throws IOException {
	List<Address> addresses = (List<Address>) addressRepo.all().filter("self.certifiedOk IS FALSE").fetch();
	
	CSVWriter csv = new CSVWriter(new java.io.FileWriter(path), "|".charAt(0), CSVWriter.NO_QUOTE_CHARACTER);
	List<String> header = new ArrayList<String>();
	header.add("Id");
	header.add("AddressL1");
	header.add("AddressL2");
	header.add("AddressL3");
	header.add("AddressL4");
	header.add("AddressL5");
	header.add("AddressL6");
	header.add("CodeINSEE");
	
	csv.writeNext(header.toArray(new String[header.size()]));
	List<String> items = new ArrayList<String>();
	for (Address a : addresses) {
		
		items.add(a.getId() != null ? a.getId().toString(): "");
		items.add(a.getAddressL2() != null ? a.getAddressL2(): "");
		items.add(a.getAddressL3() != null ? a.getAddressL3(): "");
		items.add(a.getAddressL4() != null ? a.getAddressL4(): "");
		items.add(a.getAddressL5() != null ? a.getAddressL5(): "");
		items.add(a.getAddressL6() != null ? a.getAddressL6(): "");
		items.add(a.getInseeCode() != null ? a.getInseeCode(): "");
		
		csv.writeNext(items.toArray(new String[items.size()]));
		items.clear();
	}
	csv.close();
	LOG.info("{} exported", path);
	
	return addresses.size();
}
 
Example 42
Project: sakai   File: DownloadEventBean.java   Source Code and License Vote up 5 votes
private void csvSpreadsheet(OutputStream os, List<SignupMeetingWrapper> meetingWrappers) throws IOException {
	
	CSVExport export = new CSVExport(meetingWrappers, getSakaiFacade());
	
	CSVWriter writer = new CSVWriter(new OutputStreamWriter(os), ',');
    
	//header
	List<String> header = export.getHeaderRow();
	
	int cols = header.size(); //total number of columns is based on header row
	
	String[] headerRow = new String[cols];
	headerRow = header.toArray(headerRow);
	writer.writeNext(headerRow);
	
	//data rows
	List<List<String>> data = export.getDataRows();
	Iterator<List<String>> iter = data.iterator();
	while(iter.hasNext()) {
		List<String> row = iter.next();
		String[] dataRow = new String[cols];
		dataRow = row.toArray(dataRow);
		writer.writeNext(dataRow);
	}
	
	writer.close();
	
}
 
Example 43
Project: MuSe   File: FileProvider.java   Source Code and License Vote up 5 votes
/**
 * Create CSV file out of the content of the entries array.
 * 
 * @param entries
 *          List of entry arrays. Each array represents one entry in the file.
 * @throws SQLException
 */
public void arrayToCSV(ArrayList<String[]> entries) throws IOException,
    SQLException {
  CSVWriter writer = new CSVWriter(new FileWriter(filePath), ',',
      CSVWriter.NO_QUOTE_CHARACTER);
  for (String[] entry : entries) {
    writer.writeNext(entry);
  }
  writer.close();
}
 
Example 44
Project: AIMSICDL   File: AIMSICDDbAdapter.java   Source Code and License Vote up 4 votes
/**
 * Description:     Prepares the CSV file used to upload new data to the OCID server.
 *
 * Issues:          TODO:
 *                  [ ] Add "act" in upload data for the DBi_measure:RAT
 *                  [ ] function getOCIDSubmitData() is not fully working ==> DB join not yet implemented
 *                  [ ] skip (or change) progress bar, since CSV write is too fast to be seen.
 *
 * Note:            Q: Where is this file?
 *                  A: It is wherever your device has mounted its SDCard.
 *                     For example, in:  /data/media/0/AIMSICD/OpenCellID
 *
 *                 OCID CSV upload format:
 *                  "cellid"        = CID (in UMTS long format)
 *                  "measured_at"   = time
 *                  "rating"        = gpsd_accu
 *                  "act"           = RAT (TEXT):
 *                                     1xRTT, CDMA, eHRPD, IS95A, IS95B, EVDO_0, EVDO_A, EVDO_B,
 *                                     UMTS, HSPA+, HSDPA, HSUPA, HSPA, LTE, EDGE, GPRS, GSM
 *
 */
public boolean prepareOpenCellUploadData() {
    boolean result;

    File dir = new File(mExternalFilesDirPath + "OpenCellID/");
    if (!dir.exists()) {
        result = dir.mkdirs();
        if (!result) {
            return false;
        }
    }
    File file = new File(dir, "aimsicd-ocid-data.csv");

    try {
        // Get data not yet submitted:
        Cursor c = getOCIDSubmitData();
        // Check if we have something to upload:
        if (c.getCount() > 0) {
            if (!file.exists()) {
                result = file.createNewFile();
                if (!result) {
                    c.close();
                    return false;
                }

                // OCID CSV upload format and items
                // mcc,mnc,lac,cellid,lon,lat,signal,measured_at,rating,speed,direction,act,ta,psc,tac,pci,sid,nid,bid
                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                // TODO: Add "act"
                csvWrite.writeNext("mcc,mnc,lac,cellid,lon,lat,signal,measured_at,rating");

                int size = c.getCount();
               Log.d(TAG, mTAG + "OCID UPLOAD: row count = " + size);

                while (c.moveToNext()) {
                    csvWrite.writeNext(
                            String.valueOf(c.getInt(c.getColumnIndex("MCC"))),
                            String.valueOf(c.getInt(c.getColumnIndex("MNC"))),
                            String.valueOf(c.getInt(c.getColumnIndex("LAC"))),
                            String.valueOf(c.getInt(c.getColumnIndex("CID"))),
                            c.getString(c.getColumnIndex("gpsd_lon")),
                            c.getString(c.getColumnIndex("gpsd_lat")),
                            c.getString(c.getColumnIndex("rx_signal")),
                            c.getString(c.getColumnIndex("time")),
                            //c.getString(c.getColumnIndex("RAT")),                     // OCID: "act" TODO
                            String.valueOf(c.getInt(c.getColumnIndex("gpsd_accu"))));
                }
                csvWrite.close();
                c.close();
            }
            return true;
        }
        c.close();
        return false;
    } catch (Exception e) {
       Log.e(TAG, mTAG + "prepareOpenCellUploadData(): Error creating OpenCellID Upload Data: ", e);
        return false;
    }
}
 
Example 45
Project: T2KMatch   File: ExtractedTriple.java   Source Code and License Vote up 4 votes
public static void writeCSV(File f, Collection<ExtractedTriple> triples) throws IOException {
	CSVWriter w = new CSVWriter(new FileWriter(f));
	
	w.writeNext(new String[] {
			"URL",
			"Table",
			"Column Index",
			"Subject URI",
			"Subject Value",
			"Subject Confidence",
			"Predicate URI",
			"Predicate Value",
			"Predicate Confidence",
			"Data Type",
			"Object Value",
			"Object Value in KB",
			"Object Value matches KB",
			"Object Value Similarity"
	});
	
	for(ExtractedTriple t : triples) {
		w.writeNext(new String[] {
				t.getSourceURL(),
				t.getSourceTable(),
				Integer.toString(t.getSourceColumnIndex()),
				t.getSubjectURI(),
				t.getSubjectValue(),
				Double.toString(t.getSubjectConfidence()),
				t.getPredicateURI(),
				t.getPredicateValue(),
				Double.toString(t.getPredicateConfidence()),
				t.getDataType().toString(),
				t.getObjectValue(),
				t.getObjectValueInKB(),
				Boolean.toString(t.isObjectValueMatchesKB()),
				Double.toString(t.getEvaluatedSimilarity())
		});
	}
	
	w.close();
}
 
Example 46
Project: T2KMatch   File: GoldStandardConverter.java   Source Code and License Vote up 4 votes
public void convertOldGStoNewGS() throws IOException{
	HashMap<String, Integer> tableIndices = web.getTableIndices();
	HashMap<Integer, Integer> keyIndices = web.getKeyIndices();
	
	CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(new FileOutputStream(writeLocation)));
	
	List<File> instanceGS = null;
   	
   	if(readLocation.isDirectory()) {
   		instanceGS = Arrays.asList(readLocation.listFiles());
   	} else {
   		instanceGS = Arrays.asList(new File[] { readLocation});
   	}
   	
   	for(MatchableTableRow trow : web.getRecords().get()){
   		SecondForLoop:
   		for(File f : instanceGS){
   			if(tableIndices.get(f.getName()) != null){
   				int tableID = tableIndices.get(f.getName());
   				if(trow.getTableId()==tableID){
   					if(trow.get(keyIndices.get(tableID))!=null){
   						CSVReader csvReader = new CSVReader(new InputStreamReader(new FileInputStream(f)));
   			    		String[] values;
   			    		while((values = csvReader.readNext()) != null){
   			    			String dbResourceLink = values[0];
   			    			String entity = values[1].replaceAll("\\s", "");
   			    			if(trow.get(keyIndices.get(tableID)).toString().replaceAll("\\s", "").equals(entity)){
   	    						String[] rowGS = {trow.getIdentifier(), dbResourceLink, "TRUE"};
   	    	    				csvWriter.writeNext(rowGS);
   	    	    				csvReader.close();
   	    	    				break SecondForLoop;
   	    	    			} else{
   	    	    				continue;
   	    	    			}
   			    		}
   			    		csvReader.close();
   					}
   				}
   			}
   		}
   	}
   	
   	csvWriter.close();
}
 
Example 47
Project: ICDClassifier   File: ClassifierRunner.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {

		// TODO modo interativo

		// TODO unificar dataset para morpho e topo e não precisar importar
		// mais. Usar Remove?

		final List<Configuration> configs = new ArrayList<Configuration>();

		Set<Sections> sections = new HashSet<Sections>();
		sections.add(Sections.MACROSCOPY);
		sections.add(Sections.MICROSCOPY);
		sections.add(Sections.CYTOPATHOLOGY);
		sections.add(Sections.OTHERS);
		sections.add(Sections.CONCLUSION);
		sections.add(Sections.LIQUID_CYTOPATHOLOGY);

		double cost;
		int power[] = {-7, -3, -11};
		for (int p : power) {
			cost = Math.pow(2, p);
			configs.add(new Configuration(sections, Criteria.MANY_REPORT_ONE_REGISTRY, Classifiers.SVM,
					WeightingSchemes.TFIDF, SmoothingTechniques.ADD_ONE, cost, Sources.ALL, false, 1,
					SentenceDetectors.NONE, Tokenizers.WORD, Stemmers.NONE, Chunkers.NONE, Targets.TOPOGRAPHY_GROUP, 1,
					-1, MetastasisStatus.NONM1));

		}

		ExperimentalCipeClassifier c;

		CSVWriter writer = ExperimentalCipeClassifier.getWriter("evaluation.csv");

		for (Configuration config : configs) {
			Constants.CONFIG = config;

			LOG.info("Let's begin.");
			LOG.info(config.getStringRepresentation());
			c = new ExperimentalCipeClassifier();

			LOG.info("Let's print corpus stats to a file.");
			c.printCorpusStats();

			// LOG.info("Single evaluation.");
			// c.singleEvaluate();

			// LOG.info("Results as CSV");
			// c.resultsAsCsv(new File("icdc-27-rgh.csv"), 1);

			LOG.info("Cross validation");
			c.crossValidate();
			c.printStatsAsCsvLine(writer, Double.toString(config.getSvmCostParameter()));

			LOG.info("Let's print stats to a file.");
			c.printStats();
			//
			LOG.info("Let's print classifier details to a file.");
			c.printClassifier();

			// LOG.info("Increasing words.");
			// c.increasingWords();

			// LOG.info("Increasing cross-validate.");
			// c.increasingCrossValidate();
		}

		writer.close();

		LOG.info("Finished");
	}
 
Example 48
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 49
Project: ICDClassifier   File: CipeClassifier.java   Source Code and License Vote up 4 votes
public void resultsAsCsv(File file, int threshold) {
	// TODO DRY singleEvaluate()
	int totalSize = dataset.numInstances();
	int testSize = (int) (totalSize * Constants.TEST_RATIO);
	int trainSize = totalSize - testSize;

	final Random rand = new Random(42);
	dataset.randomize(rand);

	Instances trainSet = new Instances(dataset, 0, trainSize);
	Instances testSet = new Instances(dataset, trainSize, testSize);

	try {
		model.buildClassifier(trainSet);

		Instances filteredTestSet = Filter.useFilter(testSet, ((FilteredClassifier) model).getFilter());

		Instance original = null;
		Instance filtered = null;

		CSVWriter writer = new CSVWriter(new FileWriter(file), ';');

		String[] header = { "raw", "filtered", "correct", "decided", "pos", "rgh", "year", "m", "ec" };
		writer.writeNext(header);

		for (int i = 0; i < testSet.numInstances(); i++) {
			original = testSet.instance(i);
			filtered = filteredTestSet.instance(i);

			double[] dist = model.distributionForInstance(original);
			double cls = model.classifyInstance(original);

			int pos = getCorrectPosition(dist, original.classValue());
			if (pos < threshold)
				continue;

			// inst.setValue((Attribute) attributes.elementAt(0), id);
			// inst.setValue((Attribute) attributes.elementAt(1), year);
			// inst.setValue((Attribute) attributes.elementAt(2), text);
			// inst.setValue((Attribute) attributes.elementAt(3), m);
			// inst.setValue((Attribute) attributes.elementAt(4), ec);
			// inst.setValue((Attribute) attributes.elementAt(5), code);

			String rawText = original.toString(2);
			String correctCode = original.toString(5);
			String filteredText = buildBagWords(filtered);
			String decidedCode = original.attribute(5).value((int) cls);
			String rgh = original.toString(0);
			String year = original.toString(1);
			String m = original.toString(3);
			String ec = original.toString(4);

			String[] entries = { rawText, filteredText, correctCode, decidedCode, String.valueOf(pos), rgh, year, m,
					ec };
			writer.writeNext(entries);
		}

		writer.close();

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 50
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 51
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 4 votes
/**
 * Extract bugs from CSV jhipster into a new shorter CSV
 * 
 * @param filename Name of the CSVfile
 * @param filename2 Name of the CSVfile
 * @param doublon Check doublon if true
 *  
 */
public static void createBugsCSV(String filename,String filename2,boolean doublon) throws IOException {  
	CSVWriter writerInit = new CSVWriter(new FileWriter(filename2), ';');
	String[] heads = {"Id","Log-Build"};
	writerInit.writeNext(heads);
	writerInit.close();

	CSVReader lines = new CSVReader(new FileReader(filename), ';');
	String[] row = null;

	List content = lines.readAll();

	for (Object object : content) {

		row = (String[]) object;

		String[] newline = {row[0],row[23]};

		if (row[22].equals("KO"))
		{

			boolean check = true;
			CSVReader lines2 = new CSVReader(new FileReader(filename2), ';');
			String[] row2 = null;

			List content2 = lines2.readAll();

			for (Object object2 : content2) {

				row2 = (String[]) object2;

				if (row[23].toString().equals(row2[1].toString()) && doublon)
				{
					// false if bugs already appears
					check = false;

					System.out.println("equals");
				};
			}
			lines2.close();

			if (check)
			{
				CSVWriter writer = new CSVWriter(new FileWriter(filename2, true),';');
				writer.writeNext(newline);
				writer.close();
			}
		};

	}
	lines.close();
}
 
Example 52
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 4 votes
/**
	 * Add new column in jhipster.csv bugs to categorize bugs.
	 * 
	 * @param filename Name of the CSVfile
	 * @param filename2 Name of the CSVfile
	 * @param doublon Check doublon if true
	 *  
	 */
	public static void categorizeBugsCSV(String filename, String filename2) throws IOException {  
		CSVReader lines = new CSVReader(new FileReader(filename), ';');
		String[] row = null;

		List content = lines.readAll();

		for (Object object : content) {

			row = (String[]) object;
			String bug = "newBUG";
						
			if (row[23].equals("KO")) // build = KO
			{
				//extract log
				String logCompilation = row[21];
				String logBuild = row[24];
//Error parsing reference: "jhipster - jhipster-mariadb:mariadb - jhipster-registry" is not a valid repository/tag
				//CHECK LOG TO CATEGORIZE BUGS Error parsing reference: Could not connect to address=(host=mariadb)(port=3306)(type=master) : Connection refused 
				Matcher m0 = Pattern.compile("(.*?)SocialUserConnection").matcher(logCompilation);
				Matcher m1 = Pattern.compile("(.*?)Failed to get driver instance for jdbcUrl=jdbc:mariadb://(.*?):3306/jhipster").matcher(logBuild);
				Matcher m3 = Pattern.compile("(.*?)No instances available for uaa").matcher(logBuild);
				Matcher m4 = Pattern.compile("(.*?)jhipster - jhipster-mariadb(.*?)is not a valid repository/tag").matcher(logBuild);
				Matcher m5 = Pattern.compile("(.*?)com.mysql.jdbc.exceptions.jdbc4.CommunicationsException").matcher(logBuild);
				Matcher m6 = Pattern.compile("(.*?)org.springframework.security.oauth2.provider.token.store.JdbcTokenStore").matcher(logBuild);

				while(m0.find()) bug = "BUG6:SOCIALLOGIN";
				
				while(m1.find()) bug = "BUG1:mariadb";
				
				while(m3.find()) if(row[2].toString().equals("true")) {bug = "BUG2:UAAAuthenticationDocker";}
				else {bug = "BUG7:UAAEhcache";}
				
				while(m4.find()) bug = "BUG3:mariadb";
				
				while(m5.find()) bug = "BUG4:SQL";
				
				while(m6.find()) bug = "BUG5:OAUTH2";
				
				String[] newline = {row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],
						row[9],row[10],row[11],row[12],row[13],row[14],row[15],
						row[16],row[17],row[18],row[19],row[20],row[21],row[22],row[23],row[24],bug};
				
				CSVWriter writer = new CSVWriter(new FileWriter(filename2, true),',');
				writer.writeNext(newline);
				writer.close();
				}
			};
			lines.close();
}
 
Example 53
Project: geoxygene   File: IntrinsicAssessment.java   Source Code and License Vote up 4 votes
public static void writeNodeContributionDetails(File file) throws IOException {
	/*
	 * Collections.sort(myJavaObjects, new Comparator<OSMResource>() {
	 * 
	 * @Override public int compare(OSMResource r1, OSMResource r2) { return
	 * r1.getDate().compareTo(r2.getDate()); } });
	 */
	// Create a CSV writer
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[10];
	line[0] = "id";
	line[1] = "version";
	line[2] = "changeset";
	line[3] = "uid";
	line[4] = "contributeur";
	line[5] = "date";
	line[6] = "source";
	line[7] = "nbTags";
	line[8] = "longitude";
	line[9] = "latitude";

	writer.writeNext(line);

	for (OSMResource resource : myJavaObjects) {
		if (resource.getGeom().getClass().getSimpleName().equals("OSMNode")) {
			OSMNode node = (OSMNode) resource.getGeom();
			line = new String[10];
			line[0] = Long.toString(resource.getId());
			line[1] = Integer.toString(resource.getVersion());
			line[2] = Integer.toString(resource.getChangeSet());
			line[3] = Integer.toString(resource.getUid());
			line[4] = resource.getContributeur();
			line[5] = resource.getDate().toString();
			line[6] = resource.getSource();
			line[7] = Integer.toString(resource.getNbTags());
			line[8] = Double.toString(node.getLongitude());
			line[9] = Double.toString(node.getLatitude());
			writer.writeNext(line);
		}
	}
	writer.close();
}
 
Example 54
Project: geoxygene   File: IntrinsicAssessment.java   Source Code and License Vote up 4 votes
public static void writeWayContributionDetails(File file) throws IOException {
	/*
	 * Collections.sort(myJavaObjects, new Comparator<OSMResource>() {
	 * 
	 * @Override public int compare(OSMResource r1, OSMResource r2) { return
	 * r1.getDate().compareTo(r2.getDate()); } });
	 */
	// Create a CSV writer
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[10];
	line[0] = "id";
	line[1] = "version";
	line[2] = "changeset";
	line[3] = "uid";
	line[4] = "contributeur";
	line[5] = "date";
	line[6] = "source";
	line[7] = "nbTags";
	line[8] = "nbNodes";

	writer.writeNext(line);

	for (OSMResource resource : myJavaObjects) {
		if (resource.getGeom().getClass().getSimpleName().equals("OSMWay")) {
			// OSMNode node = (OSMNode) resource.getGeom();
			OSMWay way = (OSMWay) resource.getGeom();
			line = new String[9];
			line[0] = Long.toString(resource.getId());
			line[1] = Integer.toString(resource.getVersion());
			line[2] = Integer.toString(resource.getChangeSet());
			line[3] = Integer.toString(resource.getUid());
			line[4] = resource.getContributeur();
			line[5] = resource.getDate().toString();
			line[6] = resource.getSource();
			line[7] = Integer.toString(resource.getNbTags());
			line[8] = Integer.toString(way.getVertices().size());
			writer.writeNext(line);
		}
	}
	writer.close();
}
 
Example 55
Project: IDRT-Import-and-Mapping-Tool   File: CSVWizardPage3.java   Source Code and License Vote up 4 votes
/**
 * Saves the Table to disc.
 */
public static void saveTable() {
	if ((fileConfigMap.get(lastTable) != null) && !table.isDisposed()) {

		File tmpTableFile = new File(csvFolder
				+ fileConfigMap.get(lastTable));
		try {
			CSVWriter rotatedOutput = new CSVWriter(new FileWriter(
					tmpTableFile), DEFAULTDELIM);
			TableItem[] tableItems = table.getItems();
			String[] nextLine = new String[tableItems.length + 1];

			nextLine[0] = "Spaltenname (Pflicht)"; 
			if (tableItems != null) {
				nextLine[0] = "Spaltenname (Pflicht)"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(HEADERCOLUMN);
				}
				rotatedOutput.writeNext(nextLine);

				nextLine[0] = "Datentyp (Pflicht)"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(DATATYPECOLUMN);
				}
				rotatedOutput.writeNext(nextLine);

				nextLine[0] = "Name (kann leer sein)"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(NAMECOLUMN);
				}
				rotatedOutput.writeNext(nextLine);

				//TODO Tooltip
				nextLine[0] = "Tooltip (kann leer sein)"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(TOOLTIPCOLUMN);
				}
				rotatedOutput.writeNext(nextLine);

				nextLine[0] = "Metainformationen"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(METADATACOLUMN);
				}
				rotatedOutput.writeNext(nextLine);

				nextLine[0] = "PID-Generator"; 
				for (int i = 0; i < tableItems.length; i++) {
					nextLine[i + 1] = tableItems[i].getText(PIDGENCOLUMN);
				}
				rotatedOutput.writeNext(nextLine);
				nextLine[0] = "Headline"; 
				nextLine[1] = headLineText.getText();
				rotatedOutput.writeNext(nextLine);
			}
			rotatedOutput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}
 
Example 56
Project: ezid-crawler   File: Submanifestor.java   Source Code and License Vote up 4 votes
public static void main(final String[] args) throws IOException, URISyntaxException {
    final CSVWriter csvWriter = new CSVWriter(new FileWriter(MANIFESTS_CSV));
    final JsonObject source = new JsonObject(StringUtils.read(new File(SOURCE)));
    final JsonArray jsonCanvases = source.getJsonArray("sequences").getJsonObject(0).getJsonArray("canvases");
    final String objID = source.getString("label"); // object ARK
    final List<String[]> csvData = new ArrayList<String[]>();

    for (int index = 0; index < jsonCanvases.size(); index++) {
        final JsonObject jsonCanvas = jsonCanvases.getJsonObject(index);
        final String label = jsonCanvas.getString("label");
        final JsonArray images = jsonCanvas.getJsonArray("images");
        final String thumbnail = jsonCanvas.getString("thumbnail");
        final String id = objID + "/" + label;
        final Manifest manifest = getManifest(id, label, thumbnail);
        final Sequence sequence = getSequence(id, label, 1);
        final List<Canvas> canvases = new ArrayList<Canvas>();

        csvData.add(new String[] { id, label });

        for (int imgIndex = 0; imgIndex < images.size(); imgIndex++) {
            final JsonObject jsonImage = images.getJsonObject(imgIndex);
            final JsonObject jsonResource = jsonImage.getJsonObject("resource");
            final int width = jsonResource.getInteger("width").intValue();
            final int height = jsonResource.getInteger("height").intValue();
            final JsonObject jsonService = jsonResource.getJsonObject("service");
            final String serviceLabel = jsonService.getString("label");
            // Fix for bad master manifests -- shouldn't contain info.json in service ID
            final String serviceId = jsonService.getString("@id").replace("/info.json", "");
            final Canvas canvas = getCanvas(id, serviceLabel, imgIndex + 1, width, height);
            final String imageId = getID(IIIF_SERVER, PathUtils.encodeIdentifier(id), "imageanno", 1);
            final Image image = new Image(imageId);
            final ImageResource resource = new ImageResource();
            final Service service = new Service(serviceId);

            image.setOn(canvas.getId());
            service.setProfile(IIIF_PROFILE);
            service.setContext(IIIF_CONTEXT);
            service.setLabel(canvas.getLabel());
            resource.setHeight(height);
            resource.setWidth(width);
            resource.setFormat("image/jpeg");
            resource.setService(service);
            image.setResource(resource);
            canvas.setImages(Arrays.asList(new Image[] { image }));

            if (!serviceLabel.endsWith("_color")) {
                canvas.setThumbnail(getThumbnail(getBareID(serviceId)));
                canvases.add(canvas);
            }
        }

        sequence.setCanvases(canvases);
        manifest.setSequences(Arrays.asList(new Sequence[] { sequence }));

        final String path = StringUtils.format(MANIFEST_PATH, label);
        final FileWriter writer = new FileWriter(new File(path));

        writer.write(toJson(manifest));
        writer.close();
    }

    csvWriter.writeAll(csvData);
    csvWriter.close();
}
 
Example 57
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 58
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 59
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 60
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 61
Project: bigfoot-maven-plugins   File: ChecksumValidatorMojo.java   Source Code and License Vote up 4 votes
private void storeChecksums(LinkedHashMap checksums) throws MojoExecutionException {
    // Store it.
    FileOutputStream os=null;
    try {
        boolean exists = this.checksums.exists();
        os = new FileOutputStream(this.checksums);
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(os, "UTF-8"), '=', CSVWriter.NO_QUOTE_CHARACTER);

        if( !exists ) {
            writer.writeNext(new String[]{"# This file uses a 'property file like' syntax"});
            writer.writeNext(new String[]{"# Entries are in the following format: 'artifact","checksum-1|...|checksum-n'"});
            writer.writeNext(new String[]{"# Where artifact follows the following format: 'group/id/type/version'"});
            writer.writeNext(new String[]{"# You can use '*' for the version or checksum"});
            writer.writeNext(new String[]{""});
        }
        
        for (Iterator iterator = checksums.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry i = (Map.Entry)iterator.next();            
            StringBuffer b = new StringBuffer();
            for (Iterator iterator2 = ((List)i.getValue()).iterator(); iterator2.hasNext();) {
                String s = (String)iterator2.next();            
                if( b.length()!=0 ) {
                    b.append("|");
                }
                b.append(s);
            }
            String key = (String)i.getKey();
            String value = b.toString();
            if( value.length()!=0 ) {
                writer.writeNext(new String[]{key,value});
            } else { 
                writer.writeNext(new String[]{key});
            }
        }
        writer.close();
    } catch (Throwable e) {
        throw new MojoExecutionException("Could not write: "+this.checksums);
    } finally {
        try {
            os.close();
        } catch (Throwable ignore ) {
        }
    }
}
 
Example 62
Project: kfs   File: ContractsGrantsInvoiceReportServiceImpl.java   Source Code and License Vote up 4 votes
/**
 * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateCSVToExport(org.kuali.kfs.module.ar.document.ContractsGrantsLOCReviewDocument)
 */
@Override
public byte[] convertLetterOfCreditReviewToCSV(ContractsGrantsLetterOfCreditReviewDocument LOCDocument) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(baos));
    try {
        csvWriter.writeNext(new String[] {getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_DOCUMENT_NUMBER),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_DESCRIPTION),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_NUMBER),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_EXPIRATION_DATE),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW),
                getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN)});

        if (CollectionUtils.isNotEmpty(LOCDocument.getHeaderReviewDetails()) && CollectionUtils.isNotEmpty(LOCDocument.getAccountReviewDetails())) {
            for (ContractsGrantsLetterOfCreditReviewDetail item : LOCDocument.getHeaderReviewDetails()) {
                String proposalNumber = org.apache.commons.lang.ObjectUtils.toString(item.getProposalNumber());
                String awardDocumentNumber = org.apache.commons.lang.ObjectUtils.toString(item.getAwardDocumentNumber());

                for (ContractsGrantsLetterOfCreditReviewDetail newItem : LOCDocument.getAccountReviewDetails()) {
                    final String accountExpirationDate = ObjectUtils.isNull(newItem.getAccountExpirationDate()) ?
                            KFSConstants.EMPTY_STRING :
                            getDateTimeService().toDateString(newItem.getAccountExpirationDate());
                    if (org.apache.commons.lang.ObjectUtils.equals(item.getProposalNumber(), newItem.getProposalNumber())) {
                        csvWriter.writeNext(new String[] { proposalNumber,
                            awardDocumentNumber,
                            newItem.getAccountDescription(),
                            newItem.getChartOfAccountsCode(),
                            newItem.getAccountNumber(),
                            accountExpirationDate,
                            contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAwardBudgetAmount()),
                            contractsGrantsBillingUtilityService.formatForCurrency(newItem.getClaimOnCashBalance()),
                            contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAmountToDraw()),
                            contractsGrantsBillingUtilityService.formatForCurrency(newItem.getFundsNotDrawn()) });
                    }
                }
            }
        }
    }
    finally {
        if (csvWriter != null) {
            try {
                csvWriter.close();
            }
            catch (IOException ex) {
                csvWriter = null;
                throw new RuntimeException("problem during ContractsGrantsInvoiceReportServiceImpl.generateCSVToExport()", ex);
            }
        }
    }
    return baos.toByteArray();
}
 
Example 63
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);
    }
}
 
Example 64
Project: hhmi-exp   File: EdgelMatching.java   Source Code and License Vote up 4 votes
public void saveAffinities( String fn ) throws IOException
{
	logger.info(" saving affinities to " + fn);
	
       CSVWriter csvWriter = new CSVWriter(new FileWriter(fn),',');
       
       Set<Entry<EdgelPair, Double>> entries = edgelAffinities.entrySet();
       
       
       String[] vals = null;
       for( Entry<EdgelPair, Double> entry: entries){
       	EdgelPair pair = entry.getKey();
       	Double    aff  =  entry.getValue();
       	
       	if( vals == null){
       		vals = new String[ 3 + 4*( pair.i.numDimensions() ) ];
       	}
       	logger.info(" hi " );
       	int k = 0;
       	for(int i=0; i<pair.i.numDimensions(); i++){
       		vals[k++] = Double.toString( pair.i.getDoublePosition(i) );
       	}
       	for(int i=0; i<pair.i.numDimensions(); i++){
       		vals[k++] = Double.toString( pair.i.getGradient()[i] );
       	}
       	vals[k++] = Double.toString( pair.i.getMagnitude() );
       	
       	for(int i=0; i<pair.i.numDimensions(); i++){
       		vals[k++] = Double.toString( pair.j.getDoublePosition(i) );
       	}
       	for(int i=0; i<pair.i.numDimensions(); i++){
       		vals[k++] = Double.toString( pair.j.getGradient()[i] );
       	}
       	vals[k++] = Double.toString( pair.j.getMagnitude() );
       	
       	vals[k++] = Double.toString( aff );
       	
       	csvWriter.writeNext(vals);
       
       }

       csvWriter.close();
}
 
Example 65
Project: hhmi-exp   File: EdgelMatching.java   Source Code and License Vote up 4 votes
public void computeAndWriteEdgelsAndFeatures(String fn) throws IOException{
		logger.info(" saving edgels and features to " + fn);
		
        CSVWriter csvWriter = new CSVWriter(new FileWriter(fn),',');
        String[] row = null;
        int j = 0;
        for ( Edgel e : edgels )
        {
        	int k = 0;
        	
        	double[] feats = computeEdgelFeatures(e);
        	if( row == null){
        		row = new String[ 1 + 2*( e.numDimensions()) + feats.length ];
        	}
        	
        	for(int i=0; i<e.numDimensions(); i++){
        		row[k++] = Double.toString( e.getDoublePosition(i) );
        	}
        	for(int i=0; i<e.numDimensions(); i++){
        		row[k++] = Double.toString( e.getGradient()[i] );
        	}
        	row[k++] = Double.toString( e.getMagnitude() );
        	
        	for(int i=0; i<feats.length; i++)
        	{
        		row[k++] = Double.toString( feats[i] );
        	}
        	
        	csvWriter.writeNext(row);
        	
        	if( j % 10 == 0 ){
        		logger.info(" edgel " + j + " of " + edgels.size());
        	}
//        	if( j > 20 ){
//        		csvWriter.close();
//        		break;
//        	}
        	j++;
        }
        csvWriter.close();
	}
 
Example 66
Project: saos   File: ChartCsvExporter.java   Source Code and License Vote up 4 votes
/**
 * Converts the given chart to csv and writes the csv to the given writer
 * @throws IOException in case of I/O Error during writing to the writer
 */
public void exportChartToCsv(Chart<Object, Number> chart, ChartCode chartCode, AnalysisForm analysisForm, Locale locale, Writer writer) throws IOException {
    
    CSVWriter csvWriter = createCsvWriter(writer);
    
    try {
        
        csvWriter.writeNext(chartCsvGenerator.generateHeader(chartCode, analysisForm, locale));
        
        
        int rowCount = chart.getSeriesList().get(0).getPoints().size();
        
        for (int i=0; i<rowCount; ++i) {
            csvWriter.writeNext(chartCsvGenerator.generateRow(chart, i));
        }
        
    } finally {
    
        csvWriter.close();
    
    }
}
 
Example 67
Project: MuSe   File: FileProvider.java   Source Code and License Vote up 3 votes
/**
 * Create CSV file out of the content of the result.
 * 
 * @param result
 *          Query result set.
 * @throws SQLException
 */
public void resultToCSV(ResultSet result) throws IOException, SQLException {
  CSVWriter writer = new CSVWriter(new FileWriter(filePath), ';',
      CSVWriter.NO_QUOTE_CHARACTER);
  writer.writeAll(result, true);
  writer.close();
}
 
Example 68
Project: winter   File: CreateTableStatistics.java   Source Code and License Vote up 2 votes
public void run() throws FileNotFoundException, IOException {
	
	CSVWriter resultStatisticsWriter = new CSVWriter(new FileWriter(new File(new File(resultsLocation), "table_statistics.csv"), true));
	
	for(File f : new File(tablesLocation).listFiles()) {
        Gson gson = new Gson();
        
        String json = IOUtils.toString(new FileInputStream(f));
        
        // get the data from the JSON source
        JsonTableSchema data = gson.fromJson(json, JsonTableSchema.class);
        
        // check if any data was parsed ... if the file used the schema with mappings, data will not have any contents
        // but as no exception is thrown, we have to check attributes of data for null ...
        if(data.getRelation()==null) {
        	
        	JsonTableWithMappingSchema moreData = gson.fromJson(json, JsonTableWithMappingSchema.class);
        	
        	data = moreData.getTable();
        }
        
        if(data.getRelation()!=null) {
        	
        	int rows = 0;
        	int cols = data.getRelation().length;
        	
        	for(String[] values : data.getRelation()) {
        		rows = Math.max(values.length, rows);
        	}
        	
        	rows -= data.getNumberOfHeaderRows();
        	
   			resultStatisticsWriter.writeNext(new String[] {
   					new File(tablesLocation).getName(),
   					f.getName(),
   					Integer.toString(rows),
   					Integer.toString(cols)
   			});
    		
        }
	}
	
	resultStatisticsWriter.close();

	
}
 
Example 69
Project: PdfTableAnnotator   File: CsvExport.java   Source Code and License Vote up 2 votes
/**
 * dom transformed to file
 * @param outfile
 * @throws IOException 
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerException
 */
public void toFile(File outfile) throws  ExportException, IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(outfile), ',');
	writer.writeAll(toArray());
	writer.close();
}