Class JSAccessor
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Cloneable
,Actor
,Executable
,FiringsRecordable
,Placeable
,Initializable
,AccessorOrchestrator
,TypedActor
,Changeable
,Debuggable
,DebugListener
,Derivable
,Instantiable
,ModelErrorHandler
,MoMLExportable
,Moveable
,Nameable
public class JSAccessor extends JavaScript
An component accessor that consists of an interface and a script.The "Vision of Swarmlets" paper defines three types of accessors: Interface, Component and Composite. The paper states: "A component accessor has an interface and a script... The script defines one or more functions that are invoked by the swarmlet host."
This is a specialized JavaScript actor that hides the script from casual users by putting it in "expert" mode. It also sets the actor to "restricted" mode, which restricts the functionality of the methods methods and variables provided in the JavaScript context.
FIXME: This should support versioning of accessors. It should check the accessorSource for updates and replace itself if there is a newer version and the user agrees to the replacement. This will be tricky because any parameters and connections previously set should be preserved.
This actor extends
JavaScript
and thus requires Nashorn, which is present in Java-1.8 and later.This actor will run
git
andnode
, which require network access. To skip running things that require network access, set thePT_NO_NET
environment variable to a non-empty string. For example, under bash:export PT_NO_NET=true
Note that if
PT_NO_NET
is set to any value, then the actor will attempt to avoid using the network.To always run ptdoc, set the
PT_RUN_PTDOC
environment variable. Otherwise, if PT_NO_NET is not set, then the ptdocs are only regenerated when the git pull modifies a file.References
Elizabeth Latronico, Edward A. Lee, Marten Lohstroh, Chris Shaver, Armin Wasicek, Matt Weber. A Vision of Swarmlets, IEEE Internet Computing, Special Issue on Building Internet of Things Software, 19(2):20-29, March 2015.
- Since:
- Ptolemy II 11.0
- Version:
- $Id$
- Author:
- Edward A. Lee, Contributor: Christopher Brooks
- Pt.AcceptedRating:
- Red (cxh)
- Pt.ProposedRating:
- Red (eal)
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description class
JSAccessor.ActionableAttribute
Attribute with an associated named action.-
Nested classes/interfaces inherited from class ptolemy.actor.lib.jjs.JavaScript
JavaScript.AccessorProxy, JavaScript.DeferredSend, JavaScript.PortOrParameterProxy
-
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description JSAccessor.ActionableAttribute
accessorSource
The source of the accessor (a URL).SharedParameter
checkoutOrUpdateAccessorsRepository
If true, then check out the accessors git repository when the accessor is reloaded and run ant to build the PtDoc files.-
Fields inherited from class ptolemy.actor.lib.jjs.JavaScript
_EMPTY_ARGS, _engine, _executing, _exports, _INITIAL_SCRIPT, _instance, _JAVASCRIPT_KEYWORDS, _KEYWORDS, _restricted, _running, error, script
-
Fields inherited from class ptolemy.actor.gui.AbstractPlaceableActor
_frame, _paneSize, _windowClosingAdapter, _windowProperties
-
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 JSAccessor(CompositeEntity container, java.lang.String name)
Construct an accessor with the given container and name.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description protected java.lang.String
_accessorClass()
Return the name of the accessor class.protected static java.net.URL
_sourceToURL(java.lang.String urlSpec, boolean updateRepository)
For the given URL specification, attempt to find a local copy of the resource and return that if it exists.static java.lang.String
accessorToMoML(java.lang.String urlSpec)
Generate MoML for an Accessor.static java.lang.String
accessorToMoML(java.lang.String urlSpec, boolean obeyCheckoutOrUpdateRepositoryParameter)
Generate MoML for an Accessor.void
attributeChanged(Attribute attribute)
React to a change in an attribute, and if the attribute is the script parameter, FIXME.java.lang.Object
clone(Workspace workspace)
Clone the actor into the specified workspace.static java.lang.String
createSymbolicLinks()
Create symbolic links for the modules.static boolean
getAccessorNetworkAccessAllowed()
Return true if the PT_NO_NET environment variable is set.static void
getAccessorsRepository()
Check out or update the accessor repository, unless the checkoutOrUpdateAccessorsRepository parameter is false, in which case, do nothing.static java.net.URL
getLocalURL(java.lang.String urlSpec, java.net.URL accessorOrPtDocURL)
If the URL can be found locally, return it, otherwise return the value of the passed in URL.static void
handleAccessorMoMLChangeRequest(java.lang.Object originator, java.lang.String urlSpec, NamedObj context, java.lang.String changeRequest, double x, double y)
Handle an accessor-specific MoMLChangeRequest.static java.lang.String
nodeBinary()
Return the node binary that is in the path or, if node is not found in the path, return the node binary in $PTII/vendors/node.static java.lang.String
npmBinary()
Return the npm binary that is in the path or, if npm is not found in the path, return the npm binary in $PTII/vendors/node.void
reload()
Reload an accessor.void
reload(boolean obeyCheckoutOrUpdateRepositoryParameter)
Reload an accessor.static boolean
reloadAllAccessors(CompositeEntity composite)
Reload all the JSAccessors in a CompositeEntity.static boolean
reloadAllAccessors(CompositeEntity composite, boolean promptForOverrideOfLocalModifications)
Reload all the JSAccessors in a CompositeEntity.-
Methods inherited from class ptolemy.actor.lib.jjs.JavaScript
_addPort, _checkValidity, _defaultTypeConstraints, _invokeMethodInContext, _setPortDescription, author, clearInterval, clearTimeout, createEngine, currentTime, declareDelayDependency, declareIndependence, description, description, error, error, escapeForJavaScript, fire, getEngine, getFileFromClasspathAsString, getPortOrParameterProxy, getResource, getTopLevelAccessors, initialize, input, input, invokeCallback, isExecuting, isJavaScriptKeyword, isRestricted, isValidIdentifier, localHostAddress, log, output, output, parameter, parameter, place, preinitialize, readFromInputStream, setInterval, setTimeout, stopEnclosingModel, toJSArray, version, wrapup
-
Methods inherited from class ptolemy.actor.gui.AbstractPlaceableActor
_exportMoMLContents, cleanUp, setFrame
-
Methods inherited from class ptolemy.actor.TypedAtomicActor
_containedTypeConstraints, _customTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
-
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, _declareDelayDependency, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, 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, _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
isFireFunctional, isStrict, iterate, postfire, prefire, stop, stopFire, terminate
-
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, removeInitializable
-
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
-
-
-
-
Field Detail
-
accessorSource
public JSAccessor.ActionableAttribute accessorSource
The source of the accessor (a URL).
-
checkoutOrUpdateAccessorsRepository
public SharedParameter checkoutOrUpdateAccessorsRepository
If true, then check out the accessors git repository when the accessor is reloaded and run ant to build the PtDoc files. This repository is not currently publically readable. This parameter is a boolean, and the initial default value is true. This parameter is a shared parameter, meaning that changing it for any one instance in a model will change it for all instances in the model.
-
-
Constructor Detail
-
JSAccessor
public JSAccessor(CompositeEntity container, java.lang.String name) throws NameDuplicationException, IllegalActionException
Construct an accessor with the given container and name.- Parameters:
container
- The container.name
- The name of this accessor.- 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
-
accessorToMoML
public static java.lang.String accessorToMoML(java.lang.String urlSpec) throws java.io.IOException, javax.xml.transform.TransformerConfigurationException, IllegalActionException
Generate MoML for an Accessor.The MoML is wrapped in <entity></entity> and suitable for handleAccessorMoMLChangeRequest().
The accessor is read in from a url, processed with XSLT and MoML is returned.
In this method, the value of the checkoutOrUpdateRepository parameter is honored.
- Parameters:
urlSpec
- The URL of the accessor.- Returns:
- MoML of the accessor, which is typically passed to handleAccessorMoMLChangeRequest().
- Throws:
java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.IllegalActionException
- If no source file is specified.
-
accessorToMoML
public static java.lang.String accessorToMoML(java.lang.String urlSpec, boolean obeyCheckoutOrUpdateRepositoryParameter) throws IllegalActionException, java.io.IOException, javax.xml.transform.TransformerConfigurationException
Generate MoML for an Accessor.The MoML is wrapped in <entity></entity> and suitable for handleAccessorMoMLChangeRequest().
The accessor is read in from a url, processed with XSLT and MoML is returned.
- Parameters:
urlSpec
- The URL of the accessor.obeyCheckoutOrUpdateRepositoryParameter
- If true, then use the value of the checkoutOrUpdateRepository parameter. If false, then override the value of the checkoutOrUpdateRepository parameter and do not checkout or update the repository or invoke JSDoc. During testing, this parameter is set to false after the first reload of an accessor so as to improve the performance of the tests.- Returns:
- MoML of the accessor, which is typically passed to handleAccessorMoMLChangeRequest().
- Throws:
java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.IllegalActionException
- If no source file is specified.
-
attributeChanged
public void attributeChanged(Attribute attribute) throws IllegalActionException
React to a change in an attribute, and if the attribute is the script parameter, FIXME.- Overrides:
attributeChanged
in classJavaScript
- Parameters:
attribute
- The attribute that changed.- Throws:
IllegalActionException
- If evaluating the script fails.
-
clone
public java.lang.Object clone(Workspace workspace) throws java.lang.CloneNotSupportedException
Clone the actor into the specified workspace.- Overrides:
clone
in classJavaScript
- Parameters:
workspace
- The workspace for the new object.- Returns:
- A new actor.
- Throws:
java.lang.CloneNotSupportedException
- If a derived class contains an attribute that cannot be cloned.- See Also:
Object.clone()
-
createSymbolicLinks
public static java.lang.String createSymbolicLinks() throws java.io.IOException
Create symbolic links for the modules.- Returns:
- messages about creating the links.
- Throws:
java.io.IOException
- If there is a problem creating a link.
-
getAccessorsRepository
public static void getAccessorsRepository() throws java.io.IOException
Check out or update the accessor repository, unless the checkoutOrUpdateAccessorsRepository parameter is false, in which case, do nothing. If the upate succeeds, and the response from the git server does not include "At revision ", then also run ant in the accessors/web directory to update the documentation. If the checkout or update fails once, the it will not be tried again until the JVM is restarted.- Throws:
java.io.IOException
- If the repository cannot be checked out.
-
getLocalURL
public static java.net.URL getLocalURL(java.lang.String urlSpec, java.net.URL accessorOrPtDocURL) throws java.io.IOException, java.net.MalformedURLException
If the URL can be found locally, return it, otherwise return the value of the passed in URL.- Parameters:
urlSpec
- The String URL of the accessor or *PtDoc.xml file.accessorOrPtDocURL
- The proposed URL of the accessor or *PtDoc.xml file.- Returns:
- If the urlSpec matches https*://(www\.)*icyphy.org/accessors and the corresponding file can be found in the directory returned by _accessorDirectory(), then return a URL that refers to the local file. Otherwise, return the value of the accessorOrPtDocURL argument.
- Throws:
java.io.IOException
- If thrown while getting the accessor directory.java.net.MalformedURLException
- if throw while creating a URL.
-
handleAccessorMoMLChangeRequest
public static void handleAccessorMoMLChangeRequest(java.lang.Object originator, java.lang.String urlSpec, NamedObj context, java.lang.String changeRequest, double x, double y)
Handle an accessor-specific MoMLChangeRequest. In the postParse() phase, the _location and accessorSource attributes are updated.- Parameters:
originator
- The originator of the change request.urlSpec
- The URL string specification.context
- The context in which the actor is created.changeRequest
- The text of the change request, typically generated byaccessorToMoML(String)
.x
- The x-axis value of the actor to be created.y
- The y-axis value of the actor to be created.
-
nodeBinary
public static java.lang.String nodeBinary() throws java.io.IOException
Return the node binary that is in the path or, if node is not found in the path, return the node binary in $PTII/vendors/node.- Returns:
- The node binary or "node".
- Throws:
java.io.IOException
- If there is a problem finding the node binary.
-
npmBinary
public static java.lang.String npmBinary() throws java.io.IOException
Return the npm binary that is in the path or, if npm is not found in the path, return the npm binary in $PTII/vendors/node.- Returns:
- The npm binary or "npm".
- Throws:
java.io.IOException
- If there is a problem finding the npm binary.
-
reload
public void reload() throws IllegalActionException, java.io.IOException, javax.xml.transform.TransformerConfigurationException
Reload an accessor. The repository containing the accessors is checked out or updated and JSDoc is run on the documentation.- Throws:
IllegalActionException
- If no source file is specified.java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.
-
reload
public void reload(boolean obeyCheckoutOrUpdateRepositoryParameter) throws IllegalActionException, java.io.IOException, javax.xml.transform.TransformerConfigurationException
Reload an accessor.- Parameters:
obeyCheckoutOrUpdateRepositoryParameter
- If true, then use the value of the checkoutOrUpdateRepository parameter. If false, then override the value of the checkoutOrUpdateRepository parameter and do not checkout or update the repository or invoke JSDoc. During testing, this parameter is set to false after the first reload of an accessor so as to improve the performance of the tests.- Throws:
IllegalActionException
- If no source file is specified.java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.
-
reloadAllAccessors
public static boolean reloadAllAccessors(CompositeEntity composite) throws IllegalActionException, java.io.IOException, javax.xml.transform.TransformerConfigurationException
Reload all the JSAccessors in a CompositeEntity. The first time this method is invoked, the accessors repository will be checked out or updated and JSDoc invoked. The second and subsequent times the method is invoked, the checkout or update and JSDoc invocation will not occur. This is done so as to make testing faster. If the script of a JSAccessor has local modifications, then the user is asked if they want to override them.- Parameters:
composite
- The composite that contains the JSAccessors- Returns:
- true if the model contained any JSAccessors.
- Throws:
IllegalActionException
- If no source file is specified.java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.
-
reloadAllAccessors
public static boolean reloadAllAccessors(CompositeEntity composite, boolean promptForOverrideOfLocalModifications) throws IllegalActionException, java.io.IOException, javax.xml.transform.TransformerConfigurationException
Reload all the JSAccessors in a CompositeEntity. The first time this method is invoked, the accessors repository will be checked out or updated and JSDoc invoked. The second and subsequent times the method is invoked, the checkout or update and JSDoc invocation will not occur. This is done so as to make testing faster.- Parameters:
composite
- The composite that contains the JSAccessorspromptForOverrideOfLocalModifications
- If true, then prompt the user and ask if they want to override local modifications If false, then accessors with local modifications are not reloaded.- Returns:
- true if the model contained any JSAccessors.
- Throws:
IllegalActionException
- If no source file is specified.java.io.IOException
- If the urlSpec cannot be converted, opened read, parsed or closed.javax.xml.transform.TransformerConfigurationException
- If a factory cannot be created from the xslt file.
-
_accessorClass
protected java.lang.String _accessorClass()
Return the name of the accessor class. In this base class, it returns the value of the accessorSource parameter. If the accessorSource parameter does not yet exist, then this returns "Unknown".- Overrides:
_accessorClass
in classJavaScript
- Returns:
- The value of the accessorSource parameter.
-
_sourceToURL
protected static java.net.URL _sourceToURL(java.lang.String urlSpec, boolean updateRepository) throws IllegalActionException, java.io.IOException, java.net.MalformedURLException
For the given URL specification, attempt to find a local copy of the resource and return that if it exists. Otherwise, return the URL specified. If updateRepository is true, or if an exception occurs accessing the local copy, then attempt to update the accessor repository on the local file system. Do this only once in this instance of the JVM, as it is quite costly, unless the last update was more than 12 hours ago.- Parameters:
urlSpec
- The URL specification.updateRepository
- True to update the repository before attempting to find the local file.- Returns:
- The local version of the URL, or the URL given by the specification if the local version cannot be found.
- Throws:
IllegalActionException
- If no urlSpec is given.java.io.IOException
- If the URL cannot be found.java.net.MalformedURLException
- If the URL specification is malformed.
-
getAccessorNetworkAccessAllowed
public static boolean getAccessorNetworkAccessAllowed()
Return true if the PT_NO_NET environment variable is set.
-
-