Package ptolemy.moml

Class 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.

    If the group name is "doNotOverwriteOverrides", then parameter values will be set only if either the parameter did not previously exist or it has not been overridden. This is a rather specialized attribute used to update a component or model without losing previously set parameter values.

    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$
    Author:
    Edward A. Lee, Steve Neuendorffer, John Reekie, Contributor: Christopher Brooks, Erwin de Ley.
    See Also:
    MoMLChangeRequest
    Pt.AcceptedRating:
    Red (johnr)
    Pt.ProposedRating:
    Red (eal)
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.util.List<java.lang.String> 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

      Constructors 
      Constructor Description
      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.
      MoMLParser​(Workspace workspace, VersionSpecification defaultVersionSpecification, java.lang.ClassLoader loader)
      Construct a parser that creates entities in the specified workspace with a default verisoin specification.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      protected java.lang.String _currentExternalEntity()
      Get the the URI for the current external entity.
      static void addMoMLFilter​(MoMLFilter filter)
      Add a MoMLFilter to the end of the list of MoMLFilters used to translate names.
      static void addMoMLFilter​(MoMLFilter filter, Workspace workspace)
      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.
      static void addMoMLFilters​(java.util.List filterList, Workspace workspace)
      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 or create 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 ClassLoadingStrategy getDefaultClassLoadingStrategy()
      Get the the current static _defaultClassLoadingStrategy instance.
      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 setDefaultClassLoadingStrategy​(ClassLoadingStrategy classLoadingStrategy)
      Set the static default class loading strategy that will be used by all instances of this class.
      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.
      static void setMoMLFilters​(java.util.List filterList, Workspace workspace)
      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 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. CHANGE from Triquetrum : add version attributes for director, entity & property
      • 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<java.lang.String> 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 encountered in an input statement.
    • 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.
      • MoMLParser

        public MoMLParser​(Workspace workspace,
                          VersionSpecification defaultVersionSpecification,
                          java.lang.ClassLoader loader)
        Construct a parser that creates entities in the specified workspace with a default verisoin specification. 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.
        defaultVersionSpecification - The default version specification
        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,
                                         Workspace workspace)
        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.

        To avoid leaking memory, if addMoMLFilter(), addMoMLFilters() or setMoMLFilters() is called, then call setMoMLFilters(null).

        To avoid leaking memory, it is best if the MoMLParser is created in a separate Workspace:

          Workspace workspace = new Workspace("MyWorkspace");
          MoMLParser parser = new MoMLParser(workspace);
          MoMLFilter myFilter = new ptolemy.moml.filter.ClassChanges();
          MoMLParser.addMoMLFilter(myfilter, workspace);
          
        Parameters:
        filter - The MoMLFilter to add to the list of MoMLFilters.
        workspace - MoMLFilters are passed a MoMLParser that is optionally used by a filter. This parameter determines the Workspace in which that MoMLFilter is created. To avoid memory leaks, typically the MoMLFilter that is used to parse a model is created in a new workspace. The MoMLFilters are static, so we need to pass in the Workspace from the top level MoMLFilter.
        See Also:
        addMoMLFilter(MoMLFilter filter), addMoMLFilters(List filterList), addMoMLFilters(List filterList, Workspace workspace), getMoMLFilters(), setMoMLFilters(List filterList), setMoMLFilters(List filterList, Workspace workspace)
      • addMoMLFilters

        public static void addMoMLFilters​(java.util.List filterList,
                                          Workspace workspace)
        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.

        To avoid leaking memory, if addMoMLFilter(), addMoMLFilters() or setMoMLFilters() is called, then call setMoMLFilters(null).

        To avoid leaking memory, it is best if the MoMLParser is created in a separate Workspace:

          Workspace workspace = new Workspace("MyWorkspace");
          MoMLParser parser = new MoMLParser(workspace);
          List myFiltersList = ...
          MoMLParser.addMoMLFilters(myFilterList, workspace);
          
        Parameters:
        filterList - The list of MoMLFilters to add to the list of MoMLFilters to be used to translate names.
        workspace - MoMLFilters are passed a MoMLParser that is optionally used by a filter. This parameter determines the Workspace in which that MoMLFilter is created. To avoid memory leaks, typically the MoMLFilter that is used to parse a model is created in a new workspace. The MoMLFilters are static, so we need to pass in the Workspace from the top level MoMLFilter.
        See Also:
        addMoMLFilter(MoMLFilter filter), addMoMLFilter(MoMLFilter filter, Workspace workspace), addMoMLFilters(List filterList), getMoMLFilters(), setMoMLFilters(List filterList), setMoMLFilters(List filterList, Workspace workspace)
      • 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 or create the top objects list. The top objects list is a list of top-level objects that this parser has created. This method has the side effect of starting the parser recording creation of top-level objects.
        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 - Derived methods may throw exceptions.
        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)
      • 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)
      • 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

        @Deprecated
        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

        @Deprecated
        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()
      • 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. Note that the static MoMLFilters are not reset, but the MoMLParser optionally used by the filters is reset.
        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.
      • setDefaultClassLoadingStrategy

        public static void setDefaultClassLoadingStrategy​(ClassLoadingStrategy classLoadingStrategy)
        Set the static default class loading strategy that will be used by all instances of this class.
        Parameters:
        classLoadingStrategy - The class loading strategy.
        See Also:
        getDefaultClassLoadingStrategy()
      • 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.

        To avoid leaking memory, if addMoMLFilter(), addMoMLFilters() or setMoMLFilters() is called, then call setMoMLFilters(null).

        To avoid leaking memory, it is best if the MoMLParser is created in a separate Workspace and this method is not called, instead call setMoMLFilters(List, Workspace):

          Workspace workspace = new Workspace("MyWorkspace");
          MoMLParser parser = new MoMLParser(workspace);
          List myFilters = BackwardCompatibility.allFilters();
          MoMLParser.setMoMLFilters(myFilters, workspace);
          
        Parameters:
        filterList - The List of MoMLFilters.
        See Also:
        addMoMLFilter(MoMLFilter filter), addMoMLFilter(MoMLFilter filter, Workspace workspace), getMoMLFilters(), setMoMLFilters(List filterList, Workspace workspace)
      • setMoMLFilters

        public static void setMoMLFilters​(java.util.List filterList,
                                          Workspace workspace)
        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.

        To avoid leaking memory, if addMoMLFilter(), addMoMLFilters() or setMoMLFilters() is called, then call setMoMLFilters(null).

        To avoid leaking memory, it is best if the MoMLParser is created in a separate Workspace:

          Workspace workspace = new Workspace("MyWorkspace");
          MoMLParser parser = new MoMLParser(workspace);
          List myFilters = BackwardCompatibility.allFilters();
          MoMLParser.setMoMLFilters(myFilters, workspace);
          
        Parameters:
        filterList - The List of MoMLFilters.
        workspace - MoMLFilters are passed a MoMLParser that is optionally used by a filter. This parameter determines the Workspace in which that MoMLFilter is created. To avoid memory leaks, typically the MoMLFilter that is used to parse a model is created in a new workspace. The MoMLFilters are static, so we need to pass in the Workspace from the top level MoMLFilter.
        See Also:
        addMoMLFilter(MoMLFilter filter), addMoMLFilter(MoMLFilter filter, Workspace workspace), getMoMLFilters(), setMoMLFilters(List filterList)
      • 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)
      • 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.