ptolemy.actor.lib.database
Class DatabaseManager

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.InstantiableNamedObj
          extended by ptolemy.kernel.Entity
              extended by ptolemy.kernel.ComponentEntity
                  extended by ptolemy.actor.AtomicActor
                      extended by ptolemy.actor.TypedAtomicActor
                          extended by ptolemy.actor.lib.database.DatabaseManager
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class DatabaseManager
extends TypedAtomicActor

A DatabaseManager. When preinitialized, this actor opens a connection to the specified database. When wrapup() is called, it closes the connection. A user of this class can also separately call getConnection() to open a connection, but then that user must also call closeConnection() when finished.

This class polls all available JDBC database drivers until one is willing to open the string given by the database parameter. Depending on the driver, this string may be a URL. Some database drivers are packaged with Ptolemy II and available from a vergil process. You can make others available by setting the jdbc.drivers property. For example, when invoking vergil, do something like this:

  export JAVAFLAGS=-Djdbc.drivers=com.mysql.jdbc.Driver:bad.tast.ourDriver
  $PTII/bin/vergil -verbose
 
The above lists two drivers, in order of preference, separated by a ":". More information can be found at http://java.sun.com/j2se/1.5.0/docs/api/java/sql/DriverManager.html.

Since:
Ptolemy II 8.0
Version:
$Id: DatabaseManager.java 57046 2010-01-27 23:35:53Z cxh $
Author:
Edward A. Lee
See Also:
Serialized Form
Accepted Rating:
Red (cxh)
Proposed Rating:
Red (eal)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
 
Field Summary
private  java.sql.Connection _connection
          The currently open connection.
private  char[] _password
          The password last entered.
 StringParameter database
          JDBC connection string to access the database.
 StringParameter userName
          User name.
 
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
DatabaseManager(CompositeEntity container, java.lang.String name)
          Construct an actor with the given container and name.
 
Method Summary
 void attributeChanged(Attribute attribute)
          React to a change in an attribute.
 void closeConnection()
          Close the connection to the database, if one is open.
 java.lang.String execute(java.lang.String sql)
          Execute the specified SQL statement and return the result as a string.
 ArrayToken executeQuery(java.lang.String sql)
          Execute the SQL query given in the specified string and return an array of record tokens containing the results.
 int executeUpdate(java.lang.String sql, int expectedResult)
          Execute the SQL update given in the specified string and return the number of affected rows or zero if the update does not return anything.
static DatabaseManager findDatabaseManager(java.lang.String name, NamedObj actor)
          Find a database manager with the specified name for the specified actor.
 java.sql.Connection getConnection()
          Get a connection to the database.
 void preinitialize()
          Open a connection to the database, if one is not already open, prompting the user for a password.
 void wrapup()
          Close the connection to the database, if it is open.
 
Methods inherited from class ptolemy.actor.TypedAtomicActor
_addPort, _fireAt, _fireAt, attributeTypeChanged, clone, newPort, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, addActorFiringListener, addInitializable, clone, connectionsChanged, createReceivers, declareDelayDependency, fire, getCausalityInterface, getDirector, getExecutiveDirector, getManager, initialize, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, postfire, prefire, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeList, attributeList, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
 
Methods inherited from interface ptolemy.actor.Executable
fire, isFireFunctional, isStrict, iterate, postfire, prefire, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, initialize, removeInitializable
 
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
 
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
 

Field Detail

database

public StringParameter database
JDBC connection string to access the database. This always starts with "jdbc:driver", where the specific driver chosen determines how to interpret fields in the rest of the string. For example,
    jdbc:oracle:thin:@buffy.eecs.berkeley.edu:1521:acgeecs
  
specifies a thin client for an Oracle database located at host buffy.eecs.berkeley.edu, which listens on port 1521. The "acgeecs" is the database name. Another example is
    jdbc:mysql://localhost:3306/space
  
which specifies a MySQL database on the local host, where "space" is the name of the database.


userName

public StringParameter userName
User name.


_connection

private java.sql.Connection _connection
The currently open connection.


_password

private char[] _password
The password last entered.

Constructor Detail

DatabaseManager

public DatabaseManager(CompositeEntity container,
                       java.lang.String name)
                throws NameDuplicationException,
                       IllegalActionException
Construct an actor with the given container and name.

Parameters:
container - The container.
name - The name of this actor.
Throws:
IllegalActionException - If the entity cannot be contained by the proposed container.
NameDuplicationException - If the container already has an actor with this name.
Method Detail

attributeChanged

public void attributeChanged(Attribute attribute)
                      throws IllegalActionException
React to a change in an attribute. This method is called by a contained attribute when its value changes. In this base class, the method does nothing. In derived classes, this method may throw an exception, indicating that the new attribute value is invalid. It is up to the caller to restore the attribute to a valid value if an exception is thrown.

Overrides:
attributeChanged in class NamedObj
Parameters:
attribute - The attribute that changed.
Throws:
IllegalActionException - If the change is not acceptable to this container (not thrown in this base class).

closeConnection

public void closeConnection()
                     throws IllegalActionException
Close the connection to the database, if one is open.

Throws:
IllegalActionException - If closing the connection fails.

execute

public java.lang.String execute(java.lang.String sql)
                         throws IllegalActionException
Execute the specified SQL statement and return the result as a string. Note that if there is no connection to the database, this will open one. The caller is responsible for calling closeConnection() after this.

Parameters:
sql - The query.
Returns:
The result as a string.
Throws:
IllegalActionException - If the statement fails.

executeQuery

public ArrayToken executeQuery(java.lang.String sql)
                        throws IllegalActionException
Execute the SQL query given in the specified string and return an array of record tokens containing the results. Note that if there is no connection to the database, this will open one. The caller is responsible for calling closeConnection() after this.

Parameters:
sql - The query.
Returns:
An array of record tokens containing the results, which may be empty (zero length), or null if the connection fails or is canceled.
Throws:
IllegalActionException - If the query fails.

executeUpdate

public int executeUpdate(java.lang.String sql,
                         int expectedResult)
                  throws IllegalActionException
Execute the SQL update given in the specified string and return the number of affected rows or zero if the update does not return anything. Note that if there is no connection to the database, this will open one. The caller is responsible for calling closeConnection() after this.

Parameters:
sql - The query.
expectedResult - If a non-negative number is given here, then the update is not committed unless the result matches.
Returns:
The number of rows affected or 0 if the update does not return a value, or -1 if the connection is canceled.
Throws:
IllegalActionException - If the query fails or if the result does not match the value of expectedResult.

findDatabaseManager

public static DatabaseManager findDatabaseManager(java.lang.String name,
                                                  NamedObj actor)
                                           throws IllegalActionException
Find a database manager with the specified name for the specified actor.

Parameters:
name - Database manager name.
actor - The actor.
Returns:
A database manager.
Throws:
IllegalActionException - If no database manager is found.

getConnection

public java.sql.Connection getConnection()
                                  throws IllegalActionException
Get a connection to the database. If one is already open, then simply return that one. Otherwise, use the parameter values and prompt for a password to open a new connection.

Returns:
A connection to the database, or null if the user cancels.
Throws:
IllegalActionException - If

preinitialize

public void preinitialize()
                   throws IllegalActionException
Open a connection to the database, if one is not already open, prompting the user for a password. If the user declines to provide the password (by clicking Cancel on the dialog box), then request that execution be stopped.

Specified by:
preinitialize in interface Initializable
Overrides:
preinitialize in class AtomicActor
Throws:
IllegalActionException - If opening the database fails.

wrapup

public void wrapup()
            throws IllegalActionException
Close the connection to the database, if it is open.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class AtomicActor
Throws:
IllegalActionException - If the wrapup() method of one of the associated actors throws it, or if we fail to close the database connection.