Class FilePortParameter
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Cloneable
,Initializable
,HasTypeConstraints
,Typeable
,FileOrURLAccessor
,Changeable
,Debuggable
,DebugListener
,Derivable
,HierarchyListener
,ModelErrorHandler
,MoMLExportable
,Moveable
,Nameable
,Settable
,ValueListener
public class FilePortParameter extends PortParameter implements FileOrURLAccessor
This file parameter creates an associated port that can be used to update the current value of the parameter. The value of this parameter, accessed by getExpression(), is a string that names a file or URL, possibly containing references to variables defined in scope using the syntax $ID, ${ID} or $(ID). The value returned by getToken() is name of the file with such references resolved.If the model containing this port parameter has been saved to a MoML file, then the file name can be given relative to the directory containing that MoML file. If the model has not been saved to a file, then the classpath is used for identifying relative file names.
Files can be given relative to a base, where the base is the URI of the first container above this one that has a URIAttribute. Normally, this URI specifies the file or URL containing the model definition. Thus, files that are referred to here can be kept in the same directory as the model, or in a related directory, and can moved together with the model.
The following special file names are understood:
- System.in: Standard input.
- System.out: Standard output.
Variables that get substituted. String Description Property $CWD
The current working directory user.dir
$HOME
The user's home directory user.home
$PTII
The home directory of the Ptolemy II installation ptolemy.ptII.dir
$TMPDIR
The temporary directory java.io.tmpdir
$USERNAME
The user's account name user.name
If a file name begins with the reference "$CLASSPATH", then when the file is opened for reading, the openForReading() method will search for the file relative to the classpath (using the getResource() method of the current class loader). This will only work for a file that exists, and thus the openForWriting() method will not understand the "$CLASSPATH" string; this makes sense since the classpath typically has several directories, and it would not be obvious where to create the file. The asURL() method also recognizes the "$CLASSPATH" string, but not the asFile() method (which is typically used when accessing a file for writing). NOTE: If the container of this parameter also contains a variable named CLASSPATH, then the value of that variable is used instead of the Java classpath.
This parameter has two values, which may not be equal, a current value and a persistent value. The persistent value is returned by getExpression() and is set by any of three different mechanisms:
- calling setExpression();
- calling setToken(); and
- specifying a value as a constructor argument.
- calling setCurrentValue();
- calling update() sets the current value if there is an associated port, and that port has a token to consume; and
When using this parameter in an actor, care must be exercised to call update() exactly once per firing prior to calling getToken(). Each time update() is called, a new token will be consumed from the associated port (if the port is connected and has a token). If this is called multiple times in an iteration, it may result in consuming tokens that were intended for subsequent iterations. Thus, for example, update() should not be called in fire() and then again in postfire(). Moreover, in some domains (such as DE), it is essential that if a token is provided on a port, that it is consumed. In DE, the actor will be repeatedly fired until the token is consumed. Thus, it is an error to not call update() once per iteration. For an example of an actor that uses this mechanism, see Ramp.
If this actor is placed in a container that does not implement the TypedActor interface, then no associated port is created, and it functions as an ordinary file parameter. This is useful, for example, if this is put in a library, where one would not want the associated port to appear.
There are a few situations where FilePortParameter might not do what you expect:
- If it is used in a transparent composite actor, then a token provided
to a FilePortParameter will never be read. A transparent composite actor
is one without a director.
Workaround: Put a director in the composite. - Certain actors read parameter
values only during initialization. During initialization, a
FilePortParameter can only have a value set via the parameter (it
can't have yet received a token). So if the initial value
is set to the value of the FilePortParameter, then it will
see only the parameter value, never the value provided via the
port.
Workaround: Use a RunCompositeActor to contain the model.
- Since:
- Ptolemy II 4.1
- Version:
- $Id$
- Author:
- Edward A. Lee
- See Also:
FileParameter
,ParameterPort
- Pt.AcceptedRating:
- Red (cxh)
- Pt.ProposedRating:
- Yellow (eal)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.data.expr.Variable
Variable.CircularDependencyError, Variable.VariableScope
-
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
-
Nested classes/interfaces inherited from interface ptolemy.kernel.util.Settable
Settable.Visibility
-
-
Field Summary
-
Fields inherited from class ptolemy.actor.parameters.PortParameter
_port
-
Fields inherited from class ptolemy.data.expr.Variable
_currentExpression, _needsEvaluation, _parserScope, _parseTreeValid, _suppressVariableSubstitution, _valueListeners
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
-
Fields inherited from interface ptolemy.kernel.util.Settable
EXPERT, FULL, NONE, NOT_EDITABLE
-
-
Constructor Summary
Constructors Constructor Description FilePortParameter(NamedObj container, java.lang.String name)
Construct a parameter with the given name contained by the specified entity.FilePortParameter(NamedObj container, java.lang.String name, Token token)
Construct a Parameter with the given container, name, and Token.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description java.io.File
asFile()
Return the file as a File object.java.net.URL
asURL()
Return the file as a URL.java.lang.Object
clone(Workspace workspace)
Clone the attribute into the specified workspace.void
close()
Close the file.java.net.URI
getBaseDirectory()
Return the directory to use as the base for relative file or URL names.java.io.BufferedReader
openForReading()
Open the file or URL for reading.java.io.Writer
openForWriting()
Open the file for writing.java.io.Writer
openForWriting(boolean append)
Open the file for writing or appending.void
setBaseDirectory(java.net.URI directory)
Set the directory to use as the base for relative file or URL names.java.lang.String
stringValue()
Return the string value of this parameter.-
Methods inherited from class ptolemy.actor.parameters.PortParameter
_getCurrentExpression, _propagateExistence, _setTypeConstraints, attributeChanged, getExpression, getPort, initialize, preinitialize, setContainer, setCurrentValue, setDisplayName, setExpression, setName, setToken, update
-
Methods inherited from class ptolemy.data.expr.AbstractInitializableParameter
_getInitializableContainer, addInitializable, hierarchyChanged, hierarchyWillChange, removeInitializable, wrapup
-
Methods inherited from class ptolemy.data.expr.Parameter
addChoice, exportMoML, getChoices, removeAllChoices, removeChoice
-
Methods inherited from class ptolemy.data.expr.Variable
_description, _evaluate, _notifyValueListeners, _parseIfNecessary, _propagate, _propagateToValueListeners, _propagateValue, _setToken, _setTokenAndNotify, addValueListener, getDeclaredType, getFreeIdentifiers, getParserScope, getScope, getScope, getToken, getType, getTypeTerm, getValueAsString, getVariable, getVisibility, invalidate, isKnown, isLazy, isStringMode, isSuppressVariableSubstitution, isTypeAcceptable, removeValueListener, reset, setLazy, setParseTreeEvaluator, setStringMode, setSuppressVariableSubstitution, setToken, setTypeAtLeast, setTypeAtLeast, setTypeAtMost, setTypeEquals, setTypeSameAs, setUnknown, setValueListenerAsWeakDependency, setVisibility, stringRepresentation, toString, typeConstraintList, typeConstraints, validate, valueChanged
-
Methods inherited from class ptolemy.kernel.util.AbstractSettableAttribute
getDefaultExpression
-
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, updateContent
-
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, addHierarchyListener, attributeDeleted, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, decorators, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, notifyOfNameChange, propagateExistence, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, uniqueName, validateSettables, workspace
-
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, removeInitializable, wrapup
-
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getFullName, getName, getName, setName
-
Methods inherited from interface ptolemy.kernel.util.Settable
addValueListener, getDefaultExpression, getDisplayName, getExpression, getValueAsString, getVisibility, removeValueListener, setExpression, setVisibility, validate
-
-
-
-
Constructor Detail
-
FilePortParameter
public FilePortParameter(NamedObj container, java.lang.String name) throws IllegalActionException, NameDuplicationException
Construct a parameter with the given name contained by the specified entity. The container argument must not be null, or a NullPointerException will be thrown. This parameter will create an associated port in the same container.- Parameters:
container
- The container.name
- The name of the parameter.- Throws:
IllegalActionException
- If the parameter is not of an acceptable class for the container.NameDuplicationException
- If the name coincides with a parameter already in the container.
-
FilePortParameter
public FilePortParameter(NamedObj container, java.lang.String name, Token token) throws IllegalActionException, NameDuplicationException
Construct a Parameter with the given container, name, and Token. The token defines the initial persistent and current values. The container argument must not be null, or a NullPointerException will be thrown. This parameter will use the workspace of the container for synchronization and version counts. If the name argument is null, then the name is set to the empty string. The object is not added to the list of objects in the workspace unless the container is null. Increment the version of the workspace. If the name argument is null, then the name is set to the empty string.- Parameters:
container
- The container.name
- The name.token
- The Token contained by this Parameter.- Throws:
IllegalActionException
- If the parameter is not of an acceptable class for the container.NameDuplicationException
- If the name coincides with an parameter already in the container.
-
-
Method Detail
-
asFile
public java.io.File asFile() throws IllegalActionException
Return the file as a File object. This method first attempts to directly use the file name to construct the File. If the resulting File is not absolute, then it attempts to resolve it relative to the base directory returned by getBaseDirectory(). If there is no such base URI, then it simply returns the relative File object.The file need not exist for this method to succeed. Thus, this method can be used to determine whether a file with a given name exists, prior to calling openForWriting(). A typical usage looks like this:
FileParameter fileParameter; ... File file = fileParameter.asFile(); if (file.exists()) { ... Ask the user if it's OK to overwrite... ... Throw an exception if not... } // The following will overwrite an existing file. Writer writer = new PrintWriter(fileParameter.openForWriting());
- Specified by:
asFile
in interfaceFileOrURLAccessor
- Returns:
- A File, or null if no file name has been specified.
- Throws:
IllegalActionException
- If a parse error occurs reading the file name.- See Also:
getBaseDirectory()
-
asURL
public java.net.URL asURL() throws IllegalActionException
Return the file as a URL. If the file name is relative, then it is interpreted as being relative to the directory returned by getBaseDirectory(). If the name begins with "$CLASSPATH", then search for the file relative to the classpath. If no file is found, then it throws an exception.- Specified by:
asURL
in interfaceFileOrURLAccessor
- Returns:
- A URL, or null if no file name or URL has been specified.
- Throws:
IllegalActionException
- If the file cannot be read, or if the file cannot be represented as a URL (e.g. System.in), or the name specification cannot be parsed.
-
clone
public java.lang.Object clone(Workspace workspace) throws java.lang.CloneNotSupportedException
Clone the attribute into the specified workspace. The resulting object has no base directory name nor any reference to any open stream.- Overrides:
clone
in classPortParameter
- Parameters:
workspace
- The workspace for the cloned object.- Returns:
- A new attribute.
- Throws:
java.lang.CloneNotSupportedException
- If a derived class contains an attribute that cannot be cloned.- See Also:
Object.clone()
-
close
public void close() throws IllegalActionException
Close the file. If it has not been opened using openForReading() or openForWriting(), then do nothing. Also, if the file is System.in or System.out, then do not close it (it does not make sense to close these files).- Specified by:
close
in interfaceFileOrURLAccessor
- Throws:
IllegalActionException
- If the file or URL cannot be closed.
-
getBaseDirectory
public java.net.URI getBaseDirectory()
Return the directory to use as the base for relative file or URL names. If setBaseDirectory() has been called, then that directory is returned. Otherwise, the directory containing the file returned by URIAttribute.getModelURI() is returned, which is the URI of the first container above this attribute in the hierarchy that has a URIAttribute, or null if there none.- Specified by:
getBaseDirectory
in interfaceFileOrURLAccessor
- Returns:
- A directory name, or null if there is none.
- See Also:
URIAttribute.getModelURI(NamedObj)
,setBaseDirectory(URI)
-
openForReading
public java.io.BufferedReader openForReading() throws IllegalActionException
Open the file or URL for reading. If the name begins with "$CLASSPATH", then search for the file relative to the classpath. If the name is relative, then it is relative to the directory returned by getBaseDirectory().- Specified by:
openForReading
in interfaceFileOrURLAccessor
- Returns:
- A buffered reader.
- Throws:
IllegalActionException
- If the file or URL cannot be opened.- See Also:
getBaseDirectory()
-
openForWriting
public java.io.Writer openForWriting() throws IllegalActionException
Open the file for writing. If the file does not exist, then create it. If the file name is not absolute, the it is assumed to be relative to the base directory returned by getBaseDirectory(). If permitted, this method will return a Writer that will simply overwrite the contents of the file. It is up to the user of this method to check whether this is OK (by first calling asFile() and calling exists() on the returned value).- Specified by:
openForWriting
in interfaceFileOrURLAccessor
- Returns:
- A writer, or null if no file name has been specified.
- Throws:
IllegalActionException
- If the file cannot be opened or created.- See Also:
getBaseDirectory()
,asFile()
-
openForWriting
public java.io.Writer openForWriting(boolean append) throws IllegalActionException
Open the file for writing or appending. If the file does not exist, then create it. If the file name is not absolute, the it is assumed to be relative to the base directory returned by getBaseDirectory(). If permitted, this method will return a Writer that will simply overwrite the contents of the file. It is up to the user of this method to check whether this is OK (by first calling asFile() and calling exists() on the returned value).- Specified by:
openForWriting
in interfaceFileOrURLAccessor
- Parameters:
append
- If true, then append to the file rather than overwriting.- Returns:
- A writer, or null if no file name has been specified.
- Throws:
IllegalActionException
- If the file cannot be opened or created.- See Also:
getBaseDirectory()
,asFile()
-
setBaseDirectory
public void setBaseDirectory(java.net.URI directory)
Set the directory to use as the base for relative file or URL names. If this is not called, then the default is the directory containing the file returned by URIAttribute.getModelURI().- Specified by:
setBaseDirectory
in interfaceFileOrURLAccessor
- Parameters:
directory
- The base directory.- See Also:
URIAttribute.getModelURI(NamedObj)
,getBaseDirectory()
-
stringValue
public java.lang.String stringValue() throws IllegalActionException
Return the string value of this parameter. This is equivalent to((StringToken)this.getToken()).stringValue()
- Returns:
- The string value of this parameter.
- Throws:
IllegalActionException
- If the expression cannot be parsed or cannot be evaluated, or if the result of evaluation violates type constraints, or if the result of evaluation is null and there are variables that depend on this one.
-
-