joutvhu / fixed-width-parser

Fixed Width Parser: parse fixed width string to object and export object to fixed width string
MIT License
15 stars 3 forks source link
annotation annotations fixed-width-text java parser string-parser

Fixed Width Parser

Fixed Width Parser is a small library that purpose is:

Installation

compile "com.github.joutvhu:fixed-width-parser:1.1.5"
<dependency>
    <groupId>com.github.joutvhu</groupId>
    <artifactId>fixed-width-parser</artifactId>
    <version>1.1.5</version>
</dependency>

How to use?

The Fixed Width Parser makes it easy to switch back and forth between the string and the java object. You only need to use the annotations provided by Fixed Width Parser to annotate your model class to use the parser.

Annotate the model class

Here are some annotations that the parser offers you.

In addition to the annotations to describe the fixed width fields, the fixed-width-parser provides the following constraint annotations to validate fixed width value.

See the following example:

@FixedObject(subTypes = {
        @FixedObject.Type(value = Food.class, prop = "id", matchWith = "^[0-5].+$")
}, defaultSubType = Medicine.class)
public class Product {
    @FixedField(label = "Product Id", start = 0, length = 5)
    private Long id;

    @FixedField(label = "Product Name", start = 5, length = 20)
    private String name;
}

@FixedObject
public class Food extends Product {
    @FixedFormat(format = "MM/dd/yyyy")
    @FixedField(label = "Expiry Date", start = 25, length = 10)
    private LocalDate expiryDate;

    @FixedOption(options = {"rice  ", "breads", "fruit "})
    @FixedField(label = "Type", start = 35, length = 6)
    private String type;
}

@FixedObject
public class Medicine extends Product {
    @FixedFormat(format = "Y|N")
    @FixedField(label = "Topical", start = 25, length = 1)
    private Boolean topical;

    @FixedField(label = "Ingredients", start = 26, length = 60)
    private List<@FixedParam(length = 15) String> ingredients;
}

Convert fixed width string

Food food = (Food) FixedParser
        .parser()
        .parse(Product.class, "00001Dragon Fruit        09/30/2020fruit ");

Medicine medicine = (Medicine) FixedParser
        .parser()
        .parse(Product.class, "60002Golden Star Balm    YCamphor        Peppermint oil Menthol        Tea Tree Oil   ");
String value = FixedParser
    .parser()
    .export(food);