public class JavaScript extends TypedAtomicActor
To use this actor, add input and output ports and parameters, and specify a script. Your script should define one or more of the following functions:
Usually, you will need to explicitly specify the types of the output ports. Alternatively, you can enable backward type inference on the enclosing model, and the types of output ports will be inferred by how the data are used.
You may also need to set the type of input ports. Usually, forward type inference will work, and the type of the input port will be based on the source of data. However, if the input comes from an output port whose output is undefined, such as JSONToToken or HttpRequestHandler, then you may want to enable backward type inference, and specify here the type of input that your script requires.
The context in which your functions run provide the following methods:
The following example script calculates the factorial of the input.
function fire() { var value = get(input); if (value < 0) { error("Input must be greater than or equal to 0."); } else { var total = 1; while (value > 1) { total *= value; value--; } send(total, output); } }
Your script may also store values from one firing to the next, or from initialization to firing. For example,
var init; function initialize() { init = 0; } function fire() { init = init + 1; send(init, output); }will send a count of firings to the output named "output".
Notice that you may name ports or parameters of this actor in such a way as to shadow objects in the global scope. For example, JavaScript provides a JSON object that you can use to operate on JSON strings, for example with the function JSON.parse(). However, if you name a port or parameter "JSON", then any reference to JSON in your fire() method, for example, will refer to the port or parameter, and not to the global object. To explicitly refer to the global object, use the syntax "this.JSON".
In addition, the symbol "actor" is defined to be the instance of this actor. In JavaScript, you can invoke methods on it. For example, the JavaScript
actor.toplevel().getName();will return the name of the top-level composite actor containing this actor.
Not all Ptolemy II data types translate naturally to JavaScript types. This actor converts Ptolemy types int, double, string, and boolean to and from equivalent JavaScript types. In addition, arrays are converted to native JavaScript arrays. Ptolemy II records are converted into JavaScript objects, and JavaScript objects with enumerable properties into records.
For other Ptolemy II types, the script will see the corresponding Token object. For example, if you send a number of type long to an input of a JavaScript actor, the script (inside a fire() function):
var value = get(input); print(value.getClass().toString());will print on standard out the string
"class ptolemy.data.LongToken"JavaScript does not have a long data type (as of this writing), so instead the get() call returns a JavaScript Object wrapping the Ptolemy II LongToken object. You can then invoke methods on that token, such as getClass(), as done above.
Scripts can instantiate Java classes and invoke methods on them. For example, the following script will build a simple Ptolemy II model:
importPackage(Packages.ptolemy.actor); importClass(Packages.ptolemy.actor.lib.Ramp); importClass(Packages.ptolemy.actor.lib.FileWriter); importClass(Packages.ptolemy.domains.sdf.kernel.SDFDirector); var toplevel = new TypedCompositeActor(); var ramp = new Ramp(toplevel, "ramp"); var writer = new FileWriter(toplevel, "writer"); toplevel.connect(ramp.output, writer.input); var director = new SDFDirector(toplevel, "SDFDirector"); director.iterations.setExpression("10");You can even send this out on an output port. For example,
send(toplevel, output, 0);where "output" is the name of the output port.
Subclasses of this actor may put it in "restricted" mode, which limits the functionality as follows:
Red (bilung) |
Yellow (eal) |
Modifier and Type | Class and Description |
---|---|
static class |
JavaScript.ParameterProxy
Proxy for a parameter.
|
static class |
JavaScript.PortProxy
Proxy for a port.
|
class |
JavaScript.PtolemyJavaScript
Container class for built-in methods.
|
Entity.ContainedObjectsIterator
Modifier and Type | Field and Description |
---|---|
protected org.mozilla.javascript.Script |
_compiledScript
Compiled JavaScript.
|
protected org.mozilla.javascript.Context |
_context
Rhino context.
|
protected static java.lang.Object[] |
_EMPTY_ARGS
Empty argument list for JavaScript function invocation.
|
protected boolean |
_executing
True while the model is executing (between initialize() and
wrapup(), inclusive.
|
protected org.mozilla.javascript.Scriptable |
_global
Global scope, unpolluted by anything in this actor.
|
protected static java.lang.String[] |
_JAVASCRIPT_KEYWORDS
Keywords.
|
protected static java.util.Set<java.lang.String> |
_KEYWORDS
Keywords as a Set.
|
(package private) java.util.List<io.socket.SocketIO> |
_openSockets
List of open sockets.
|
protected boolean |
_restricted
If set to true in the constructor of a base class, then put this actor in "restricted"
mode.
|
protected org.mozilla.javascript.Scriptable |
_scope
Scope in which to evaluate scripts.
|
StringAttribute |
script
The script to execute when this actor fires.
|
TypedIOPort |
scriptIn
Alternative way to provide a script to execute when this actor fires.
|
_typesValid
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
COMPLETED, NOT_READY, STOP_ITERATING
Constructor and Description |
---|
JavaScript(CompositeEntity container,
java.lang.String name)
Construct an actor with the given container and name.
|
Modifier and Type | Method and Description |
---|---|
protected java.util.Set<Inequality> |
_defaultTypeConstraints()
Return null, becuase the default type constraints, where output
types are greater than or equal to all input types, make no sense
for this actor.
|
java.lang.Object |
clone(Workspace workspace)
Clone the actor into the specified workspace.
|
void |
fire()
Execute the script, handling inputs and producing outputs as described.
|
void |
initialize()
Register the ports and parameters with the JavaScript engine.
|
static boolean |
isValidIdentifierName(java.lang.String identifier)
Return true if the specified string is not a JavaScript keyword and is a valid JavaScript identifier.
|
void |
preinitialize()
Set the state to equal the value of the init parameter.
|
void |
wrapup()
Execute the wrapup function, if it is defined, and exit the context for this thread.
|
_containedTypeConstraints, _customTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
_actorFiring, _actorFiring, _declareDelayDependency, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, postfire, prefire, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
_addPort, _description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, addHierarchyListener, attributeChanged, 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
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
isFireFunctional, isStrict, iterate, postfire, prefire, stop, stopFire, terminate
addInitializable, removeInitializable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
getDerivedLevel, getDerivedList, propagateValue
public StringAttribute script
public TypedIOPort scriptIn
protected org.mozilla.javascript.Script _compiledScript
protected org.mozilla.javascript.Context _context
protected static final java.lang.Object[] _EMPTY_ARGS
protected boolean _executing
protected org.mozilla.javascript.Scriptable _global
protected static final java.lang.String[] _JAVASCRIPT_KEYWORDS
protected static final java.util.Set<java.lang.String> _KEYWORDS
protected boolean _restricted
protected org.mozilla.javascript.Scriptable _scope
java.util.List<io.socket.SocketIO> _openSockets
public JavaScript(CompositeEntity container, java.lang.String name) throws NameDuplicationException, IllegalActionException
container
- The container.name
- The name of this actor.IllegalActionException
- If the actor cannot be contained
by the proposed container.NameDuplicationException
- If the container already has an
actor with this name.public java.lang.Object clone(Workspace workspace) throws java.lang.CloneNotSupportedException
clone
in class TypedAtomicActor
workspace
- The workspace for the new object.java.lang.CloneNotSupportedException
- If a derived class contains
an attribute that cannot be cloned.NamedObj.exportMoML(Writer, int, String)
,
NamedObj.setDeferringChangeRequests(boolean)
public void fire() throws IllegalActionException
fire
in interface Executable
fire
in class AtomicActor<TypedIOPort>
IllegalActionException
- If calling send() or super.fire()
throws it.public void initialize() throws IllegalActionException
initialize
in interface Initializable
initialize
in class AtomicActor<TypedIOPort>
IllegalActionException
- If calling send() or super.fire()
throws it.public static boolean isValidIdentifierName(java.lang.String identifier)
identifier
- The proposed name.public void preinitialize() throws IllegalActionException
preinitialize
in interface Initializable
preinitialize
in class AtomicActor<TypedIOPort>
IllegalActionException
- If the parent class throws it.public void wrapup() throws IllegalActionException
wrapup
in interface Initializable
wrapup
in class AtomicActor<TypedIOPort>
IllegalActionException
- If the parent class throws it.protected java.util.Set<Inequality> _defaultTypeConstraints()
_defaultTypeConstraints
in class TypedAtomicActor