/*
* @author : Mark Drake
* @version : 1.0
* Development Environment : Oracle9i JDeveloper
* Name of the File : BaseApplication.java
* Creation / Modification History :
* Shefali Bansal 25-Jan-2003 Modified
* Modifications Made:
* 1. Provided for getting the Table Name and Logging mode from the connection.xml file
* 2. Removed methods related to OCI Pooling
* 3. Renamed the doSomething() method as doBulkLoad() method
* 4. Removed the Main() method
*/
//Package name
package oracle.otnsamples.xmldb.simplebulkloader.common.baseApp;
// IO Imports
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
//JDBC imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Import 'Alert' class
import oracle.otnsamples.xmldb.simplebulkloader.common.trace.Alert;
// Oracle SQL Imports
import oracle.sql.CLOB;
// XML Parser Imports
import oracle.xml.parser.v2.DOMParser;
import oracle.xml.parser.v2.XMLDocument;
// W3C DOM Imports
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
//ORG XML Imports
import org.xml.sax.SAXException;
/**
* 'BaseApplication' class is part of the Simple Bulk Loader application. This
* class provides base methods for bulk loading of XML files into the XML DB
* database.
*/
public class BaseApplication extends Object {
// Declare the static variables required
public static final boolean DEBUG = true;
// Static variables handling connection parameters
public static final String CONNECTION = "Connection";
public static final String DRIVER = "Driver";
public static final String HOSTNAME = "Hostname";
public static final String PORT = "Port";
public static final String SID = "SID";
public static final String SERVICENAME = "ServiceName";
public static final String SERVERMODE = "Server";
public static final String SCHEMA = "Schema";
public static final String PASSWORD = "Password";
public static final String THIN_DRIVER = "thin";
public static final String OCI_DRIVER = "oci8";
public static final String TABLE = "Table";
public static final String LOGGER = "Logger";
public static final String DEFAULT_CONNECTION_SETTINGS = "c:\\temp\\connection.xml"; // Please mention the directory path according to the OS
public static final String DEFAULT_DRIVER = OCI_DRIVER;
public static final String DEFAULT_HOSTNAME = "localhost";
public static final String DEFAULT_PORT = "1521";
public static final String DEFAULT_SID = "ORCL";
public static final String DEFAULT_SERVICENAME = "ORCL";
public static final String DEFAULT_SERVERMODE = "DEDICATED";
public static final String DEFAULT_SCHEMA = "scott";
public static final String DEFAULT_PASSWORD = "tiger";
public static final String DEFAULT_TABLE = "UserTable";
public static final String DEFAULT_LOGGER = "CONSOLE";
// Declare the member variables required
protected Connection m_Connection; // Holds the db connection object
protected XMLDocument m_ConnectionSettings; // Holds the XML Document giving db connection information
/*
* Setter method for connection parameters from the XML file
*
* @param doc The connection.xml XMLDocument
*/
private void setConnectionSettings( XMLDocument doc ) {
m_ConnectionSettings = doc;
}
/**
* Setter method for connection object
*
* @param conn Database connection object
*/
private void setConnection( Connection conn ) {
m_Connection = conn;
}
/**
* Displays the connection parameters information on the system console and
* in logger file
*
* @throws IOException
*/
private void dumpConnectionSettings( ) throws IOException {
StringWriter sw = new StringWriter( );
PrintWriter pw = new PrintWriter( sw );
m_ConnectionSettings.print( pw );
pw.close( );
Alert.log( "Connection Settings = " );
Alert.log( sw.toString( ) );
Alert.log( DRIVER + " = " + getDriver( ) );
Alert.log( HOSTNAME + " = " + getHostname( ) );
Alert.log( PORT + " = " + getPort( ) );
Alert.log( SERVICENAME + " = " + getServiceName( ) );
Alert.log( SERVERMODE + " = " + getServerMode( ) );
Alert.log( SCHEMA + " = " + getSchema( ) );
Alert.log( PASSWORD + " = " + getPassword( ) );
Alert.log( TABLE + " = " + getTable( ) );
Alert.log( LOGGER + " = " + getLoggerMode( ) );
Alert.log( "Database URL = " + getDatabaseURL( ) );
}
/**
* Returns the Connection object
*
* @return Connection
*
* @exception Exception
*/
public Connection getConnection( ) throws Exception {
return m_Connection;
}
/**
* Returns the connection object for the schema name and password passed
*
* @param schema String specifying the database schema name
* @param passwd String specifying the database schema password
*
* @return Connection
*
* @throws Exception
*/
public Connection getConnection( String schema, String passwd )
throws Exception {
return m_Connection;
}
/**
* This is the method that will perform the actual loading of the XML files
* into the XML DB. This method is overridden by the doBulkLoad() method in
* SimpleBulkLoader class to implement the required behavior.
*
* @param args array
*
* @throws Exception
*/
public void doBulkLoad( String[] args ) throws Exception {
}
/**
* Creates a temporary CLOB to hold the input stream content. Once the
* temporary CLOB is created the contents of the input stream are read and
* copied into this CLOB
*
* @param conn object containing DB connection info
* @param is InputStream specifying the content of the XML files
*
* @return CLOB
*
* @throws SQLException
* @throws IOException
*/
public CLOB createCLOB( Connection conn, InputStream is )
throws SQLException, IOException {
// If the temporary CLOB has not yet been created, create a new one
CLOB clob = CLOB.createTemporary( conn, false, CLOB.DURATION_SESSION );
// Write the contents into this temporary CLOB
writeToClob( clob, is );
// Return the temporary CLOB object
return clob;
}
/**
* Writes the content of the input stream to the temporary CLOB object passed
* to it and returns the data containing the CLOB object
*
* @param clob CLOB object to hold the input stream content
* @param is XML data containing stream
*
* @return CLOB
*
* @throws SQLException
* @throws IOException This exception is thrown if the xml file is not found
*/
public CLOB writeToClob( CLOB clob, InputStream is )
throws SQLException, IOException {
InputStreamReader reader = new InputStreamReader( is );
// Get the output stream to write
Writer writer = clob.getCharacterOutputStream( );
// Read the input stream
char[] buffer = new char[clob.getChunkSize( )];
for ( int charsRead = reader.read( buffer ); charsRead > -1;
charsRead = reader.read( buffer ) ) {
// Write the data into the temporary CLOB
writer.write( buffer, 0, charsRead );
}
// Close the stream
writer.close( );
// Return the XML content containing CLOB Object
return clob;
}
/**
* Getter method for getting the text value of a node given the node name
* from the XML document contained in "connection.xml" file.
*
* @param nodeName String specifying the nodename whose text value is to be
* retrieved
*
* @return String the text value of the node name passed
*/
public String getTextNode( String nodeName ) {
return getTextNode( nodeName, null );
}
/**
* Getter method for getting the text value of a node given the node name
* from the XML document contained in "connection.xml" file.
*
* @param nodeName specifying the node name
* @param defaultValue default text value of the node, if node name specified
* is not found in the DOM
*
* @return String the text value of the node name passed
*/
public String getTextNode( String nodeName, String defaultValue ) {
String textValue = null;
// Get the DOM element for the XML document
Element root = m_ConnectionSettings.getDocumentElement( );
// Get the list of nodes having the same name as the Node name passed
NodeList children = root.getElementsByTagName( nodeName );
// If the nodes with name matching as the node name exists then
if ( children.getLength( ) != 0 ) {
// Get the details of the first node from the list
Element element = (Element) children.item( 0 );
Text text = (Text) element.getFirstChild( );
// Get the text value of the node
if ( text != null ) {
return text.getData( );
}
// If there are no nodes matching the node name specified then
else {
return defaultValue;
}
}
else {
return defaultValue;
}
}
/**
* Getter method for Driver information
*
* @return the driver information
*/
protected String getDriver( ) {
return getTextNode( DRIVER, DEFAULT_DRIVER );
}
/**
* Getter method for Hostname information
*
* @return the host name
*/
protected String getHostname( ) {
return getTextNode( HOSTNAME, DEFAULT_HOSTNAME );
}
/**
* Getter method for Port information
*
* @return the port number
*/
protected String getPort( ) {
return getTextNode( PORT, DEFAULT_PORT );
}
/**
* Getter method for database Table information
*
* @return the table
*/
protected String getTable( ) {
return getTextNode( TABLE, DEFAULT_TABLE );
}
/**
* Getter method for Service Name information
*
* @return the service name
*/
protected String getServiceName( ) {
return getTextNode( SERVICENAME, DEFAULT_SERVICENAME );
}
/**
* Getter method for Server Mode information
*
* @return the Server Mode
*/
protected String getServerMode( ) {
return getTextNode( SERVERMODE, DEFAULT_SERVERMODE );
}
/**
* Getter method for SID information
*
* @return the SID
*/
protected String getSID( ) {
return getTextNode( SID, DEFAULT_SID );
}
/**
* Getter method for Schema information
*
* @return Schema Name information
*/
protected String getSchema( ) {
return getTextNode( SCHEMA, DEFAULT_SCHEMA );
}
/**
* Getter method for Schema password information
*
* @return Schema password information
*/
protected String getPassword( ) {
return getTextNode( PASSWORD, DEFAULT_PASSWORD );
}
/**
* Getter method for Logger mode information
*
* @return Logger mode information
*/
protected String getLoggerMode( ) {
return getTextNode( LOGGER, DEFAULT_LOGGER );
}
/**
* Gets the connection information from connection.xml file
*
* @throws IOException
* @throws SAXException
*/
public void getConnectionSettings( ) throws IOException, SAXException {
// Get the name of the Connection File
String filename = DEFAULT_CONNECTION_SETTINGS;
try {
// Create a Reader on the Connection File
File file = new File( filename );
// Check for the existence of the file
if ( file.exists( ) ) {
Reader reader = new FileReader( new File( filename ) );
DOMParser parser = new DOMParser( );
// Parse the Connection File
parser.parse( reader );
// Obtain the DOM
XMLDocument doc = parser.getDocument( );
setConnectionSettings( doc );
// Get the logger mode entered in the config XML file by the user
String mode = getLoggerMode( );
// Based on the logger mode entered by the user, set the same in the Alert class
Alert alert = new Alert( );
alert.setLoggerMode( mode );
if ( DEBUG ) {
dumpConnectionSettings( );
}
}
else {
throw new NullPointerException( );
}
} catch ( NullPointerException ex ) {
System.out.println( "BaseApplication.getConnectionSettings:The system cannot find configuration XML file -connection.xml- in the directory location specified : FileNotFound Exception" );
throw ex;
} catch ( IOException ex ) {
Alert.log( "BaseApplication.getConnectionSettings:The system cannot find the configuration XML file in the directory location specified : IO Exception" );
}
}
/**
* Getter method for the database Connection URL based on the driver type
*
* @return Database connection URL
*/
protected String getDatabaseURL( ) {
// Based on the driver return the database URL information
if ( getDriver( ) != null ) {
if ( getDriver( ).equalsIgnoreCase( THIN_DRIVER ) ) {
// Return the database connection URL information
return "jdbc:oracle:thin:@" + getHostname( ) + ":" + getPort( ) +
":" + getSID( );
}
else {
// Return the database connection URL information
return "jdbc:oracle:oci8:@(description=(address=(host=" +
getHostname( ) + ")(protocol=tcp)(port=" + getPort( ) +
"))(connect_data=(service_name=" + getServiceName( ) +
")(server=" + getServerMode( ) + ")))";
}
}
else {
return null;
}
}
/**
* Opens the DB connection once the DB connection parameters are available
*
* @return Connection
*
* @throws Exception
*/
public Connection openConnection( ) throws Exception {
String user = getSchema( );
String password = getPassword( );
String connectionString = user + "/" + password + "@" + getDatabaseURL( );
Connection conn = null;
if ( DEBUG ) {
Alert.log( "BaseApplication.getConnection(): Connecting as " +
connectionString );
}
//Load the Oracle JDBC Driver and register it.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver( ) );
try {
//The following statement creates a database connection object using the
//DriverManager.getConnection method.
conn = DriverManager.getConnection( getDatabaseURL( ), user, password );
if ( DEBUG ) {
Alert.log( "BaseApplication.getConnection(): Database Connection Established" );
}
}
catch ( SQLException sqle ) {
// Get the error code for the SQL Exception
int err = sqle.getErrorCode( );
Alert.log( "BaseApplication.getConnection(): Failed to connect using " +
connectionString );
// Display in the log, the exception that has occurred
Alert.log( sqle );
throw sqle;
}
// Return the database connection object
return conn;
}
/**
* Creates a DB connection
*
* @throws Exception
*/
public void createConnection( ) throws Exception {
getConnectionSettings( );
setConnection( openConnection( ) );
}
}