Search code examples
javaapache-camelfileparsingbean-io

Multiple Objects parsing in single file using BeanIO


I have following 2 types of records in a file, I can parse this file using BeanIO for any one of the record type 1 or 2 but I could not do both of them in a single parsor.I don't know how to use both of my mappings in single records. Please give me your guidance to do it.Thanks.

1   Length(20)    5       5        5      5      5
    Columns     S.No    Name    Street  City    Zip

2   Columns     S.No    Age Position        
    Length(20)    5      2   18 

mapping.xml

<record name="employee" class="com.Employee" collection="list" minOccurs="1" maxOccurs="unbounded">
<field name="S.No" length="5" />
<field name="Name" length="5" />
<field name="Street" length="5" />
<field name="City" length="5" />
<field name="Zip" length="5" />
</record>

<record name="employee" class="com.Employee" collection="list" minOccurs="1" maxOccurs="unbounded">
<field name="S.No" length="5" />
<field name="Age" length="2" />
<field name="Position" length="12" />
</record>

Update1: we can distinguish record using S.No There is no order of records also no dependency between records.

    001  Jose Str1 City 56005
    001  Hene Str1 City 66005
    005  20 General Manager  
    001  King Str1 City 76005
    005  20 General Manager  
    001  Leo  Str1 City 86005
    005  90 COO                
    005  70 Deputy Manager

Solution

  • You would need to have a class that contains a list of your Employee records

    public class EmployeeGroup {
    
      private List<Employee> employees;
      // getter + setter
    }
    

    Then you need a group definition in your mapping.xml to read all the Employee records

    <stream name="example" format="fixedlength">
      <group name="employeeGroup" class="com.EmployeeGroup">
        <record name="employees" class="com.Employee" minOccurs="1" maxOccurs="unbounded" collection="list">
          <field name="S.No" length="5" rid="true" literal="001"/>
          <field name="Name" length="5"/>
          <field name="Street" length="5"/>
          <field name="City" length="5"/>
          <field name="Zip" length="5"/>
        </record>
        <record name="employees" class="com.Employee" minOccurs="1" maxOccurs="unbounded" collection="list">
          <field name="S.No" length="5" rid="true" literal="005"/>
          <field name="Age" length="2"/>
          <field name="Position" length="12"/>
        </record>
      </group>
    </stream>
    

    Note the values for the literal attribute to identify the different records.