BeanIO Commands

Published: 2018-01-20, Updated: 2022-10-14

Exemplos

Classe comum para geração de CSV e Factories

public class CsvFactory {

  StreamFactory microsoftCsvFactory(Consumer<StreamBuilder> additionalConfigsHandler);
  
  void write(StreamFactory factory, Writer delegateWriter, Collection<?>... lists);
}

Escrever Header dynamicamente baseado no nome setado na anotação @Field do Record

public class Headers {

  public static void main(String[] args) {

    final String factoryName = "comma delimited csv factory";
    final String headerName = "CarHeader";

    final var builder = new StreamBuilder(factoryName)
        .format("csv")
        .addRecord(Headers.of(Car.class, headerName))
        .addRecord(Car.class)
        ;

    final var factory = StreamFactory.newInstance();
    factory.define(builder);

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final BeanWriter writer = factory.createWriter(factoryName, new OutputStreamWriter(bout));
    try {
      writer.write(headerName, null);
      writer.write(new Car("Ford Ka", 2016));
      writer.write(new Car("Ford Fusion", 2020));
    } finally {
      writer.close();
    }

    System.out.println(bout.toString());
//    Model,Year
//    Ford Ka,2016
//    Ford Fusion,2020
  }

  public static RecordBuilder of(Class<?> clazz, String name) {
    final RecordBuilder builder = new RecordBuilder(name)
        .order(1)
        .maxOccurs(1);

    if (clazz.getAnnotation(Record.class) == null) {
      throw new IllegalArgumentException("Class must be a BeanIo Record, annotated with @Record");
    }
    for (java.lang.reflect.Field classField : clazz.getDeclaredFields()) {

      final Field fieldAnnotation = classField.getAnnotation(Field.class);
      if (fieldAnnotation == null) {
        continue;
      }
      builder.addField(
          new FieldBuilder(fieldAnnotation.name())
              .defaultValue(fieldAnnotation.name())
      );

    }
    return builder;
  }

  @Record(order = 2)
  static class Car {

    @Field(name = "Model")
    private String model;

    @Field(name = "Year")
    private Integer year;

    public Car(String model, Integer year) {
      this.model = model;
      this.year = year;
    }

    public String getModel() {
      return model;
    }

    public Integer getYear() {
      return year;
    }

    public Car setModel(String model) {
      this.model = model;
      return this;
    }

    public Car setYear(Integer year) {
      this.year = year;
      return this;
    }
  }
}

CSV Exporter

public PedreiroExporter() {
	final RecordParserFactory parserFactory = new CsvParserBuilder()
		.delimiter(',')
		.recordTerminator("\r\n")
		.build()
		.getInstance();

	final StreamBuilder builder = new StreamBuilder(getClass().getName())
		.format("csv")
		.parser(parserFactory)
		.addTypeHandler(ListHandler.class.getName(), new ListHandler())
		.addRecord(PedreiroHeaderCSV.class)
		.addRecord(PedreiroCSV.class);

	factory = StreamFactory.newInstance();
	factory.define(builder);
}

public BeanWriter createWriter(Writer w){
	return this.factory.createWriter(getClass().getName(), w);
}

Criando um handler


public class ListHandler implements TypeHandler {
	@Override
	public Object parse(String text) throws TypeConversionException {
		throw new UnsupportedOperationException();
	}

	@Override
	public String format(Object value) {
		if(value == null){
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for (Object o : ((Collection) value)) {
			sb.append(o);
			sb.append(", ");
		}
		if(sb.length() > 0){
			sb.delete(sb.length() - 2, sb.length());
		}
		return sb.toString();
	}

	@Override
	public Class<?> getType() {
		return List.class;
	}
}

Gerando com zeros campos inteiros que sao nulos

Por default o beanio vai gerar o campo com espaços mesmo que voce especifique o padding 0 se ele nao for primitivo, eg. Integer, Long; para gerar com zeros mesmo assim ha duas opcoes

@Field(required = true)
@Field(defaultValue = true)
final StreamFactory factory = StreamFactory.newInstance();
final FixedLengthParserBuilder parser = new FixedLengthParserBuilder().recordTerminator("\n");
final StreamBuilder builder = new StreamBuilder("myname").format("fixedlength")
	.parser(parser)
	.addRecord(MyBean.class);
factory.define(builder);
final StringWriter out = new StringWriter();
final BeanWriter writer = factory.createWriter("myname", out);
writer.write(new MyBean());
writer.flush();

System.out.println(out.toString());


@Record
public class MyBean {

	@Field(align = Align.RIGHT, padding = '0', length = 10, required = true)
	private Integer id;
	
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
}

Keywords

beanio bean io


Counter Strike Commands Como escolher o melhor mouse para a sua mão - Logitech G Pro vs G403 vs G502 vs Deathader Elite

Comments