/** * For each port of the given entity, if the port's derived level is greater than 0 (i.e., it is * created automatically by the entity), store the persistent attributes of the port in a "port" * XML element. * * @param entity The entity whose ports are looked at. * @param output The output writer. * @param depth The depth for the MoML output. * @exception IOException If the output writer cannot be written to. */ public static void exportPortProperties(GTEntity entity, Writer output, int depth) throws IOException { if (entity instanceof Entity) { Entity ptEntity = (Entity) entity; for (Object portObject : ptEntity.portList()) { Port port = (Port) portObject; if (port.getDerivedLevel() == 0) { continue; } boolean outputStarted = false; for (Object attributeObject : port.attributeList()) { Attribute attribute = (Attribute) attributeObject; if (attribute.isPersistent()) { if (!outputStarted) { output.write( StringUtilities.getIndentPrefix(depth) + "<port name=\"" + port.getName() + "\">\n"); outputStarted = true; } attribute.exportMoML(output, depth + 1); } } if (outputStarted) { output.write(StringUtilities.getIndentPrefix(depth) + "</port>\n"); } } } }
/** * Return the container entity for the specified ASTPtRootNode. * * @param node The specified ASTPtRootNode. * @return The container entity for the specified ASTPtRootNode. */ public Entity getContainerEntity(ASTPtRootNode node) { Attribute attribute = _solver.getAttribute(node); NamedObj container = attribute.getContainer(); while (!(container instanceof Entity)) { container = container.getContainer(); } return (Entity) container; }
/** * Return the list of property-able Attributes. A property-able Attribute is a StringAttribute * with the name "guardTransition", a StringAttribute in an Expression actor, a StringAttribute * with the name "expression" or a Variable with full visibility. However, Variables with certain * names are excluded. * * @return The list of property-able Attributes. */ protected List<Attribute> _getPropertyableAttributes() { List<Attribute> result = new LinkedList<Attribute>(); Iterator attributes = ((Entity) getComponent()).attributeList().iterator(); while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); // only consider StringAttributes, ignore all subclasses if (attribute.getClass().equals(ptolemy.kernel.util.StringAttribute.class)) { if (((StringAttribute) attribute).getName().equalsIgnoreCase("guardTransition") || ((StringAttribute) attribute).getContainer() instanceof Expression && ((StringAttribute) attribute).getName().equalsIgnoreCase("expression")) { result.add(attribute); } } else if (attribute instanceof Variable) { if (((Variable) attribute).getVisibility() == Settable.FULL) { // filter Parameters with certain names; ignore all // subclasses if (attribute instanceof PortParameter) { result.add(attribute); } else if (attribute.getClass().equals(ptolemy.data.expr.Parameter.class) || attribute.getClass().equals(ptolemy.data.expr.StringParameter.class)) { // FIXME: implement filter interface, so that adapter // classes can specify which attributes // need to be filtered (either by name or by class) // Currently all filtered attributes need to be // specified here if (((Parameter) attribute).getName().equals("firingCountLimit") || ((Parameter) attribute).getName().equals("NONE") || ((Parameter) attribute).getName().equals("_hideName") || ((Parameter) attribute).getName().equals("_showName") || ((Parameter) attribute).getName().equals("conservativeAnalysis") || ((Parameter) attribute).getName().equals("directorClass") || ((Parameter) attribute).getName().equals("stateDependentCausality") || ((Parameter) attribute).getName().equals("delayed") || ((Parameter) attribute).getName().equals("displayWidth")) { // do nothing, ignore the parameter } else { result.add(attribute); } } } } } return result; }
/** * this function returns an array conatining the Attributes added by the opal interface it took me * lots of time to figure out this code, maybe there is a cleaner way to get them... */ private Attribute[] _getOpalAttributes() throws IllegalActionException { List attrList = this.attributeList(); // list of attributes that will be deleted ArrayList opalAttrs = new ArrayList(); Iterator attrs = attrList.iterator(); // first we have to find the parameter we wanna delete while (attrs.hasNext()) { Attribute a = (Attribute) attrs.next(); if ((!a.getName().equals("serviceURL")) && // these are the types that we wanna save all the other // will be deleted (!a.getName().equals("methods")) && (!a.getName().equals("class")) && (!a.getName().equals("semanticType00")) && (!a.getName().equals("semanticType11")) && (!a.getName().equals("KeplerDocumentation")) && (!a.getName().equals("entityId")) && (!a.getName().equals("numberOfExtraInputFiles")) && (!a.getName().startsWith("_"))) { log.info("Opal attribute: " + a.getName()); opalAttrs.add(a); // a.setContainer(null); } // if } // while return (Attribute[]) opalAttrs.toArray(new Attribute[opalAttrs.size()]); }
/** * Check the class of the container in which the attribute is to be placed. If the container is * not an intended one, throw an IllegalActionException. * * @param attribute The attribute to check. * @param container The container. * @param containerClass The intended class of container. * @param deep Whether containers of the container should be checked instead, if the container * does not qualify. * @exception IllegalActionException If this attribute cannot be used with the given container. */ public static void checkContainerClass( Attribute attribute, NamedObj container, Class<? extends CompositeEntity> containerClass, boolean deep) throws IllegalActionException { while (deep && container != null && !containerClass.isInstance(container) && !(container instanceof EntityLibrary)) { container = container.getContainer(); if (container instanceof EntityLibrary) { return; } } if (container == null || !containerClass.isInstance(container) && !(container instanceof EntityLibrary)) { _delete(attribute); throw new IllegalActionException( attribute.getClass().getSimpleName() + " can only be added to " + containerClass.getSimpleName() + "."); } }
/* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (element == null) return ""; if (element instanceof GeneralAttribute) { GeneralAttribute.ATTRIBUTE_TYPE type = ((GeneralAttribute) element).getType(); switch (type) { case NAME: return "Name"; case TYPE: return "Type"; case CLASS: return "Class"; } return ""; } final Attribute att = (Attribute) element; return att.getDisplayName(); }
/** * puts entity in container * * @param container The new container value * @param entity The new container value * @exception NameDuplicationException Description of the Exception * @exception IllegalActionException Description of the Exception */ private static void setContainer(CompositeEntity container, NamedObj entity) throws NameDuplicationException, IllegalActionException { if (entity instanceof Attribute) { ((Attribute) entity).setContainer(container); } else if (entity instanceof ComponentEntity) { ((ComponentEntity) entity).setContainer(container); } }
/** * React to a change in an attribute. * * @param attribute The changed parameter. * @exception IllegalActionException If the parameter set is not valid. */ public void attributeChanged(Attribute attribute) throws IllegalActionException { String tmp = null; if (attribute == serverName) { // -------------- the user has changed serverName ----------- String strServerName = serverName.getExpression(); if (_serverNameString == null) { // the value is loaded from the moml file // don't cal the _createSubmission _serverNameString = strServerName; log.info("_serverNameString is set according to original value of moml file."); if (!strServerName.equals("")) { _appMetadata = AppMetadataParser.parseAppMetadata(strServerName); if (_appMetadata == null) { // something bad happen while getting the appMetadata log.error("Failed to parse metadata at " + strServerName); throw new IllegalActionException( this, "The selected URL does not point to a valid Opal service"); } } } else if (!strServerName.equals(_serverNameString)) { // the user changed the value, we have to update the actor log.info("Got a new server name: " + strServerName); _appMetadata = AppMetadataParser.parseAppMetadata(strServerName); if (_appMetadata != null) { if (_appMetadata.isArgMetadataEnable()) // complex submission form _createSubmission(_appMetadata); else // simple submission form _createSimpleSubmission(_appMetadata); _addDocumentation(_appMetadata); } else { // something bad happen while getting the appMetadata log.error("Failed to parse metadata at " + strServerName); throw new IllegalActionException( this, "The selected URL does not point to a valid Opal service"); } _serverNameString = strServerName; this.propagateValues(); } } else if (attribute == numberFiles) { // -------------- the user has changed the number of files ----------- int numFiles = 1; try { numFiles = Integer.parseInt(numberFiles.stringValue()); } catch (NumberFormatException e) { throw new IllegalActionException( this, "The numberFiles parameter is not a valid integer, please correct the value"); } if (numFiles != _numberFiles) { _updateUploadFileNumber(numFiles); _numberFiles = numFiles; } } else { log.debug("the user has changed: " + attribute.toString()); } super.attributeChanged(attribute); } // attributeChanged
/** * Check whether the attribute is unique in the given container. * * @param attribute The attribute to check. * @param container The container. * @exception IllegalActionException If the container already has an attribute in the same class. */ public static void checkUniqueness(Attribute attribute, NamedObj container) throws IllegalActionException { if (container instanceof EntityLibrary) { return; } try { container.workspace().getReadAccess(); List<? extends Attribute> attributeList = container.attributeList(attribute.getClass()); for (Attribute existingAttribute : attributeList) { if (existingAttribute != attribute && existingAttribute.isPersistent()) { _delete(attribute); throw new IllegalActionException( "Only 1 " + attribute.getClass().getSimpleName() + " can be used."); } } } finally { container.workspace().doneReading(); } }
/** * Remove all the attributes in the given class from the given container and all of its children * including ports, entities and relations, but not including attributes. * * @param container The container. * @param attributeClass The attribute class. * @exception IllegalActionException If an attribute cannot be removed. */ public static void deepRemoveAttributes( NamedObj container, Class<? extends Attribute> attributeClass) throws IllegalActionException { List<Object> attributes = new LinkedList<Object>(container.attributeList(attributeClass)); for (Object attribute : attributes) { try { ((Attribute) attribute).setContainer(null); } catch (NameDuplicationException e) { // This should not happen. } } for (Object child : getChildren(container, false, true, true, true)) { deepRemoveAttributes((NamedObj) child, attributeClass); } }
@Override public void attributeChanged(Attribute attribute) throws IllegalActionException { if ("portMode".equalsIgnoreCase(attribute.getName())) { try { PortMode newMode = PortMode.valueOf(((Settable) attribute).getExpression()); if (!newMode.equals(getMode())) { setMode(newMode); } } catch (Exception e) { // ignore just keep default portmode then } } else { super.attributeChanged(attribute); } }
/** * Request a MoMLChangeRequest to delete this attribute from its container. * * @param attribute The attribute to be deleted. */ private static void _delete(Attribute attribute) { String moml = "<deleteProperty name=\"" + attribute.getName() + "\"/>"; attribute.requestChange(new MoMLChangeRequest(attribute, attribute.getContainer(), moml)); }
/** * Specify the container. If the container is not the same as the previous container, then start * monitoring the new container. * * @param container The container to attach this attribute to.. * @exception IllegalActionException If this attribute is not of the expected class for the * container, or it has no name, or the attribute and container are not in the same workspace, * or the proposed container would result in recursive containment. * @exception NameDuplicationException If the container already has an attribute with the name of * this attribute. * @see #getContainer() */ public void setContainer(final NamedObj container) throws IllegalActionException, NameDuplicationException { if (_debugging) { _debug("set container method called"); } NamedObj previousContainer = getContainer(); if (previousContainer == container) { return; } if ((previousContainer != null) && (previousContainer instanceof CompositeActor)) { // _piggybackContainer should be non-null, but we check anyway. if (_piggybackContainer != null) { _piggybackContainer.removePiggyback(_executable); } _executable = null; String name; try { workspace().getWriteAccess(); List<Actor> entities = ((CompositeActor) previousContainer).deepEntityList(); for (Actor entity : entities) { List<Attribute> paramList = ((Entity) entity).attributeList(); for (Attribute param : paramList) { name = param.getDisplayName(); if (name.equals("WCET") || name.equals("executionTime")) { // param.setPersistent(false); } } } } catch (Exception ex) { // this should later be replaced with a more specific exception throw new InternalErrorException(ex); } finally { workspace().doneTemporaryWriting(); } if (_debugging) { _debug("I should remove all the attributes that were added here."); } } super.setContainer(container); if (container != null && container instanceof CompositeActor) { if (_executable == null) { _executable = new Executable() { public void initialize() throws IllegalActionException { if (_random == null || ((BooleanToken) resetOnEachRun.getToken()).booleanValue()) { _createGenerator(); } _needNew = true; } public boolean postfire() throws IllegalActionException { if (_debugging) { _debug("I should now check to see if there are cumulative overruns"); } _needNew = true; // here check to see if there were cumulative timing overruns if (_debugging) { _debug( "execution times are: " + _totalObservedExecutionTime + " period is: " + _totalExpectedExecutionTime); } if (_totalObservedExecutionTime > _totalExpectedExecutionTime) { if (_debugging) { _debug("There was a timing overrun"); } if (_debugging) { _debug("There was a timing overrun"); } handleModelError( container, new IllegalActionException( container, "total ExecutionTime of (" + _totalObservedExecutionTime + ") is larger than Period of (" + _totalExpectedExecutionTime + ") for actor " + container.getDisplayName())); } _totalObservedExecutionTime = 0; // reset the observed time ChangeRequest request = new ChangeRequest( this, "SetVariable change request", true /*Although this not a structural change in my point of view , we however for some reason need to specify it is, otherwise the GUI won't update.*/) { protected void _execute() throws IllegalActionException {} }; // To prevent prompting for saving the model, mark this // change as non-persistent. request.setPersistent(false); requestChange(request); if (_debugging) { _debug("Finished checking for overruns"); } return true; } public void wrapup() { ChangeRequest request = new ChangeRequest(this, "SetVariable change request", true) { protected void _execute() throws IllegalActionException {} }; // To prevent prompting for saving the model, mark this // change as non-persistent. request.setPersistent(false); requestChange(request); } public void fire() throws IllegalActionException { if (!_readyToFire) { return; } if (_debugging) { _debug("Inside the fire method and the container is " + container); } if (_debugging) { _debug("Fire method called in the quantity manager"); } if (_needNewGenerator) { _createGenerator(); } if (_needNew) { _generateRandomNumber(); _needNew = false; } if (!_readyToFire) { return; } while ((_unitIndex < _schedule.size())) { // Grab the next minor cycle (unit) schedule to execute. Schedule unitSchedule = (Schedule) _schedule.get(_unitIndex); Iterator scheduleIterator = unitSchedule.iterator(); while (scheduleIterator.hasNext()) { Actor actor = ((Firing) scheduleIterator.next()).getActor(); if (_debugging) { _debug("actor to be fired in this iteration has name " + actor.getFullName()); } _myPhysicalTime = actor.getDirector().getModelTime().getDoubleValue() + _overRunThusFar; double actorWCET; Attribute executionTime = ((Entity) actor).getAttribute("executionTime"); Attribute WCET = ((Entity) actor).getAttribute("WCET"); actorWCET = ((DoubleToken) ((Variable) WCET).getToken()).doubleValue(); double t = _random.nextDouble() * 2 * actorWCET; // I multiply by actorWCET in an attempt to scale if (_debugging) { _debug("simulated execution time is " + t); } _totalObservedExecutionTime += t; if (t > actorWCET) { _overRunThusFar += (t - actorWCET); _myPhysicalTime += t; // (_overRunThusFar; if (_debugging) { _debug( "the actor WCET estimate was " + actorWCET + " and the actual execution time was " + t); _debug( "there was an error at model time " + (actor.getDirector().getModelTime().getDoubleValue() + actorWCET) + "physical time is actually " + _myPhysicalTime); } } Parameter dummyP = (Parameter) executionTime; dummyP.setExpression(Double.toString(t)); if (_debugging) { _debug( "Done firing actor " + actor + " now going to check to see if it went over time."); } } scheduleIterator = unitSchedule.iterator(); while (scheduleIterator.hasNext()) { Actor actor1 = ((Firing) scheduleIterator.next()).getActor(); if (_debugging) { _debug("Iterating " + ((NamedObj) actor1).getFullName()); } if (actor1.iterate(1) == STOP_ITERATING) { // FIXME: How to handle this? // put the actor on a no-fire hashtable? System.err.println( "Warning: Giotto iterate returned " + "STOP_ITERATING for actor \"" + actor1.getFullName() + "\""); } } _unitIndex++; } if (_unitIndex >= _schedule.size()) { _unitIndex = 0; } } public boolean isFireFunctional() { return true; } public boolean isStrict() { return true; } public int iterate(int count) { return Executable.COMPLETED; } public boolean prefire() throws IllegalActionException { return true; } public void stop() {} public void stopFire() {} public void terminate() {} public void addInitializable(Initializable initializable) {} public void preinitialize() throws IllegalActionException { double wcet = 0; double _periodValue = 0; wcet = _getDirectorWCET(container); _periodValue = _getDirectorPeriod(container); // Next, construct the schedule. // FIXME: Note that mutations will not be supported since the // schedule is constructed only once. GiottoScheduler scheduler = (GiottoScheduler) ((GiottoDirector) ((CompositeActor) container).getDirector()) .getScheduler(); _schedule = scheduler.getSchedule(); // _unitTimeIncrement = scheduler._getMinTimeStep(_periodValue); if (_debugging) { _debug( "the WCET time seen by the director is " + wcet + " and the period is " + _periodValue); } if (wcet > _periodValue) { if (_debugging) { _debug("throw an exception"); } // this is the static check before execution throw new IllegalActionException( container, "total WCET of (" + wcet + ") is larger than period (" + _periodValue + ") for actor " + ((CompositeActor) (getContainer())).getDisplayName()); } // end of if if (_debugging) { _debug("at the end of preinitialize in the timing quantity manager."); } } public void removeInitializable(Initializable initializable) {} }; } _piggybackContainer = (CompositeActor) container; _piggybackContainer.addPiggyback(_executable); } }
/** * this function adds all the parameters necessary to have the documentation of the OpalClient * abviously this documentation is fetch from the remote server */ private void _addDocumentation(AppMetadata app) throws IllegalActionException { // let's get the variable we need Attribute documentation = this.getAttribute("KeplerDocumentation"); if (documentation == null) throw new IllegalActionException( this, "Unable to set the custom documentation (KeplerDocumentation not present)."); Attribute userDoc = documentation.getAttribute("userLevelDocumentation"); if (userDoc == null) throw new IllegalActionException( this, "Unable to set the custom documentation (userLevelDocumentation not present)."); // -- we have to delete all the documentation that is already there // before updating it List tempList = documentation.attributeList(); Attribute[] paramArray = (Attribute[]) tempList.toArray(new Attribute[tempList.size()]); for (int i = 0; i < paramArray.length; i++) { try { if (paramArray[i].getName().startsWith("prop:") || paramArray[i].getName().startsWith("port:output") || paramArray[i].getName().startsWith("port:baseUrl")) // let's remove the parameters paramArray[i].setContainer(null); } catch (NameDuplicationException e) { log.error( "The parameter could not be deleted from the documentation. Error message: " + e.getMessage()); throw new IllegalActionException( this, "Error resetting the ducumentation, there is a duplicated name: " + e.getMessage()); } } // After deleting we can finally set the documentation String stringDoc = _docHead; // let's set the general documentaion if (app.getUsage() != null) stringDoc += "<p>" + app.getUsage() + "</p>"; if (app.getInfo() != null) { String[] infos = app.getInfo(); for (int i = 0; i < infos.length; i++) stringDoc += "<pre>" + forXML(infos[i]) + "</pre>"; } // if log.debug("the stringDoc is: " + stringDoc); ((ConfigurableAttribute) userDoc).setExpression(stringDoc); // -- let's set the documentation for the various properties -- // some properties are always there... hence also the documentation // should be always there try { ((ConfigurableAttribute) userDoc).value(); ConfigurableAttribute parameterDoc = new ConfigurableAttribute(documentation, "port:output"); parameterDoc.setExpression( "It returns a list of Strings, containing the URL of the output files"); parameterDoc = new ConfigurableAttribute(documentation, "port:baseUrl"); parameterDoc.setExpression( "The base URL containing the working directory of the running jobs"); parameterDoc = new ConfigurableAttribute(documentation, "prop:serviceURL"); parameterDoc.setExpression("The URL of the Opal service that you want to execute"); parameterDoc = new ConfigurableAttribute(documentation, "prop:numberOfExtraInputFiles"); parameterDoc.setExpression( "The number of extra input files that are needed to execture the application"); // parameterDoc = new ConfigurableAttribute(documentation, // "prop:methods"); // parameterDoc.setExpression("Not implemented yet."); } catch (NameDuplicationException e) { log.error("The parameter could not be instantiated. Error message: " + e.getMessage()); throw new IllegalActionException( this, "Error building the ducumentation, there is a duplicated name: " + e.getMessage()); } catch (IOException e) { log.error("There is an error while setting the general documentation: " + e.getMessage()); } // we have to list the documentation for every parameters if (app.isArgMetadataEnable()) { Group[] group = app.getGroups(); try { if (group != null) { for (int i = 0; i < group.length; i++) { // first the parameters ArgParam[] argParams = group[i].getArgParams(); if (argParams != null) { for (int paramCount = 0; paramCount < argParams.length; paramCount++) { ConfigurableAttribute parameterDoc = new ConfigurableAttribute( documentation, "prop:" + argParams[paramCount].getId()); parameterDoc.setExpression(forXML(argParams[paramCount].getTextDesc())); } // for argParam } // argParams // and then the flags ArgFlag[] argFlags = group[i].getArgFlags(); if (argFlags != null) { for (int paramCount = 0; paramCount < argFlags.length; paramCount++) { ConfigurableAttribute parameterDoc = new ConfigurableAttribute( documentation, "prop:" + argFlags[paramCount].getId()); parameterDoc.setExpression(forXML(argFlags[paramCount].getTextDesc())); log.info( "The parameter " + argFlags[paramCount].getId() + " has the following doc: " + parameterDoc.value()); parameterDoc.validate(); } } // argFlags } } // group } catch (NameDuplicationException e) { log.error("The parameter could not be instantiated. Error message: " + e.getMessage()); throw new IllegalActionException( this, "Error building the ducumentation, there is a duplicated name: " + e.getMessage()); } catch (IOException e) { log.error( "There is an error while setting the documentation of an element with messge: " + e.getMessage()); } } // if we have metadata else { // if we don't have metadata we document the standard parameters try { ConfigurableAttribute parameterDoc = new ConfigurableAttribute(documentation, "prop:commandLine"); parameterDoc.setExpression( "Insert the command line you want to execute (without the application name)"); parameterDoc = new ConfigurableAttribute(documentation, "prop:cpuNumber"); parameterDoc.setExpression("If it is a parallel application insert the CPU number"); parameterDoc = new ConfigurableAttribute(documentation, "prop:inputFile"); parameterDoc.setExpression("Select an input file"); } catch (NameDuplicationException e) { log.error("The parameter could not be instantiated. Error message: " + e.getMessage()); throw new IllegalActionException( this, "Error building the ducumentation, there is a duplicated name: " + e.getMessage()); } } } // _addDocumentation
/** * Get the change request to update the object in the host model. * * @param pattern The pattern of the transformation rule. * @param replacement The replacement of the transformation rule. * @param matchResult The match result. * @param patternObject The object in the pattern, or null. * @param replacementObject The object in the replacement that corresponds to the object in the * pattern. * @param hostObject The object in the host model corresponding to the object in the replacement. * @return The change request. * @exception IllegalActionException If error occurs in generating the change request. */ @Override public ChangeRequest getChangeRequest( Pattern pattern, Replacement replacement, MatchResult matchResult, NamedObj patternObject, NamedObj replacementObject, NamedObj hostObject) throws IllegalActionException { if (_valueParseTree == null) { _reparse(); } String attributeName = ((StringToken) _attributeName.getToken()).stringValue(); String attributeClass; if (isAttributeClassEnabled()) { attributeClass = _attributeClass; } else { Attribute oldAttribute = hostObject.getAttribute(attributeName); if (oldAttribute == null) { throw new IllegalActionException( "Unable to determine the class" + " of attribute " + _attributeName + " for entity " + hostObject + "."); } attributeClass = oldAttribute.getClassName(); } ParserScope scope = NamedObjVariable.getNamedObjVariable(hostObject, true).getParserScope(); GTParameter.Evaluator evaluator = new GTParameter.Evaluator(pattern, matchResult); String expression; if (_valueParseTree instanceof ASTPtSumNode) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < _valueParseTree.jjtGetNumChildren(); i++) { ASTPtRootNode child = (ASTPtRootNode) _valueParseTree.jjtGetChild(i); if (!(child.isConstant() && child.getToken() instanceof StringToken)) { ASTPtLeafNode newNode = _evaluate(child, evaluator, scope); buffer.append(_parseTreeWriter.parseTreeToExpression(newNode)); } else { buffer.append(((StringToken) child.getToken()).stringValue()); } } expression = buffer.toString(); } else if (!(_valueParseTree.isConstant() && _valueParseTree.getToken() instanceof StringToken)) { ASTPtRootNode newRoot = _evaluate(_valueParseTree, evaluator, scope); expression = _parseTreeWriter.parseTreeToExpression(newRoot); } else { expression = _attributeValue.get(); } String moml = "<property name=\"" + attributeName + "\" class=\"" + attributeClass + "\" value=\"" + StringUtilities.escapeForXML(expression) + "\"/>"; return new MoMLChangeRequest(this, hostObject, moml, null); }
/** * Evaluate the specified command. * * @param command The command. * @return The return value of the command, or null if there is none. * @exception Exception If something goes wrong processing the command. */ public String evaluateCommand(String command) throws Exception { if (command.trim().equals("")) { return ""; } PtParser parser = new PtParser(); ASTPtRootNode node = parser.generateSimpleAssignmentParseTree(command); String targetName = null; // Figure out if we got an assignment... if so, then get the // identifier name and only evaluated the expression part. if (node instanceof ASTPtAssignmentNode) { ASTPtAssignmentNode assignmentNode = (ASTPtAssignmentNode) node; targetName = assignmentNode.getIdentifier(); node = assignmentNode.getExpressionTree(); } final NamedObj model = ((ExpressionShellEffigy) getContainer()).getModel(); ParserScope scope = new ModelScope() { public ptolemy.data.Token get(String name) throws IllegalActionException { Variable result = getScopedVariable(null, model, name); if (result != null) { return result.getToken(); } else { return null; } } public ptolemy.data.type.Type getType(String name) throws IllegalActionException { Variable result = getScopedVariable(null, model, name); if (result != null) { return result.getType(); } else { return null; } } public InequalityTerm getTypeTerm(String name) throws IllegalActionException { Variable result = getScopedVariable(null, model, name); if (result != null) { return result.getTypeTerm(); } else { return null; } } public Set identifierSet() { return getAllScopedVariableNames(null, model); } }; Token result = _evaluator.evaluateParseTree(node, scope); // If a target was specified, instantiate a new token. if (targetName != null) { Attribute attribute = model.getAttribute(targetName); if (attribute != null && !(attribute instanceof Parameter)) { attribute.setContainer(null); attribute = null; } if (attribute == null) { attribute = new Parameter(model, targetName); } ((Parameter) attribute).setToken(result); } if (result == null) { return ""; } else { return result.toString(); } }
/** * Write a MoML description of the contents of this object, wrapped in a configure element. This * is done by first populating the model, and then exporting its contents into a configure * element. This method is called by exportMoML(). Each description is indented according to the * specified depth and terminated with a newline character. * * @param output The output stream to write to. * @param depth The depth in the hierarchy, to determine indenting. * @exception IOException If an I/O error occurs. */ protected void _exportMoMLContents(Writer output, int depth) throws IOException { populate(); // Export top level attributes and ports List _attributes = attributeList(); String _displayName = getDisplayName(); // FIXME: start of duplicated code from NamedObj // If the display name has been set, then include a display element. // Note that copying parameters that have _displayName set need // to export _displayName. // See: http://bugzilla.ecoinformatics.org/show_bug.cgi?id=3361 if (!_displayName.equals(getName())) { output.write("<display name=\""); output.write(StringUtilities.escapeForXML(_displayName)); output.write("\"/>"); } // Callers of this method should hold read access // so as to avoid ConcurrentModificationException. if (_attributes != null) { // Iterator attributes = _attributes.elementList().iterator(); Iterator attributes = _attributes.iterator(); while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); attribute.exportMoML(output, depth); } } // FIXME: end of duplicated code from NamedObj // FIXME: start of duplicated code from Entity Iterator ports = portList().iterator(); while (ports.hasNext()) { Port port = (Port) ports.next(); port.exportMoML(output, depth); } // FIXME: end of duplicated code from Entity // Everything else is in a configure output.write(_getIndentPrefix(depth) + "<configure>\n"); output.write(_getIndentPrefix(depth + 1) + "<group>\n"); // FIXME: start of duplicated code from CompositeEntity Iterator classes = classDefinitionList().iterator(); while (classes.hasNext()) { ComponentEntity entity = (ComponentEntity) classes.next(); entity.exportMoML(output, depth + 2); } Iterator entities = entityList().iterator(); while (entities.hasNext()) { ComponentEntity entity = (ComponentEntity) entities.next(); entity.exportMoML(output, depth + 2); } Iterator relations = relationList().iterator(); while (relations.hasNext()) { ComponentRelation relation = (ComponentRelation) relations.next(); relation.exportMoML(output, depth + 2); } // NOTE: We used to write the links only if // this object did not defer to another // (getMoMLInfo().deferTo was null), and // would instead record links in a MoMLAttribute. // That mechanism was far too fragile. // EAL 3/10/04 output.write(exportLinks(depth + 2, null)); // FIXME: end of duplicated code from CompositeEntity output.write(_getIndentPrefix(depth + 1) + "</group>\n"); output.write(_getIndentPrefix(depth) + "</configure>\n"); }