Copyright 2009,2010, Lapetus Systems Ltd. (All rights reserved)

com.lapetus_ltd.api.db.control
Class TLptsFactoryConnection

java.lang.Object
  extended by com.lapetus_ltd.api.db.control.TLptsFactoryConnection

public class TLptsFactoryConnection
extends java.lang.Object

Class Description : The class responsible for initiating and managing database Connections.


This class is the main hub of the database system as it contains and controls the lists of database connections.
The process of initiating a connection and listening for a connection status is done through this class.
The TLptsFactoryConnection, like many other classes in dbJAPI, has a list of static functions which provides access
to the capabilities of class.
The class is structured in such a way that it cannot be instantiated, but is created by dbJAPI through TLptsMainDatabase.init().

How it all works :
----------------
Well, it is really quite neat, as the listeners give you the control at the right time.
Below we have diagram of the process, with all the required classes, and below that there is sample code for the process.

The overall process is as follows:

       -------------------------------------------------     ILptsFactoryConnectionListener
       | Add listeners to the TLptsFactoryConnection,  |     TLptsFactoryConnection
       | TLptsFactoryStatement and TLptsFactoryRowSet  |     TLptsFactoryStatement
       -------------------------------------------------     ILptsFactoryStatementListener
                                |                            TLptsFactoryRowSet
                                |                            ILptsFactoryRowSetListener
                                |
                              \ | /
                               \/
      --------------------------------------------------------
      | Connection Class creation with TLptsDBConnectionType |     TLptsDBConnectionType
      | Set details and find driver TLptsDriverLoader        |     TLptsDriverLoader
      | Initiate the Connection with TLptsFactoryConnection  |     TLptsFactoryConnection
      --------------------------------------------------------
                                |
                                |
                                |
                              \ | /
                               \/
      ---------------------------------------------------------------------
      | The connection listener gets the successful connection            |  ILptsFactoryConnectionListener
      | and builds statements as required, using the statement class.     |  TLptsFactoryStatement.createNewStatement(com.lapetus_ltd.api.db.control.TLptsConnection, com.lapetus_ltd._2009.xml.types.XLptsDBStatementType)
      | The new statements are 'caught' by the statement factory listener.|  ILptsFactoryStatementListener
      | The statement is then executed with the RowSet Factory.           |  TLptsFactoryRowSet.executeSelectStatement(com.lapetus_ltd.api.db.control.TLptsStatement, int, int, boolean)
      ---------------------------------------------------------------------
                                |
                                |
                                |
                              \ | /
                               \/
      --------------------------------------------------------------------------------
      | The row set listener gets the rowset or single rows and then processes them. |
      | The row and rowset events show the status of the generated data and are      |
      | used to process the data, especially with dynamic data.                      |
      --------------------------------------------------------------------------------
 


The whole process includes many threads and is well synchronised. All lists used in the process and supplied by the classes
are thread safe and can be used without synchronisation.
Within an implementation of the above listeners, which always run on a separate worker thread, the application should execute any
GUI code on the Swing Thread as below:

  if (SwingUtilities.isEventDispatchThread())   // it will probably not go in here as the listeners run on worker threads.
  {
    ///////// GUI CODE
  }
  else
  {
  try
     {
     SwingUtilities.invokeAndWait(new Runnable()  // use this to do something that needs to be done immediately.
      {
        public void run()
        {
          ///////// SAME GUI CODE
        }
      });
    } catch (Exception e)
    {
      SwingUtilities.invokeLater(new Runnable()  // if the system cannot do it now, at least do it later.
      {
        public void run()
        {
          ///////// SAME GUI CODE
        }
      });
    }
  }
 


Below we have partial sample code showing the whole process described above.
Please refer to the ExampleXXX.java files for complete code or if you are an advanced software engineer have a look at the TestXXX.java source files.
 

TLptsMainDatabase.init(); // this is required at the beginning of every software

TLptsFactoryConnection.addListener(new ConnectionStatementListener()); TLptsFactoryStatement.addListener(new StatementListener()); TLptsFactoryRowSet.addListener(new RowSetListener());

TLptsDBConnectionType connectionType = new TLptsDBConnectionType(); connectionType.setTitle(fileName);

XLptsDriverType driverType = TLptsDriverLoader.getDriverTypeByClassName("sun.jdbc.odbc.JdbcOdbcDriver");

if (driverType != null) connectionType.setDriverType(new TLptsDriverType(driverType)); else { System.out.println("Could not find driver for class : sun.jdbc.odbc.JdbcOdbcDriver. Cannot connect."); return; }

connectionType.setDataFileUrl(fileName); connectionType.setConnectionString(driverType.getConnectionStringFormat()); connectionType.setCredentials(TLptsCryptoUtil.defaultEncryptCredentialsRSA(driverType.getGuestUser(), driverType.getGuestPassword()));

TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!!

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { System.out.println("New Connection created successfully. Statements can be processed.");

XLptsDBStatementType statement = new XLptsDBStatementType(); statement.setTitle("TRANS"); statement.setSqlStatementUser("SELECT * FROM TRANSACTIONS"); statement.setSqlStatementModified(true); // use the sql statement above and do not automatically generate statement.setSqlDatabaseFormat(XLptsDBSqlDatabaseFormat.DEFAULT_ODBC); statement.setTypeOfStatement(XLptsDBTypeOfStatementType.SELECT);

TLptsFactoryStatement.createNewStatement(connection, statement); }

... }

private class StatementListener implements ILptsFactoryStatementListener { public void newStatementCreated(TLptsConnection connection, TLptsStatement statement) { System.out.println("New Statement created. RowSets can be generated."); TLptsFactoryRowSet.executeSelectStatement(statement, 1, 0, false); }

... }

private class RowSetListener implements ILptsFactoryRowSetListener { public void rowEvent(TLptsRowEvent rowEvent) { if (rowEvent.getEventType().equals(TLptsRowEvent.EVENT_TYPE.MOVED_TO_NEXT_RECORD)) { // we have the data and types rowEvent.getRowObjectList()... rowEvent.getColumnNameList()... rowEvent.getColumnTypeList()... rowEvent.getByteValueList()... } }

public boolean processNewRowSetRows(TLptsRowSetEvent rowSetEvent) { return true; // we want the DB API to process all the records and send them to us one at a time. // This is very useful with dynamic processing as all the relations are created by the subsystem. } }



$LastChangedRevision: 1210 $
$LastChangedDate:: 2010-11-29 15:22:58#$


Field Summary
static java.lang.String TABLE_TYPE_ALIAS
          This is the alias type.
static java.lang.String TABLE_TYPE_GLOBAL_TEMP
          This is the global temporary type.
static java.lang.String TABLE_TYPE_LOCAL_TEMP
          This is the local temporary type.
static java.lang.String TABLE_TYPE_SYNONYM
          This is the synonym type.
static java.lang.String TABLE_TYPE_SYSTEM_TABLES
          This is the system table type.
static java.lang.String TABLE_TYPE_TABLES
          This is the user table type.
static java.lang.String TABLE_TYPE_VIEWS
          This is the user view type.
 
Method Summary
static void addListener(ILptsFactoryConnectionListener listener)
           Add a Listener that implements ILptsFactoryConnectionListener.
static TLptsConnection getConnection(java.lang.String id)
           Gets a Connection by its id.
static java.util.List<TLptsConnection> getConnectionList()
           Gets the Connection List.
static int getConnectionListSize()
           Gets the size of Connection List.
static java.util.List<java.sql.Driver> getDriverList()
           Gets the Driver List from the java DriverManager.
static void initiateConnection(XLptsDBConnectionType connectionType)
           This function is used to initialise a connection to a data source.
static void removeConnection(TLptsConnection connection, boolean forceful)
           Remove Connection from System.
static void removeListener(ILptsFactoryConnectionListener listener)
           Remove a Listener that implements ILptsFactoryConnectionListener.
static TLptsDBConnectionGroupType zgCG()
          Obfuscated as it is not required by the application interface.
static XLptsDriverLoaderType zgDLT()
          Obfuscated as it is not required by the application interface.
static XLptsODBCDriverType zgODT()
          Obfuscated as it is not required by the application interface.
static void zI()
          Obfuscated, as it is not required by the application.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

TABLE_TYPE_ALIAS

public static java.lang.String TABLE_TYPE_ALIAS
This is the alias type.


TABLE_TYPE_GLOBAL_TEMP

public static java.lang.String TABLE_TYPE_GLOBAL_TEMP
This is the global temporary type.


TABLE_TYPE_LOCAL_TEMP

public static java.lang.String TABLE_TYPE_LOCAL_TEMP
This is the local temporary type.


TABLE_TYPE_SYNONYM

public static java.lang.String TABLE_TYPE_SYNONYM
This is the synonym type.


TABLE_TYPE_SYSTEM_TABLES

public static java.lang.String TABLE_TYPE_SYSTEM_TABLES
This is the system table type. Use tables are stored here for Excel data sources.


TABLE_TYPE_TABLES

public static java.lang.String TABLE_TYPE_TABLES
This is the user table type.


TABLE_TYPE_VIEWS

public static java.lang.String TABLE_TYPE_VIEWS
This is the user view type.

Method Detail

addListener

public static void addListener(ILptsFactoryConnectionListener listener)

Add a Listener that implements ILptsFactoryConnectionListener.

Thread Safe : Yes.

Spawns its own Thread : No.

May Return NULL : No.

Notes :

Example :

 

public class MyApp { private ConnectionStatementListener connectionListener;

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(connectionListener); } ... private void connectToDB() { ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! } ... private void exitButtonActionPerformed() { TLptsFactoryConnection.removeListener(connectionListener); }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { System.out.println("New Connection created successfully. Statements can be processed."); }

public void newConnectionProcessStarted() { System.out.println("Connecting..."); }

public void newConnectionFailed(TLptsLog log) { System.out.println("New Connection Failed. The logger got this."); }

public void removedAndClosedConnection(TLptsConnection connection) { System.out.println("Connection removed from Connection Manager and closed successfully ... " + connection.getTitle()); } } }

Parameters:
listener - to be informed about connection events.

getConnection

public static TLptsConnection getConnection(java.lang.String id)

Gets a Connection by its id.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : Yes.

Notes :

Example :

 public class MyApp
 {
    private ConnectionStatementListener connectionListener;
    private String connId;
 

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(connectionListener); connectToDB(); } ... private void connectToDB() { ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! } ... private void exitButtonActionPerformed() { TLptsFactoryConnection.removeListener(connectionListener); }

private void startDataProcessing() { TLptsConnection odbcConnection = null; for(TLptsConnection conn : TLptsFactoryConnection.getConnectionList()) if(conn.getId().equals(connId)); odbcConnection = conn; if(odbcConnection == null) return; ... }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { System.out.println("New Connection created successfully. Statements can be processed."); //We create 4 connections to process data. So wait for the connection and then proceed if(TLptsFactoryConnection.getConnectionListSize()==4) startDataProcessing(); }

public void newConnectionProcessStarted() { System.out.println("Connecting..."); }

public void newConnectionFailed(TLptsLog log) { System.out.println("New Connection Failed. The logger got this."); }

public void removedAndClosedConnection(TLptsConnection connection) { System.out.println("Connection removed from Connection Manager and closed successfully ... " + connection.getTitle()); } } }

Parameters:
id - The ID of the connection to find in the list. This is a GUUID string.
Returns:
get connection by id

getConnectionList

public static java.util.List<TLptsConnection> getConnectionList()

Gets the Connection List.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : Never, an empty list in the worst case.

Notes :

Example :

 public class MyApp
 {
    private ConnectionStatementListener connectionListener;
    private String connId;
 

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(connectionListener); connectToDB(); }

private void connectToDB() { TLptsDBConnectionType connectionType = new TLptsDBConnectionType(); connId = connectionType.getId(); // we keep this so that we can find the connection afterwards. connectionType.setTitle("POSTGRESQL BANK-DB");

XLptsDriverType driverType = TLptsDriverLoader.getDriverTypeByClassName("org.postgresql.ds.PGSimpleDataSource");

if (driverType==null) { System.out.println("Could not find driver for class : org.postgresql.ds.PGSimpleDataSource"); return; }

TLptsDriverType dt = new TLptsDriverType(driverType);

// changing values that are default in the driver.loader.xml file. // the DB is now set correctly and will filter through to the Datasource interface execution dt.setValueForInterfaceFunctionParameter("setDatabaseName","Database Name","bank"); connectionType.setDriverType(dt);

connectionType.setCredentials(TLptsCryptoUtil.defaultEncryptCredentialsRSA("postgres","test"));

TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! }

private void exitButtonActionPerformed() { TLptsFactoryConnection.removeListener(connectionListener); }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { if (connection.getId().equals(connId)) System.out.println("Yupee - we found our connection and it is ready to go. Now we can create statements for it!"); }

public void newConnectionProcessStarted() { System.out.println("Connecting..."); }

public void newConnectionFailed(TLptsLog log) { System.out.println("New Connection Failed. The logger got this."); }

public void removedAndClosedConnection(TLptsConnection connection) { System.out.println("Connection removed from Connection Manager and closed successfully ... " + connection.getTitle()); } } }

Returns:
the list of current connections to data sources.

getConnectionListSize

public static int getConnectionListSize()

Gets the size of Connection List.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : Never.

Notes :

Example :

 public class MyApp
 {
    private ConnectionStatementListener connectionListener;
 

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(connectionListener); } ... private void connectToDB() { ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! } ... private void exitButtonActionPerformed() { TLptsFactoryConnection.removeListener(connectionListener); }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { System.out.println("New Connection created successfully. Statements can be processed.");

//We create 4 connections to process data. So wait for all the connections and then proceed. if(TLptsFactoryConnection.getConnectionListSize()==4) startDataProcessing(); }

public void newConnectionProcessStarted() { System.out.println("Connecting..."); }

public void newConnectionFailed(TLptsLog log) { System.out.println("New Connection Failed. The logger got this."); }

public void removedAndClosedConnection(TLptsConnection connection) { System.out.println("Connection removed from Connection Manager and closed successfully ... " + connection.getTitle()); } } }

Returns:
the size of connection list.

getDriverList

public static java.util.List<java.sql.Driver> getDriverList()

Gets the Driver List from the java DriverManager.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : Never, an empty list in the worst case.

Notes :

Example :

 List dl = TLptsFactoryConnection.getDriverList();
 

for (Driver d : dl) { d.getClass(); d.acceptsURL("jdbc:sqlserver://MyServerNameOrIP:1433\SQLEXRESSS;"); d.jdbcCompliant(); ... }

Returns:
A list of Drivers that implement java.sql.Driver interface and that are loaded in the DriverManager.

initiateConnection

public static void initiateConnection(XLptsDBConnectionType connectionType)

This function is used to initialise a connection to a data source.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : N/A

Notes :
This is the starting point of any interaction with a database.
This function is not called createConnection as it may not actually create a connection.
It will return a connection (through ILptsFactoryConnectionListener) to the data source with the information supplied.
This connection may be from the connection pool if it already exists with all the supplied parameters.

Example :

 private void connectToDB(String title, String driverClassName, String dbName, String username, String password)
 {
   TLptsDBConnectionType connectionType = new TLptsDBConnectionType();
   connectionType.setTitle(title);
 

XLptsDriverType driverType = TLptsDriverLoader.getDriverTypeByClassName(driverClassName);

if (driverType==null) { System.out.println("Could not find driver for class : " + driverClassName); return; }

connectionType.setDriverType(new TLptsDriverType(driverType));

// changing values that are default in the driver.loader.xml file. // the DB is now set correctly and will filter through to the Datasource interface execution if(dbName!=null) dt.setValueForInterfaceFunctionParameter("setDatabaseName","Database Name",dbName);

if(username==null || password==null) connectionType.setCredentials(TLptsCryptoUtil.defaultEncryptCredentialsRSA(driverType.getGuestUser(),driverType.getGuestPassword())); else connectionType.setCredentials(TLptsCryptoUtil.defaultEncryptCredentialsRSA(username,password));

TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! }

Parameters:
connectionType - The connection information to be used for the connection.

removeConnection

public static void removeConnection(TLptsConnection connection,
                                    boolean forceful)

Remove Connection from System.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : N/A

Notes :
Be careful not to remove a connection directly after a call to TLptsFactoryStatement.createStatement or
TLptsFactoryRowSet.executeSelectStatement, that are using the connection to be removed.
The safest place to remove a connection is when all the processing is complete (shown below).

Example :

 public class MyApp
 {
    private ConnectionStatementListener connectionListener;
    private String connId;
 

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(new ConnectionStatementListener()); TLptsFactoryStatement.addListener(new StatementFactoryListener()); TLptsFactoryRowSet.addListener(new RowSetListener()); } ... private void connectToDB() { TLptsDBConnectionType connectionType = new TLptsDBConnectionType(); .. // initialise it for a MySQL db. TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { TLptsStatement statement = new TLptsStatement(connection,XLptsDBTypeOfStatementType.SELECT); statement.setTitle(tableName); statement.setSqlDatabaseFormat(XLptsDBSqlDatabaseFormat.DEFAULT_MYSQL);

XLptsDBStatementTableType table = statement.getTableItemByName("MyTable"); table.setSelected(true); statement.setSelectOnAllColumns(table.getTableName(), true); statement.getCriteriaType().setType(XLptsDBCriteriaType.NONE); // no WHERE clause

TLptsFactoryStatement.createNewStatement(connection, statement); // spawns a seperate thread. } ... }

private class StatementFactoryListener implements ILptsFactoryStatementListener { public void newStatementCreated(TLptsConnection connection, TLptsStatement statement) { TLptsFactoryRowSet.executeSelectStatement(statement,1,0,false); // spawns another thread. false mean no limit on any sub-statements. } .... }

private class RowSetListener implements ILptsFactoryRowSetListener { public void rowEvent(final TLptsRowEvent rowEvent) { if (rowEvent.getEventType().equals(TLptsRowEvent.EVENT_TYPE.PROCESSING_COMPLETE)) { // true means to remove all statements for this connection before actually removing the connection. (forceful) TLptsFactoryConnection.removeConnection((TLptsConnection)(rowEvent.getStatement()).getConnectionWE(), true); } } ... } }

Parameters:
connection - to remove.
forceful - set true to delete all statements and connection. False will try to delete connection, but if there are statement, result will be negative.

removeListener

public static void removeListener(ILptsFactoryConnectionListener listener)

Remove a Listener that implements ILptsFactoryConnectionListener.

Thread Safe : Yes

Spawns its own Thread : No

May Return NULL : No

Notes :

Example :

    private ConnectionStatementListener connectionListener;
 

public MyApp() { ... connectionListener = new ConnectionStatementListener() TLptsFactoryConnection.addListener(connectionListener); } ... private void connectToDB() { ... TLptsFactoryConnection.initiateConnection(connectionType); // This generates another thread!! } ... private void exitButtonActionPerformed() { TLptsFactoryConnection.removeListener(connectionListener); }

private class ConnectionStatementListener implements ILptsFactoryConnectionListener { public synchronized void newConnectionCreated(TLptsConnection connection) { System.out.println("New Connection created successfully. Statements can be processed."); }

public void newConnectionProcessStarted() { System.out.println("Connecting..."); }

public void newConnectionFailed(TLptsLog log) { System.out.println("New Connection Failed. The logger got this."); }

public void removedAndClosedConnection(TLptsConnection connection) { System.out.println("Connection removed from Connection Manager and closed successfully ... " + connection.getTitle()); } } }


Parameters:
listener - the listener that no longer requires to be informed about connection changes.

zgCG

public static TLptsDBConnectionGroupType zgCG()
Obfuscated as it is not required by the application interface.


zgDLT

public static XLptsDriverLoaderType zgDLT()
Obfuscated as it is not required by the application interface.


zgODT

public static XLptsODBCDriverType zgODT()
Obfuscated as it is not required by the application interface.


zI

public static void zI()
Obfuscated, as it is not required by the application.



Copyright 2009,2010, Lapetus Systems Ltd. (All rights reserved)