Java Code Examples for com.fasterxml.jackson.dataformat.csv.CsvSchema#Builder

The following examples show how to use com.fasterxml.jackson.dataformat.csv.CsvSchema#Builder . 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: SystemController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping( value = { "/uid", "/id" }, method = RequestMethod.GET, produces = { "application/csv" } )
public void getUidCsv( @RequestParam( required = false, defaultValue = "1" ) Integer limit, HttpServletResponse response )
    throws IOException, InvalidTypeException
{
    limit = Math.min( limit, 10000 );

    CsvGenerator csvGenerator = CSV_FACTORY.createGenerator( response.getOutputStream() );

    CsvSchema.Builder schemaBuilder = CsvSchema.builder()
        .addColumn( "uid" )
        .setUseHeader( true );

    csvGenerator.setSchema( schemaBuilder.build() );

    for ( int i = 0; i < limit; i++ )
    {
        csvGenerator.writeStartObject();
        csvGenerator.writeStringField( "uid", CodeGenerator.generateUid() );
        csvGenerator.writeEndObject();
    }

    csvGenerator.flush();
}
 
Example 2
Source File: CsvSchemaFactory.java    From s3-inventory-usage-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Build a CSV schema according to the content of the fileSchema in the manifest file
 * @param inventoryManifest the original manifest of the inventory report
 * @return CsvSchema
 */
public static CsvSchema buildSchema(InventoryManifest inventoryManifest){
    List<String> columnList = Arrays.asList(
            inventoryManifest.getFileSchema().split("\\s*,\\s*"));
    CsvSchema.Builder schemaBuilder = new CsvSchema.Builder();
    for (String eachColumn: columnList) {
        schemaBuilder.addColumn(eachColumn);
    }
    return schemaBuilder.build();
}
 
Example 3
Source File: FileTargetProcessorSubmitIssues.java    From FortifyBugTrackerUtility with MIT License 5 votes vote down vote up
@Override
protected boolean processMaps(Context context, String groupName, List<Object> currentGroup, List<LinkedHashMap<String, Object>> listOfMaps) {
	CsvSchema.Builder schemaBuilder = CsvSchema.builder();
    for (String col : getFields().keySet()) {
           schemaBuilder.addColumn(col);
       }
    CsvSchema schema = schemaBuilder.build().withHeader();
    try {
		new CsvMapper().writer(schema).writeValue(new File(groupName), listOfMaps);
	} catch (Exception e) {
		throw new RuntimeException("Error writing data to file "+groupName, e);
	}
	LOG.info(String.format("[File] Submitted %d vulnerabilities to %s", currentGroup.size(), groupName));
	return true;
}
 
Example 4
Source File: CsvNodeSerializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void startSerialize( RootNode rootNode, OutputStream outputStream ) throws Exception
{
    csvGenerator = CSV_FACTORY.createGenerator( outputStream );

    CsvSchema.Builder schemaBuilder = CsvSchema.builder()
        .setUseHeader( true );

    // build schema
    for ( Node child : rootNode.getChildren() )
    {
        if ( child.isCollection() )
        {
            if ( !child.getChildren().isEmpty() )
            {
                Node node = child.getChildren().get( 0 );

                for ( Node property : node.getChildren() )
                {
                    if ( property.isSimple() )
                    {
                        schemaBuilder.addColumn( property.getName() );
                    }
                }
            }
        }
    }

    csvGenerator.setSchema( schemaBuilder.build() );
}
 
Example 5
Source File: ReconciliationLogic.java    From syncope with Apache License 2.0 5 votes vote down vote up
private CsvSchema.Builder csvSchema(final AbstractCSVSpec spec) {
    CsvSchema.Builder schemaBuilder = new CsvSchema.Builder().setUseHeader(true).
            setColumnSeparator(spec.getColumnSeparator()).
            setArrayElementSeparator(spec.getArrayElementSeparator()).
            setQuoteChar(spec.getQuoteChar()).
            setLineSeparator(spec.getLineSeparator()).
            setNullValue(spec.getNullValue()).
            setAllowComments(spec.isAllowComments());
    if (spec.getEscapeChar() != null) {
        schemaBuilder.setEscapeChar(spec.getEscapeChar());
    }
    return schemaBuilder;
}
 
Example 6
Source File: CSVStreamConnector.java    From syncope with Apache License 2.0 5 votes vote down vote up
public CSVStreamConnector(
        final String keyColumn,
        final String arrayElementsSeparator,
        final CsvSchema.Builder schemaBuilder,
        final InputStream in,
        final OutputStream out,
        final String... columns) {

    this.keyColumn = keyColumn;
    this.arrayElementsSeparator = arrayElementsSeparator;
    this.schemaBuilder = schemaBuilder;
    this.in = in;
    this.out = out;
    this.columns = List.of(columns);
}
 
Example 7
Source File: JacksonCSVRecordReader.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JacksonCSVRecordReader(final InputStream in, final ComponentLog logger, final RecordSchema schema, final CSVFormat csvFormat, final boolean hasHeader, final boolean ignoreHeader,
                              final String dateFormat, final String timeFormat, final String timestampFormat, final String encoding) throws IOException {
    super(logger, schema, hasHeader, ignoreHeader, dateFormat, timeFormat, timestampFormat);

    final Reader reader = new InputStreamReader(new BOMInputStream(in));

    CsvSchema.Builder csvSchemaBuilder = CsvSchema.builder()
            .setColumnSeparator(csvFormat.getDelimiter())
            .setLineSeparator(csvFormat.getRecordSeparator())
            // Can only use comments in Jackson CSV if the correct marker is set
            .setAllowComments("#" .equals(CharUtils.toString(csvFormat.getCommentMarker())))
            // The call to setUseHeader(false) in all code paths is due to the way Jackson does data binding/mapping. Missing or extra columns may not
            // be handled correctly when using the header for mapping.
            .setUseHeader(false);

    csvSchemaBuilder = (csvFormat.getQuoteCharacter() == null) ? csvSchemaBuilder : csvSchemaBuilder.setQuoteChar(csvFormat.getQuoteCharacter());
    csvSchemaBuilder = (csvFormat.getEscapeCharacter() == null) ? csvSchemaBuilder : csvSchemaBuilder.setEscapeChar(csvFormat.getEscapeCharacter());

    if (hasHeader) {
        if (ignoreHeader) {
            csvSchemaBuilder = csvSchemaBuilder.setSkipFirstDataRow(true);
        }
    }

    CsvSchema csvSchema = csvSchemaBuilder.build();

    // Add remaining config options to the mapper
    List<CsvParser.Feature> features = new ArrayList<>();
    features.add(CsvParser.Feature.INSERT_NULLS_FOR_MISSING_COLUMNS);
    if (csvFormat.getIgnoreEmptyLines()) {
        features.add(CsvParser.Feature.SKIP_EMPTY_LINES);
    }
    if (csvFormat.getTrim()) {
        features.add(CsvParser.Feature.TRIM_SPACES);
    }

    ObjectReader objReader = mapper.readerFor(String[].class)
            .with(csvSchema)
            .withFeatures(features.toArray(new CsvParser.Feature[features.size()]));

    recordStream = objReader.readValues(reader);
}
 
Example 8
Source File: SimpleCSV.java    From synthea with Apache License 2.0 3 votes vote down vote up
/**
 * Convert the data in the given List of Maps to a String of CSV data. 
 * Each Map in the List represents one line of the resulting CSV. Uses the keySet from the 
 * first Map to populate the set of columns. This means that the first Map must contain all 
 * the columns desired in the final CSV. The order of the columns is specified by the order
 * provided by the first Map's keySet, so using an ordered Map implementation 
 * (such as LinkedHashMap) is recommended.
 * 
 * @param data List of Map data. CSV data read/modified from SimpleCSV.parse(...)
 * @return data formatted as a String containing raw CSV data
 * @throws IOException on file IO write errors.
 */
public static String unparse(List<? extends Map<String, String>> data) throws IOException {
  CsvMapper mapper = new CsvMapper();
  CsvSchema.Builder schemaBuilder = CsvSchema.builder();
  schemaBuilder.setUseHeader(true);

  Collection<String> columns = data.get(0).keySet();
  schemaBuilder.addColumns(columns, ColumnType.STRING);

  return mapper.writer(schemaBuilder.build()).writeValueAsString(data);
}