ptolemy.actor.lib.embeddedJava
Class CompiledCompositeActor

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.kernel.CompositeEntity
                      extended by ptolemy.actor.CompositeActor
                          extended by ptolemy.actor.TypedCompositeActor
                              extended by ptolemy.actor.lib.embeddedJava.CompiledCompositeActor
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Actor, Executable, FiringsRecordable, Initializable, TypedActor, Changeable, Debuggable, DebugListener, Derivable, Instantiable, ModelErrorHandler, MoMLExportable, Moveable, Nameable
Direct Known Subclasses:
EmbeddedJavaActor

public class CompiledCompositeActor
extends TypedCompositeActor

A composite actor that can be optionally code generated and then invoked via reflection.

Since:
Ptolemy II 8.0
Version:
$Id: CompiledCompositeActor.java 57044 2010-01-27 22:41:05Z cxh $
Author:
Gang Zhou, contributors: Christopher Brooks, Edward A. Lee, Bert Rodiers
See Also:
Serialized Form
Accepted Rating:
red (zgang)
Proposed Rating:
red (zgang)

Nested Class Summary
 
Nested classes/interfaces inherited from class ptolemy.kernel.CompositeEntity
CompositeEntity.ContainedObjectsIterator
 
Field Summary
private  java.lang.reflect.Method _fireMethod
           
private  long _generatedCodeVersion
          The workspace version for which the code was generated.
private  java.lang.reflect.Method _initializeMethod
           
private  long _loadedCodeVersion
          The workspace version for which the code was loaded.
private static int _noEffigyVersion
          The version of the shared object to use if we have no effigy.
private  java.lang.Object _objectWrapper
           
private  java.lang.String _sanitizedActorName
          The sanitized actor name.
private  int _version
          The version of the shared object.
private  java.lang.reflect.Method _wrapupMethod
           
 FileParameter codeDirectory
          The directory in which to put the generated code.
 Parameter executeEmbeddedCode
          If true, then invoke the generated code in the action methods (fire(), etc.).
 StringParameter generatorPackage
          The name of the package in which to look for helper class code generators.
 Parameter inline
          If true, generate file with no functions.
 Parameter overwriteFiles
          If true, overwrite preexisting files.
 
Fields inherited from class ptolemy.actor.CompositeActor
_actorFiringListeners, _causalityInterface, _initializables, _notifyingActorFiring, _publishedPorts, _publisherRelations, _stopRequested
 
Fields inherited from class ptolemy.kernel.CompositeEntity
_levelCrossingLinks
 
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
CompiledCompositeActor()
          Construct a CodeGenerationCompositeActor in the default workspace with no container and an empty string as its name.
CompiledCompositeActor(CompositeEntity container, java.lang.String name)
          Create an actor with a name and a container.
CompiledCompositeActor(Workspace workspace)
          Construct a CodeGenerationCompositeActor in the specified workspace with no container and an empty string as a name.
 
Method Summary
private  boolean _buildSharedObjectFile()
          Return true if the shared object file should be built.
protected  void _generateAndCompileEmbeddedJavaCode()
          Generate and compile Java code.
private  void _init()
          Initialize parameters.
private  java.lang.Object _invokeHelperMethod(java.lang.String methodName)
          Invoke a method in the corresponding helper class.
private  java.lang.String _sharedObjectPath(java.lang.String sanitizedActorName)
          Get the name of the shared object.
private  java.lang.Object _transferInputs(IOPort port)
           
private  void _transferOutputs(IOPort port, java.lang.Object outputTokens)
           
private  void _updateSanitizedActorName()
          Update the _sanitizedActorName variable.
 void fire()
          If executeEmbeddedCode is true, then execute the fire() method of the generated code.
 java.lang.String getSanitizedName()
          Return the sanitized file name of this actor.
 void initialize()
          If executeEmbeddedCode is true, then generate and compile the code (if necessary), and then execute the initialize() method of the generated code.
 void wrapup()
          If executeEmbeddedCode is true, then execute the wrapup() method of the generated code.
 
Methods inherited from class ptolemy.actor.TypedCompositeActor
_addEntity, _addPort, _addRelation, _checkTypesFromTo, _typeConstraintsFromTo, newPort, newRelation, resolveTypes, typeConstraintList, typeConstraints
 
Methods inherited from class ptolemy.actor.CompositeActor
_actorFiring, _actorFiring, _finishedAddEntity, _getPublishedPort, _setDirector, addActorFiringListener, addInitializable, addPiggyback, clone, connectionsChanged, createReceivers, createSchedule, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inferringWidths, inferWidths, inputPortList, isFireFunctional, isOpaque, isStrict, iterate, linkToPublishedPort, linkToPublishedPort, needsWidthInference, newInsideReceiver, newReceiver, notifyConnectivityChange, outputPortList, postfire, prefire, preinitialize, recordFiring, registerPublisherPort, removeActorFiringListener, removeInitializable, removePiggyback, requestChange, setContainer, setDirector, setManager, stop, stopFire, terminate, unlinkToPublishedPort, unlinkToPublishedPort, unregisterPublisherPort
 
Methods inherited from class ptolemy.kernel.CompositeEntity
_adjustDeferrals, _deepOpaqueEntityList, _description, _exportMoMLContents, _recordDecoratedAttributes, _removeEntity, _removeRelation, _validateSettables, allAtomicEntityList, allCompositeEntityList, allowLevelCrossingConnect, classDefinitionList, connect, connect, containedObjectsIterator, deepEntityList, deepGetEntities, deepOpaqueEntityList, deepRelationSet, entityList, entityList, exportLinks, exportMoML, getAttribute, getEntities, getEntity, getPort, getRelation, getRelations, isAtomic, lazyAllAtomicEntityList, lazyAllCompositeEntityList, lazyClassDefinitionList, lazyDeepEntityList, lazyEntityList, lazyRelationList, numberOfEntities, numberOfRelations, numEntities, numRelations, relationList, removeAllEntities, removeAllRelations, setClassDefinition, statistics, uniqueName
 
Methods inherited from class ptolemy.kernel.ComponentEntity
_checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
 
Methods inherited from class ptolemy.kernel.Entity
_removePort, connectedPortList, connectedPorts, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts
 
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, 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, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, attributeChanged, attributeList, attributeList, attributeTypeChanged, clone, 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, 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
isFireFunctional, isStrict, iterate, postfire, prefire, stop, stopFire, terminate
 
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, preinitialize, 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

codeDirectory

public FileParameter codeDirectory
The directory in which to put the generated code. This is a file parameter that must specify a directory. The default is $HOME/codegen.


generatorPackage

public StringParameter generatorPackage
The name of the package in which to look for helper class code generators. This is a string that defaults to "ptolemy.codegen.java".


inline

public Parameter inline
If true, generate file with no functions. If false, generate file with functions. The default value is a parameter with the value true.


executeEmbeddedCode

public Parameter executeEmbeddedCode
If true, then invoke the generated code in the action methods (fire(), etc.). If the value is false, this actor will be executed executing like an ordinary composite actor. Classes like EmbeddedJavaActor set embedded to true when there is only Java code specifying the functionality of an actor.


overwriteFiles

public Parameter overwriteFiles
If true, overwrite preexisting files. The default value is a parameter with the value true.


_objectWrapper

private java.lang.Object _objectWrapper

_fireMethod

private transient java.lang.reflect.Method _fireMethod

_initializeMethod

private transient java.lang.reflect.Method _initializeMethod

_wrapupMethod

private transient java.lang.reflect.Method _wrapupMethod

_sanitizedActorName

private java.lang.String _sanitizedActorName
The sanitized actor name. The name has the underscores removed and the value of the _version variable appended. Call _updateSanitizedActorName() to properly set this variable.


_generatedCodeVersion

private long _generatedCodeVersion
The workspace version for which the code was generated. If the workspace version and this variable differ, Then there is a chance we should regenerate the code.


_loadedCodeVersion

private long _loadedCodeVersion
The workspace version for which the code was loaded. If the workspace version and this variable differ, then we should reload the code. Note that we don't want to reload the same dll multiple times or we will get "Native Library foo.dll already loaded in another classloader"


_version

private int _version
The version of the shared object. Each time we rebuild, the version number gets incremented. If you change _version, then consider calling _updateSanitizedActorName.


_noEffigyVersion

private static int _noEffigyVersion
The version of the shared object to use if we have no effigy. If we don't have an effigy, then we increment this variable and set _version to its value.

Constructor Detail

CompiledCompositeActor

public CompiledCompositeActor()
Construct a CodeGenerationCompositeActor in the default workspace with no container and an empty string as its name. Add the actor to the workspace directory. You should set a director before attempting to execute it. You should set the container before sending data to it. Increment the version number of the workspace.


CompiledCompositeActor

public CompiledCompositeActor(Workspace workspace)
Construct a CodeGenerationCompositeActor in the specified workspace with no container and an empty string as a name. You can then change the name with setName(). If the workspace argument is null, then use the default workspace. You should set a director before attempting to execute it. You should set the container before sending data to it. Increment the version number of the workspace.

Parameters:
workspace - The workspace that will list the actor.

CompiledCompositeActor

public CompiledCompositeActor(CompositeEntity container,
                              java.lang.String name)
                       throws IllegalActionException,
                              NameDuplicationException
Create an actor with a name and a container. The container argument must not be null, or a NullPointerException will be thrown. This actor will use the workspace of the container for synchronization and version counts. If the name argument is null, then the name is set to the empty string. Increment the version of the workspace. This actor will have no local director initially, and its executive director will be simply the director of the container. You should set a director before attempting to execute it.

Parameters:
container - The container actor.
name - The name of this actor.
Throws:
IllegalActionException - If the container is incompatible with this actor.
NameDuplicationException - If the name coincides with an actor already in the container.
Method Detail

fire

public void fire()
          throws IllegalActionException
If executeEmbeddedCode is true, then execute the fire() method of the generated code. Otherwise, delegate to the superclass, which executes this actor like an ordinary composite actor.

Specified by:
fire in interface Executable
Overrides:
fire in class CompositeActor
Throws:
IllegalActionException - If thrown by the super class, or if there are problems invoking the fire() method of wrapper class.

getSanitizedName

public java.lang.String getSanitizedName()
Return the sanitized file name of this actor. The sanitized name is created by invoking StringUtilities.sanitizeName(String), removing underscores and appending a version number. The version number is necessary so that we can reload the shared object.

Returns:
The sanitized actor name.

initialize

public void initialize()
                throws IllegalActionException
If executeEmbeddedCode is true, then generate and compile the code (if necessary), and then execute the initialize() method of the generated code. Otherwise, delegate to the superclass, which initializes this actor like an ordinary composite actor.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class CompositeActor
Throws:
IllegalActionException - If there is no director, or if the director's initialize() method throws it, or if the actor is not opaque.

wrapup

public void wrapup()
            throws IllegalActionException
If executeEmbeddedCode is true, then execute the wrapup() method of the generated code. Otherwise, delegate to the superclass, which executes this actor like an ordinary composite actor.

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class CompositeActor
Throws:
IllegalActionException - If there is no director, or if the director's wrapup() method throws it, or if this actor is not opaque.

_generateAndCompileEmbeddedJavaCode

protected void _generateAndCompileEmbeddedJavaCode()
                                            throws IllegalActionException
Generate and compile Java code.

Throws:
IllegalActionException - If the helper class cannot be found, or if the static generateCode(TypedCompositeActor) method in the helper class cannot be found or invoked.

_buildSharedObjectFile

private boolean _buildSharedObjectFile()
                                throws IllegalActionException
Return true if the shared object file should be built. The shared object file must be built if shared object file does not exist or if the model has been modified and not saved or if the modification time of the shared object file is earlier than the modification time of the model file. This method always copies files listed in the fileDependency block.

Returns:
true if the shared object file should be built.
Throws:
IllegalActionException - If there is a problem generating the path to the shared object.

_sharedObjectPath

private java.lang.String _sharedObjectPath(java.lang.String sanitizedActorName)
                                    throws IllegalActionException
Get the name of the shared object.

Parameters:
sanitizedActorName - The sanitized actor name on which to base the name of the shared object.
Returns:
The name of the .dll or .so file.
Throws:
IllegalActionException - If there is a problem reading the codeDirectory parameter.

_invokeHelperMethod

private java.lang.Object _invokeHelperMethod(java.lang.String methodName)
                                      throws IllegalActionException
Invoke a method in the corresponding helper class.

Parameters:
methodName - The name of a method in the helper class. The method must be static and take a TypedCompositeArgument as its only argument.
Returns:
The return value from the method, see java.lang.Method.invoke().
Throws:
IllegalActionException - If the helper class can't be found or if the method cannot be invoked.

_init

private void _init()
Initialize parameters.


_transferInputs

private java.lang.Object _transferInputs(IOPort port)
                                  throws IllegalActionException
Throws:
IllegalActionException

_transferOutputs

private void _transferOutputs(IOPort port,
                              java.lang.Object outputTokens)
                       throws IllegalActionException
Throws:
IllegalActionException

_updateSanitizedActorName

private void _updateSanitizedActorName()
Update the _sanitizedActorName variable. Consider calling this method each time _version is updated.