org.apache.torque.betwixt
Class Importer

java.lang.Object
  extended by org.apache.torque.betwixt.XMLEventNotifier
      extended by org.apache.torque.betwixt.Importer
All Implemented Interfaces:
org.xml.sax.ErrorHandler

public class Importer
extends XMLEventNotifier
implements org.xml.sax.ErrorHandler

Top level controller for importing XML into Torque OM objects and storing them into the database. Uses the org.apache.common.betwixt package to do the conversion to objects and registered RecordHandler classes to deal with managing the DB transactions.

The input XML can use the dataset attributes, action and onError, to specify what effect these objects should have on the underlying data base. E.g., action can be: add, addUpdate, update, or delete. onError can be: continue, stop, rollback.

This class configures Betwixt using a supplied Resolver to locate the required mapping file and DTD file, to so that Betwixt can convert the XML input stream into Torque (and possibly other) objects contained in a Dataset object.

Then, based on the action specified in the dataset object, it dispatches each of the imported objects to the matching RecordHandler method for record specific processing required to perform this action on the data in the DB. E.g., resolving id and foreign key issues, data validation, and the like.

It also handles top level error handling and transaction grouping to support the specified onError attribute setting.

Event listeners can be registered with this class so that import status (as specified in the ACTION_* static variables) can be reported to users and/or other reporting agents.

TODO: Support for having mix of records from different databases?

Author:
Greg Monroe

Field Summary
static int ADD_ONLY
          Only add records action flag value
static int ADD_UPDATE
          Add or update record action flag value
static int DELETE
          Delete records action flag value
static int ON_ERROR_CONTINUE
          Continue on error flag value
static int ON_ERROR_ROLLBACK
          Roll back on error flag value
static int ON_ERROR_STOP
          Stop importing on error flag value
static int UPDATE_ONLY
          Only update records action flag value
 
Fields inherited from class org.apache.torque.betwixt.XMLEventNotifier
ACTION_ADD, ACTION_DELETE, ACTION_ERROR, ACTION_INFO, ACTION_TYPE, ACTION_UPDATE, EXPORT_END, EXPORT_RECORD, EXPORT_START, IMPORT_END, IMPORT_START
 
Constructor Summary
Importer()
          Handles parsing XML records into a Dataset object and then dispatching them to the correct record handlers to be processed.
 
Method Summary
 org.apache.commons.betwixt.io.BeanReader createBeanReader(Resolver resolver)
          Create a Betwixt BeanReader to parse XML with.
 void deregisterListener(XMLEventListener listener)
          Remove a listener.
 void error(org.xml.sax.SAXParseException e)
           
 void fatalError(org.xml.sax.SAXParseException e)
           
protected  RecordHandler findRecordHandler(java.lang.Object record)
          Search the registered record handlers for one that matches the class or superclass of the supplied record.
 int getAction()
           
 java.sql.Connection getConnection()
          Get the connection to save information with.
 int getDatasetRecordNumber()
          Get the (1 based) number of the current record object being processed.
protected  java.util.Map getHandlers()
          Get the record handlers hash table.
protected  java.util.List getListeners()
          Gets the registered listeners.
 int getOnError()
           
 void importData(java.io.Reader xmlReader, Resolver resolver)
          Create a BeanReader; parse the supplied XML input stream into a Dataset; and then process the Dataset.
 void initHandlers()
          Initialize the default set of record handlers when class is created.
protected  void initOptions(Dataset records)
          Parses the text version of the Dataset action and onError attributes into option flag values.
protected  boolean isErrorParsing()
           
 void notifyListeners(int recordNum, java.lang.String action, java.lang.String info)
          Calls all registered listeners to let them know an action occured.
 Dataset parseXML(java.io.Reader importReader, org.apache.commons.betwixt.io.BeanReader beanReader)
          Populate a Dataset object from the supplied XML input stream.
 void processDataset(Dataset records)
          The main driver for importing data into a Torque managed database from XML.
 void registerHandler(java.lang.Class recordType, RecordHandler handler)
          Register or modify a recordHandler to be used with the specifed class or subclass.
 void registerListener(XMLEventListener listener)
          Register a listener that will be notified of export actions.
protected  void rollbackTransaction()
          Attempt to roll back all changes made prior to an error occuring.
protected  void setAction(int action)
           
protected  void setConnection(java.sql.Connection connection)
          Set the database connection to use.
 void setDatasetRecordNumber(int datasetRecordNumber)
          Sets the (1 based) number of the current record object being processed.
protected  void setErrorParsing(boolean errorParsing)
           
protected  void setHandlers(java.util.Hashtable handlers)
          Set a new record handler hash table.
protected  void setOnError(int onError)
           
 java.lang.String simpleClassName(java.lang.Class c)
          Get the name of a class without it's package.
protected  void startTransaction(java.lang.Object record)
          Start a transaction grouping.
 void warning(org.xml.sax.SAXParseException e)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ON_ERROR_CONTINUE

public static final int ON_ERROR_CONTINUE
Continue on error flag value

See Also:
Constant Field Values

ON_ERROR_STOP

public static final int ON_ERROR_STOP
Stop importing on error flag value

See Also:
Constant Field Values

ON_ERROR_ROLLBACK

public static final int ON_ERROR_ROLLBACK
Roll back on error flag value

See Also:
Constant Field Values

ADD_UPDATE

public static final int ADD_UPDATE
Add or update record action flag value

See Also:
Constant Field Values

ADD_ONLY

public static final int ADD_ONLY
Only add records action flag value

See Also:
Constant Field Values

UPDATE_ONLY

public static final int UPDATE_ONLY
Only update records action flag value

See Also:
Constant Field Values

DELETE

public static final int DELETE
Delete records action flag value

See Also:
Constant Field Values
Constructor Detail

Importer

public Importer()
Handles parsing XML records into a Dataset object and then dispatching them to the correct record handlers to be processed.

Method Detail

initHandlers

public void initHandlers()
Initialize the default set of record handlers when class is created. Handlers can be changed/added via registerHandler method.


importData

public void importData(java.io.Reader xmlReader,
                       Resolver resolver)
                throws java.lang.Exception
Create a BeanReader; parse the supplied XML input stream into a Dataset; and then process the Dataset.

Parameters:
xmlReader - The XML input source.
resolver - A resolver object to locate needed information.
Throws:
org.xml.sax.SAXException
java.io.IOException
java.lang.Exception

parseXML

public Dataset parseXML(java.io.Reader importReader,
                        org.apache.commons.betwixt.io.BeanReader beanReader)
                 throws java.beans.IntrospectionException,
                        java.io.IOException,
                        org.xml.sax.SAXException,
                        java.lang.Exception
Populate a Dataset object from the supplied XML input stream.

Parameters:
importReader - The XML input stream
beanReader - The betwixt BeanReader configured to parse the XML input.
Throws:
java.beans.IntrospectionException
java.io.IOException
org.xml.sax.SAXException
java.lang.Exception

createBeanReader

public org.apache.commons.betwixt.io.BeanReader createBeanReader(Resolver resolver)
                                                          throws java.beans.IntrospectionException,
                                                                 java.io.IOException,
                                                                 org.xml.sax.SAXException
Create a Betwixt BeanReader to parse XML with. Validating is set to true and this class is the error handler.

Parameters:
resolver - A class used to locate DTD and mapping files needed to validate and convert the input XML into objects.. Cannot be null.
Returns:
A Betwixt BeanReader object with the mapping file registered and syntax error checking turned on.
Throws:
java.beans.IntrospectionException
java.io.IOException
org.xml.sax.SAXException

processDataset

public void processDataset(Dataset records)
                    throws java.lang.Exception
The main driver for importing data into a Torque managed database from XML. Calls the appropriate RecordHandler implimentation method for each item in the dataset based on class (or superclass) and the options set in the dataset. Handles notifying registered listeners of import status. Manages DB transaction logic (connection, commit, rollback, etc).

Parameters:
records - The dataset of records to process.
Throws:
java.lang.Exception

initOptions

protected void initOptions(Dataset records)
                    throws java.lang.IllegalArgumentException,
                           java.lang.Exception
Parses the text version of the Dataset action and onError attributes into option flag values. Text options are case insensitive.

Parameters:
records - The dataset with the options
Throws:
java.lang.IllegalArgumentException - If an unknown value is found.
java.lang.Exception

startTransaction

protected void startTransaction(java.lang.Object record)
                         throws org.apache.torque.TorqueException
Start a transaction grouping.

Parameters:
record -
Throws:
org.apache.torque.TorqueException

findRecordHandler

protected RecordHandler findRecordHandler(java.lang.Object record)
                                   throws java.lang.CloneNotSupportedException
Search the registered record handlers for one that matches the class or superclass of the supplied record.

Parameters:
record - The record to process.
Returns:
A clone of the registered record handler object to process this object type or null if none found.
Throws:
java.lang.CloneNotSupportedException

rollbackTransaction

protected void rollbackTransaction()
                            throws java.lang.Exception
Attempt to roll back all changes made prior to an error occuring.

Throws:
java.lang.Exception

getConnection

public java.sql.Connection getConnection()
                                  throws java.lang.IllegalStateException
Get the connection to save information with. Note: To support rollbacks, all records are stored via a single transaction wrapped connection.

Returns:
The transaction connection object.
Throws:
java.lang.IllegalStateException - if has not been initialized

setConnection

protected void setConnection(java.sql.Connection connection)
Set the database connection to use.

Parameters:
connection - The connection to set.

notifyListeners

public void notifyListeners(int recordNum,
                            java.lang.String action,
                            java.lang.String info)
                     throws java.lang.Exception
Calls all registered listeners to let them know an action occured. Notification will occure in the order they were registered.

Overrides:
notifyListeners in class XMLEventNotifier
Parameters:
action -
info -
recordNum - the (1 based) index of the record object being processed.
Throws:
java.lang.Exception

registerListener

public void registerListener(XMLEventListener listener)
Register a listener that will be notified of export actions.

Overrides:
registerListener in class XMLEventNotifier
Parameters:
listener -

deregisterListener

public void deregisterListener(XMLEventListener listener)
Remove a listener.

Overrides:
deregisterListener in class XMLEventNotifier
Parameters:
listener -

getListeners

protected java.util.List getListeners()
Gets the registered listeners.

Overrides:
getListeners in class XMLEventNotifier
Returns:
A list of registered listeners.

registerHandler

public void registerHandler(java.lang.Class recordType,
                            RecordHandler handler)
Register or modify a recordHandler to be used with the specifed class or subclass.

Parameters:
recordType -
handler -

getHandlers

protected java.util.Map getHandlers()
Get the record handlers hash table.

Returns:
Returns the handlers.

setHandlers

protected void setHandlers(java.util.Hashtable handlers)
Set a new record handler hash table.

Parameters:
handlers - The handlers to set.

getAction

public int getAction()
Returns:
Returns the action.

setAction

protected void setAction(int action)
Parameters:
action - The action to set.

getOnError

public int getOnError()
Returns:
Returns the onError.

setOnError

protected void setOnError(int onError)
Parameters:
onError - The onError to set.

warning

public void warning(org.xml.sax.SAXParseException e)
             throws org.xml.sax.SAXException
Specified by:
warning in interface org.xml.sax.ErrorHandler
Throws:
org.xml.sax.SAXException

error

public void error(org.xml.sax.SAXParseException e)
           throws org.xml.sax.SAXException
Specified by:
error in interface org.xml.sax.ErrorHandler
Throws:
org.xml.sax.SAXException

fatalError

public void fatalError(org.xml.sax.SAXParseException e)
                throws org.xml.sax.SAXException
Specified by:
fatalError in interface org.xml.sax.ErrorHandler
Throws:
org.xml.sax.SAXException

isErrorParsing

protected boolean isErrorParsing()
Returns:
Returns the errorParsing.

setErrorParsing

protected void setErrorParsing(boolean errorParsing)
Parameters:
errorParsing - The errorParsing to set.

simpleClassName

public java.lang.String simpleClassName(java.lang.Class c)
Get the name of a class without it's package.

Parameters:
c - A class object to find the simple name of.
Returns:
The simple class name.

getDatasetRecordNumber

public int getDatasetRecordNumber()
Get the (1 based) number of the current record object being processed. Note: Record 0 = setup/xml parsing phase.

Returns:
Returns the datasetRecordNumber.

setDatasetRecordNumber

public void setDatasetRecordNumber(int datasetRecordNumber)
Sets the (1 based) number of the current record object being processed.

Parameters:
datasetRecordNumber - The datasetRecordNumber to set.


Copyright © 2006 Torque Add-ons Project. All Rights Reserved.