com.csvreader.CsvWriter Java Examples

The following examples show how to use com.csvreader.CsvWriter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UnstructuredStorageWriterUtil.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public static String doTransportOneRecord(List<String> splitedRows,
        char fieldDelimiter, String fileFormat) {
    if (splitedRows.isEmpty()) {
        LOG.info("Found one record line which is empty.");
    }
    // warn: false means plain text(old way), true means strict csv format
    if (Constant.FILE_FORMAT_TEXT.equals(fileFormat)) {
        return StringUtils.join(splitedRows, fieldDelimiter)
                + IOUtils.LINE_SEPARATOR;
    } else {
        StringWriter sw = new StringWriter();
        CsvWriter csvWriter = new CsvWriter(sw, fieldDelimiter);
        csvWriter.setTextQualifier('"');
        csvWriter.setUseTextQualifier(true);
        // warn: in linux is \n , in windows is \r\n
        csvWriter.setRecordDelimiter(IOUtils.LINE_SEPARATOR.charAt(0));
        UnstructuredStorageWriterUtil.csvWriteSlience(csvWriter,
                splitedRows);
        return sw.toString();
        // sw.close(); //no need do this
    }
}
 
Example #2
Source File: BulkResultSetTest.java    From components with Apache License 2.0 6 votes vote down vote up
private int prepareSafetySwitchTest(boolean safetySwitchParameter, int columnLength) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CsvWriter csvWriter = new CsvWriter(new BufferedOutputStream(out), ',', Charset.forName("UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < columnLength; i++) {
        sb.append("a");
    }
    String[] data = new String[] { "fieldValueA", "fieldValueB", sb.toString() };
    csvWriter.writeRecord(data);
    csvWriter.close();

    CsvReader csvReader = new CsvReader(new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())), ',',
            Charset.forName("UTF-8"));
    csvReader.setSafetySwitch(safetySwitchParameter);
    BulkResultSet resultSet = new BulkResultSet(csvReader, Arrays.asList("fieldA", "fieldB", "fieldC"));
    BulkResult result = resultSet.next();
    return ((String) result.getValue("fieldC")).length();
}
 
Example #3
Source File: AbstractStatisticsReportHandler.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeReport(OutputStream outputStream) throws IOException {
    CsvWriter writer = new CsvWriter(outputStream, ',', Charset.defaultCharset());
    try {
        List<String> header = getHeaderColumns();
        writer.writeRecord(header.toArray(new String[0]));
        for (ReportRow row : getReportRows()) {
            for (String columnName : header) {
                ReportValue cellValue = row.get(columnName);
                String toWrite = cellValue != null ? cellValue.toString() : StringUtils.EMPTY;
                writer.write(toWrite);
            }
            writer.endRecord();
        }
    } finally {
        writer.close();
    }
}
 
Example #4
Source File: UnstructuredStorageWriterUtil.java    From DataLink with Apache License 2.0 5 votes vote down vote up
private static void csvWriteSlience(CsvWriter csvWriter,
        List<String> splitedRows) {
    try {
        csvWriter
                .writeRecord((String[]) splitedRows.toArray(new String[0]));
    } catch (IOException e) {
        // shall not happen
        throw DataXException.asDataXException(
                UnstructuredStorageWriterErrorCode.RUNTIME_EXCEPTION,
                String.format("转换CSV格式失败[%s]",
                        StringUtils.join(splitedRows, " ")));
    }
}
 
Example #5
Source File: BulkResultSetTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testResultSet() throws IOException {

    final int recordCount = 100;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CsvWriter csvWriter = new CsvWriter(new BufferedOutputStream(out),
            ',', Charset.forName("UTF-8"));

    for (int i = 0; i < recordCount; i++) {
        csvWriter.writeRecord(new String[]{
                "fieldValueA" + i,
                "fieldValueB" + i,
                "fieldValueC" + i
        });
    }
    csvWriter.close();

    CsvReader csvReader = new CsvReader(
            new BufferedInputStream(new ByteArrayInputStream(out.toByteArray())),
            ',', Charset.forName("UTF-8"));

    BulkResultSet resultSet = new BulkResultSet(csvReader, Arrays.asList("fieldA", "fieldB", "fieldC"));

    int count = 0;
    BulkResult result;
    while ((result = resultSet.next()) != null) {
        assertEquals("fieldValueA" + count, result.getValue("fieldA"));
        assertEquals("fieldValueB" + count, result.getValue("fieldB"));
        assertEquals("fieldValueC" + count, result.getValue("fieldC"));

        count++;
    }

    assertEquals(recordCount, count);
}
 
Example #6
Source File: S3OutputWriter.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
public void open(String uId) throws IOException {
    // connect to s3
    s3_client = S3Connection.createClient(properties);
    //Test whether the bucket exist and authorized to current user.
    s3_client.getBucketAcl(properties.getDatasetProperties().bucket.getValue());

    // prepare the local target, will upload it to s3 and clear it in the close method
    data_file = File.createTempFile("s3-", ".csv");

    OutputStream outputStream = new FileOutputStream(data_file);
    writer = new CsvWriter(new OutputStreamWriter(outputStream), ';');
}
 
Example #7
Source File: BulkFileWriter.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
public void open(String uId) throws IOException {
    this.uId = uId;
    this.result = new Result(uId);
    String filepath = bulkProperties.bulkFilePath.getStringValue();
    if (filepath == null || filepath.isEmpty()) {
        throw new RuntimeException("Please set a valid value for \"Bulk File Path\" field.");
    }
    File file = new File(bulkProperties.bulkFilePath.getStringValue());
    file.getParentFile().mkdirs();
    csvWriter = new CsvWriter(new OutputStreamWriter(new java.io.FileOutputStream(file, isAppend), charset), separator);

    fileIsEmpty = (file.length() == 0);
}
 
Example #8
Source File: PerformanceMonitor.java    From Benchmark with GNU General Public License v3.0 5 votes vote down vote up
public PerformanceMonitor(Map<String, String> queryMap, long duration, int duplicates, String resultName)
		throws Exception {
	qMap = queryMap;
	this.duration = duration;
	this.resultName = resultName;
	this.duplicates = duplicates;
	File outputFile = new File("result_log" + File.separator + resultName + ".csv");
	if (outputFile.exists())
		throw new Exception("Result log file already exists.");
	cw = new CsvWriter(new FileWriter(outputFile, true), ',');
	cw.write("");
	qList = new ArrayList(this.qMap.keySet());
	Collections.sort(qList);

	for (String qid : qList) {
		latencyMap.put(qid, new ArrayList<Long>());
		resultCntMap.put(qid, (long) 0);
		cw.write("latency-" + qid);
	}
	// for (String qid : qList) {
	// cw.write("cnt-" + qid);
	// }
	cw.write("memory");
	cw.endRecord();
	// cw.flush();
	// cw.
	this.globalInit = System.currentTimeMillis();
}
 
Example #9
Source File: GridUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Writes a CSV representation of the given Grid to the given OutputStream.
 */
public static void toCsv( Grid grid, Writer writer )
    throws IOException
{
    if ( grid == null )
    {
        return;
    }

    CsvWriter csvWriter = new CsvWriter( writer, CSV_DELIMITER );

    Iterator<GridHeader> headers = grid.getHeaders().iterator();

    if ( !grid.getHeaders().isEmpty() )
    {
        while ( headers.hasNext() )
        {
            csvWriter.write( headers.next().getColumn() );
        }

        csvWriter.endRecord();
    }

    for ( List<Object> row : grid.getRows() )
    {
        for ( Object value : row )
        {
            csvWriter.write( value != null ? String.valueOf( value ) : StringUtils.EMPTY );
        }

        csvWriter.endRecord();
    }
}
 
Example #10
Source File: StreamingCsvDataValueSet.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public StreamingCsvDataValueSet( CsvWriter writer )
{
    this.writer = writer;
    
    try
    {
        this.writer.writeRecord( StreamingCsvDataValue.getHeaders() ); // Write headers
    }
    catch ( IOException ex )
    {
        throw new RuntimeException( "Failed to write CSV headers", ex );
    }
}
 
Example #11
Source File: CVSManager.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean exportBodyParts(File exportDir, Profile pProfile) {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_H_m_s", Locale.getDefault());
        Date date = new Date();

        // use FileWriter constructor that specifies open for appending
        CsvWriter cvsOutput = new CsvWriter(exportDir.getPath() + "/" + "EF_" + pProfile.getName() + "_CustomBodyPart_" + dateFormat.format(date) + ".csv", ',', Charset.forName("UTF-8"));
        DAOBodyPart daoBodyPart = new DAOBodyPart(mContext);
        daoBodyPart.open();


        List<BodyPart> bodyParts;
        bodyParts = daoBodyPart.getList();

        cvsOutput.write(TABLE_HEAD);
        cvsOutput.write(DAOBodyPart.KEY);
        cvsOutput.write(DAOBodyPart.CUSTOM_NAME);
        cvsOutput.write(DAOBodyPart.CUSTOM_PICTURE);
        cvsOutput.endRecord();

        for (BodyPart bp : bodyParts ) {
            if (bp.getBodyPartResKey()==-1) { // Only custom BodyPart are exported
                cvsOutput.write(DAOBodyMeasure.TABLE_NAME);
                cvsOutput.write(Long.toString(bp.getId()));
                cvsOutput.write(bp.getName(mContext));
                cvsOutput.write(bp.getCustomPicture());
                cvsOutput.endRecord();
            }
        }
        cvsOutput.close();
        daoBodyPart.close();
    } catch (Exception e) {
        //if there are any exceptions, return false
        e.printStackTrace();
        return false;
    }
    //If there are no errors, return true.
    return true;
}
 
Example #12
Source File: LocalOnlineApplication.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
private void writeCsvViolations(String basecase, List<LimitViolation> networkViolations, CsvWriter cvsWriter)
        throws IOException {
    for (LimitViolation violation : networkViolations) {
        String[] values = new String[] {basecase, violation.getSubjectId(), violation.getLimitType().name(),
                Double.toString(violation.getValue()), Double.toString(violation.getLimit()) };
        cvsWriter.writeRecord(values);
    }
    cvsWriter.flush();
}
 
Example #13
Source File: StatisticsUtils.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static void writeTagGroupReportRow(TagGroupReportRow row,DecimalFormat format, CsvWriter writer) throws IOException {
    writer.write(Arrays.toString(row.getDimensionsPath()));
    //writer.write(Long.toString(row.getTotalExecTime()));
    writer.write(row.getFormattedExecTime());
    writer.write(Long.toString(row.getTotalTcCount()));
    writer.write(Long.toString(row.getPassedCount()));
    writer.write(Long.toString(row.getFailedCount()));
    writer.write(Long.toString(row.getConditionallyPassedCount()));
    writer.write(format.format(row.getPassedPercent()));
    writer.write(format.format(row.getConditionallyPassedPercent()));
    writer.write(format.format(row.getFailedPercent()));
    writer.write(format.format(row.getTotalMatrices()));
    writer.write(format.format(row.getFailedMatrices()));
    writer.endRecord();
}
 
Example #14
Source File: StatisticsUtils.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static void writeChildNotes(String parentName, DecimalFormat format, List<TagGroupReportResult> results,
                                    int curLevelIndex, CsvWriter writer) throws IOException {
    List<TagGroupReportRow> rowsCurrentLev = results.get(curLevelIndex).getRows();
    for (TagGroupReportRow row : rowsCurrentLev) {
        if (parentName == null || row.getDimensionsPath()[curLevelIndex - 1].equals(parentName)) {
            writeTagGroupReportRow(row, format, writer);
            if(curLevelIndex < results.size() -1) {
                writeChildNotes(row.getDimensionsPath()[curLevelIndex], format, results, curLevelIndex + 1, writer);
            }
        }
    }
}
 
Example #15
Source File: StatisticsUtils.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
private static void writeTagGroupReportToCsv(List<TagGroupReportResult> results, CsvWriter writer) throws IOException {
    if(results == null || results.isEmpty()) {
        return;
    }
    DecimalFormat format = new DecimalFormat("###.00");
    writeChildNotes(null, format, results, 0, writer);
}
 
Example #16
Source File: PrintOnlineWorkflowWcaResultsTool.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) throws Exception {
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    String workflowId = line.getOptionValue("workflow");
    OnlineWorkflowWcaResults wfWcaResults = onlinedb.getWcaResults(workflowId);
    if (wfWcaResults != null) {
        if (!wfWcaResults.getContingencies().isEmpty()) {
            Table table = new Table(7, BorderStyle.CLASSIC_WIDE);
            StringWriter content = new StringWriter();
            CsvWriter cvsWriter = new CsvWriter(content, ',');
            String[] headers = new String[7];
            int i = 0;
            table.addCell("Contingency", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Contingency";
            table.addCell("Cluster 1", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Cluster 1";
            table.addCell("Cluster 2", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Cluster 2";
            table.addCell("Cluster 3", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Cluster 3";
            table.addCell("Cluster 4", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Cluster 4";
            table.addCell("Undefined", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Undefined";
            table.addCell("Cause", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Cause";
            cvsWriter.writeRecord(headers);
            for (String contingencyId : wfWcaResults.getContingencies()) {
                String[] values = new String[7];
                i = 0;
                table.addCell(contingencyId);
                values[i++] = contingencyId;
                int[] clusterIndexes = new int[]{1, 2, 3, 4, -1};
                for (int k = 0; k < clusterIndexes.length; k++) {
                    if (clusterIndexes[k] == wfWcaResults.getClusterIndex(contingencyId)) {
                        table.addCell("X", new CellStyle(CellStyle.HorizontalAlign.center));
                        values[i++] = "X";
                    } else {
                        table.addCell("-", new CellStyle(CellStyle.HorizontalAlign.center));
                        values[i++] = "-";
                    }
                }
                table.addCell(Objects.toString(wfWcaResults.getCauses(contingencyId), " "), new CellStyle(CellStyle.HorizontalAlign.center));
                values[i++] = Objects.toString(wfWcaResults.getCauses(contingencyId), " ");
                cvsWriter.writeRecord(values);
            }
            cvsWriter.flush();
            if (line.hasOption("csv")) {
                context.getOutputStream().println(content.toString());
            } else {
                context.getOutputStream().println(table.render());
            }
            cvsWriter.close();
        } else {
            context.getOutputStream().println("\nNo results of security rules applications for this workflow");
        }
    } else {
        context.getOutputStream().println("No results for this workflow");
    }
    onlinedb.close();
}
 
Example #17
Source File: PrintOnlineWorkflowOptimizerResultsTool.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
@Override
    public void run(CommandLine line, ToolRunningContext context) throws Exception {
        OnlineConfig config = OnlineConfig.load();
        OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
        String workflowId = line.getOptionValue("workflow");
        OnlineWorkflowResults wfResults = onlinedb.getResults(workflowId);
        if (wfResults != null) {
            if (!wfResults.getContingenciesWithActions().isEmpty()) {
                Table table = new Table(5, BorderStyle.CLASSIC_WIDE);
                StringWriter content = new StringWriter();
                CsvWriter cvsWriter = new CsvWriter(content, ',');
                String[] headers = new String[5];
                int i = 0;
                table.addCell("Contingency", new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = "Contingency";
                table.addCell("State", new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = "State";
                table.addCell("Actions Found", new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = "Actions Found";
                table.addCell("Status", new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = "Status";
                table.addCell("Actions", new CellStyle(CellStyle.HorizontalAlign.center));
                headers[i++] = "Actions";
                cvsWriter.writeRecord(headers);
                for (String contingencyId : wfResults.getContingenciesWithActions()) {
                    for (Integer stateId : wfResults.getUnsafeStatesWithActions(contingencyId).keySet()) {
                        String[] values = new String[5];
                        i = 0;
                        table.addCell(contingencyId);
                        values[i++] = contingencyId;
                        table.addCell(stateId.toString(), new CellStyle(CellStyle.HorizontalAlign.right));
                        values[i++] = stateId.toString();
                        table.addCell(Boolean.toString(wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId)), new CellStyle(CellStyle.HorizontalAlign.right));
                        values[i++] = Boolean.toString(wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId));
                        table.addCell(wfResults.getStateStatus(contingencyId, stateId).name());
                        values[i++] = wfResults.getStateStatus(contingencyId, stateId).name();
                        String json = "-";
                        if (wfResults.getActionsIds(contingencyId, stateId) != null) {
//                            json = Utils.actionsToJson(wfResults, contingencyId, stateId);
                            json = Utils.actionsToJsonExtended(wfResults, contingencyId, stateId);
                        }
                        table.addCell(json);
                        values[i++] = json;
                        cvsWriter.writeRecord(values);
                    }
                }
                cvsWriter.flush();
                if (line.hasOption("csv")) {
                    context.getOutputStream().println(content.toString());
                } else {
                    context.getOutputStream().println(table.render());
                }
                cvsWriter.close();
            } else {
                context.getOutputStream().println("\nNo contingencies requiring corrective actions");
            }
        } else {
            context.getOutputStream().println("No results for this workflow");
        }
        onlinedb.close();
    }
 
Example #18
Source File: CVSManager.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean exportRecords(File exportDir, Profile pProfile) {
    try {
        // FONTE
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_H_m_s", Locale.getDefault());
        Date date = new Date();

        CsvWriter csvOutputFonte = new CsvWriter(exportDir.getPath() + "/" + "EF_" + pProfile.getName() + "_Records_" + dateFormat.format(date) + ".csv", ',', Charset.forName("UTF-8"));

        /**This is our database connector class that reads the data from the database.
         * The code of this class is omitted for brevity.
         */
        DAORecord dbc = new DAORecord(mContext);
        dbc.open();

        /**Let's read the first table of the database.
         * getFirstTable() is a method in our DBCOurDatabaseConnector class which retrieves a Cursor
         * containing all records of the table (all fields).
         * The code of this class is omitted for brevity.
         */
        List<Record> records = null;
        Cursor cursor = dbc.getAllRecordsByProfile(pProfile);
        records = dbc.fromCursorToList(cursor);


        //Write the name of the table and the name of the columns (comma separated values) in the .csv file.
        csvOutputFonte.write(TABLE_HEAD);
        csvOutputFonte.write(ID_HEAD);
        csvOutputFonte.write(DAORecord.DATE);
        csvOutputFonte.write(DAORecord.TIME);
        csvOutputFonte.write(DAORecord.EXERCISE);
        csvOutputFonte.write(DAORecord.EXERCISE_TYPE);
        csvOutputFonte.write(DAORecord.PROFILE_KEY);
        csvOutputFonte.write(DAORecord.SETS);
        csvOutputFonte.write(DAORecord.REPS);
        csvOutputFonte.write(DAORecord.WEIGHT);
        csvOutputFonte.write(DAORecord.WEIGHT_UNIT);
        csvOutputFonte.write(DAORecord.SECONDS);
        csvOutputFonte.write(DAORecord.DISTANCE);
        csvOutputFonte.write(DAORecord.DISTANCE_UNIT);
        csvOutputFonte.write(DAORecord.DURATION);
        csvOutputFonte.write(DAORecord.NOTES);
        csvOutputFonte.write(DAORecord.RECORD_TYPE);
        csvOutputFonte.endRecord();

        for (int i = 0; i < records.size(); i++) {
            csvOutputFonte.write(DAORecord.TABLE_NAME);
            csvOutputFonte.write(Long.toString(records.get(i).getId()));

            Date dateRecord = records.get(i).getDate();

            csvOutputFonte.write(DateConverter.dateToDBDateStr(dateRecord));
            csvOutputFonte.write(records.get(i).getTime());
            csvOutputFonte.write(records.get(i).getExercise());
            csvOutputFonte.write(Integer.toString(ExerciseType.STRENGTH.ordinal()));
            csvOutputFonte.write(Long.toString(records.get(i).getProfileId()));
            csvOutputFonte.write(Integer.toString(records.get(i).getSets()));
            csvOutputFonte.write(Integer.toString(records.get(i).getReps()));
            csvOutputFonte.write(Float.toString(records.get(i).getWeight()));
            csvOutputFonte.write(Integer.toString(records.get(i).getWeightUnit().ordinal()));
            csvOutputFonte.write(Integer.toString(records.get(i).getSeconds()));
            csvOutputFonte.write(Float.toString(records.get(i).getDistance()));
            csvOutputFonte.write(Integer.toString(records.get(i).getDistanceUnit().ordinal()));
            csvOutputFonte.write(Long.toString(records.get(i).getDuration()));
            if (records.get(i).getNote() == null) csvOutputFonte.write("");
            else csvOutputFonte.write(records.get(i).getNote());
            csvOutputFonte.write(Integer.toString(records.get(i).getRecordType().ordinal()));
            csvOutputFonte.endRecord();
        }
        csvOutputFonte.close();
        dbc.closeAll();
    } catch (Exception e) {
        //if there are any exceptions, return false
        e.printStackTrace();
        return false;
    }
    //If there are no errors, return true.
    return true;
}
 
Example #19
Source File: CVSManager.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean exportBodyMeasures(File exportDir, Profile pProfile) {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_H_m_s", Locale.getDefault());
        Date date = new Date();

        // use FileWriter constructor that specifies open for appending
        CsvWriter cvsOutput = new CsvWriter(exportDir.getPath() + "/" + "EF_" + pProfile.getName() + "_BodyMeasures_" + dateFormat.format(date) + ".csv", ',', Charset.forName("UTF-8"));
        DAOBodyMeasure daoBodyMeasure = new DAOBodyMeasure(mContext);
        daoBodyMeasure.open();

        DAOBodyPart daoBodyPart = new DAOBodyPart(mContext);

        List<BodyMeasure> bodyMeasures;
        bodyMeasures = daoBodyMeasure.getBodyMeasuresList(pProfile);

        cvsOutput.write(TABLE_HEAD);
        cvsOutput.write(ID_HEAD);
        cvsOutput.write(DAOBodyMeasure.DATE);
        cvsOutput.write("bodypart_label");
        cvsOutput.write(DAOBodyMeasure.MEASURE);
        cvsOutput.write(DAOBodyMeasure.PROFIL_KEY);
        cvsOutput.endRecord();

        for (int i = 0; i < bodyMeasures.size(); i++) {
            cvsOutput.write(DAOBodyMeasure.TABLE_NAME);
            cvsOutput.write(Long.toString(bodyMeasures.get(i).getId()));
            Date dateRecord = bodyMeasures.get(i).getDate();
            cvsOutput.write(DateConverter.dateToDBDateStr(dateRecord));
            BodyPart bp = daoBodyPart.getBodyPart(bodyMeasures.get(i).getBodyPartID());
            cvsOutput.write(bp.getName(mContext)); // Write the full name of the BodyPart
            cvsOutput.write(Float.toString(bodyMeasures.get(i).getBodyMeasure()));
            cvsOutput.write(Long.toString(bodyMeasures.get(i).getProfileID()));

            cvsOutput.endRecord();
        }
        cvsOutput.close();
        daoBodyMeasure.close();
    } catch (Exception e) {
        //if there are any exceptions, return false
        e.printStackTrace();
        return false;
    }
    //If there are no errors, return true.
    return true;
}
 
Example #20
Source File: CVSManager.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private boolean exportExercise(File exportDir, Profile pProfile) {
    try {
        // FONTE
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_H_m_s", Locale.getDefault());
        Date date = new Date();

        CsvWriter csvOutput = new CsvWriter(exportDir.getPath() + "/" + "EF_" + pProfile.getName() + "_Exercises_" + dateFormat.format(date) + ".csv", ',', Charset.forName("UTF-8"));

        /**This is our database connector class that reads the data from the database.
         * The code of this class is omitted for brevity.
         */
        DAOMachine dbcMachine = new DAOMachine(mContext);
        dbcMachine.open();

        /**Let's read the first table of the database.
         * getFirstTable() is a method in our DBCOurDatabaseConnector class which retrieves a Cursor
         * containing all records of the table (all fields).
         * The code of this class is omitted for brevity.
         */
        List<Machine> records = null;
        records = dbcMachine.getAllMachinesArray();

        //Write the name of the table and the name of the columns (comma separated values) in the .csv file.
        csvOutput.write(TABLE_HEAD);
        csvOutput.write(ID_HEAD);
        csvOutput.write(DAOMachine.NAME);
        csvOutput.write(DAOMachine.DESCRIPTION);
        csvOutput.write(DAOMachine.TYPE);
        csvOutput.write(DAOMachine.BODYPARTS);
        csvOutput.write(DAOMachine.FAVORITES);
        //csvOutput.write(DAOMachine.PICTURE_RES);
        csvOutput.endRecord();

        for (int i = 0; i < records.size(); i++) {
            csvOutput.write(DAOMachine.TABLE_NAME);
            csvOutput.write(Long.toString(records.get(i).getId()));
            csvOutput.write(records.get(i).getName());
            csvOutput.write(records.get(i).getDescription());
            csvOutput.write(Integer.toString(records.get(i).getType().ordinal()));
            csvOutput.write(records.get(i).getBodyParts());
            csvOutput.write(Boolean.toString(records.get(i).getFavorite()));
            //write the record in the .csv file
            csvOutput.endRecord();
        }
        csvOutput.close();
        dbcMachine.close();
    } catch (Exception e) {
        //if there are any exceptions, return false
        e.printStackTrace();
        return false;
    }
    //If there are no errors, return true.
    return true;
}
 
Example #21
Source File: ExcelUtils.java    From FEBS-Security with Apache License 2.0 4 votes vote down vote up
public boolean toCsv(List<?> data, String path) {
    try {
        requiredbuilderParams();
        if (data == null || data.isEmpty()) {
            return false;
        }

        // 导出列查询。
        ExportConfig currentExportConfig;
        ExportItem currentExportItem;
        List<ExportItem> exportItems = new ArrayList<>();
        for (Field field : mClass.getDeclaredFields()) {

            currentExportConfig = field.getAnnotation(ExportConfig.class);
            if (currentExportConfig != null) {
                currentExportItem = new ExportItem().setField(field.getName())
                        .setDisplay("field".equals(currentExportConfig.value()) ? field.getName()
                                : currentExportConfig.value())
                        .setConvert(currentExportConfig.convert()).setReplace(currentExportConfig.replace());
                exportItems.add(currentExportItem);
            }

        }

        String cellValue;
        FileOutputStream out = new FileOutputStream(path);
        // 解决乱码
        out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
        CsvWriter csvWriter = new CsvWriter(out, ',', Charset.forName("UTF-8"));
        String[] csvHeadersArr = exportItems.stream().map(ExportItem::getDisplay).toArray(String[]::new);
        csvWriter.writeRecord(csvHeadersArr);
        for (Object aData : data) {
            List<Object> csvContent = new ArrayList<>();
            for (ExportItem exportItem : exportItems) {
                // 处理单元格值
                cellValue = exportItem.getReplace();
                if (!StringUtils.isNotBlank(cellValue)) {
                    cellValue = BeanUtils.getProperty(aData, exportItem.getField());
                }

                // 格式化单元格值
                if (StringUtils.isNotBlank(exportItem.getConvert())) {
                    cellValue = convertCellValue(cellValue, exportItem.getConvert());
                }
                csvContent.add(cellValue);
            }
            String[] csvContentArr = csvContent.toArray(new String[0]);
            csvWriter.writeRecord(csvContentArr);
        }
        csvWriter.close();
        return true;
    } catch (Exception e) {
        log.error(e.getMessage());
        return false;
    }
}
 
Example #22
Source File: StreamingCsvDataValue.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public StreamingCsvDataValue( CsvWriter writer )
{
    this.writer = writer;
    this.values = new ArrayList<>();
}
 
Example #23
Source File: FileOperation.java    From Benchmark with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	// File trafficRawDirectory = new File("streams");
	// File[] trafficRawFiles = trafficRawDirectory.listFiles();
	// for (File tr : trafficRawFiles) {
	// System.out.println("renaming: " + tr.toPath());
	// File newTr;
	// if (tr.getName().contains("traffic")) {
	// newTr = new File("streams" + File.separator + "AarhusT"
	// + tr.getName().substring(1, tr.getName().length()));
	// tr.renameTo(newTr);
	// } else if (tr.getName().contains("pollution")) {
	// newTr = new File("streams" + File.separator + "AarhusP"
	// + tr.getName().substring(1, tr.getName().length()));
	// tr.renameTo(newTr);
	// }
	//
	// // Files.copy(tr.toPath(), newTr.toPath());
	// }
	CsvReader streamData = new CsvReader("dataset/aarhus_parking.csv");
	streamData.setTrimWhitespace(false);
	streamData.setDelimiter(',');
	streamData.readHeaders();

	List<String> streamNames = new ArrayList<String>();
	streamNames.add("NORREPORT");
	streamNames.add("BUSGADEHUSET");
	streamNames.add("BRUUNS");
	streamNames.add("SKOLEBAKKEN");
	streamNames.add("SCANDCENTER");
	streamNames.add("SALLING");
	streamNames.add("MAGASIN");
	streamNames.add("KALKVAERKSVEJ");

	Map<String, CsvWriter> writerMap = new HashMap<String, CsvWriter>();
	for (String s : streamNames)
		try {
			// use FileWriter constructor that specifies open for appending
			String outputFile = "dataset/AarhusParkingData-" + s + ".stream";
			boolean alreadyExists = new File(outputFile).exists();
			CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

			// if the file didn't already exist then we need to write out the header line
			if (!alreadyExists) {
				csvOutput.write("vehiclecount");
				csvOutput.write("updatetime");
				csvOutput.write("_id");
				csvOutput.write("totalspaces");
				csvOutput.write("garagecode");
				csvOutput.write("streamtime");
				csvOutput.endRecord();
			}
			// }
			writerMap.put(s, csvOutput);
			// csvOutput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	while (streamData.readRecord()) {
		String code = streamData.get("garagecode");
		writerMap.get(code).write(streamData.get("vehiclecount"));
		writerMap.get(code).write(streamData.get("updatetime"));
		writerMap.get(code).write(streamData.get("_id"));
		writerMap.get(code).write(streamData.get("totalspaces"));
		writerMap.get(code).write(streamData.get("garagecode"));
		writerMap.get(code).write(streamData.get("streamtime"));
		writerMap.get(code).endRecord();
	}
	for (CsvWriter csv : writerMap.values())
		csv.close();
}
 
Example #24
Source File: CsvMessageWriter.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
public void writeAndClose(File file, List<MessageAdapter> messages) throws IOException {
	
	CsvWriter writer = new CsvWriter(new FileWriter(file), ',');
	writer.writeRecord( createHeader() );
	for(MessageAdapter m : messages) {
		writer.writeRecord(splitMessage(m));
	}
	writer.close();
}
 
Example #25
Source File: ExecutionReportExporter.java    From sailfish-core with Apache License 2.0 3 votes vote down vote up
public ExecutionReportExporter() throws IOException {
	
	resultFile = File.createTempFile("BBReport", null);
	
	writer = new CsvWriter(resultFile.getAbsolutePath());
	
	writeHeaders();
	
}
 
Example #26
Source File: CSVMatrixWriter.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
public CSVMatrixWriter(OutputStream outputStream, char delimiter, Charset charset) {

        writer = new CsvWriter(outputStream, delimiter, charset);
    }
 
Example #27
Source File: CsvUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Returns a {@link CsvWriter} using the UTF-8 char set.
 *
 * @param writer the {@link Writer}.
 * @return a {@link CsvWriter}.
 */
public static CsvWriter getWriter( Writer writer )
{
    return new CsvWriter( writer, DELIMITER );
}