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

The following are Jave code examples for showing how to use writeNext() 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: sstore-soft   File: VoltTableUtil.java   Source Code and License Vote up 6 votes
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);
    
    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
 
Example 3
Project: s-store   File: VoltTableUtil.java   Source Code and License Vote up 6 votes
/**
 * Dump out a VoltTable as a CSV to the given writer
 * If the header flag is set to true, then the output will include 
 * the column names in the first row
 * @param out
 * @param vt
 * @param write_header
 */
public static void csv(Writer out, VoltTable vt, boolean header) {
    CSVWriter writer = new CSVWriter(out);
    
    if (header) {
        String cols[] = new String[vt.getColumnCount()];
        for (int i = 0; i < cols.length; i++) {
            cols[i] = vt.getColumnName(i);
        } // FOR
        writer.writeNext(cols);
    }
    vt.resetRowPosition();
    while (vt.advanceRow()) {
        String row[] = vt.getRowStringArray();
        assert(row != null);
        assert(row.length == vt.getColumnCount());
        writer.writeNext(row);
    } // WHILE
}
 
Example 4
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 5
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 6
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 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: murmur   File: OpenCSVTest.java   Source Code and License Vote up 6 votes
@Test
public void testWrite() throws IOException { 
  String[] row1 = new String[] { "oneone", "onetwo", "onethree" };
  String[] row2 = new String[] { "twoone", "twotwo", "twothree" };

  StringWriter sWriter = new StringWriter();
  CSVWriter writer = new CSVWriter(sWriter, ',', '\'');

  writer.writeNext(row1);
  writer.writeNext(row2);

  String written = sWriter.toString();

  CSVReader reader = new CSVReader(new StringReader(written), ',', '\'');
  List<String[]> rows = reader.readAll();
  assertTrue(Arrays.equals(rows.get(0), row1));
  assertTrue(Arrays.equals(rows.get(1), row2));
}
 
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
private void dumpSecurityStructure(CSVWriter csvWriter, String securityType, ManageableSecurity firstSecurity) {
  if (firstSecurity == null) {
    s_logger.error("null security passed to dumpSecurityStructure");
    return;
  }
  s_logger.info("Processing security " + firstSecurity);
  csvWriter.writeNext(new String[] {securityType });
  csvWriter.writeNext(new String[] {firstSecurity.metaBean().beanName() });
  csvWriter.writeNext(new String[] {"Type", "Name", "Example"});
  Iterable<MetaProperty<?>> metaPropertyIterable = firstSecurity.metaBean().metaPropertyIterable();
  for (MetaProperty<?> metaProperty : metaPropertyIterable) {
    s_logger.info("Field" + metaProperty.name());
    String strValue;
    try {
      strValue = metaProperty.getString(firstSecurity);
    } catch (IllegalStateException ise) {
      strValue = metaProperty.get(firstSecurity).toString();
    }
    csvWriter.writeNext(new String[] {metaProperty.propertyType().getSimpleName(), metaProperty.name(), strValue });
  }
  csvWriter.writeNext(new String[] {});
}
 
Example 11
Project: FinanceAnalytics   File: CsvSheetWriter.java   Source Code and License Vote up 6 votes
public CsvSheetWriter(String filename, String[] columns) {

    ArgumentChecker.notEmpty(filename, "filename");
    ArgumentChecker.notNull(columns, "columns");

    // Open file
    OutputStream fileOutputStream = openFile(filename);

    // Set up CSV Writer
    _csvWriter = new CSVWriter(new OutputStreamWriter(fileOutputStream));
    
    // Set columns
    setColumns(columns);
    
    // Write the column row
    _csvWriter.writeNext(columns);
    flush();
  }
 
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: IDRT-Import-and-Mapping-Tool   File: RegexWizard.java   Source Code and License Vote up 6 votes
@Override
	public boolean performFinish() {

		try {
			CSVWriter writer = new CSVWriter(new FileWriter(new File(FileHandler.getCFGFilePath("regex.csv"))), ';');
			writer.writeNext(new String[] {"Name","Regex"});
			for (Regex r : CombineNodesCommand.getRegex()) {
				if (!r.getName().isEmpty())
					writer.writeNext(new String[] {r.getName(),r.getRegex().replaceAll("\\\\", "\\\\\\\\"), r.getTable()});
			}
			writer.flush();
			writer.close();
//			MyOntologyTrees.createRegexMenu();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
 
Example 15
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 16
Project: bactimas   File: BeanToCsv.java   Source Code and License Vote up 6 votes
public boolean write(MappingStrategy<T> mapper, CSVWriter csv,
                     List<?> objects) {
    if (objects == null || objects.isEmpty())
        return false;

    try {
        csv.writeNext(processHeader(mapper));
        List<Method> getters = findGetters(mapper);
        for (Object obj : objects) {
            String[] line = processObject(getters, obj);
            csv.writeNext(line);
        }
        return true;
    } catch (Exception e) {
        throw new RuntimeException("Error writing CSV !", e);
    }
}
 
Example 17
Project: RedMetrics   File: PlayerCsvEntityConverter.java   Source Code and License Vote up 6 votes
@Override
public void write(CSVWriter csvWriter, List<Player> models) {
    csvWriter.writeNext(new String[]{
            "id",
            "birthDate",
            "region",
            "country",
            "gender",
            "externalId",
            "customData"
    });

    for(Player model : models) {
        csvWriter.writeNext(new String[]{
                model.getId().toString(),
                CsvHelper.formatDate(model.getBirthDate()),
                model.getRegion(),
                model.getCountry(),
                model.getGender() != null ? model.getGender().name() : null,
                model.getExternalId(),
                model.getCustomData()
        });
    }
}
 
Example 18
Project: mica2   File: CsvTaxonomyCoverageWriter.java   Source Code and License Vote up 6 votes
private List<String> writeHeader(CSVWriter writer, MicaSearch.TaxonomiesCoverageDto coverage) {
  List<String> headers = Lists.newArrayList("Taxonomy", "Vocabulary", "Term");
  List<String> bucketNames = Lists.newArrayList();
  if(coverage.getTaxonomiesCount() > 0) {
    coverage.getTaxonomiesList().forEach(taxo -> {
      if(taxo.getBucketsCount() > 0) {
        taxo.getBucketsList().stream().filter(bucket -> !bucketNames.contains(bucket.getValue()))
          .forEach(bucket -> bucketNames.add(bucket.getValue()));
      }
    });
  }
  headers.addAll(bucketNames);

  writer.writeNext(headers.toArray(new String[headers.size()]));

  return bucketNames;
}
 
Example 19
Project: mica2   File: VariablesCsvReportGenerator.java   Source Code and License Vote up 6 votes
@Override
protected void writeHeader(CSVWriter writer) {

  List<String> line = new ArrayList<>();

  line.add("name");
  line.add("search.variable.label");
  if (mustShow("showVariablesTypeColumn"))
    line.add("type");
  if (mustShow("showVariablesStudiesColumn"))
    line.add("search.study.label");
  if (mustShow("showVariablesDatasetsColumn"))
    line.add("search.dataset.label");

  String[] translatedLine = line.stream().map(key -> translator.translate(key)).toArray(String[]::new);

  writer.writeNext(translatedLine);
}
 
Example 20
Project: datatree-adapters   File: CsvOpenCSV.java   Source Code and License Vote up 5 votes
@SuppressWarnings({ "resource" })
@Override
public String toString(Object value, Object meta, boolean pretty, boolean insertMeta) {
	if (value == null) {
		return "";
	}
	StringWriter writer = new StringWriter(512);
	CSVWriter mapper = new CSVWriter(writer, defaultSeparatorChar, defaultQuoteChar, defaultEscapeChar,
			defaultLineEnd);
	Collection<?> lines = objectToCollection(value);
	if (lines != null) {
		final Iterator<?> iterator = lines.iterator();
		Collection<?> cells;
		String[] array;
		Object line;
		int index;
		while (iterator.hasNext()) {
			line = iterator.next();
			cells = objectToCollection(line);
			if (cells != null) {
				array = new String[cells.size()];
				index = 0;
				for (Object cell : cells) {
					try {
						array[index++] = DataConverterRegistry.convert(String.class, cell);
					} catch (Exception e) {
						array[index++] = "";
					}
				}
				mapper.writeNext(array);
			}
		}
	}
	return writer.toString();
}
 
Example 21
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 22
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 23
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 24
Project: streaminggraphpartitioning   File: StreetTest8.java   Source Code and License Vote up 5 votes
/** 
 * Create the test case
 *
 * @param testName name of the test case
 * @throws IOException 
 */
public StreetTest8( String testName ) throws IOException
{
	super( testName );
	writer = new CSVWriter(new FileWriter(CSV_FILENAME,true));
	writer.writeNext(HEADER);
}
 
Example 25
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 26
Project: streaminggraphpartitioning   File: StreetTest3.java   Source Code and License Vote up 5 votes
/** 
 * Create the test case
 *
 * @param testName name of the test case
 * @throws IOException 
 */
public StreetTest3( String testName ) throws IOException
{
	super( testName );
	writer = new CSVWriter(new FileWriter(CSV_FILENAME,true));
	writer.writeNext(HEADER);
}
 
Example 27
Project: geoxygene   File: IntrinsicAssessment.java   Source Code and License Vote up 5 votes
public static void writeContributionSummary(HashMap<Long, OSMObject> myOSMObjects, File file) throws IOException {
	// Create a CSV writer
	CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
	// write header
	String[] line = new String[8];
	line[0] = "id";
	line[1] = "versions";
	line[2] = "contributeurs";
	line[3] = "geom-edition";
	line[4] = "tag-edition";
	line[5] = "stable-tags";
	line[6] = "datemin";
	line[7] = "datemax";
	writer.writeNext(line);
	for (OSMObject myObject : myOSMObjects.values()) {
		line = new String[8];
		line[0] = String.valueOf(myObject.getOsmId());
		line[1] = String.valueOf(myObject.getNbVersions());
		line[2] = String.valueOf(myObject.getNbContributors());
		line[3] = String.valueOf(myObject.getNbGeomEdition());
		line[4] = String.valueOf(myObject.getNbTagEdition());
		line[5] = String.valueOf(myObject.getNbStableTags());
		line[6] = String.valueOf(myObject.getDateMin());
		line[7] = String.valueOf(myObject.getDateMax());
		writer.writeNext(line);
	}
	writer.close();
}
 
Example 28
Project: streaminggraphpartitioning   File: StreetTest5.java   Source Code and License Vote up 5 votes
/** 
 * Create the test case
 *
 * @param testName name of the test case
 * @throws IOException 
 */
public StreetTest5( String testName ) throws IOException
{
	super( testName );
	writer = new CSVWriter(new FileWriter(CSV_FILENAME,true));
	writer.writeNext(HEADER);
}
 
Example 29
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillNumberOfNodesCSV(CSVWriter writer) throws IOException {
    writer.writeNext(NUMBER_OF_NODES_HEADER);
    SortedSet<Long> times = new TreeSet<>(blockchainInfo.getTimeToNumNodes().keySet());
    for (Long time : times) {
        String[] entry = {String.valueOf(time), String.valueOf(blockchainInfo.getTimeToNumNodes().get(time))};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 30
Project: streaminggraphpartitioning   File: StreetTest2.java   Source Code and License Vote up 5 votes
/** 
 * Create the test case
 *
 * @param testName name of the test case
 * @throws IOException 
 */
public StreetTest2( String testName ) throws IOException
{
	super( testName );
	writer = new CSVWriter(new FileWriter(CSV_FILENAME,true));
	writer.writeNext(HEADER);
}
 
Example 31
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 32
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 33
Project: ICDClassifier   File: ExperimentalCipeClassifier.java   Source Code and License Vote up 5 votes
public void printBaseline(CSVWriter writer) {
	String[] baseline = { "0", "0", "0", "0", "0", "0", "0" };
	writer.writeNext(baseline);
	try {
		writer.flush();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 34
Project: blockchain-benchmarking   File: CSVComposer.java   Source Code and License Vote up 5 votes
private void fillTransactionsCSV(CSVWriter writer) throws IOException {
    writer.writeNext(TRANSACTIONS_HEADER);
    for (TransactionInfo transactionInfo : blockchainInfo.getTransactions().values()) {
        String[] entry = {String.valueOf(transactionInfo.getTransactionId()),
                String.valueOf(transactionInfo.getBlockId()),
                String.valueOf(transactionInfo.getTransactionSize()),
                String.valueOf(transactionInfo.getTime()),
                String.valueOf(transactionInfo.getNodeId())};
        writer.writeNext(entry);
        writer.flush();
    }
}
 
Example 35
Project: spring-usc   File: Data2Features.java   Source Code and License Vote up 5 votes
public static void Traindata2CSV(
		HashMap<String, Vector<String>> class2Records, String fpath,
		RecordFeatureSet rf) {
	try {
		CSVWriter writer = new CSVWriter(new FileWriter(new File(fpath)));
		Vector<String> vsStrings = new Vector<String>();
		for (Vector<String> vecs : class2Records.values()) {
			vsStrings.addAll(vecs);
		}
		// get attribute names
		Collection<String> attrStrings = rf.getFeatureNames();
		String[] attr_names = attrStrings.toArray(new String[attrStrings
				.size() + 1]);
		attr_names[attr_names.length - 1] = "label";
		writer.writeNext(attr_names);
		for (String label : class2Records.keySet()) {

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

		}
		writer.flush();
		writer.close();
	} catch (Exception ex) {
		logger.error("" + Arrays.toString(ex.getStackTrace()));
	}
}
 
Example 36
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 37
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 38
Project: tech-gallery   File: ExportUtils.java   Source Code and License Vote up 5 votes
private static StringWriter createCsv(Workbook workBook) throws IOException {

    Sheet sheet = workBook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    StringWriter stringWriter = new StringWriter();
    CSVWriter csvOutput = new CSVWriter(stringWriter);

    while (rowIterator.hasNext()) {
      Row row = rowIterator.next();
      int i = 0;
      String[] cellValues = new String[SHEET_CELL_SIZE];
      Iterator<Cell> cellIterator = row.cellIterator();
      while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        switch (cell.getCellType()) {
          case Cell.CELL_TYPE_STRING:
            cellValues[i] = cell.getStringCellValue();
            break;
          case Cell.CELL_TYPE_NUMERIC:
            cellValues[i] = String.valueOf(cell.getNumericCellValue());
            break;
          case Cell.CELL_TYPE_BLANK:
            cellValues[i] = "";
            break;
        }
        i = i + 1;
      }
      csvOutput.writeNext(cellValues);
    }
    csvOutput.close();
    return stringWriter;
  }
 
Example 39
Project: near-image-replica-detection   File: DatasetGenerator.java   Source Code and License Vote up 5 votes
protected static String imageToCSV(CSVWriter writer, long id, String full, String path) {
	String ext = Files.getFileExtension(path);
	Mat src = Highgui.imread(full, Highgui.CV_LOAD_IMAGE_ANYCOLOR);
	writer.writeNext(new String[]{String.valueOf(id), path, ext,
			String.valueOf(src.size().height), String.valueOf(src.size().width), 
			null, null, null, null});
	return ext;
}
 
Example 40
Project: near-image-replica-detection   File: DatasetGenerator.java   Source Code and License Vote up 5 votes
protected static void replicaToCSV(CSVWriter writer, Replica rep, String extension) {
	writer.writeNext(new String[]{ String.valueOf(rep.getId()), rep.getPath(), extension, 
			String.valueOf(rep.getImage().size().height), String.valueOf(rep.getImage().size().width), 
			rep.getReplicaLabel(), rep.getParameters()[0], rep.getParameters()[1], 
			String.valueOf(rep.getImageSrcId())} );
	
}
 
Example 41
Project: foodcoapp   File: Report.java   Source Code and License Vote up 5 votes
private float writeRow(Trace.Txn balance, Trace.Txn t, Trace.Prod p,
                              String account, CSVWriter csv, boolean aktiva) {
    if (p.value() == 0) return 0;
    float sum = 0;
    String[] row = new String[7];
    row[0] = df.format(p.date);
    if (!row[0].contains(year + "")){
        System.out.println("ANOTHER YEAR!!! " + p);
    }
    if (p.account.equals(account)) {
        if ((aktiva? 1 : -1) * p.quantity() < 0 ||
                (aktiva? 1 : -1) * balance.get(p).value() < 0) {
            row[1] = "   " + p.label();
            row[2] = format((aktiva? 1 : -1) * p.value());
            //System.out.println( " * INTERN " + p);
        } else {
            row[1] = p.label();
            row[2] = format((aktiva? 1 : -1) * p.value());
            //System.out.println( " * " + p);
        }
    } else {
        //System.out.println( " * " + p);
        row[5] = format((aktiva? -1 : 1) * p.value());
        row[6] = "  " + p;
    }
    if (csv != null) csv.writeNext(row);
    balance.add(p);
    sum += p.value();
    return sum;
}
 
Example 42
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 43
Project: mica2   File: SpecificStudyReportGenerator.java   Source Code and License Vote up 5 votes
@Override
protected void writeEachLine(CSVWriter writer) {

  for (String studyId : studyIds) {
    BaseStudy publishedStudy = publishedStudyService.findById(studyId);

    if (publishedStudy != null) {

      List<String> publishedStudyDetails = generatePublishedStudyDetails(publishedStudy);

      Iterator<Population> populationIterator = publishedStudy.getPopulations().iterator();

      if (!populationIterator.hasNext()) {
        writer.writeNext(publishedStudyDetails.toArray(new String[publishedStudyDetails.size()]));
      }

      while (populationIterator.hasNext()) {
        List<String> buildingCompleteLine = new ArrayList<>(publishedStudyDetails);
        Population next = populationIterator.next();
        buildingCompleteLine.addAll(generatePopulationDetails(next));
        writer.writeNext(buildingCompleteLine.toArray(new String[buildingCompleteLine.size()]));
      }
    } else {

      BaseStudy draftStudy = studyService.findStudy(studyId);
      if (draftStudy != null) {
        List<String> lineOfDratStudy = generateDraftStudyDetails(draftStudy);
        writer.writeNext(lineOfDratStudy.toArray(new String[lineOfDratStudy.size()]));
      }
    }
  }
}
 
Example 44
Project: sisob-data-extractor   File: CrawlerTrace.java   Source Code and License Vote up 5 votes
public synchronized void anotate(String type, String line)
{
    try {            
        CSVWriter writer = this.urls_trace_files.get(type);
        if(writer != null){
            writer.writeNext(line.split("\t"));
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);                    
    }
}
 
Example 45
Project: quandl4j   File: RecordingRESTDataProvider.java   Source Code and License Vote up 5 votes
private void initWriter(final File rootPath) {
  _rootPath = rootPath;
  try {
    File file = new File(_rootPath, INDEX_FILE_NAME);
    _writer = new CSVWriter(new FileWriter(file));
    _writer.writeNext(new String[] { RESTReponseIndexColumns.URI.getColumnLabel(), RESTReponseIndexColumns.FILE.getColumnLabel(), 
                                     RESTReponseIndexColumns.EXCEPTION_CLASS.getColumnLabel(), RESTReponseIndexColumns.EXCEPTION_MESSAGE.getColumnLabel() });
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }    
}
 
Example 46
Project: DF14_Demo   File: FileProcessor.java   Source Code and License Vote up 5 votes
public static File generateResponseSubmissionDate(File inputFile, String fieldName, File outputFile) throws IOException {
	CSVReader reader = new CSVReader(new FileReader(inputFile));
	String[] cols;
	int fieldIndex = -1;
	CSVWriter writer = new CSVWriter(new FileWriter(outputFile), ',', '"', '\\', "\n");
	cols = reader.readNext(); 
	System.out.println(cols.length);
	writer.writeNext(cols);
	writer.flush();
	for(String str : cols) {
		System.out.println(str);
	}
	//TO find the index position of field for which we are going to add Monthly Date Diff.
	for(int i = 0; i < cols.length; i++) {
		if(cols[i].trim().equalsIgnoreCase(fieldName)) {
			fieldIndex	= i;
			cols = reader.readNext();
			break;
		}
	}
	
	if(fieldIndex > -1) {
		while(cols != null) {
			int daysDiff = Integer.parseInt(cols[fieldIndex]);
			cols[fieldIndex] = DateUtil.addDays(new Date(),daysDiff, "yyyy-MM-dd'T'HH:mm:ss");
			writer.writeNext(cols);
			writer.flush();
			cols = reader.readNext();
		}
	}
	else
		throw new RuntimeException("The input file : " + inputFile.getAbsolutePath() + " did not have the required field name : " + fieldName);
	
	return outputFile;
}
 
Example 47
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 48
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 49
Project: sisob-data-extractor   File: CrawlerTrace.java   Source Code and License Vote up 5 votes
public synchronized void anotate(String type, CandidateTypeURL c)
{
    try {            
        CSVWriter writer = this.urls_trace_files.get(type);
        if(writer != null){
            writer.writeNext(new String[] {c.sURL, c.sText, c.sFromURL});
        }
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);                    
    }
}
 
Example 50
Project: mica2   File: NetworkCsvReportGenerator.java   Source Code and License Vote up 5 votes
@Override
protected void writeHeader(CSVWriter writer) {

  List<String> line = new ArrayList<>();

  line.add("acronym");
  line.add("name");

  if (mustShow("showNetworksStudiesColumn"))
    line.add("studies");

  String datasetsLabel = translator.translate("datasets");
  if (mustShow("showStudiesStudyDatasetsColumn"))
    line.add(String.format("%s:%s", datasetsLabel, translator.translate("search.dataset.collected")));
  if (mustShow("showStudiesHarmonizationDatasetsColumn"))
    line.add(String.format("%s:%s", datasetsLabel, translator.translate("search.dataset.harmonized")));

  if (mustShow("showStudiesVariablesColumn")) {
    String variablesLabel = translator.translate("variables");
    if (mustShow("showStudiesStudyVariablesColumn"))
      line.add(String.format("%s:%s", variablesLabel, translator.translate("search.variable.collected")));
    if (mustShow("showStudiesDataschemaVariablesColumn")) {
      line.add(String.format("%s:%s", variablesLabel, translator.translate("search.variable.dataschema")));
    }
  }

  String[] translatedLine = line.stream().map(key -> translator.translate(key)).toArray(String[]::new);

  writer.writeNext(translatedLine);
}
 
Example 51
Project: mica2   File: VariablesCsvReportGenerator.java   Source Code and License Vote up 5 votes
@Override
protected void writeEachLine(CSVWriter writer) {

  for (Mica.DatasetVariableResolverDto datasetVariableDto : datasetVariableDtos) {
    List<String> lineContent = generateLineContent(datasetVariableDto);
    writer.writeNext(lineContent.toArray(new String[lineContent.size()]));
  }
}
 
Example 52
Project: mica2   File: CsvContingencyWriter.java   Source Code and License Vote up 5 votes
private void writeContingencyCategorical(CSVWriter writer, Mica.DatasetVariableContingencyDto c, List<String> values,
  List<String> terms) {
  List<List<Integer>> tmp = ContingencyUtils.getCategoricalRows(c, values, terms);

  IntStream.range(0, values.size()).forEach(i -> writer.writeNext(
    Lists.asList(values.get(i), tmp.get(i).stream().map(x -> x.toString()).toArray()).toArray(new String[0])));

  writer.writeNext(Lists.asList("Total", tmp.get(tmp.size() - 1).stream().map(x -> x.toString()).toArray()).stream()
    .toArray(String[]::new));
}
 
Example 53
Project: mica2   File: CsvHarmonizationVariablesWriter.java   Source Code and License Vote up 5 votes
private void writeHeader(CSVWriter writer, HarmonizationDataset dataset, String locale) {
  List<String> headers = Lists.newArrayList(dataset.getBaseStudyTables()).stream()
      .map(table -> {
        LocalizedString name = table.getName();
        String id = table instanceof StudyTable ? ((StudyTable)table).getStudyId() : ((HarmonizationStudyTable) table).getStudyId();

        return id + (name != null ?  " (" + name.get(locale) +")" : "");
      })
      .collect(Collectors.toList());

  headers.add(0, "Variable");
  writer.writeNext(headers.toArray(new String[headers.size()]));
}
 
Example 54
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 55
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 56
Project: mica2   File: CsvContingencyWriter.java   Source Code and License Vote up 5 votes
private void writeHeaders(CSVWriter writer, Mica.DatasetVariableContingencyDto c, List<String> terms) {
  if(c.hasStudyTable()) writer.writeNext(new String[] { String
    .format("%s - %s - %s", c.getStudyTable().getProject(), c.getStudyTable().getTable(),
      c.getStudyTable().getDceId()) });
  else if(c.hasHarmonizationStudyTable()) writer.writeNext(new String[] { String
    .format("%s - %s - %s", c.getHarmonizationStudyTable().getProject(), c.getHarmonizationStudyTable().getTable(),
    c.getHarmonizationStudyTable().getPopulationId())});
  writer.writeNext(concat(concat(Stream.of(""), terms.stream()), Stream.of("Total")).toArray(String[]::new));
}
 
Example 57
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 58
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 59
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 60
Project: streaminggraphpartitioning   File: AllGraphsTest.java   Source Code and License Vote up 4 votes
public void testStreet() throws HeuristicNotFound, IOException, InterruptedException, IllegalArgumentException, IllegalAccessException {
	File fold = new File(FOLDER);
	//seq
	File[] fls = fold.listFiles(p -> p.getName().endsWith(".graph"));
	Arrays.sort(fls, (p1,p2) -> (int)p1.length() - (int)p2.length());
	
	for (File fpin: fls) {
		String graphName = FOLDER + fpin.getName();
		
		String[] ords = {".bfs",".dfs",".rnd"};
		
		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);
			File graphNameRnd = new File(graphName + ".rnd." + 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();
			
			log.info("Making RND graph: " + i);
			RandomOrdinator ordinatorGraphLoader = new RandomOrdinator(new FileInputStream(fpin), new FileOutputStream(graphNameRnd), null);
			ordinatorGraphLoader.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);
			}
			
		}
		writer.close();
	}
}
 
Example 61
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 62
Project: streaminggraphpartitioning   File: NormalizedVariables.java   Source Code and License Vote up 4 votes
@Test
public void test() throws FileNotFoundException, IOException {
	File fold = new File(FOLDER);
	for (File f : fold.listFiles(p -> p.getName().endsWith(".graph"))) {
		log.info("Test for : " + f.getName());
		writer = new CSVWriter(new FileWriter(new File(f.getName() + ".csv")));
		writer.writeNext(header);
		for (int k = 2; k < MAX_PARTS; k*=2) 
			for (double A = 0.1; A < 10.0; A+=STEP) {
				for (double B = 0.1; B < 10.0; B+= STEP) {
					for (double C = 0.1; C < 10.0; C+=STEP) {
						log.info("Testing for A: " + A + ", B: " + B + " , C: " + C);
						for (int i = 0; i < ITER_TIME; i++) {
							SGPHeuristic heuristic = new LinearAbsoluteWeightedDispersionBased(A, B,C, true);
							GraphLoader gl = new TraversingGraphLoader(new FileInputStream(f), new FileOutputStream(f+"-r"),
									k, heuristic, -1, false, new BFSTraversing());
							gl.runPartition();
							QualityChecker qc = new ParallelQualityChecker();
							String[] res = {
									f.getName(),
									Integer.toString(gl.getNodeNumbers()),
									Integer.toString(gl.getEdgeNumbers()),
									Integer.toString(k),
									Double.toString(A),
									Double.toString(B),
									Double.toString(C),
									qc.getCuttingEdgesCount(gl.getGraphPartitionator().getGraph()).toString(),
									qc.getCuttingEdgeRatio(gl.getGraphPartitionator().getGraph()).toString(),
									ITER_TIME.toString()
							};
							writer.writeNext(res);
							writer.flush();
						}
					}
				}
			}
			writer.close();
		
	}

}
 
Example 63
Project: FinanceAnalytics   File: ViewportResultsJsonCsvWriter.java   Source Code and License Vote up 4 votes
public String getCsv(ViewportResults viewportResults) {
  GridColumnGroups columnGroups = viewportResults.getColumns();
  String[] header1 = new String[columnGroups.getGroups().size()];
  String[] header2 = new String[columnGroups.getColumnCount()];
  
  int index = 0;
  for (GridColumnGroup gridColumnGroup : columnGroups.getGroups()) {
    header1[index++] = gridColumnGroup.getName();
  }
  
  List<GridColumn> columns = columnGroups.getColumns();
  index = 0;
  for (GridColumn gridColumn : columns) {
    header2[index++] = gridColumn.getHeader();
  }
  
  StringWriter stringWriter = new StringWriter();
  @SuppressWarnings("resource")
  CSVWriter csvWriter = new CSVWriter(stringWriter);
  
  csvWriter.writeNext(header1);
  csvWriter.writeNext(header2);
  
  List<ResultsCell> viewportCells = viewportResults.getResults();
  Iterable<List<ResultsCell>> results = Iterables.partition(viewportCells, columnGroups.getColumnCount());
  for (List<ResultsCell> row : results) {
    String[] rowArray = new String[row.size()];
    int col = 0;
    for (ResultsCell cell : row) {
      Object cellValue = cell.getValue();
      if (cellValue instanceof RowTarget) {
        rowArray[col++] = ((RowTarget) cellValue).getName();
        continue;
      }
      
      ValueSpecification cellValueSpec = cell.getValueSpecification();
      Object formattedValue = _formatter.format(cellValue, cellValueSpec, cell.getFormat(), cell.getInlineKey());
      if (formattedValue instanceof String) {
        rowArray[col++] = (String) formattedValue;
      } else {
        rowArray[col++] = formattedValue.toString();
      }
    }
    csvWriter.writeNext(rowArray);
  }
  return stringWriter.toString();
}
 
Example 64
Project: spring-usc   File: Tools.java   Source Code and License Vote up 4 votes
public void transformFile(String fpath) {
	try {
		Vector<String[]> examples = new Vector<String[]>();
		ArrayList<String> data = new ArrayList<String>();
		// read and write the data
		File nf = new File(fpath);
		BufferedReader cr = new BufferedReader(new FileReader(fpath));
		String pair = "";
		Vector<String> vtmp = new Vector<String>();
		while ((pair = cr.readLine()) != null) {
			pair = pair.trim();
			if (pair.length() == 0)
				continue;
			if (pair.charAt(0) == '\"') {
				pair = pair.substring(1);
			}
			if (pair.charAt(pair.length() - 1) == '\"') {
				pair = pair.substring(0, pair.length() - 1);
			}
			vtmp.add(pair);
		}
		DataPreProcessor dpp = new DataPreProcessor(vtmp);
		dpp.run();
		Messager msger = new Messager();
		while (true) {

			Vector<String[]> result = new Vector<String[]>();
			System.out.print("Enter raw value\n");
			// open up standard input
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			String raw = null;
			raw = br.readLine();
			if (raw.compareTo("end") == 0) {
				break;
			}
			System.out.print("Enter tar value\n");
			// open up standard input
			String tar = null;
			tar = br.readLine();

			// learn the program
			String[] xStrings = { "<_START>" + raw + "<_END>", tar };
			examples.add(xStrings);
			for (String[] elem : examples) {
				System.out.println("Examples inputed: "
						+ Arrays.toString(elem));
			}
			String ofpath = "/Users/bowu/Research/50newdata/tmp/"
					+ nf.getName();
			CSVWriter cw = new CSVWriter(new FileWriter(new File(ofpath)));
			ProgSynthesis psProgSynthesis = new ProgSynthesis();				
			psProgSynthesis.inite(examples,dpp,msger); //
			Collection<ProgramRule> ps = psProgSynthesis.run_main();
			msger.updateCM_Constr(psProgSynthesis.partiCluster
					.getConstraints());
			msger.updateWeights(psProgSynthesis.partiCluster.weights);
			ProgramRule pr = ps.iterator().next();
			System.out.println(""+psProgSynthesis.myprog.toString());
			System.out.println("" + pr.toString());
			for(String org: vtmp)
			{
				String ttar = pr.transform(org);
				String[] pValue = {org,ttar};
				cw.writeNext(pValue);
				System.out.println(String.format("%s,%s", org,ttar ));
				result.add(pValue);
			}
			cw.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 65
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 66
Project: liferaylms-portlet   File: GeneralStats.java   Source Code and License Vote up 4 votes
@Override
public void serveResource(ResourceRequest resourceRequest,
		ResourceResponse resourceResponse) throws IOException,
		PortletException {
	String action = ParamUtil.getString(resourceRequest, "action");
	long[] courseIds=ParamUtil.getLongValues(resourceRequest, "courseIds");
	ThemeDisplay themeDisplay  =(ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
	if(action.equals("export")){
		try
		{
		String charset = LanguageUtil.getCharset(themeDisplay.getLocale());
		if (Validator.isNull(charset)) {
			charset = LanguageUtil.getCharset(LocaleUtil.getDefault());
		}
		charset = StringPool.UTF8;
		resourceResponse.setCharacterEncoding(charset);
		resourceResponse.setContentType("text/csv;charset="+charset);
		resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=generalstats."+Long.toString(System.currentTimeMillis())+".csv");
		if (StringPool.UTF8.equals(charset)) {
	        byte b[] = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
	        resourceResponse.getPortletOutputStream().write(b);
		}
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(resourceResponse.getPortletOutputStream(),charset),';');
        String[] linea=new String[8];
        linea[0]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.name");
        linea[1]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.registered");
        linea[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.starts.course");
        linea[3]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.ends.course");
        linea[4]=LanguageUtil.get(themeDisplay.getLocale(),"closed");
        linea[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.marks.average");
        linea[6]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulecounter");
        linea[7]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.activitiescounter");
        writer.writeNext(linea);
        long[] userExcludedIds = null;
        for(long courseId:courseIds)
        {
        	Course course=CourseLocalServiceUtil.getCourse(courseId);
        	userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course);
	        linea=new String[8];
	        linea[0]=course.getTitle(themeDisplay.getLocale());
	        		        
			long registered=CourseLocalServiceUtil.countStudents(courseId, themeDisplay.getCompanyId(), null, null, null, null, false);
			long iniciados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsStarted(courseId, userExcludedIds) : 0;
			long finalizados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFinished(courseId, userExcludedIds) : 0;
			double avgResult=0;
			if(finalizados>0){
				avgResult=CourseResultLocalServiceUtil.avgResultByCourseIdUserExcludedIds(course.getCourseId(), true, userExcludedIds);
			}
			long activitiesCount=LearningActivityLocalServiceUtil.countLearningActivitiesOfGroup(course.getGroupCreatedId());
			long modulesCount=ModuleLocalServiceUtil.countByGroupId(course.getGroupCreatedId());
			String closed=course.getClosed()?LanguageUtil.get(themeDisplay.getLocale(),"yes"):LanguageUtil.get(themeDisplay.getLocale(),"no");
			
			linea[1]=Long.toString(registered);
			linea[2]=Long.toString(iniciados);
			linea[3]=Long.toString(finalizados);
			DecimalFormat df = new DecimalFormat("#.#");
			linea[4]=closed;
			linea[5]=df.format(avgResult);
			linea[6]=Long.toString(modulesCount);
			linea[7]=Long.toString(activitiesCount);
	        writer.writeNext(linea);
	        //resourceResponse.getPortletOutputStream().write(b);
        }
        writer.flush();
		writer.close();
		resourceResponse.getPortletOutputStream().flush();
		resourceResponse.getPortletOutputStream().close();
		
		}
		catch(Exception e)
		{
			
		}
	}
}
 
Example 67
Project: liferaylms-portlet   File: CourseStats.java   Source Code and License Vote up 4 votes
private void exportCourse(ResourceResponse resourceResponse, long courseId,
						  long teamId, ThemeDisplay themeDisplay) 
								  throws IOException, UnsupportedEncodingException {
	try {
		Course course = CourseLocalServiceUtil.getCourse(courseId);
		//Lo primero que hacemos es pedir la lista de usuarios sobre la que queremos los resultados para no repetirlo en cada función
		long[] userIds  = null;
		long[] userExcludedIds = null;
		if(teamId > 0){
			userIds = getUsersStudentsTeam(course, themeDisplay.getCompanyId(), teamId);
		}else{
			userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course);
		}
		
		CourseStatsView courseView  = getCourseStats(course, teamId, themeDisplay.getLocale(), userExcludedIds, userIds);
		List<Module> modules = ModuleLocalServiceUtil.findAllInGroup(course.getGroupCreatedId());
		CSVWriter writer = initCsv(resourceResponse);
		 
		//Cabecera del curso
		int numCols = 6;  
		String[] cabeceras = new String[numCols];
		cabeceras[0]=LanguageUtil.get(themeDisplay.getLocale(),"title");
		cabeceras[1]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.registered");
		cabeceras[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.start.student");
		cabeceras[3]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.end.student");
		cabeceras[4]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.passed");
		cabeceras[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.failed");
		writer.writeNext(cabeceras);
		
		//Resultados del curso
		String[] resultados = new String[numCols];
		resultados[0]=courseView.getCourseTitle();
    	resultados[1]=Long.toString(courseView.getRegistered());
    	resultados[2]=Long.toString(courseView.getStarted());
    	resultados[3]=Long.toString(courseView.getFinished());
    	resultados[4]=Long.toString(courseView.getPassed());
    	resultados[5]=Long.toString(courseView.getFailed());	
      	writer.writeNext(resultados);
		
      	//Cabecera del modulo
	    numCols = 7;
	    cabeceras = new String[numCols];
	    cabeceras[0]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.module");
	    cabeceras[1]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.stardate");
	    cabeceras[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.enddate");
	    cabeceras[3]=LanguageUtil.get(themeDisplay.getLocale(),"total.activity");
	    cabeceras[4]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.start.student");
	    cabeceras[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.end.student");
	    cabeceras[6]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.dependencies");
	    writer.writeNext(cabeceras);
   	
	    
	    //Resultados de los modulos
    	Schedule sch = ScheduleLocalServiceUtil.getScheduleByTeamId(teamId);
    	ModuleStatsView moduleStats;
	    for(Module module:  modules){
	    	resultados = new String[numCols];
	    	moduleStats = getModuleStats(module, teamId, themeDisplay.getLocale(), themeDisplay.getTimeZone(), sch, userExcludedIds, userIds);
	    	resultados[0]=moduleStats.getModuleTitle();
	    	resultados[1]=moduleStats.getStartDateString();
	    	resultados[2]=moduleStats.getEndDateString();
	    	resultados[3]=Long.toString(moduleStats.getActivityNumber());
	    	resultados[4]=Long.toString(moduleStats.getStarted());
	    	resultados[5]=Long.toString(moduleStats.getFinished());		    	
	    	resultados[6]=moduleStats.getPrecedence();
	        writer.writeNext(resultados);
	    }
	    endCsv(resourceResponse, writer);
	    
	} catch (NestableException e) {
		e.printStackTrace();
	}finally{
		resourceResponse.getPortletOutputStream().flush();
		resourceResponse.getPortletOutputStream().close();
	}
}
 
Example 68
Project: IDRT-Import-and-Mapping-Tool   File: DBImportWizard.java   Source Code and License Vote up 4 votes
private void createDBExportConfigCSV(List<ExportConfig> exportConfigs,
		String fileName) {
	try {
		File file = new File(fileName);
		CSVWriter writer = new CSVWriter(new FileWriter(file), ';');
		String[] nextLine = new String[10];

		// Header
		int k = 0;
		nextLine[k++] = "Server Name";
		nextLine[k++] = "Server IP";
		nextLine[k++] = "Server Port";
		nextLine[k++] = "Server SID";
		nextLine[k++] = "Server Username";
		nextLine[k++] = "Server Password";
		nextLine[k++] = "Server Schema";
		nextLine[k++] = "Server Table";
		nextLine[k++] = "Server DatabaseType";
		nextLine[k++] = "mssqlSchema";
		writer.writeNext(nextLine);
		for (int i = 0; i < exportConfigs.size(); i++) {
			k = 0;
			nextLine[k++] = exportConfigs.get(i).getServer().getName();
			nextLine[k++] = exportConfigs.get(i).getServer().getIp();
			nextLine[k++] = exportConfigs.get(i).getServer().getPort();
			nextLine[k++] = exportConfigs.get(i).getServer().getSID();
			nextLine[k++] = exportConfigs.get(i).getServer().getUser();
			nextLine[k++] = exportConfigs.get(i).getServer().getPassword();
			nextLine[k++] = exportConfigs.get(i).getSchema();
			nextLine[k++] = exportConfigs.get(i).getTable();
			nextLine[k++] = exportConfigs.get(i).getServer().getDatabaseType();
			if(exportConfigs.get(i).getServer().getDatabaseType().equalsIgnoreCase("mssql"))
				nextLine[k++] = ServerList.getTableMap().get(exportConfigs.get(i).getTable()).getDatabaseSchema();
			else
				nextLine[k++]="";
			writer.writeNext(nextLine);
		}
		writer.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
Example 69
Project: RedMetrics   File: SnapshotCsvEntityConverter.java   Source Code and License Vote up 4 votes
@Override
public void write(CSVWriter csvWriter, List<Snapshot> models) {
    String[] staticColumnNames = {
            "id",
            "serverTime",
            "userTime",
            "gameVersion",
            "playerId",
            "playerBirthdate",
            "playerRegion",
            "playerCountry",
            "playerGender",
            "playerExternalId",
            "playerCustomData",
            "type",
            "section"
    };

    CsvHelper.UnpackedCustomData unpackedCustomData = CsvHelper.unpackCustomData(models);

    String[] customDataColumnNames = unpackedCustomData.columnNames.toArray(new String[0]);
    String[] allColumnNames = CsvHelper.concatenateArrays(staticColumnNames, customDataColumnNames);

    csvWriter.writeNext(allColumnNames);

    // Write out rows
    for(int i = 0; i < models.size(); i++) {
        Snapshot model = models.get(i);

        // We need to include additional fields of the player
        // OPT: does this force a new request each time? if so we should join automatically
        playerDao.refresh(model.getPlayer());

        String[] staticRowValues = {
                model.getId().toString(),
                CsvHelper.formatDate(model.getServerTime()),
                CsvHelper.formatDate(model.getUserTime()),
                model.getGameVersion().getId().toString(),
                model.getPlayer().getId().toString(),
                CsvHelper.formatDate(model.getPlayer().getBirthDate()),
                model.getPlayer().getRegion(),
                model.getPlayer().getCountry(),
                CsvHelper.formatGender(model.getPlayer().getGender()),
                model.getPlayer().getExternalId(),
                model.getPlayer().getCustomData(),
                model.getSection()
        };

        // Write out the custom data in order, skipping fields with no data
        Map<String, String> rowValues = unpackedCustomData.rowValues.get(i);
        String[] customDataRowValues = unpackedCustomData.columnNames.stream().map(columnName -> rowValues.get(columnName)).toArray(String[]::new);
        String[] allRowValues = CsvHelper.concatenateArrays(staticRowValues, customDataRowValues);

        csvWriter.writeNext(allRowValues);
    }
}
 
Example 70
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 71
Project: Thesis-JHipster   File: CSVUtils.java   Source Code and License Vote up 2 votes
/**
 * add new line to the CSVfile 
 * 
 * @param filename Name of the CSVfile
 * @param new line)
 *  
 */
public static void writeNewLineCSV(String filename, String[] line) throws IOException {
	CSVWriter writer = new CSVWriter(new FileWriter(filename, true),';');
	writer.writeNext(line);
	writer.close();
}
 
Example 72
Project: voc   File: LocalProfile.java   Source Code and License Vote up 2 votes
/**
 *
 * @param writer
 * @param line
 * @throws IOException
 */
public static void saveCSVLine (CSVWriter writer, String[] line) throws IOException {
    writer.writeNext(line);
}