Database Factory


Now that you have a lock manager, you can address the database factory portion of the assignment. A database factory is how the system creates a database object based on command-line parameters. A database factory can create a local or remote database. The client doesn't care which database object the database factory creates because the object reference looks the same to the client, as both are of the type DatabaseInterface . When the client starts, it sends a request for a database connection to the database factory. The factory must determine whether the mode of operation is local or remote. For local mode, the database factory returns an object that has opened the local database file. For remote mode, it returns an object that connects, through Remote Method Invocation (RMI), to a remote server, which in turn opens the database file local to it. The client doesn't care where the database is, and none of its code can be mode specific. The factory bears the responsibility for figuring out how to handle mode-specific matters.

The sample code in Listing 7.2 uses a database that is in-memory (for example, a two-dimensional String array for rows of data). For the real solution, you might use a database file, such as database.bin. The pathing parameters in the listing point to this database file. If you choose to implement a file-based solution rather than an in-memory one, I recommend locating the database.bin file in the install directory. You can provide a default path to database.bin in case no parameters are supplied. The database.bin functionality is provided for completeness here, but the code doesn't actually open that file; it is a template to help you with the real certification project.

Listing 7.2, which shows an example of a database factory, uses RMI. For readers who choose socket communication, the code will be different. Please refer to Chapter 11, "Networking with NIO," for detailed information on sockets if you prefer using them instead of RMI.

Listing 7.2 An Example of a Database Factory
 package superbowl.database; import java.util.Vector; import java.io.IOException; import java.rmi.RemoteException; import java.rmi.NotBoundException; import java.rmi.Naming; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; /**  * This class provides a choice of network connections. Depending on the  * number of parameters, one parameter pair of "-dbpath {DBPATH}" returns a  * local connection. Two parameters of "-host {HOST} -port {PORT}" will  * return a network connection. If the parameters are invalid, null will be  * returned.  *  * I used Adapter because I'm able to program the client UI solely in terms  * of Database type. Whether in local or remote mode, the factory returns  * an object of type DatabaseInterface.  * @author     Alain Trottier  * @version 1.0  10-Feb-2003  */ public class DatabaseFactory {     private Database db;     private String dbpath;     private String lookupString;     private static final String PORT             = "1099";     private static final String HOST             = "localhost";     private static final String DBPATH           = "database.bin";     private static final String RMI_SERVICE_NAME = "DatabaseService";     private static final String UNEXPECTED =             "DatabaseRMIServer-Unexpected database access problem: ";     private static final String cmdError = ""             + "\nYou must provide either the data file location "             + "or the RMI host and port parameters:\n"             + "\n -dbpath " + DBPATH             + "\nWhere path is either database.bin or $ROOT\database.bin"             + " (\"\\" for Windows; \"/\" for Unix)"             + "\nIf you provide network parameters you must use:"             + "\n-host {HOST} -port {PORT}"             + "\nFor example: -host " + HOST + " -port " + PORT             + "\nThe parameter pairs may be in any order, "             + "but both pairs are required.";     /**     * For the real solution, use a database file such as database.bin.     * The pathing parameters point to this database file. It should be     * located in the install directory. You can choose to provide     * a default path to database.bin in case no parameters are supplied.     * This method is provided for completeness, but is not supported.     * @exception IOException Thrown if cannot open connection.     */     public DatabaseFactory() throws IOException     {         String currentDirectory = System.getProperty("user.dir");         String fileSeperator = System.getProperty("file.separator");         dbpath = currentDirectory + fileSeperator + "database.bin";     }     /**     * Depending on the supplied parameters, a specific connection will     * be returned. Invalid parameters will lead to null return.     * @param cmdArgs String array of connection parameters     * @return An instance of the database.     * @exception SuperBowlException Thrown if cannot open connection.     */     public DatabaseInterface getDatabase(String[] cmdArgs)                              throws SuperBowlException     {         int cmdArgsLength = cmdArgs.length;         String host     = HOST;         String port     = PORT;                dbpath   = DBPATH;         try         {             // test if local database is wanted             if (cmdArgsLength == 0)             {                 return new Database("database.bin");             // test if local database is wanted             } else if (cmdArgsLength == 2                   && cmdArgs[0].equalsIgnoreCase("-dbpath"))             {                 dbpath = cmdArgs[1];                 return new Database(dbpath);             // test if remote database is wanted             } else if (cmdArgsLength == 4)             {                 // parse RMI server command line                 int i      = 0;                 while (i < cmdArgsLength)                 {                     String arg = cmdArgs[i++];                     if (arg.equalsIgnoreCase("-host"))                     {                         host = cmdArgs[i++];                     } else if (arg.equalsIgnoreCase("-port"))                     {                         port = cmdArgs[i++];                     } else                     {                     // exit if user mistypes a command parameter                     System.out.println( cmdError );                     System.out.println( "rmi://"                                + host + ":"                                + port + "/"                                + RMI_SERVICE_NAME );                     System.exit( 0 );                     }                 }                 lookupString = "rmi://"                      + host + ":"                      + port + "/"                      + RMI_SERVICE_NAME;                 return (DatabaseInterface)Naming.lookup(lookupString);             } else             {                 // user provided wrong parameters                 throw new SuperBowlException(cmdError);             }          } catch (RemoteException rex)          {             throw new SuperBowlException(lookupString + "\n"                              + UNEXPECTED + "\n"                              + rex);          } catch (NotBoundException nbe)          {             throw new SuperBowlException(lookupString + "\n"                              + UNEXPECTED + "\n" + nbe);          } catch (IOException ioe)          {             throw new SuperBowlException(lookupString + "\n"                              + UNEXPECTED + "\n" + ioe);          } catch (Exception e)          {             throw new SuperBowlException(lookupString + "\n"                              + UNEXPECTED + "\n" + e);          }     }     /**     * A local database connection will be returned.     *     * @return An instance of the database.     * @exception SuperBowlException Thrown if cannot open connection.     */     public DatabaseInterface getDatabase()                  throws SuperBowlException     {         try         {         // assumes "database.bin" is in the install directory         return new Database(dbpath);         } catch(IOException ioe)         {             throw new SuperBowlException(UNEXPECTED + ioe);         }     }     /**     * A local database connection will be returned.     * @param dbpath The database file path     * @return An instance of the database.     * @exception SuperBowlException - Thrown if cannot open connection.     */     public DatabaseInterface getDatabase(String dbpath)                  throws SuperBowlException     {         try         {         // opens "database.bin" at beginning of file for random access         return new Database(dbpath);         } catch(IOException ioe)         {             throw new SuperBowlException(UNEXPECTED + ioe);         }     } } 

You'll notice that this database factory parses command-line parameters. From the parameters, it figures out whether the client is in local or remote mode. Furthermore, because the database connection is passed to the client typed by an interface ( DatabaseInterface ), the client can remain unaware of whether the database is actually a local or remote object.



JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
JavaT 2 Developer Exam CramT 2 (Exam CX-310-252A and CX-310-027)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 187

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net