JDBC Importer

JDBC Importer Logo

JDBC Importer Tutorial 3 : One Table, Fixed Delimited File (New Delimiter Parser)

Please make sure you have the appropriate libraries in your classpath (including the JDBC driver used to connect to your database) before starting the tutorials.

In this tutorial, you'll learn the basics of creating a new Delimiter Parser and running the import with it. The table that will contain the rows imported is called employee and it has the following columns :

employee
NameType
idnumber(6)
firstnamevarchar(10)
lastnamevarchar(10)
jobdescriptionvarchar(10)
manageridnumber(6)
startdatedate
salarynumber(9,2)
departmentnumber(6)

Make sure that these table(s) are created in the database that you'll be importing data. You can find the oracle creation script in the samples directory under the filename : 'tutorial3/createtable_ora.sql'.

Now that the database is setup, you can examine the architecture to see how the Delimiter Parser is used during the import.

Architecture Background

The Delimiter Parser is used during the import for two functions: splitting the file into multiple rows that will be imported (the getNextRow() method) and splitting each row into multiple columns (the getValues() method).

The JDBCImporter requires that each Delimiter Parser be a Java Bean like object. All <property> tags defined inside the '<delimiter>' will be passed to the appropriate set method. For example, with the CSV Delimiter Parser, you define a property tag with the name 'columnDelimiter' inside the '<delimiter>' tag. The JDBCImporter looks for the 'setColumnDelimiter' method in the CSVDelimtierParser.java and calls it with the property value.

After the Delimiter Parser is created, the JDBCImporter will set the input reader (the setReader() method) before calling the two methods. The JDBCImporter will call the getNextRow() (followed by getValues()) until getNextRow() returns null.

Custom Delimiter Parser

The Delimiter Parser that you will be creating will be similar to the CSV Delimiter Parser found under the package net.sourceforge.jdbcimporter.parser. Here are the requirements for the Fixed Delimiter Parser :

The first thing to do is create the class FixedDelimiterParser that implements the DelimiterParser interface.

import java.io.Reader;
import java.io.BufferedReader;
import net.sourceforge.jdbcimporter.DelimiterParser;

public class FixedDelimiterParser implements DelimiterParser
{
  protected BufferedReader reader;
	
  public void setReader( Reader input ) 
  {
    reader = new BufferedReader( input );
  }
	
  public String   getNextRow() throws IOException 
  {
    /* todo implement this method */
    return null;	
  }
	
  public ColumnValue[] getValues(String nextRow) throws MalformedDataException
  {
    /* todo implement this method */
    return null;
  }
}
				
Initial Code

You would like the user to configure the Fixed Delimiter Parser with the number ranges for each column. So, the FixedDelimiterParser class needs to have a method to set the ranges. The method that we will use will take a double-array of ints. The first index will define the column index, while the second index will define the start and end point of the column data :

...

public class FixedDelimiterParser implements DelimiterParser
{
  ...
  protected int[][] columnPositions;
	
  ...
  public void setColumnPositions( int[][] positions )
  {
    columnPositions = positions;
  }
}
				
ColumnPositions property

You can define the XML in the import config file that will be used to construct and configure the Fixed Delimiter Parser. The XML will contain one property element named 'columnPositions' that will have a comma-separated list of number ranges. Here is an example:

  <delimiter type="tutorial_fixed"> 
    <property name="columnPositions" value="1-5,6-20,25-35"/> 
  </delimiter> 
Sample XML For Fixed Delimiter Parser

You now need to convert the comma-separated list of number ranges into a double array of integers. Following the Java Bean specification, you will have to create two classes: 'FixedDelimiterParserBeanInfo' and 'FixedDelimiterParserColumnPositionsEditor'. The 'FixedDelimiterParserBeanInfo' simply tells the JDBCImporter that there is a property called 'columnPositions' and that it should use the 'FixedDelimiterParserColumnPositionsEditor' to convert the string representation into a double array of integers. Here are both classes :

import java.beans.SimpleBeanInfo;
import java.beans.PropertyDescriptor;
import java.beans.BeanDescriptor;

public class FixedDelimiterParserBeanInfo extends SimpleBeanInfo 
{

  PropertyDescriptor[] descriptors;
  BeanDescriptor descriptor;
	
  public FixedDelimiterParserBeanInfo() throws java.beans.IntrospectionException
  {
    try
    {
      descriptors = new PropertyDescriptor[1];
      descriptors[0] = new PropertyDescriptor( "columnPositions", FixedDelimiterParser.class, null, "setColumnPositions" );
      descriptors[0].setPropertyEditorClass( FixedDelimiterParserColumnPositionsEditor.class );
    }
    catch ( java.beans.IntrospectionException e )
    {
      e.printStackTrace();
      throw e;
    }
    descriptor = new BeanDescriptor(FixedDelimiterParser.class);
  }
	
  public BeanDescriptor getBeanDescriptor()
  {
    return descriptor;
  }
	
  public PropertyDescriptor[] getPropertyDescriptors()
  {
    return descriptors;
  }
}
				
Bean Info for Fixed Delimiter Parser
import java.beans.PropertyEditorSupport;
import java.util.StringTokenizer;

public class FixedDelimiterParserColumnPositionsEditor extends PropertyEditorSupport 
{

  public void setAsText( String val ) throws IllegalArgumentException
  {
    StringTokenizer tokenizer = new StringTokenizer( val, "," );
    int[][] realColumnDefs = new int[tokenizer.countTokens()][2];
    int index = 0;
    while (tokenizer.hasMoreTokens())
    {
      String columnDef = tokenizer.nextToken();
      StringTokenizer rangeTokenizer = new StringTokenizer( columnDef, "-" );
      if ( rangeTokenizer.countTokens() != 2 )
      {
        throw new IllegalArgumentException( "Invalid column range '"+columnDef+"'" );
      }
      try
      {
        realColumnDefs[index][0] = Integer.parseInt( rangeTokenizer.nextToken() );
        if ( realColumnDefs[index][0] < 1 )
        {
          throw new IllegalArgumentException( "Invalid start column "+realColumnDefs[index][0] );
        }
        realColumnDefs[index][1] = Integer.parseInt( rangeTokenizer.nextToken() );
        if ( realColumnDefs[index][1] < 1 )
        {
          throw new IllegalArgumentException( "Invalid end column "+realColumnDefs[index][1] );
        }
        if ( realColumnDefs[index][0] >= realColumnDefs[index][1] )
        {
          throw new IllegalArgumentException( 
             "Invalid column range : "+realColumnDefs[index][0]+" >= "+realColumnDefs[index][1]);
        }
      }
      catch ( NumberFormatException n )
      {
        throw new IllegalArgumentException( "Invalid column range '"+columnDef+"'" );
      }
      index++;
    }
    setValue( realColumnDefs ); 
  }
}
				
Property Editor for ColumnPositions property

The 'FixedDelimiterParserColumnPositionEditor' parses the comma-separated string and validates each individual range. If the comma-separated string or the individual range is invalid then a IllegalArgumentException will be thrown. Otherwise, a properly configured Fixed Delimiter Parser will be returned.

Now that the Fixed Delimiter Parser is properly setup, the two methods need to be implemented. The first method 'getNextRow()' is implemented simply by reading the next line in the Reader:

...
public class FixedDelimiterParser implements DelimiterParser
{
...	
  public String getNextRow() throws IOException
  {
    return reader.readLine();
  }
...
}
				
getNextRow Implementation

The second method 'getValues()' will take the string and create a ColumnValue[] array by calling substring on the line.

...
public class FixedDelimiterParser implements DelimiterParser
{
...	
  public ColumnValue[] getValues(String nextRow) throws MalformedDataException
  {
    ColumnValue[] vals = new ColumnValue[columnPositions.length];
		
    for ( int i = 0; i < columnPositions.length; i++ )
    {
      if ( nextRow.length() < columnPositions[i][1] )
      {
        throw new MalformedDataException("Row is too short : "+nextRow.length()+" < "+columnPositions[i][1], nextRow, null );
      }
      vals[i] = new ColumnValue();
      vals[i].setString( nextRow.substring( columnPositions[i][0]-1, columnPositions[i][1] ) );
    }
    return vals;
  }
...
}
				
getValues Implementation

The Fixed Delimiter Parser validates the next row is long enough for each column range. It then sets the value of each ColumnValue. Its is important to note that the order of the ColumnValue array is the same as the order of the columnPositions.

This ends the tutorial for creating the custom Delimiter Parser. The full source code of the Fixed Delimiter Parser (with FixedDelimiterParserBeanInfo and FixedDelimiterParserColumnPositionsEditor) are found under the package samples.delimiterparser. What follows now is the instructions on how to use the custom Delimiter Parser during the import. If you have read through the first tutorial then you may wish to skip to the delimiter parser definition section. The other sections are the same as the first tutorial.

Import Config XML

Now that the database is setup, you can examine the import XML config file that will be used (in the samples directory under the filename : 'tutorial3/import.xml'). The file begins with the standard XML document declaration followed by the '<import>' tag. This tag indicates that there is an import to be processed. There are seven attributes specified on the '<import>' tag: the 'log' attribute, the 'bad' attribute, the 'commitCount', the 'batchCount' attribute, the 'preSQLFile' attribute, the 'postSQLFile' attribute and the 'trimValues' attribute. The 'log' attribute specifies a filename into which JDBCImporter writes all audit, error, and warnings that occur during the import. The 'bad' attribute specifies a filename into which JDBCImporter writes data that was not properly imported into the database. The 'commitCount' attribute specifies how many rows to import before calling commit on the JDBC Connection. The 'batchCount' attribute specifies how many rows to import before calling executeBatch on the import engine (when the JDBC driver supports batch mode). By default, the 'commitCount' and 'batchCount' attributes are set 1, auto commit is turned on and batch mode is not used. The 'preSQLFile' and the 'postSQLFile' attributes specify filenames that contain sql statements to be executed before and after the import , respectively. The 'trimValues' attribute specifies whether strings values read from the Delimiter Parser are trimmed (ie. remove leading and trailing whitespace). By default, it is set to false.

There are two parts inside the '<import>' tag that define how and where the data is imported: the connection definition and the entity definitions.

Connection Definition

The connection definition begins with '<connection>' tag and contains the information needed to connect to the database. In this tutorial, you will be using the JDBC DriverManager to initialize a connection to the database. To indicate this, the 'type' attribute's value, inside the '<connection>' tag, is 'jdbc'. The specific connection information is found inside the '<connection>' tag as '<property>' tags. A '<property>' tag has two attributes: 'name' specifies the name of the property and 'value' specifies the string value of the property. For the JDBC DriverManager, you will need to specify the following information: the driver class name (with the property name 'driver'), the connection url (with the property name 'url'), the username (with the property name 'username'), the password (with the property name 'password'). The following is an example of the connection definition :

 <connection type="jdbc"> 
    <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> 
    <property name="username" value="scott"/> 
    <property name="password" value="tiger"/> 
 </connection> 
Sample XML for Connection Definition

Entity Definition

Since you will be importing data into one table, there will be only one entity definition.In general, you will need an entity definition for each table that you will be importing data. Remember to specify the entity definitions in the order that the import should occur. For example, if table 'ingredient' depends on table 'recipe' (ie. has a foreign key), the entity definition of table 'recipe' should be placed before the entity definition of table 'ingredient'. Every entity definition begins with '<entity>' tag.

The 'table' attribute must contain the name of the table. Optionally, you can further specify the table by providing values for the 'schema' and the 'catalog' attributes.

To specify a custom import engine to process the entity, you may add the 'engine' attribute, whose value is the classname of the import engine.In this tutorial, you will be using the default import engine.

The 'source' attribute must contain the data file location. From looking at the sample data (found under 'samples/tutorial3/employee.dat'), you will see that the file is a fixed delimited file.

There are three parts inside the '<entity>' tag : the delimiter parser definition, row translator definition, and the list of columns found in the data file.

Delimiter Parser

The delimiter parser definition begins with the '<delimiter>' tag and contains the information needed to parse the input file into a set of rows that will be imported into the table.In this tutorial, you will be using the custom Delimiter Parser 'Fixed Delimiter Parser'. To indicate this, you must choose an identifier for the custom Delimiter Parser (ex. 'tutorial_fixed') and set the 'type' attribute's value, inside the '<delimiter>' tag, to that identifier. The specific delimiter parser information is found inside the '<delimiter>' tag. For the Fixed Delimiter Parser, you will need to specify the following information (as '<property>' tags): the number ranges for each column (in the property named 'columnPositions' ). Since, the data file has the following number ranges : 1-4,5-14,15-24,25-34,35-38,39-48,49-53,54-58 (note the first column is 1), the delimiter parser definition will look like this :

  <delimiter type="tutorial_fixed"> 
    <property name="columnPositions" value="1-4,5-14,15-24,25-34,35-38,39-48,49-53,54-58"/> 
  </delimiter> 
Sample XML for Fixed Delimiter Parser

Row Translator

The row translator definition is optional and begins with the '<translator>' tag. It contains the information needed to translate each row's values and may add, remove column values or skip the whole row. In this tutorial, you will not be using a row translator. Therefore the '<translator>' does not appear as a child inside the '<entity>' tag.

List of Columns

The final portion of the entity definition is the list of columns that are to be imported from the input file into the database. The list of columns should be the same order as they appear in the input file. Each column is defined inside the '<column>' tag. The name of the column must appear in the 'name' attribute of the '<column>' tag. Optionally, the java.sql.Type may be specified in the 'SQLType' attribute of the '<column>'.You will be letting the JDBC Importer figure out most of the column types (except for dates) in the database, so the 'SQLType' attribute is omitted except for the 'startdate' column. Here is an example of how the list of columns are defined in the import definition:

  <column name="id"></column>
  <column name="firstname"></column>
  <column name="lastname"></column>
Sample XML for List of Columns

Running the Import

By now, the import definition should look like this (with your appropriate connection information):

<import log="import.log bad="import.bad"> 
  <connection type="jdbc"> 
     <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 
     <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> 
     <property name="username" value="scott"/> 
     <property name="password" value="tiger"/> 
  </connection> 
  <entity table="employee" source="employee.dat">
    <delimiter type="tutorial_fixed"> 
      <property name="columnPositions" value="1-4,5-14,15-24,25-34,35-38,39-48,49-53,54-58"/> 
    </delimiter> 
    <column name="id"></column>
    <column name="firstname"></column>
    <column name="lastname"></column>
    <column name="jobdescription"></column>
    <column name="managerid"></column>
    <column name="startdate" SQLType="DATE"></column>
    <column name="salary"></column>
    <column name="department"></column>
  </entity> 
</import> 
Sample XML for Tutorial 3

Since you are using the custom Delimiter Parser (Fixed Delimiter Parser), you will have to create a property file with one entry that maps the identifier to the full name of the class that implements the DelimiterParser interface. The entry's key should start with 'delimiter.' (this indicates that the custom component is a Delimiter Parser). It should look like this:

delimiter.tutorial_fixed=samples.delimiterparser.FixedDelimiterParser
				
Property File Entry for Fixed Delimiter Parser

You will also have to include an extra jar file in the classpath before you can use the custom Delimiter Parser (the jar file 'jdbcimporter-samples.jar' under the directory 'lib' contains the custom Delimiter Parser).

You can run the import by issuing the following command (assuming that the import definition and property file is in the current directory and is called 'import.xml' and 'custom.properties', respectively):

java net.sourceforge.jdbcimporter.Importer import.xml custom.properties

If all goes well then the two log files should be created. In the normal log file there should be an informational message indicating that all rows were imported. In the bad log file there should be a heading for the import table.

Generating an Error

Because all rows were imported successfully, there was no error messages. To generate an error message, change the employee.dat file to have an invalid record. For example, if you change line 48, so that the length is less then 46 (by deleting a few characters), the import will fail for this line. After running the import, the normal log file should contain a message indicating that 74 out of 75 rows were imported and a linenumber/stack trace for the invalid row. The invalid line 48 should be written into the bad log file.