Package ptolemy.actor.lib.database
Class DatabaseManager
- java.lang.Object
-
- ptolemy.kernel.util.NamedObj
-
- ptolemy.kernel.InstantiableNamedObj
-
- ptolemy.kernel.Entity<T>
-
- ptolemy.kernel.ComponentEntity<T>
-
- ptolemy.actor.AtomicActor<TypedIOPort>
-
- ptolemy.actor.TypedAtomicActor
-
- ptolemy.actor.lib.database.DatabaseManager
-
- All Implemented Interfaces:
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://download.oracle.com/javase/6/docs/api/java/sql/DriverManager.html- Since:
- Ptolemy II 8.0
- Version:
- $Id$
- Author:
- Edward A. Lee
- Pt.AcceptedRating:
- Red (cxh)
- Pt.ProposedRating:
- Red (eal)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description StringParameter
database
JDBC connection string to access the database.FileParameter
passwordFile
The file that contains the password.StringParameter
userName
User name.-
Fields inherited from class ptolemy.actor.TypedAtomicActor
_typesValid
-
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _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
Constructors Constructor Description DatabaseManager(CompositeEntity container, java.lang.String name)
Construct an actor with the given container and name.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description 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
_containedTypeConstraints, _customTypeConstraints, _defaultTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
-
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, _declareDelayDependency, addActorFiringListener, addInitializable, 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
_addPort, _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, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, addHierarchyListener, attributeDeleted, attributeList, attributeList, decorators, 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, notifyOfNameChange, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, 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.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
-
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
-
-
-
-
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 isjdbc:mysql://localhost:3306/space
which specifies a MySQL database on the local host, where "space" is the name of the database.
-
passwordFile
public FileParameter passwordFile
The file that contains the password. If this parameter is non-empty, then it is assumed to refer to a file that contains the password. If this parameter is empty, or names a file that cannot be read, then a dialog is displayed for the user to enter the password. It is up to the user to properly protect the file from unauthorized readers by using the file system permissions. The default value is the empty string, meaning that the dialog will be displayed.
-
userName
public StringParameter userName
User name.
-
-
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 class, if the database or userName is changed, this method closes the connection with the database and forgets the password.- Overrides:
attributeChanged
in classNamedObj
- 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 the password file cannot be read and "ptolemy.ptII.isRunningNightlyBuild" property exists and is not empty or if the "ptolemy.ptII.batchMode" property exists and is not empty and the property "ptolemyII.ptII.testingMessageHandler" is not set.
-
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 interfaceInitializable
- Overrides:
preinitialize
in classAtomicActor<TypedIOPort>
- 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 interfaceInitializable
- Overrides:
wrapup
in classAtomicActor<TypedIOPort>
- Throws:
IllegalActionException
- If the wrapup() method of one of the associated actors throws it, or if we fail to close the database connection.
-
-