ptolemy.moml
Class MoMLParser

java.lang.Object
  extended by com.microstar.xml.HandlerBase
      extended by ptolemy.moml.MoMLParser
All Implemented Interfaces:
XmlHandler, ChangeListener

public class MoMLParser
extends HandlerBase
implements ChangeListener

This class constructs Ptolemy II models from specifications in MoML (modeling markup language), which is based on XML. The class contains an instance of the Microstar Ælfred XML parser and implements callback methods to interpret the parsed XML. The way to use this class is to call its parse() method. The returned value is top-level composite entity of the model.

For convenience, there are several forms of the parse method. Most of these take two arguments, a base, and some specification of the MoML to parse (a stream or the text itself). The base is used to interpret relative URLs that might be present in the MoML. For example, the base might be the document base of an applet. An applet might use this class as follows:

 MoMLParser parser = new MoMLParser();
 URL docBase = getDocumentBase();
 URL xmlFile = new URL(docBase, modelURL);
 NamedObj toplevel = parser.parse(docBase, xmlFile);
 
If the first argument to parse() is null, then it is assumed that all URLs in the MoML file are absolute.

It can be difficult to create an appropriate URL to give as a base, particularly if what you have is a file or file name in the directory that you want to use as a base. The easiest technique is to use the toURL() method of the File class. Some of the URL constructors, for reasons we don't understand, create URLs that do not work.

The MoML code given to a parse() method may be a fragment, and does not need to include the "<?xml ... >" element nor the DOCTYPE specification. However, if the DOCTYPE specification is not given, then the DTD will not be read. The main consequence of this, given the parser we are using, is that default values for attributes will not be set. This could cause errors. The parser itself is not a validating parser, however, so it makes very limited use of the DTD. This may change in the future, so it is best to give the DOCTYPE element.

The parse() methods can be used for incremental parsing. After creating an initial model using a call to parse(), further MoML fragments without top-level entity or derived objects can be evaluated to modify the model. You can specify the context in which the MoML to be interpreted by calling setContext(). However, the XML parser limits each fragment to one element. So there always has to be one top-level element. If you wish to evaluate a group of MoML elements in some context, set the context and then place your MoML elements within a group element, as follows:

 <group>
 ... sequence of MoML elements ...
 </group>
 
The group element is ignored, and just serves to aggregate the MoML elements, unless it has a name attribute. If it has a name attribute, then the name becomes a prefix (separated by a colon) of all the names of items immediately in the group element. If the value of the name attribute is "auto", then the group is treated specially. Each item immediately contained by the group (i.e. not deeply contained) will be created with its specified name or a modified version of that name that does not match a pre-existing object already contained by the container. That is, when name="auto" is specified, each item is forced to be created with unique name, rather than possibly matching a pre-existing item.

The parse methods throw a variety of exceptions if the parsed data does not represent a valid MoML file or if the stream cannot be read for some reason.

This parser supports the way Ptolemy II handles hierarchical models, where components are instances cloned from reference models called "classes." A model (a composite entity) is a "class" in Ptolemy II if the elementName field of its MoMLInfo object is the string "class". If a component is cloned from a class, then when that component exports MoML, it references the class from which it was cloned and exports only differences from that class. I.e., if further changes are made to the component, it is important that when the component exports MoML, that those changes are represented in the exported MoML. This effectively implements an inheritance mechanism, where a component inherits all the features of the master from which it is cloned, but then extends the model with its own changes.

This class always processes MoML commands in the following order within a "class" or "entity" element, irrespective of the order in which they appear:

  1. Create properties, entities, ports and relations; and
  2. Create links.
Within each category, the order of actions depends on the order in which the commands appear in the MoML text.

This class works closely with MoMLChangeRequest to implement another feature of Ptolemy II hierarchy. In particular, if an entity is cloned from another that identifies itself as a "class", then any changes that are made to the class via a MoMLChangeRequest are also made to the clone. This parser ensures that those changes are not exported when MoML is exported by the clone, because they will be exported when the master exports MoML.

Since:
Ptolemy II 0.4
Version:
$Id: MoMLParser.java 59167 2010-09-21 17:08:02Z cxh $
Author:
Edward A. Lee, Steve Neuendorffer, John Reekie, Contributor: Christopher Hylands
See Also:
MoMLChangeRequest
Accepted Rating:
Red (johnr)
Proposed Rating:
Red (eal)

Nested Class Summary
private  class MoMLParser.DeleteRequest
           
private  class MoMLParser.LinkRequest
           
private  class MoMLParser.UnlinkRequest
           
 
Field Summary
private static java.util.Set _approvedRemoteXmlFiles
           
private  java.util.List _attributeNameList
           
private  java.util.Map _attributes
           
private static java.lang.String _AUTO_NAMESPACE
           
private  java.net.URL _base
           
private  java.lang.ClassLoader _classLoader
           
private  int _configureNesting
           
private  java.lang.String _configureSource
           
private  java.util.Stack _containers
           
private  NamedObj _current
           
private  java.lang.StringBuffer _currentCharData
           
private  java.lang.String _currentDocName
           
private static java.lang.String _DEFAULT_NAMESPACE
           
private static int _DELETE_ENTITY
           
private static int _DELETE_PORT
           
private static int _DELETE_PROPERTY
           
private static int _DELETE_RELATION
           
private  java.util.List _deleteRequests
           
private  java.util.Stack _deleteRequestStack
           
private  int _docNesting
           
private  java.util.Stack _externalEntities
           
private static java.util.List _filterList
           
private static ErrorHandler _handler
           
private static IconLoader _iconLoader
          IconLoader used to load icons.
private  java.util.Stack _ifElementStack
           
private static java.util.Map _imports
           
private  java.util.List _linkRequests
           
private  java.util.Stack _linkRequestStack
           
private static boolean _modified
           
private  java.lang.String _namespace
           
private  java.util.Stack _namespaces
           
private  boolean _namespacesPushed
           
private  java.util.Stack _namespaceTranslations
           
private  java.util.Map _namespaceTranslationTable
           
private  NamedObj _originalContext
           
private  java.util.Set _paramsToParse
           
private  boolean _previousDeferStatus
           
private  int _skipElement
           
private  boolean _skipElementIsNew
           
private  java.lang.String _skipElementName
           
private  boolean _skipRendition
           
private  NamedObj _toplevel
           
private  java.util.List _topObjectsCreated
           
private  UndoContext _undoContext
           
private  java.util.Stack _undoContexts
           
private static boolean _undoDebug
           
private  boolean _undoEnabled
           
private  java.util.List<UndoAction> _undoForOverrides
           
private  java.util.List _unrecognized
           
private  Workspace _workspace
           
private  java.net.URL _xmlFile
          The XML file being read, if any.
private  java.lang.String _xmlFileName
          The name of the XMLFile, which we cache for performance reasons.
private  XmlParser _xmlParser
          The XmlParser.
static java.util.List inputFileNamesToSkip
          List of Strings that name files to be skipped.
static java.lang.String MoML_DTD_1
          The standard MoML DTD, represented as a string.
static java.lang.String MoML_PUBLIC_ID_1
          The public ID for version 1 MoML.
 
Constructor Summary
MoMLParser()
          Construct a parser that creates a new workspace into which to put the entities created by the parse() method.
MoMLParser(Workspace workspace)
          Construct a parser that creates entities in the specified workspace.
MoMLParser(Workspace workspace, java.lang.ClassLoader loader)
          Construct a parser that creates entities in the specified workspace.
 
Method Summary
private  void _addParamsToParamsToParse(NamedObj object)
          Add all (deeply) contained instances of Settable to the _paramsToParse list, which will ensure that they get validated.
private  ComponentEntity _attemptToFindMoMLClass(java.lang.String className, java.lang.String source)
          Attempt to find a MoML class from an external file.
private  void _checkClass(java.lang.Object object, java.lang.Class correctClass, java.lang.String msg)
           
private  void _checkForNull(java.lang.Object object, java.lang.String message)
           
private  NamedObj _createEntity(java.lang.String className, java.lang.String entityName, java.lang.String source, boolean isClass)
          Create a new entity from the specified class name, give it the specified entity name, and specify that its container is the current container object.
private  NamedObj _createInstance(java.lang.Class newClass, java.lang.Object[] arguments)
          Create an instance of the specified class name by finding a constructor that matches the specified arguments.
protected  java.lang.String _currentExternalEntity()
          Get the the URI for the current external entity.
private  NamedObj _deleteEntity(java.lang.String entityName)
          Delete the entity after verifying that it is contained (deeply) by the current environment.
private  Port _deletePort(java.lang.String portName, java.lang.String entityName)
          Delete the port after verifying that it is contained (deeply) by the current environment.
private  Attribute _deleteProperty(java.lang.String attributeName)
          Delete an attribute after verifying that it is contained (deeply) by the current environment.
private  Relation _deleteRelation(java.lang.String relationName)
          Delete the relation after verifying that it is contained (deeply) by the current environment.
private  NamedObj _findOrParse(MoMLParser parser, java.net.URL base, java.lang.String file, java.lang.String className, java.lang.String source)
          Use the specified parser to parse the file or URL, which contains MoML, using the specified base to find the URL.
private  int _getColumnNumber()
          Return the column number from the XmlParser.
private  java.lang.String _getCurrentElement(java.lang.String elementName)
           
private  int _getLineNumber()
          Return the line number from the XmlParser.
private  ComponentPort _getPort(java.lang.String portspec, CompositeEntity context)
          Return the port corresponding to the specified port name in the specified composite entity.
private  java.lang.String _getUndoForDeleteAttribute(Attribute toDelete)
          Return the MoML commands to undo deleting the specified attribute from the current context.
private  java.lang.String _getUndoForDeleteEntity(ComponentEntity toDelete)
          Return the MoML commands to undo deleting the specified entity from the current context.
private  java.lang.String _getUndoForDeletePort(Port toDelete)
          Return the MoML commands to undo deleting the specified port from the current context.
private  java.lang.String _getUndoForDeleteRelation(ComponentRelation toDelete)
          Return the MoML commands to undo deleting the specified relation from the current context.
private  void _handlePropertyElement(java.lang.String className, java.lang.String propertyName, java.lang.String value)
          Create a property and/or set its value.
private  boolean _isLinkInClass(NamedObj context, Port port, Relation relation)
          Return true if the link between the specified port and relation is part of the class definition.
private  boolean _isLinkInClass(NamedObj context, Relation relation1, Relation relation2)
          Return true if the link between the specified relations is part of the class definition.
private  boolean _isUndoableElement(java.lang.String elementName)
          Return whether or not the given element name is undoable.
private  boolean _loadFileInContext(java.lang.String fileName, NamedObj context)
          If the file with the specified name exists, parse it in the context of the specified instance.
private  boolean _loadIconForClass(java.lang.String className, NamedObj context)
          Look for a MoML file associated with the specified class name, and if it exists, parse it in the context of the specified instance.
private  void _markContentsDerived(NamedObj object, int depth)
          Mark the contents as being derived objects at a depth one greater than the depth argument, and then recursively mark their contents derived.
private  void _markParametersToParse(NamedObj object)
          Mark deeply contained parameters as needing validation.
private  NamedObj _parse(MoMLParser parser, java.net.URL base, java.lang.String source)
          Use the specified parser to parse the file or URL, which contains MoML, using the specified base to find the URL.
private  void _processLink(java.lang.String relation1Name, java.lang.String relation2Name)
          Process a link command between two relations.
private  void _processLink(java.lang.String portName, java.lang.String relationName, java.lang.String insertAtSpec, java.lang.String insertInsideAtSpec)
          Process a link command between a port and a relation.
private  void _processPendingRequests()
          Process pending link and delete requests, if any.
private  void _processUnlink(java.lang.String relation1Name, java.lang.String relation2Name)
          Process an unlink request between two relations.
private  void _processUnlink(java.lang.String portName, java.lang.String relationName, java.lang.String indexSpec, java.lang.String insideIndexSpec)
          Process an unlink request between a port and relation.
private  void _pushContext()
          Push the current context.
private  void _resetUndo()
          Reset the undo information to give a fresh setup for the next incremental change.
private  Attribute _searchForAttribute(java.lang.String name)
          Given a name that is either absolute (with a leading period) or relative to _current, find an attribute with that name.
private  ComponentEntity _searchForClassInContext(java.lang.String name, java.lang.String source)
          Search for a class definition in the current context or anywhere above it in the hierarchy.
private  ComponentEntity _searchForEntity(java.lang.String name, NamedObj context)
          Given a name that is either absolute (with a leading period) or relative to the specified context, find a component entity with that name.
private  Port _searchForPort(java.lang.String name)
          Given a name that is either absolute (with a leading period) or relative to _current, find a port with that name.
private  ComponentRelation _searchForRelation(java.lang.String name)
          Given a name that is either absolute (with a leading period) or relative to _current, find a relation with that name.
private  void _setXmlFile(java.net.URL xmlFile)
          Store the value of the file being read.
static void addMoMLFilter(MoMLFilter filter)
          Add a MoMLFilter to the end of the list of MoMLFilters used to translate names.
static void addMoMLFilters(java.util.List filterList)
          Add a List of MoMLFilters to the end of the list of MoMLFilters used to translate names.
 void attribute(java.lang.String name, java.lang.String value, boolean specified)
          Handle an attribute assignment that is part of an XML element.
 void changeExecuted(ChangeRequest change)
          React to a change request has been successfully executed.
 void changeFailed(ChangeRequest change, java.lang.Exception exception)
          React to a change request has resulted in an exception.
 void charData(char[] chars, int offset, int length)
          Handle character data.
 void clearTopObjectsList()
          Clear the top objects list.
 void doctypeDecl(java.lang.String name, java.lang.String publicID, java.lang.String systemID)
          If a public ID is given, and is not that of MoML, then throw a CancelException, which causes the parse to abort and return null.
 void endDocument()
          End the document.
 void endElement(java.lang.String elementName)
          End an element.
 void endExternalEntity(java.lang.String systemID)
          Handle the end of an external entity.
 void error(java.lang.String message, java.lang.String systemID, int line, int column)
          Indicate a fatal XML parsing error.
 java.net.URL fileNameToURL(java.lang.String source, java.net.URL base)
          Given a file name or URL description, find a URL on which openStream() will work.
static ErrorHandler getErrorHandler()
          Get the error handler to handle parsing errors.
static IconLoader getIconLoader()
          Get the icon loader for all MoMLParsers.
static java.util.List getMoMLFilters()
          Get the List of MoMLFilters used to translate names.
 NamedObj getToplevel()
          Get the top-level entity associated with this parser, or null if none.
static boolean isModified()
          Return the value set by setModified(), or false if setModified() has yet not been called.
 NamedObj parse(java.lang.String text)
          Parse the given string, which contains MoML.
 NamedObj parse(java.net.URL base, java.io.InputStream input)
          Deprecated. Use parse(URL base, String systemID, InputStream input) for better error messages that include the name of the file being read.
 NamedObj parse(java.net.URL base, java.io.Reader reader)
          Deprecated. Use parse(URL base, String systemID, Reader reader) for better error messages that include the name of the file being read.
 NamedObj parse(java.net.URL base, java.lang.String text)
          Parse the given string, which contains MoML, using the specified base to evaluate relative references.
 NamedObj parse(java.net.URL base, java.lang.String systemID, java.io.InputStream input)
          Parse the given stream, using the specified url as the base to expand any external references within the MoML file.
 NamedObj parse(java.net.URL base, java.lang.String systemID, java.io.Reader reader)
          Parse the given stream, using the specified url as the base The reader is wrapped in a BufferedReader before being used.
 NamedObj parse(java.net.URL base, java.net.URL input)
          Parse the MoML file at the given URL, which may be a file on the local file system, using the specified base to expand any relative references within the MoML file.
 NamedObj parseFile(java.lang.String filename)
          Parse the file with the given name, which contains MoML.
 void processingInstruction(java.lang.String target, java.lang.String data)
          Handle a processing instruction.
static void purgeAllModelRecords()
          Purge all records of models opened.
static void purgeModelRecord(java.lang.String filename)
          Purge any record of a model opened from the specified file name.
static void purgeModelRecord(java.net.URL url)
          Purge any record of a model opened from the specified URL.
 void reset()
          Reset the MoML parser.
 void resetAll()
          Reset the MoML parser, forgetting about any previously parsed models.
 java.lang.Object resolveEntity(java.lang.String publicID, java.lang.String systemID)
          Resolve an external entity.
 ComponentEntity searchForClass(java.lang.String name, java.lang.String source)
          Given the name of a MoML class and a source URL, check to see whether this class has already been instantiated, and if so, return the previous instance.
 void setContext(NamedObj context)
          Set the context for parsing.
static void setErrorHandler(ErrorHandler handler)
          Set the error handler to handle parsing errors.
static void setIconLoader(IconLoader loader)
          Set the icon loader for all MoMLParsers.
static void setModified(boolean modified)
          Record whether the parsing of the moml modified the data.
static void setMoMLFilters(java.util.List filterList)
          Set the list of MoMLFilters used to translate names.
 void setToplevel(NamedObj toplevel)
          Set the top-level entity.
 void setUndoable(boolean undoable)
          Set the current context as undoable.
 void startDocument()
          Start a document.
 void startElement(java.lang.String elementName)
          Start an element.
 void startExternalEntity(java.lang.String systemID)
          Handle the start of an external entity.
 java.util.List topObjectsCreated()
          Get the top objects list.
 
Methods inherited from class com.microstar.xml.HandlerBase
ignorableWhitespace
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

MoML_DTD_1

public static java.lang.String MoML_DTD_1
The standard MoML DTD, represented as a string. This is used to parse MoML data when a compatible PUBLIC DTD is specified. NOTE: This DTD includes a number of elements that are deprecated. They are included here for backward compatibility. See the MoML chapter of the Ptolemy II design document for a view of the current (nondeprecated) DTD.


MoML_PUBLIC_ID_1

public static java.lang.String MoML_PUBLIC_ID_1
The public ID for version 1 MoML.


inputFileNamesToSkip

public static java.util.List inputFileNamesToSkip
List of Strings that name files to be skipped. This variable is used primarily for testing configurations. The value of this variable is a List of Strings, where each element names a file name that should _not_ be loaded if it is encounted in an input statement.


_approvedRemoteXmlFiles

private static java.util.Set _approvedRemoteXmlFiles

_attributes

private java.util.Map _attributes

_attributeNameList

private java.util.List _attributeNameList

_AUTO_NAMESPACE

private static java.lang.String _AUTO_NAMESPACE

_base

private java.net.URL _base

_classLoader

private java.lang.ClassLoader _classLoader

_configureNesting

private int _configureNesting

_configureSource

private java.lang.String _configureSource

_containers

private java.util.Stack _containers

_current

private NamedObj _current

_currentCharData

private java.lang.StringBuffer _currentCharData

_currentDocName

private java.lang.String _currentDocName

_DEFAULT_NAMESPACE

private static java.lang.String _DEFAULT_NAMESPACE

_DELETE_ENTITY

private static int _DELETE_ENTITY

_DELETE_PORT

private static int _DELETE_PORT

_DELETE_PROPERTY

private static int _DELETE_PROPERTY

_DELETE_RELATION

private static int _DELETE_RELATION

_deleteRequests

private java.util.List _deleteRequests

_deleteRequestStack

private java.util.Stack _deleteRequestStack

_docNesting

private int _docNesting

_externalEntities

private java.util.Stack _externalEntities

_handler

private static ErrorHandler _handler

_filterList

private static java.util.List _filterList

_iconLoader

private static IconLoader _iconLoader
IconLoader used to load icons.


_imports

private static java.util.Map _imports

_linkRequests

private java.util.List _linkRequests

_linkRequestStack

private java.util.Stack _linkRequestStack

_modified

private static boolean _modified

_namespace

private java.lang.String _namespace

_namespaces

private java.util.Stack _namespaces

_namespacesPushed

private boolean _namespacesPushed

_namespaceTranslationTable

private java.util.Map _namespaceTranslationTable

_namespaceTranslations

private java.util.Stack _namespaceTranslations

_originalContext

private NamedObj _originalContext

_paramsToParse

private java.util.Set _paramsToParse

_xmlParser

private XmlParser _xmlParser
The XmlParser.


_previousDeferStatus

private boolean _previousDeferStatus

_ifElementStack

private java.util.Stack _ifElementStack

_skipElement

private int _skipElement

_skipElementIsNew

private boolean _skipElementIsNew

_skipElementName

private java.lang.String _skipElementName

_skipRendition

private boolean _skipRendition

_toplevel

private NamedObj _toplevel

_topObjectsCreated

private java.util.List _topObjectsCreated

_undoContexts

private java.util.Stack _undoContexts

_undoContext

private UndoContext _undoContext

_undoDebug

private static boolean _undoDebug

_undoEnabled

private boolean _undoEnabled

_undoForOverrides

private java.util.List<UndoAction> _undoForOverrides

_unrecognized

private java.util.List _unrecognized

_workspace

private Workspace _workspace

_xmlFile

private java.net.URL _xmlFile
The XML file being read, if any. Do not set _xmlFile directly, instead call _setXmlFile().


_xmlFileName

private java.lang.String _xmlFileName
The name of the XMLFile, which we cache for performance reasons.

Constructor Detail

MoMLParser

public MoMLParser()
Construct a parser that creates a new workspace into which to put the entities created by the parse() method.


MoMLParser

public MoMLParser(Workspace workspace)
Construct a parser that creates entities in the specified workspace. If the argument is null, create a new workspace with an empty name. Classes will be created using the classloader that created this class.

Parameters:
workspace - The workspace into which to place entities.

MoMLParser

public MoMLParser(Workspace workspace,
                  java.lang.ClassLoader loader)
Construct a parser that creates entities in the specified workspace. If the workspace argument is null, then create a new workspace with an empty name. Classes will be created using the classloader that created this class.

Parameters:
workspace - The workspace into which to place entities.
loader - The class loader that will be used to create classes, or null if the the bootstrap class loader is to be used.
Method Detail

addMoMLFilter

public static void addMoMLFilter(MoMLFilter filter)
Add a MoMLFilter to the end of the list of MoMLFilters used to translate names. If the list of MoMLFilters already contains the filter, then the filter is not added again. Note that this method is static. The specified MoMLFilter will filter all MoML for any instances of this class.

Parameters:
filter - The MoMLFilter to add to the list of MoMLFilters.
See Also:
addMoMLFilters(List filterList), getMoMLFilters(), setMoMLFilters(List filterList)

addMoMLFilters

public static void addMoMLFilters(java.util.List filterList)
Add a List of MoMLFilters to the end of the list of MoMLFilters used to translate names. The argument list of filters is added even if the current list already contains some of the filters in the argument list. Note that this method is static. The specified MoMLFilter will filter all MoML for any instances of this class.

Parameters:
filterList - The list of MoMLFilters to add to the list of MoMLFilters to be used to translate names.
See Also:
addMoMLFilter(MoMLFilter filter), getMoMLFilters(), setMoMLFilters(List filterList)

attribute

public void attribute(java.lang.String name,
                      java.lang.String value,
                      boolean specified)
               throws XmlException
Handle an attribute assignment that is part of an XML element. This method is called prior to the corresponding startElement() call, so it simply accumulates attributes in a hashtable for use by startElement().

Specified by:
attribute in interface XmlHandler
Overrides:
attribute in class HandlerBase
Parameters:
name - The name of the attribute.
value - The value of the attribute, or null if the attribute is #IMPLIED and not specified.
specified - True if the value is specified, false if the value comes from the default value in the DTD rather than from the XML file.
Throws:
XmlException - If the name or value is null.
See Also:
XmlHandler.attribute(java.lang.String, java.lang.String, boolean)

changeExecuted

public void changeExecuted(ChangeRequest change)
React to a change request has been successfully executed. This method is called after a change request has been executed successfully. It does nothing.

Specified by:
changeExecuted in interface ChangeListener
Parameters:
change - The change that has been executed, or null if the change was not done via a ChangeRequest.

changeFailed

public void changeFailed(ChangeRequest change,
                         java.lang.Exception exception)
React to a change request has resulted in an exception. This method is called after a change request was executed, but during the execution an exception was thrown. Presumably the change was a propagation request. If there is a registered error handler, then the error is delegated to that handler. Otherwise, the error is reported to stderr.

Specified by:
changeFailed in interface ChangeListener
Parameters:
change - The change that was attempted or null if the change was not done via a ChangeRequest.
exception - The exception that resulted.

charData

public void charData(char[] chars,
                     int offset,
                     int length)
Handle character data. In this implementation, the character data is accumulated in a buffer until the end element. Character data appears only in doc and configure elements. Ælfred will call this method once for each chunk of character data found in the contents of elements. Note that the parser may break up a long sequence of characters into smaller chunks and call this method once for each chunk.

Specified by:
charData in interface XmlHandler
Overrides:
charData in class HandlerBase
Parameters:
chars - The character data.
offset - The starting position in the array.
length - The number of characters available.
See Also:
XmlHandler.charData(char[], int, int)

clearTopObjectsList

public void clearTopObjectsList()
Clear the top objects list. The top objects list is a list of top-level objects that this parser has created.

See Also:
topObjectsCreated()

doctypeDecl

public void doctypeDecl(java.lang.String name,
                        java.lang.String publicID,
                        java.lang.String systemID)
                 throws CancelException
If a public ID is given, and is not that of MoML, then throw a CancelException, which causes the parse to abort and return null. Note that the version number is not checked, so future versions of MoML should also work.

Specified by:
doctypeDecl in interface XmlHandler
Overrides:
doctypeDecl in class HandlerBase
Parameters:
name - The name of the document type.
publicID - The public ID of the document type.
systemID - The system ID of the document type.
Throws:
CancelException - If the public ID is not that of MoML.
See Also:
XmlHandler.doctypeDecl(java.lang.String, java.lang.String, java.lang.String)

endDocument

public void endDocument()
                 throws java.lang.Exception
End the document. The MoMLParser calls this method once, when it has finished parsing the complete XML document. It is guaranteed that this will be the last method called in the XML parsing process. As a consequence, it is guaranteed that all dependencies between parameters used in the XML description are resolved. This method executes any change requests that may have been made during the parsing process.

Specified by:
endDocument in interface XmlHandler
Overrides:
endDocument in class HandlerBase
Throws:
CancelException - If an error occurs parsing one of the parameter values, and the user clicks on "cancel" to cancel the parse.
java.lang.Exception - The handler may throw any exception.
See Also:
XmlHandler.endDocument()

endElement

public void endElement(java.lang.String elementName)
                throws java.lang.Exception
End an element. This method pops the current container from the stack, if appropriate, and also adds specialized properties to the container, such as _doc, if appropriate. Ælfred will call this method at the end of each element (including EMPTY elements).

Specified by:
endElement in interface XmlHandler
Overrides:
endElement in class HandlerBase
Parameters:
elementName - The element type name.
Throws:
java.lang.Exception - If thrown while adding properties.
See Also:
XmlHandler.endElement(java.lang.String)

endExternalEntity

public void endExternalEntity(java.lang.String systemID)
Handle the end of an external entity. This pops the stack so that error reporting correctly reports the external entity that causes the error.

Specified by:
endExternalEntity in interface XmlHandler
Overrides:
endExternalEntity in class HandlerBase
Parameters:
systemID - The URI for the external entity.
See Also:
XmlHandler.endExternalEntity(java.lang.String)

error

public void error(java.lang.String message,
                  java.lang.String systemID,
                  int line,
                  int column)
           throws XmlException
Indicate a fatal XML parsing error. Ælfred will call this method whenever it encounters a serious error. This method simply throws an XmlException.

Specified by:
error in interface XmlHandler
Overrides:
error in class HandlerBase
Parameters:
message - The error message.
systemID - The URI of the entity that caused the error.
line - The approximate line number of the error.
column - The approximate column number of the error.
Throws:
XmlException - If called.
See Also:
XmlHandler.error(java.lang.String, java.lang.String, int, int)

fileNameToURL

public java.net.URL fileNameToURL(java.lang.String source,
                                  java.net.URL base)
                           throws java.lang.Exception
Given a file name or URL description, find a URL on which openStream() will work. If a base is given, the URL can be found relative to that base. If the URL cannot be found relative to this base, then it is searched for relative to the current working directory (if this is permitted with the current security restrictions), and then relative to the classpath. If the URL is external and is not relative to a previously defined base, then the user will be warned about a security concern and given the opportunity to cancel.

NOTE: This may trigger a dialog with the user (about security concerns), and hence should be called in the event thread.

Parameters:
source - A file name or URL description.
base - The base URL for relative references, or null if there is none.
Returns:
A URL on which openStream() will succeed.
Throws:
java.lang.Exception - If the file or URL cannot be found or if the user cancels on being warned of a security concern.

getErrorHandler

public static ErrorHandler getErrorHandler()
Get the error handler to handle parsing errors. Note that this method is static. The returned error handler will handle all errors for any instance of this class.

Returns:
The ErrorHandler currently handling errors.
See Also:
setErrorHandler(ErrorHandler)

getIconLoader

public static IconLoader getIconLoader()
Get the icon loader for all MoMLParsers.

Returns:
The IconLoader for all MoMLParsers.
See Also:
setIconLoader(IconLoader)

getMoMLFilters

public static java.util.List getMoMLFilters()
Get the List of MoMLFilters used to translate names. Note that this method is static. The returned MoMLFilters will filter all MoML for any instances of this class.

Returns:
The MoMLFilters currently filtering.
See Also:
addMoMLFilter(MoMLFilter filter), setMoMLFilters(List filterList)

getToplevel

public NamedObj getToplevel()
Get the top-level entity associated with this parser, or null if none.

Returns:
The top-level associated with this parser.
See Also:
setToplevel(NamedObj)

isModified

public static boolean isModified()
Return the value set by setModified(), or false if setModified() has yet not been called.

Returns:
True if the data has been modified.
See Also:
setModified(boolean)

parse

public NamedObj parse(java.net.URL base,
                      java.net.URL input)
               throws java.lang.Exception
Parse the MoML file at the given URL, which may be a file on the local file system, using the specified base to expand any relative references within the MoML file. If the input URL has already been parsed, then return the model that was previously parsed. Note that this means that an application that opens and then closes a model and expects to re-parse the XML when re-opening must call purgeModelRecord() when closing it. This method uses parse(URL, InputStream).

Parameters:
base - The base URL for relative references, or null if not known.
input - The stream from which to read XML.
Returns:
The top-level composite entity of the Ptolemy II model, or null if the file is not recognized as a MoML file.
Throws:
java.lang.Exception - If the parser fails.
See Also:
purgeModelRecord(URL), purgeAllModelRecords()

parse

public NamedObj parse(java.net.URL base,
                      java.io.InputStream input)
               throws java.lang.Exception
Deprecated. Use parse(URL base, String systemID, InputStream input) for better error messages that include the name of the file being read.

Parse the given stream, using the specified url as the base to expand any external references within the MoML file. This method uses parse(URL, Reader). Note that this bypasses the mechanism of parse(URL, URL) that returns a previously parsed model. This method will always re-parse using data from the stream.

Parameters:
base - The base URL for relative references, or null if not known.
input - The stream from which to read XML.
Returns:
The top-level composite entity of the Ptolemy II model, or null if the file is not recognized as a MoML file.
Throws:
java.lang.Exception - If the parser fails.

parse

public NamedObj parse(java.net.URL base,
                      java.lang.String systemID,
                      java.io.InputStream input)
               throws java.lang.Exception
Parse the given stream, using the specified url as the base to expand any external references within the MoML file. This method uses parse(URL, Reader). Note that this bypasses the mechanism of parse(URL, URL) that returns a previously parsed model. This method will always re-parse using data from the stream.

Parameters:
base - The base URL for relative references, or null if not known.
systemID - The URI of the document.
input - The stream from which to read XML.
Returns:
The top-level composite entity of the Ptolemy II model, or null if the file is not recognized as a MoML file.
Throws:
java.lang.Exception - If the parser fails.

parse

public NamedObj parse(java.net.URL base,
                      java.io.Reader reader)
               throws java.lang.Exception
Deprecated. Use parse(URL base, String systemID, Reader reader) for better error messages that include the name of the file being read.

Parse the given stream, using the specified url as the base The reader is wrapped in a BufferedReader before being used. Note that this bypasses the mechanism of parse(URL, URL) that returns a previously parsed model. This method will always re-parse using data from the stream.

Parameters:
base - The base URL for relative references, or null if not known.
reader - The reader from which to read XML.
Returns:
The top-level composite entity of the Ptolemy II model, or null if the file is not recognized as a MoML file.
Throws:
java.lang.Exception - If the parser fails.

parse

public NamedObj parse(java.net.URL base,
                      java.lang.String systemID,
                      java.io.Reader reader)
               throws java.lang.Exception
Parse the given stream, using the specified url as the base The reader is wrapped in a BufferedReader before being used. Note that this bypasses the mechanism of parse(URL, URL) that returns a previously parsed model. This method will always re-parse using data from the stream.

Parameters:
base - The base URL for relative references, or null if not known.
systemID - The URI of the document.
reader - The reader from which to read XML.
Returns:
The top-level composite entity of the Ptolemy II model, or null if the file is not recognized as a MoML file.
Throws:
java.lang.Exception - If the parser fails.

parse

public NamedObj parse(java.lang.String text)
               throws java.lang.Exception
Parse the given string, which contains MoML. If there are external references in the MoML, they are interpreted relative to the current working directory. Note that this method attempts to read the user.dir system property, which is not generally available in applets. Hence it is probably not a good idea to use this method in applet code, since it will probably fail outright.

Parameters:
text - The string from which to read MoML.
Returns:
The top-level composite entity of the Ptolemy II model.
Throws:
java.lang.Exception - If the parser fails.
java.lang.SecurityException - If the user.dir system property is not available.

parse

public NamedObj parse(java.net.URL base,
                      java.lang.String text)
               throws java.lang.Exception
Parse the given string, which contains MoML, using the specified base to evaluate relative references. This method uses parse(URL, Reader).

Parameters:
base - The base URL for relative references, or null if not known.
text - The string from which to read MoML.
Returns:
The top-level composite entity of the Ptolemy II model.
Throws:
java.lang.Exception - If the parser fails.

parseFile

public NamedObj parseFile(java.lang.String filename)
                   throws java.lang.Exception
Parse the file with the given name, which contains MoML. If there are external references in the MoML, they are interpreted relative to the current working directory.

If you have an absolute pathname, rather than calling this method, you may want to try:

  CompositeActor toplevel = (CompositeActor) parser.parse(null,
           new File(xmlFilename).toURL());
  

Note that this method attempts to read the user.dir system property, which is not generally available in applets. Hence it is probably not a good idea to use this method in applet code, since it will probably fail outright.

If the file has already been parsed, then return the model that previously parsed. Note that this means that an application that opens and then closes a model and expects to re-parse the XML when re-opening should call purgeModelRecord() when closing it.

Parameters:
filename - The file name from which to read MoML.
Returns:
The top-level composite entity of the Ptolemy II model.
Throws:
java.lang.Exception - If the parser fails.
java.lang.SecurityException - If the user.dir system property is not available.
See Also:
purgeModelRecord(String), purgeAllModelRecords()

processingInstruction

public void processingInstruction(java.lang.String target,
                                  java.lang.String data)
Handle a processing instruction. Processing instructions are allowed in doc and configure elements, and are passed through unchanged. In the case of the doc element, they will be stored in the Documentation attribute. In the case of the configure element, they will be passed to the configure() method of the parent object.

Specified by:
processingInstruction in interface XmlHandler
Overrides:
processingInstruction in class HandlerBase
Parameters:
target - The name of the processing instruction.
data - The body of the processing instruction.
See Also:
XmlHandler.processingInstruction(java.lang.String, java.lang.String)

purgeAllModelRecords

public static void purgeAllModelRecords()
Purge all records of models opened. This is here for testing only.

See Also:
purgeModelRecord(URL), resetAll()

purgeModelRecord

public static void purgeModelRecord(java.net.URL url)
Purge any record of a model opened from the specified URL. The record will not be purged if the model is a class definition that has child instances. Note that you may also need to call reset() so that the _toplevel is reset on any parser.

Parameters:
url - The URL.
See Also:
parse(URL, URL), purgeAllModelRecords()

purgeModelRecord

public static void purgeModelRecord(java.lang.String filename)
                             throws java.net.MalformedURLException
Purge any record of a model opened from the specified file name.

Note that this method attempts to read the user.dir system property, which is not generally available in applets. Hence it is probably not a good idea to use this method in applet code, since it will probably fail outright.

Note that you may also need to call reset() so that the _toplevel is reset.

Parameters:
filename - The file name from which to read MoML.
Throws:
java.net.MalformedURLException - If the file name cannot be converted to a URL.
java.lang.SecurityException - If the user.dir system property is not available.
See Also:
parse(URL, String), purgeAllModelRecords()

reset

public void reset()
Reset the MoML parser. Note that this method does not purge records of the models that have been parsed. To completely reset the MoMLParser, see resetAll().

See Also:
resetAll(), purgeModelRecord(String), purgeAllModelRecords()

resetAll

public void resetAll()
Reset the MoML parser, forgetting about any previously parsed models. This method differs from reset() in that this method does as complete a reset of the MoMLParser as possible.

See Also:
purgeModelRecord(String), purgeAllModelRecords()

resolveEntity

public java.lang.Object resolveEntity(java.lang.String publicID,
                                      java.lang.String systemID)
Resolve an external entity. If the first argument is the name of the MoML PUBLIC DTD ("-//UC Berkeley//DTD MoML 1//EN"), then return a StringReader that will read the locally cached version of this DTD (the public variable MoML_DTD_1). Otherwise, return null, which has the effect of deferring to Ælfred for resolution of the URI. Derived classes may return a a modified URI (a string), an InputStream, or a Reader. In the latter two cases, the input character stream is provided.

Specified by:
resolveEntity in interface XmlHandler
Overrides:
resolveEntity in class HandlerBase
Parameters:
publicID - The public identifier, or null if none was supplied.
systemID - The system identifier.
Returns:
Null, indicating to use the default system identifier.
See Also:
XmlHandler.resolveEntity(java.lang.String, java.lang.String)

searchForClass

public ComponentEntity searchForClass(java.lang.String name,
                                      java.lang.String source)
                               throws java.lang.Exception
Given the name of a MoML class and a source URL, check to see whether this class has already been instantiated, and if so, return the previous instance. If the source is non-null, then this finds an instance that has been previously opened by this application from the same URL. If the source is null and the class name is absolute (starting with a period), then look for the class in the current top level. If the source is null and the class name is relative, then look for the class relative to the current context.

Parameters:
name - The name of the MoML class to search for.
source - The URL source
Returns:
If the class has already been instantiated, return the previous instance, otherwise return null.
Throws:
java.lang.Exception - If thrown while searching for the class

setContext

public void setContext(NamedObj context)
Set the context for parsing. This can be used to associate this parser with a pre-existing model, which can then be modified via incremental parsing. This calls reset() and sets the top-level entity to the top-level of the specified object.

Callers should be careful about calling this method and resetting the modified flag to false when parsing moml that has been modified by the backward compatibility filter. It is safer to do something like:

   boolean modified = isModified();
   MoMLParser newParser = new MoMLParser(...);
   newParser.setContext(context);
   setModified(modified);
  

Parameters:
context - The context for parsing.

setErrorHandler

public static void setErrorHandler(ErrorHandler handler)
Set the error handler to handle parsing errors. Note that this method is static. The specified error handler will handle all errors for any instance of this class.

Parameters:
handler - The ErrorHandler to call.
See Also:
getErrorHandler()

setIconLoader

public static void setIconLoader(IconLoader loader)
Set the icon loader for all MoMLParsers.

Parameters:
loader - The IconLoader for all MoMLParsers.
See Also:
getIconLoader()

setMoMLFilters

public static void setMoMLFilters(java.util.List filterList)
Set the list of MoMLFilters used to translate names. Note that this method is static. The specified MoMLFilters will filter all MoML for any instances of this class.

Parameters:
filterList - The List of MoMLFilters.
See Also:
addMoMLFilter(MoMLFilter filter), getMoMLFilters()

setModified

public static void setModified(boolean modified)
Record whether the parsing of the moml modified the data. If a MoMLFilter modifies the model by returning a different value, then the MoMLFilter should call this method with a true argument.

Parameters:
modified - True if the data was modified while parsing.
See Also:
isModified(), MoMLFilter

setToplevel

public void setToplevel(NamedObj toplevel)
Set the top-level entity. This can be used to associate this parser with a pre-existing model, which can then be modified via incremental parsing. This calls reset().

Parameters:
toplevel - The top-level to associate with this parser.
See Also:
getToplevel()

setUndoable

public void setUndoable(boolean undoable)
Set the current context as undoable. If set to true, the next MoML parsed will be able to be undone via a call to undo().

Parameters:
undoable - The new Undoable value
Since:
Ptolemy II 2.1

startDocument

public void startDocument()
Start a document. This method is called just before the parser attempts to read the first entity (the root of the document). It is guaranteed that this will be the first method called. In this implementation, this method resets some private variables, and if there is a top level model associated with this parser, sets it so that change requests are deferred rather than executed. The change requests will be executed as a batch in endDocument().

Specified by:
startDocument in interface XmlHandler
Overrides:
startDocument in class HandlerBase
See Also:
endDocument()

startElement

public void startElement(java.lang.String elementName)
                  throws XmlException
Start an element. This is called at the beginning of each XML element. By the time it is called, all of the attributes for the element will already have been reported using the attribute() method. Unrecognized elements are ignored.

Specified by:
startElement in interface XmlHandler
Overrides:
startElement in class HandlerBase
Parameters:
elementName - The element type name.
Throws:
XmlException - If the element produces an error in constructing the model.
See Also:
XmlHandler.startElement(java.lang.String)

startExternalEntity

public void startExternalEntity(java.lang.String systemID)
Handle the start of an external entity. This pushes the stack so that error reporting correctly reports the external entity that causes the error.

Specified by:
startExternalEntity in interface XmlHandler
Overrides:
startExternalEntity in class HandlerBase
Parameters:
systemID - The URI for the external entity.
See Also:
XmlHandler.startExternalEntity(java.lang.String)

topObjectsCreated

public java.util.List topObjectsCreated()
Get the top objects list. The top objects list is a list of top-level objects that this parser has created.

Returns:
The list of top objects created since clearTopObjectsList() was called, or null if it has not been called.
See Also:
clearTopObjectsList()

_currentExternalEntity

protected java.lang.String _currentExternalEntity()
Get the the URI for the current external entity.

Returns:
A string giving the URI of the external entity being read, or null if none.

_addParamsToParamsToParse

private void _addParamsToParamsToParse(NamedObj object)
Add all (deeply) contained instances of Settable to the _paramsToParse list, which will ensure that they get validated.

Parameters:
object - The object to be scanned for Settables.

_attemptToFindMoMLClass

private ComponentEntity _attemptToFindMoMLClass(java.lang.String className,
                                                java.lang.String source)
                                         throws java.lang.Exception
Attempt to find a MoML class from an external file. If there is no source defined, then search for the file relative to the classpath.

Parameters:
className - The class name.
source - The source as specified in the XML.
Returns:
The class definition.
Throws:
java.lang.Exception

_checkClass

private void _checkClass(java.lang.Object object,
                         java.lang.Class correctClass,
                         java.lang.String msg)
                  throws XmlException
Throws:
XmlException

_checkForNull

private void _checkForNull(java.lang.Object object,
                           java.lang.String message)
                    throws XmlException
Throws:
XmlException

_createEntity

private NamedObj _createEntity(java.lang.String className,
                               java.lang.String entityName,
                               java.lang.String source,
                               boolean isClass)
                        throws java.lang.Exception
Create a new entity from the specified class name, give it the specified entity name, and specify that its container is the current container object. If the current container already contains an entity with the specified name and class, then return that entity. If the class name matches a class that has been previously defined in the scope (or with an absolute name), then that class is instantiated. Otherwise, the class name is interpreted as a Java class name and we attempt to construct the entity. If instantiating a Java class doesn't work, then we look for a MoML file on the classpath that defines a class by this name. The file is assumed to be named "foo.xml", where "foo" is the name of the class. Moreover, the classname is assumed to have no periods (since a MoML name does not allow periods, this is reasonable). If _current is not an instance of CompositeEntity, then an XML exception is thrown. If an object is created and we are propagating, then that object is marked as a derived object. The third argument, if non-null, gives a URL to import to create a reference class from which to instantiate this entity.

Parameters:
className -
entityName -
source -
isClass - True to create a class definition, false to create an instance.
Returns:
The created NamedObj
Throws:
java.lang.Exception - If anything goes wrong.

_createInstance

private NamedObj _createInstance(java.lang.Class newClass,
                                 java.lang.Object[] arguments)
                          throws java.lang.Exception
Create an instance of the specified class name by finding a constructor that matches the specified arguments. The specified class must be NamedObj or derived, or a ClassCastException will be thrown. NOTE: This mechanism does not support instantiation of inner classes, since those take an additional argument (the first argument), which is the enclosing class. Static inner classes, however, work fine. This method marks the contents of what it creates as derived objects, since they are defined in the Java code of the constructor. If we are currently propagating, then it also marks the new instance itself as a derived object.

Parameters:
newClass - The class.
arguments - The constructor arguments.
Throws:
java.lang.Exception - If no matching constructor is found, or if invoking the constructor triggers an exception.

_deleteEntity

private NamedObj _deleteEntity(java.lang.String entityName)
                        throws java.lang.Exception
Delete the entity after verifying that it is contained (deeply) by the current environment. If no object is found, then do nothing and return null. This is because deletion of a class may result in deletion of other objects that make this particular delete call redundant.

Parameters:
entityName - The relative or absolute name of the entity to delete.
Returns:
The deleted object, or null if none was found.
Throws:
java.lang.Exception - If there is no such entity or if the entity is defined in the class definition.

_deletePort

private Port _deletePort(java.lang.String portName,
                         java.lang.String entityName)
                  throws java.lang.Exception
Delete the port after verifying that it is contained (deeply) by the current environment. If no object is found, then do nothing and return null. This is because deletion of a class may result in deletion of other objects that make this particular delete call redundant.

Parameters:
portName - The relative or absolute name of the port to delete.
entityName - Optional name of the entity that contains the port (or null to use the current context).
Returns:
The deleted object, or null if none is found.
Throws:
java.lang.Exception - If there is no such port or if the port is defined in the class definition.

_deleteProperty

private Attribute _deleteProperty(java.lang.String attributeName)
                           throws java.lang.Exception
Delete an attribute after verifying that it is contained (deeply) by the current environment. If no object is found, then do nothing and return null. This is because deletion of a class may result in deletion of other objects that make this particular delete call redundant.

Parameters:
attributeName - The relative or absolute name of the attribute to delete.
Returns:
The deleted object, or null if none is found.
Throws:
java.lang.Exception - If there is no such attribute or if the attribute is defined in the class definition.

_deleteRelation

private Relation _deleteRelation(java.lang.String relationName)
                          throws java.lang.Exception
Delete the relation after verifying that it is contained (deeply) by the current environment. If no object is found, then do nothing and return null. This is because deletion of a class may result in deletion of other objects that make this particular delete call redundant.

Parameters:
relationName - The relative or absolute name of the relation to delete.
Returns:
The deleted object, or null if none is found.
Throws:
java.lang.Exception - If there is no such relation or if the relation is defined in the class definition.

_findOrParse

private NamedObj _findOrParse(MoMLParser parser,
                              java.net.URL base,
                              java.lang.String file,
                              java.lang.String className,
                              java.lang.String source)
                       throws java.lang.Exception
Use the specified parser to parse the file or URL, which contains MoML, using the specified base to find the URL. If the URL has been previously parsed by this application, then return the instance that was the result of the previous parse. If the URL cannot be found relative to this base, then it is searched for relative to the current working directory (if this is permitted with the current security restrictions), and then relative to the classpath.

Parameters:
parser - The parser to use.
base - The base URL for relative references, or null if not known.
file - The file or URL from which to read MoML.
className - The class name to assign if the file is parsed anew.
source - The source file to assign if the file is parsed anew, or null to not assign one.
Returns:
The top-level composite entity of the Ptolemy II model.
Throws:
java.lang.Exception - If the parser fails.

_getColumnNumber

private int _getColumnNumber()
Return the column number from the XmlParser.

Returns:
the column number from the XmlParser. Return -1 if _xmlParser is null.

_getCurrentElement

private java.lang.String _getCurrentElement(java.lang.String elementName)

_getLineNumber

private int _getLineNumber()
Return the line number from the XmlParser.

Returns:
the line number from the XmlParser. Return -1 if _xmlParser is null.

_getPort

private ComponentPort _getPort(java.lang.String portspec,
                               CompositeEntity context)
                        throws XmlException
Return the port corresponding to the specified port name in the specified composite entity. If the port belongs directly to the composite entity, then the argument is a simple name. If the port belongs to a component entity, then the name is the entity name, a period, and the port name. Throw an exception if there is no such port. The returned value is never null.

Parameters:
portspec - The relative port name.
context - The context in which to look for the port.
Returns:
The port.
Throws:
XmlException - If no such port is found.

_getUndoForDeleteAttribute

private java.lang.String _getUndoForDeleteAttribute(Attribute toDelete)
                                             throws java.io.IOException
Return the MoML commands to undo deleting the specified attribute from the current context.

Parameters:
toDelete - The component to delete.
Throws:
java.io.IOException

_getUndoForDeleteEntity

private java.lang.String _getUndoForDeleteEntity(ComponentEntity toDelete)
                                          throws java.io.IOException
Return the MoML commands to undo deleting the specified entity from the current context. Unless the container implements the marker interface HandlesInternalLinks, this will generate undo MoML that takes care of re-creating any links that get broken as a result of deleting the specified entity. If both ends of the link are defined in the base class, however, then the link is not reported.

Parameters:
toDelete - The component to delete.
Throws:
java.io.IOException

_getUndoForDeletePort

private java.lang.String _getUndoForDeletePort(Port toDelete)
                                        throws java.io.IOException
Return the MoML commands to undo deleting the specified port from the current context. Unless the container implements the marker interface HandlesInternalLinks, this will generate undo MoML that takes care of re-creating any inside links that get broken as a result of deleting the specified port. Unless the container of the container implements HandlesInternalLinks, this will also generate undo to recreate the outside links.

Parameters:
toDelete - The component to delete.
Throws:
java.io.IOException

_getUndoForDeleteRelation

private java.lang.String _getUndoForDeleteRelation(ComponentRelation toDelete)
                                            throws java.io.IOException
Return the MoML commands to undo deleting the specified relation from the current context. Unless the container implements the marker interface HandlesInternalLinks, this will generate undo MoML that takes care of re-creating any links that get broken as a result of deleting the specified relation.

Parameters:
toDelete - The component to delete.
Throws:
java.io.IOException

_handlePropertyElement

private void _handlePropertyElement(java.lang.String className,
                                    java.lang.String propertyName,
                                    java.lang.String value)
                             throws java.lang.Exception
Create a property and/or set its value.

Parameters:
className - The class name field, if present.
propertyName - The property name field.
value - The value, if present.
Throws:
java.lang.Exception - If something goes wrong.

_isLinkInClass

private boolean _isLinkInClass(NamedObj context,
                               Port port,
                               Relation relation)
Return true if the link between the specified port and relation is part of the class definition. It is part of the class definition if either the port and the relation are at the same level of hierarchy and are both derived objects, or if the relation and the container of the port are both class elements. If the relation is null, then this return true if the port and its container are derived objects. NOTE: This is not perfect, since a link could have been created between these elements in a subclass.

Parameters:
context - The context containing the link.
port - The port.
relation - The relation.
Returns:
True if the link is part of the class definition.

_isLinkInClass

private boolean _isLinkInClass(NamedObj context,
                               Relation relation1,
                               Relation relation2)
Return true if the link between the specified relations is part of the class definition. It is part of the class definition if both are derived objects, and the container whose parent-child relationship makes them derived is the same container. NOTE: This is not perfect, since a link could have been created between these elements in a subclass.

Parameters:
context - The context containing the link.
relation1 - The first relation.
relation2 - The second relation.
Returns:
True if the link is part of the class definition.

_isUndoableElement

private boolean _isUndoableElement(java.lang.String elementName)
Return whether or not the given element name is undoable. NOTE: we need this method as the list of actions on namespaces and _current does not apply to elements such as "link"

Parameters:
elementName - Description of Parameter
Returns:
Description of the Returned Value
Since:
Ptolemy 2.1

_loadFileInContext

private boolean _loadFileInContext(java.lang.String fileName,
                                   NamedObj context)
                            throws java.lang.Exception
If the file with the specified name exists, parse it in the context of the specified instance. If it does not exist, do nothing. If the file creates new objects, then mark those objects as a class element with the same depth as the context.

Parameters:
fileName - The file name.
context - The context into which to load the file.
Returns:
True if a file was found.
Throws:
java.lang.Exception - If the file exists but cannot be read for some reason.

_loadIconForClass

private boolean _loadIconForClass(java.lang.String className,
                                  NamedObj context)
                           throws java.lang.Exception
Look for a MoML file associated with the specified class name, and if it exists, parse it in the context of the specified instance. If setIconLoader(IconLoader) has been called with a non-null argument, then invoke the IconLoader.loadIconForClass(String, NamedObj) method. If setIconLoader(IconLoader) has not been called, or was called with a null argument, then The file name is constructed from the class name by replacing periods with file separators ("/") and appending "Icon.xml". So, for example, for the class name "ptolemy.actor.lib.Ramp", if there is a file "ptolemy/actor/lib/RampIcon.xml" in the classpath then that file be read.

Parameters:
className - The class name.
context - The context into which to load the file.
Returns:
True if a file was found.
Throws:
java.lang.Exception - If the file exists but cannot be read for some reason or if there is some other problem loading the icon.
See Also:
setIconLoader(IconLoader), IconLoader

_markContentsDerived

private void _markContentsDerived(NamedObj object,
                                  int depth)
Mark the contents as being derived objects at a depth one greater than the depth argument, and then recursively mark their contents derived. This makes them not export MoML, and prohibits name and container changes. Normally, the argument is an Entity, but this method will accept any NamedObj. This method also adds all (deeply) contained instances of Settable to the _paramsToParse list, which ensures that they will be validated.

Parameters:
object - The instance that is defined by a class.
depth - The depth (normally 0).

_markParametersToParse

private void _markParametersToParse(NamedObj object)
Mark deeply contained parameters as needing validation. This method adds all (deeply) contained instances of Settable to the _paramsToParse list, which ensures that they will be validated.

Parameters:
object - The instance to mark.

_parse

private NamedObj _parse(MoMLParser parser,
                        java.net.URL base,
                        java.lang.String source)
                 throws java.lang.Exception
Use the specified parser to parse the file or URL, which contains MoML, using the specified base to find the URL. If the URL cannot be found relative to this base, then it is searched for relative to the current working directory (if this is permitted with the current security restrictions), and then relative to the classpath.

Parameters:
parser - The parser to use.
base - The base URL for relative references, or null if not known.
source - The URL from which to read MoML.
Returns:
The top-level composite entity of the Ptolemy II model.
Throws:
java.lang.Exception - If the parser fails.

_processLink

private void _processLink(java.lang.String relation1Name,
                          java.lang.String relation2Name)
                   throws XmlException,
                          IllegalActionException
Process a link command between two relations.

Parameters:
relation1Name - The first relation name.
relation2Name - The second relation name.
Throws:
XmlException
IllegalActionException

_processLink

private void _processLink(java.lang.String portName,
                          java.lang.String relationName,
                          java.lang.String insertAtSpec,
                          java.lang.String insertInsideAtSpec)
                   throws XmlException,
                          IllegalActionException
Process a link command between a port and a relation.

Parameters:
portName - The port name.
relationName - The relation name.
insertAtSpec - The place to insert.
insertInsideAtSpec - The place to insert inside.
Throws:
XmlException
IllegalActionException

_processPendingRequests

private void _processPendingRequests()
                              throws java.lang.Exception
Process pending link and delete requests, if any.

Throws:
java.lang.Exception - If something goes wrong.

_processUnlink

private void _processUnlink(java.lang.String relation1Name,
                            java.lang.String relation2Name)
                     throws XmlException,
                            IllegalActionException
Process an unlink request between two relations.

Parameters:
relation1Name - The first relation name.
relation2Name - The second relation name.
Throws:
XmlException - If something goes wrong.
IllegalActionException - If the link is part of a class definition.

_processUnlink

private void _processUnlink(java.lang.String portName,
                            java.lang.String relationName,
                            java.lang.String indexSpec,
                            java.lang.String insideIndexSpec)
                     throws XmlException,
                            IllegalActionException
Process an unlink request between a port and relation.

Parameters:
portName - The port name.
relationName - The relation name.
indexSpec - The index of the channel.
insideIndexSpec - The index of the inside channel.
Throws:
XmlException - If something goes wrong.
IllegalActionException - If the link is part of a class definition.

_pushContext

private void _pushContext()
Push the current context.


_resetUndo

private void _resetUndo()
Reset the undo information to give a fresh setup for the next incremental change. NOTE: this resets all the undo information except for the UndoStackAttribute which is associated with the model.


_searchForAttribute

private Attribute _searchForAttribute(java.lang.String name)
                               throws XmlException
Given a name that is either absolute (with a leading period) or relative to _current, find an attribute with that name. The attribute is required to be contained (deeply) by the current environment, or an XmlException will be thrown.

Parameters:
name - The name of the attribute, relative or absolute.
Returns:
The attribute.
Throws:
XmlException - If the attribute is not found.

_searchForClassInContext

private ComponentEntity _searchForClassInContext(java.lang.String name,
                                                 java.lang.String source)
                                          throws java.lang.Exception
Search for a class definition in the current context or anywhere above it in the hierarchy. If a instance of a MoML class with a matching name and source is found, then return it. Otherwise, return null.

Parameters:
name - The name of the class.
source - The source for the class.
Returns:
A class, if it exists.
Throws:
java.lang.Exception - If a source is specified and it cannot be opened.

_searchForEntity

private ComponentEntity _searchForEntity(java.lang.String name,
                                         NamedObj context)
                                  throws XmlException,
                                         IllegalActionException
Given a name that is either absolute (with a leading period) or relative to the specified context, find a component entity with that name. Return null if it is not found.

Parameters:
name - The name of the entity.
context - The context in which to search.
Returns:
An entity with the specified name, or null if none is found.
Throws:
XmlException - If the name refers to an entity in an innappropriate context or if the context is not an instance of CompositeEntity.
IllegalActionException - If the name is ambiguous in that more than one entity in workspace matches. This will only occur if the name is absolute and is not inside the current model.

_searchForPort

private Port _searchForPort(java.lang.String name)
                     throws XmlException
Given a name that is either absolute (with a leading period) or relative to _current, find a port with that name. The port is required to be contained (deeply) by the current environment, or an XmlException will be thrown.

Parameters:
name - The name of the port.
Returns:
The port.
Throws:
XmlException - If the port is not found.

_searchForRelation

private ComponentRelation _searchForRelation(java.lang.String name)
                                      throws XmlException
Given a name that is either absolute (with a leading period) or relative to _current, find a relation with that name. The relation is required to be contained (deeply) by the current environment, or an XmlException will be thrown.

Parameters:
name - The name of the relation.
Returns:
The relation.
Throws:
XmlException - If the relation is not found.

_setXmlFile

private void _setXmlFile(java.net.URL xmlFile)
Store the value of the file being read. We do this for performance reasons because URL.toString() is expensive. For large models, caching results in a 2x speed-up in opening time under Mac OS X.