Exemplo n.º 1
0
 /**
  * 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
Exemplo n.º 2
0
  /**
   * Provide content to the specified web exporter to be included in a web page for the container of
   * this object. This class provides a default title for the web page and for each object as
   * specified by <i>include</i> and <i>instancesOf</i>.
   *
   * @throws IllegalActionException If a subclass throws it.
   */
  public void provideContent(WebExporter exporter) throws IllegalActionException {

    String titleValue = stringValue();
    if (titleValue == null || titleValue.equals("")) {
      // Use the model name as the default title.
      titleValue = getContainer().getName();
    }
    exporter.setTitle(titleValue, ((BooleanToken) showTitleInHTML.getToken()).booleanValue());

    boolean entities = false, attributes = false;
    String includeValue = include.stringValue().toLowerCase();
    if (includeValue.equals("all")) {
      entities = true;
      attributes = true;
    } else if (includeValue.equals("entities")) {
      entities = true;
    } else if (includeValue.equals("attributes")) {
      attributes = true;
    }
    List<NamedObj> objects;
    String instances = instancesOf.stringValue();
    NamedObj container = getContainer();
    if (entities && container instanceof CompositeEntity) {
      if (instances.trim().equals("")) {
        objects = ((CompositeEntity) container).entityList();
      } else {
        try {
          Class restrict = Class.forName(instances);
          objects = ((CompositeEntity) container).entityList(restrict);
        } catch (ClassNotFoundException e) {
          throw new IllegalActionException(this, "No such class: " + instances);
        }
      }
      for (NamedObj object : objects) {
        _provideOutsideContent(exporter, object);
      }
    }
    if (attributes) {
      if (instances.trim().equals("")) {
        objects = ((CompositeEntity) container).attributeList();
      } else {
        try {
          Class restrict = Class.forName(instances);
          objects = ((CompositeEntity) container).attributeList(restrict);
        } catch (ClassNotFoundException e) {
          throw new IllegalActionException(this, "No such class: " + instances);
        }
      }
      for (NamedObj object : objects) {
        _provideOutsideContent(exporter, object);
      }
    }
  }
Exemplo n.º 3
0
  /**
   * Override the base class to define an href attribute to associate with the area of the image map
   * corresponding to its container.
   *
   * @param exporter The web exporter to which to write content.
   * @exception IllegalActionException If evaluating the value of this parameter fails.
   */
  @Override
  protected void _provideAttributes(WebExporter exporter) throws IllegalActionException {

    boolean entities = false, attributes = false;
    String includeValue = include.stringValue().toLowerCase(Locale.getDefault());
    if (includeValue.equals("all")) {
      entities = true;
      attributes = true;
    } else if (includeValue.equals("entities")) {
      entities = true;
    } else if (includeValue.equals("attributes")) {
      attributes = true;
    }
    List<NamedObj> objects;
    String instances = instancesOf.stringValue();
    NamedObj container = getContainer();
    if (entities && container instanceof CompositeEntity) {
      if (instances.trim().equals("")) {
        objects = ((CompositeEntity) container).entityList();
      } else {
        try {
          Class restrict = Class.forName(instances);
          objects = ((CompositeEntity) container).entityList(restrict);
        } catch (ClassNotFoundException e) {
          throw new IllegalActionException(this, "No such class: " + instances);
        }
      }
      for (NamedObj object : objects) {
        _provideEachAttribute(exporter, object);
      }
    }
    if (attributes) {
      if (instances.trim().equals("")) {
        objects = ((CompositeEntity) container).attributeList();
      } else {
        try {
          Class restrict = Class.forName(instances);
          objects = ((CompositeEntity) container).attributeList(restrict);
        } catch (ClassNotFoundException e) {
          throw new IllegalActionException(this, "No such class: " + instances);
        }
      }
      for (NamedObj object : objects) {
        _provideEachAttribute(exporter, object);
      }
    }
  }
  private void populateDataBasedFunctions(
      final Map<String, Serializable> data, IFunction function) {

    if (function instanceof CompositeFunction) {
      CompositeFunction compositeFunction = (CompositeFunction) function;
      for (IFunction func : compositeFunction.getFunctions()) {
        populateDataBasedFunctions(data, func);
      }
    }

    if (function instanceof IDataBasedFunction) {
      IDataBasedFunction dbFunction = (IDataBasedFunction) function;

      String sdName = seedDataName.getExpression();
      String sdAxis = seedAxisName.getExpression();
      Dataset seedDataset = DatasetFactory.createFromObject(data.get(sdName)).clone();
      Dataset seedAxisDataset = DatasetFactory.createFromObject(data.get(sdAxis)).clone();
      dbFunction.setData(seedAxisDataset, seedDataset);
    }
  }
  /**
   * Execute the compile and run commands in the <i>codeDirectory</i> directory.
   *
   * @return The return value of the last subprocess that was executed or -1 if no commands were
   *     executed.
   * @exception IllegalActionException If there are problems reading parameters or executing the
   *     commands.
   */
  @Override
  protected int _executeCommands() throws IllegalActionException {
    List<String> commands = new LinkedList<String>();

    // The compile command.
    if (((BooleanToken) compile.getToken()).booleanValue()) {
      if (((BooleanToken) useMake.getToken()).booleanValue()) {
        commands.add("make -f " + _sanitizedModelName + ".mk ");
      } else {
        String command =
            CodeGeneratorUtilities.substitute(
                ((StringToken) compileCommand.getToken()).stringValue(), _substituteMap);
        System.out.println("JavaCodeGenerator: compile command: " + command);
        commands.add(command);
      }
    }

    // The run command.
    if (_isTopLevel()) {
      if (((BooleanToken) run.getToken()).booleanValue()) {
        if (((BooleanToken) useMake.getToken()).booleanValue()) {
          commands.add("make -f " + _sanitizedModelName + ".mk run");
        } else {
          String command =
              CodeGeneratorUtilities.substitute(
                  ((StringToken) runCommand.getToken()).stringValue(), _substituteMap);
          System.out.println("JavaCodeGenerator: run command: " + command);
          commands.add(command);
        }
      }
    }

    if (commands.size() == 0) {
      return -1;
    }

    _executeCommands.setCommands(commands);
    _executeCommands.setWorkingDirectory(codeDirectory.asFile());

    try {
      // FIXME: need to put this output in to the UI, if any.
      _executeCommands.start();
    } catch (Throwable throwable) {
      StringBuffer errorMessage = new StringBuffer();
      Iterator<?> allCommands = commands.iterator();
      while (allCommands.hasNext()) {
        errorMessage.append((String) allCommands.next() + _eol);
      }
      throw new IllegalActionException(
          "Problem executing the " + "commands:" + _eol + errorMessage + _eol + throwable);
    }
    return _executeCommands.getLastSubprocessReturnCode();
  }
Exemplo n.º 6
0
  /**
   * @param container
   * @param name
   * @throws ptolemy.kernel.util.NameDuplicationException
   * @throws ptolemy.kernel.util.IllegalActionException
   */
  public MathFunction(final CompositeEntity container, final String name)
      throws NameDuplicationException, IllegalActionException {
    super(container, name);
    // Parameters
    function = new StringParameter(this, "function");
    function.setExpression("exp");
    function.addChoice("exp");
    function.addChoice("log");
    function.addChoice("modulo");
    function.addChoice("sign");
    function.addChoice("square");
    function.addChoice("sqrt");
    _function = _EXP;

    // Ports
    // secondOperand port is not allocated in the constructor
    // instead it will allocated dynamically during run-time

    firstOperand = PortFactory.getInstance().createInputPort(this, "input", Double.class);
    output = PortFactory.getInstance().createOutputPort(this, "output");

    _attachText(
        "_iconDescription",
        "<svg>\n"
            + "<rect x=\"-30\" y=\"-15\" "
            + "width=\"60\" height=\"30\" "
            + "style=\"fill:white\"/>\n"
            + "</svg>\n");
  }
  @Override
  protected DataMessageComponent getTransformedMessage(List<DataMessageComponent> cache)
      throws DataMessageException {

    // get the data out of the message, name of the item should be specified
    final Map<String, Serializable> data = MessageUtils.getList(cache);
    Map<String, AFunction> functions;
    try {
      functions = MessageUtils.getFunctions(cache);
    } catch (Exception e) {
      throw new DataMessageException(
          "Could not parse the Funcitons comming into the FunctionToDatsetActor", null, e);
    }

    // prepare the output message
    DataMessageComponent result = MessageUtils.copy(cache);

    // get the required datasets
    String dataset = datasetName.getExpression();
    String xAxis = xAxisName.getExpression();
    String functionString = functionName.getExpression();

    // Get the actual objects
    Dataset xAxisDS = DatasetFactory.createFromObject(data.get(xAxis)).clone();
    AFunction function = functions.get(functionString);

    populateDataBasedFunctions(data, function);

    // process the data
    // TODO Add Null Protection here.
    DoubleDataset createdDS = function.calculateValues(xAxisDS);
    createdDS.setName(dataset);

    // Add it to the result
    result.addList(createdDS.getName(), createdDS);

    return result;
  }
Exemplo n.º 8
0
 /** This function returns the number of CPU selected by the user */
 private int _getCpuNumber() throws IllegalActionException {
   StringParameter cpuNumber = null;
   int value = 0;
   try {
     cpuNumber = (StringParameter) this.getAttribute("cpuNumber", StringParameter.class);
   } catch (IllegalActionException e) {
     throw new IllegalActionException(
         this, "Unable to find the command line parameter: " + e.getMessage());
   }
   if (cpuNumber == null) {
     return 0;
   }
   if (cpuNumber.getExpression().length() == 0) {
     return 0;
   }
   try {
     value = Integer.valueOf(cpuNumber.getExpression());
   } catch (Exception e) {
     throw new IllegalActionException(this, "The number of CPU must be an integer!");
   }
   log.debug("Invoking Opal with " + cpuNumber.getExpression() + " CPUs");
   return value;
 }
 /**
  * Create a top-level viewer for the specified object with the specified parent window.
  *
  * @param object The object to configure, which is required to contain a parameter with name
  *     matching <i>parameterName</i> and value that is an array of records.
  * @param parent The parent window, which is required to be an instance of TableauFrame.
  */
 @Override
 public void createEditor(NamedObj object, Frame parent) {
   try {
     Parameter attributeToEdit =
         (Parameter) object.getAttribute(parameterName.getExpression(), Parameter.class);
     if (attributeToEdit == null) {
       MessageHandler.error("No such parameter: " + parameterName.getExpression());
       return;
     }
     Token value = attributeToEdit.getToken();
     if (!(value instanceof ArrayToken)) {
       MessageHandler.error(
           "Parameter does not contain an array token: " + attributeToEdit.toString());
       return;
     }
     ArrayOfRecordsPane pane = new ArrayOfRecordsPane();
     pane.display((ArrayToken) value, (ArrayToken) columns.getToken());
     new ComponentDialog(parent, object.getFullName(), pane);
   } catch (KernelException ex) {
     MessageHandler.error("Cannot get specified string attribute to edit.", ex);
     return;
   }
 }
Exemplo n.º 10
0
  /**
   * Return a label figure for the specified token.
   *
   * @param row The row.
   * @param column The column.
   * @return A label figure.
   */
  private LabelFigure _labelFigure(RecordToken row, String column) {
    Token token = row.get(column);
    String label = "";
    if (token instanceof StringToken) {
      label = ((StringToken) token).stringValue();
    } else if (token != null) {
      label = token.toString();
    }
    Color color = Color.black;
    try {
      if (!colorKey.stringValue().equals("")) {
        Token colorToken = row.get(colorKey.stringValue());
        if (colorToken != null) {
          color = _uniqueColor(colorToken.toString());
        }
      }
    } catch (IllegalActionException e) {
      // Ignore. Use black.
    }

    LabelFigure tableElement =
        new LabelFigure(label, _labelFont, 1.0, SwingConstants.NORTH_WEST, color);
    return tableElement;
  }
Exemplo n.º 11
0
 @Override
 public void attributeChanged(final Attribute attribute) throws IllegalActionException {
   try {
     if (attribute == function) {
       final String functionName = function.stringValue();
       if (functionName.equals("exp")) {
         _function = _EXP;
         if (secondOperand != null) {
           secondOperand.setContainer(null);
         }
       } else if (functionName.equals("log")) {
         _function = _LOG;
         if (secondOperand != null) {
           secondOperand.setContainer(null);
         }
       } else if (functionName.equals("modulo")) {
         _function = _MODULO;
         _createSecondPort();
       } else if (functionName.equals("sign")) {
         _function = _SIGN;
         if (secondOperand != null) {
           secondOperand.setContainer(null);
         }
       } else if (functionName.equals("square")) {
         _function = _SQUARE;
         if (secondOperand != null) {
           secondOperand.setContainer(null);
         }
       } else if (functionName.equals("sqrt")) {
         _function = _SQRT;
         if (secondOperand != null) {
           secondOperand.setContainer(null);
         }
       } else {
         throw new IllegalActionException(this, "Unrecognized math function: " + functionName);
       }
     } else {
       super.attributeChanged(attribute);
     }
   } catch (final NameDuplicationException nameDuplication) {
     throw new InternalErrorException(this, nameDuplication, "Unexpected name duplication");
   }
 }
Exemplo n.º 12
0
  /**
   * Read multiple arrays of XMLTokens from the input and combine them according to the specified
   * template. If the template contains invalid delimiters, then return the template file with the
   * valid ones replaced and the invalid ones unmodified.
   *
   * @exception IllegalActionException If thrown by the parent class, while reading a parameter or
   *     while reading the input.
   */
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    template.update();
    String outputString = removeHeader(template.getToken());
    String all = "";
    for (int j = 0; j < input.getWidth(); j++) {
      ArrayToken a = (ArrayToken) input.get(j);

      // FIXME: use StringBuffer instead of concatenating a String.
      String allInArray = "";
      int i;
      for (i = 0; i < a.length(); i++) {
        String elemInArray = removeHeader(a.getElement(i));
        if (i == 0) {
          allInArray = allInArray.concat(elemInArray);
        } else {
          allInArray = allInArray.concat('\n' + elemInArray);
        }
        String elemTag = "$input" + Integer.toString(j) + ',' + Integer.toString(i);
        outputString = outputString.replace(elemTag, elemInArray);
      }
      String arrayTag = "$input" + Integer.toString(j) + ",n";
      outputString = outputString.replace(arrayTag, allInArray);
      if (j == 0) {
        all = all.concat(allInArray);
      } else {
        all = all.concat('\n' + allInArray);
      }
    }
    outputString = outputString.replace("$inputn", all);
    String ADDheader = headerParameter.stringValue() + "\n";
    ADDheader = ADDheader.concat(outputString);
    try {
      XMLToken out = new XMLToken(ADDheader);
      output.broadcast(out);
    } catch (Exception e) {
      // FIXME: throw an exception that uses "this" so we
      // know in which actor the error is located
      throw new InternalErrorException(e);
    }
  }
Exemplo n.º 13
0
 /**
  * This method instantiates the parameters needed for the submission of a Opal job without
  * metadata
  */
 private void _createSimpleSubmission(AppMetadata app) throws IllegalActionException {
   _emptyParamtersArray();
   // TODO delete this _interfaceParameters is useless
   log.info("Creating simple submission form. For service URL: " + app.getURL());
   try {
     (new StringParameter(this, "commandLine")).setContainer(this);
     (new StringParameter(this, "cpuNumber")).setContainer(this);
     // let's try to get the number of files
     int numFiles;
     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");
     }
     _updateUploadFileNumber(numFiles);
   } catch (NameDuplicationException e) {
     log.error("The parameter could not be instantiated. Error message: " + e.getMessage(), e);
   }
 }
Exemplo n.º 14
0
 /**
  * Get the TableauParameter to be used by the event that requires a tableau in its actions.
  *
  * @param event The event.
  * @param referredTableau The parameter that contains the name of the TableauParameter to be used,
  *     if not empty.
  * @param defaultTableau The default TableauParameter to be used.
  * @return The TableauParameter.
  * @exception IllegalActionException If the TableauParameter cannot be found.
  */
 public static TableauParameter getTableauParameter(
     Event event, StringParameter referredTableau, TableauParameter defaultTableau)
     throws IllegalActionException {
   String tableauName = referredTableau.stringValue().trim();
   if (tableauName.equals("")) {
     return defaultTableau;
   } else {
     Variable variable = ModelScope.getScopedVariable(null, event, tableauName);
     if (variable == null || !(variable instanceof TableauParameter)) {
       throw new IllegalActionException(
           event,
           "Unable to find "
               + "variable with name \""
               + tableauName
               + "\", or the "
               + "variable is not an instanceof TableauParameter.");
     }
     return (TableauParameter) variable;
   }
 }
Exemplo n.º 15
0
  /** this function build the command line reading the parameters selected by the user */
  private String _makeCmd() throws IllegalActionException {
    String str = "";
    if (_appMetadata.isArgMetadataEnable()) {
      // complex submission form
      if (_appMetadata.getArgFlags() != null) {
        // let's do the falgs
        ArgFlag[] flags = _appMetadata.getArgFlags();
        for (int i = 0; i < flags.length; i++) {
          Parameter flagTemp = null;
          if ((flagTemp = (Parameter) this.getAttribute(flags[i].getId())) == null)
            throw new IllegalActionException(
                this, "Unable to find the command line parameter (flag): " + flags[i].getId());
          if (((BooleanToken) flagTemp.getToken()).booleanValue()) str += " " + flags[i].getTag();
        } // for
      }
      if (_appMetadata.getArgParams() != null) {
        // and then the params
        ArgParam[] params = _appMetadata.getArgParams();
        String taggedParams = "";
        String separator = _appMetadata.getSeparator();
        if (separator == null) {
          separator = " ";
        }
        String[] untaggedParams =
            new String[_appMetadata.getNumUnttagedParams()]; // we make an array to contain
        // the untagged params
        for (int i = 0; i < untaggedParams.length; i++)
          // we initialized it to empty
          untaggedParams[i] = "";
        log.info("We have " + _appMetadata.getNumUnttagedParams() + " untaggged parameters.");
        for (int i = 0; i < params.length; i++) {
          log.info("Analizing param: " + params[i].getId());
          Attribute attr = this.getAttribute(params[i].getId());
          if (attr == null)
            throw new IllegalActionException(
                this, "We could not find the attribute " + params[i].getId());
          if (params[i].getTag() != null) {
            // tagged params
            if (attr instanceof FilePortParameter) {
              if (((FilePortParameter) attr).asFile() != null)
                // we have a file!
                taggedParams +=
                    " "
                        + params[i].getTag()
                        + separator
                        + ((FilePortParameter) attr).asFile().getName();
            } else if ((((StringParameter) attr).stringValue() != null)
                && (((StringParameter) attr).stringValue().length() > 0)) // basically the user
              // has entered some text
              taggedParams +=
                  " " + params[i].getTag() + separator + ((StringParameter) attr).stringValue();
          } else {
            // untagged parameters
            if (attr instanceof FilePortParameter) {
              if (((FilePortParameter) attr).asFile() != null)
                // we have a file
                untaggedParams[params[i].getPosition()] =
                    " " + ((FilePortParameter) attr).asFile().getName();
            } else if ((((StringParameter) attr).stringValue() != null)
                && (((StringParameter) attr).stringValue().length() > 0)) { // basically the user
              // has entered some
              // text
              // untagged params this is a bit unreadable!!
              untaggedParams[params[i].getPosition()] =
                  " " + ((StringParameter) attr).stringValue();
              log.info(
                  "Adding the "
                      + i
                      + " untagged paramters with: "
                      + untaggedParams[params[i].getPosition()]);
            } // if
          } // else
        } // for
        if (taggedParams.length() > 0) str += taggedParams;
        for (int i = 0; i < _appMetadata.getNumUnttagedParams(); i++) str += untaggedParams[i];
      }
      log.info("The command line is: " + str);
      return str;

    } else {
      // simple case
      StringParameter commandLine = null;
      try {
        commandLine = (StringParameter) this.getAttribute("commandLine", StringParameter.class);
        log.debug(
            "passing by here with commandLine = "
                + commandLine
                + " for server name: "
                + _serverNameString);
      } catch (IllegalActionException e) {
        throw new IllegalActionException(
            this, "Unable to find the command line parameter: " + e.getMessage());
      }
      return commandLine.getExpression();
    }
  } // _makeCmd
Exemplo n.º 16
0
  /**
   * Consume at most one array from the input ports and produce the index of the first bin that
   * breaks the threshold.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    start.update();

    if (array.hasToken(0)) {
      ArrayToken inputArray = (ArrayToken) array.get(0);
      int inputSize = inputArray.length();

      int startValue = ((IntToken) start.getToken()).intValue();

      if ((startValue >= inputSize) || (startValue < 0)) {
        throw new IllegalActionException(this, "start is out of range: " + startValue);
      }

      int increment = -1;

      if (((BooleanToken) forwards.getToken()).booleanValue()) {
        increment = 1;
      }

      double reference = ((DoubleToken) inputArray.getElement(startValue)).doubleValue();

      double thresholdValue = ((DoubleToken) threshold.getToken()).doubleValue();

      String scaleValue = scale.stringValue();

      boolean aboveValue = ((BooleanToken) above.getToken()).booleanValue();

      if (scaleValue.equals("relative amplitude decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 20));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 20));
        }
      } else if (scaleValue.equals("relative power decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 10));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 10));
        }
      } else if (scaleValue.equals("relative linear")) {
        if (aboveValue) {
          thresholdValue = reference + thresholdValue;
        } else {
          thresholdValue = reference - thresholdValue;
        }
      }

      // Default output if we don't find a crossing.
      int bin = -1;

      for (int i = startValue; (i < inputSize) && (i >= 0); i += increment) {
        double currentValue = ((DoubleToken) inputArray.getElement(i)).doubleValue();

        if (aboveValue) {
          // Searching for values above the threshold.
          if (currentValue > thresholdValue) {
            bin = i;
            break;
          }
        } else {
          // Searching for values below the threshold.
          if (currentValue < thresholdValue) {
            bin = i;
            break;
          }
        }
      }

      output.send(0, new IntToken(bin));
    }
  }
Exemplo n.º 17
0
  /**
   * this function instantiate all the parameter necessary to display an advanced submission form
   * for the current selected opal service
   */
  private void _createSubmission(AppMetadata app) throws IllegalActionException {
    _emptyParamtersArray();
    log.info("Creating complex submission form. For service URL: " + app.getURL());
    try {
      Group[] group = app.getGroups();
      ArrayList tempParam = new ArrayList();
      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++) {
              if (argParams[paramCount].getType().equals("FILE")
                  && argParams[paramCount].getIoType().equals("INPUT")) {
                // This is an input file box
                FilePortParameter param =
                    new FilePortParameter(this, argParams[paramCount].getId());
                if (argParams[paramCount].getSelectedValue() != null)
                  // setting the default value
                  param.setExpression(argParams[paramCount].getSelectedValue());
                tempParam.add(param);
              } else if (argParams[paramCount].getValues() != null) {
                String[] choices = argParams[paramCount].getValues();
                // this is a multiple choices
                StringParameter param = new StringParameter(this, argParams[paramCount].getId());
                for (int z = 0; z < choices.length; z++) param.addChoice(choices[z]);
                if (argParams[paramCount].getSelectedValue() != null)
                  // setting the default value
                  param.setExpression(argParams[paramCount].getSelectedValue());
                tempParam.add(param);
              } else {
                // this is a string
                StringParameter param = new StringParameter(this, argParams[paramCount].getId());
                if (argParams[paramCount].getSelectedValue() != null)
                  // setting the default value
                  param.setExpression(argParams[paramCount].getSelectedValue());
                tempParam.add(param);
              } // else
            } // for argParam
          } // argParams
          // and then the flags
          ArgFlag[] argFlags = group[i].getArgFlags();
          if (argFlags != null) {
            for (int paramCount = 0; paramCount < argFlags.length; paramCount++) {
              Parameter check = null;
              if (argFlags[paramCount].isSelected())
                check = new Parameter(this, argFlags[paramCount].getId(), BooleanToken.TRUE);
              else check = new Parameter(this, argFlags[paramCount].getId(), BooleanToken.FALSE);
              check.setTypeEquals(BaseType.BOOLEAN);
              tempParam.add(check);
            }
          } // argFlags
        }
      } // group
      // set the numberFiles to 0
      StringParameter param = (StringParameter) this.getAttribute("numberFiles");
      if (param != null) param.setToken(new StringToken("0"));

      // not needed anymore delete the tempParam
      // _interfaceParameters = (Parameter []) tempParam.toArray(new
      // Parameter[tempParam.size()]);
    } catch (NameDuplicationException e) {
      log.error("The parameter could not be instantiated. Error message: " + e.getMessage());
      throw new IllegalActionException(
          this, "The complex submission form could not be initialized: " + e.getMessage());
    }
    return;
  }
Exemplo n.º 18
0
  /**
   * Create a new background figure. This overrides the base class to draw a box around the value
   * display, where the width of the box depends on the value.
   *
   * @return A new figure.
   */
  public Figure createBackgroundFigure() {
    NamedObj container = getContainer();
    CompositeFigure result = new CompositeFigure();
    if (container != null) {
      try {
        ArrayToken fieldsValue = (ArrayToken) fields.getToken();
        Attribute associatedAttribute = container.getAttribute(variableName.getExpression());
        if (associatedAttribute instanceof Variable) {
          Token value = ((Variable) associatedAttribute).getToken();
          if (value instanceof ArrayToken) {
            // Find the number of rows and columns.
            int numRows = ((ArrayToken) value).length();
            int numColumns = fieldsValue.length();
            if (numColumns == 0) {
              // All columns should be included.
              // Make a pass to figure out how many that is.
              for (int i = 0; i < numRows; i++) {
                Token row = ((ArrayToken) value).getElement(i);
                if (row instanceof RecordToken) {
                  int rowWidth = ((RecordToken) row).labelSet().size();
                  if (rowWidth > numColumns) {
                    numColumns = rowWidth;
                  }
                }
              }
            }

            // Find the width of each column and the height of each row.
            // All rows are the same height, but column widths can vary.
            double rowHeight = 0.0;
            double columnWidth[] = new double[numColumns];
            for (int i = 1; i < numColumns; i++) {
              columnWidth[i] = 0.0;
            }
            LabelFigure tableElement[][] = new LabelFigure[numRows][numColumns];
            // Iterate over rows.
            for (int i = 0; i < numRows; i++) {
              Token row = ((ArrayToken) value).getElement(i);
              if (row instanceof RecordToken) {
                if (fieldsValue.length() == 0) {
                  // Display all fields.
                  Iterator labelSet = ((RecordToken) row).labelSet().iterator();
                  int j = 0;
                  while (labelSet.hasNext()) {
                    String column = (String) labelSet.next();
                    tableElement[i][j] = _labelFigure((RecordToken) row, column);
                    Rectangle2D bounds = tableElement[i][j].getBounds();
                    double width = bounds.getWidth();
                    if (width > columnWidth[j]) {
                      columnWidth[j] = width;
                    }
                    double height = bounds.getHeight();
                    if (height > rowHeight) {
                      rowHeight = height;
                    }
                    j++;
                  }
                } else {
                  // Display specified fields.
                  for (int j = 0; j < fieldsValue.length(); j++) {
                    if (j >= numColumns) {
                      break;
                    }
                    String column = ((StringToken) fieldsValue.getElement(j)).stringValue();
                    tableElement[i][j] = _labelFigure((RecordToken) row, column);
                    Rectangle2D bounds = tableElement[i][j].getBounds();
                    double width = bounds.getWidth();
                    if (width > columnWidth[j]) {
                      columnWidth[j] = width;
                    }
                    double height = bounds.getHeight();
                    if (height > rowHeight) {
                      rowHeight = height;
                    }
                  }
                }
              }
            }

            // Now make a pass to position and add all the figures.
            double rowPosition = _VERTICAL_PADDING;
            // Iterate over rows.
            for (int i = 0; i < numRows; i++) {
              Token row = ((ArrayToken) value).getElement(i);
              if (row instanceof RecordToken) {
                if (fieldsValue.length() == 0) {
                  // Display all fields.
                  Iterator labelSet = ((RecordToken) row).labelSet().iterator();
                  int j = 0;
                  double columnPosition = _HORIZONTAL_PADDING;
                  while (labelSet.hasNext()) {
                    /*String column = (String) */ labelSet.next();
                    tableElement[i][j].translateTo(columnPosition, rowPosition);
                    result.add(tableElement[i][j]);
                    columnPosition += columnWidth[j] + _HORIZONTAL_PADDING;
                    j++;
                  }
                } else {
                  // Display specified fields.
                  double columnPosition = _HORIZONTAL_PADDING;
                  for (int j = 0; j < fieldsValue.length(); j++) {
                    // String column = ((StringToken)fieldsValue.getElement(j)).stringValue();
                    tableElement[i][j].translateTo(columnPosition, rowPosition);
                    result.add(tableElement[i][j]);
                    columnPosition += columnWidth[j] + _HORIZONTAL_PADDING;
                  }
                }
              }
              rowPosition += rowHeight + _VERTICAL_PADDING;
            }
          }
        }
      } catch (IllegalActionException e) {
        // Stick the error message in the icon.
        result.add(new LabelFigure(e.getMessage()));
      }
    }
    // Now put a box around it all.
    Rectangle2D bounds = result.getBounds();
    // Double the padding below to allow for both sides.
    double width = Math.floor(bounds.getWidth()) + _HORIZONTAL_PADDING * 2;
    double height = Math.floor(bounds.getHeight()) + _VERTICAL_PADDING * 2;
    Figure rectangle = new BasicRectangle(0, 0, width, height, boxColor.asColor(), 1);
    CompositeFigure finalResult = new CompositeFigure(rectangle);
    finalResult.add(result);
    return finalResult;
  }