Ejemplo n.º 1
0
  /**
   * Probe a port
   *
   * @param port The port to probe.
   * @return The probe report.
   */
  public static String portInfo(TypedIOPort port) {

    String width = "";
    try {
      width = Integer.valueOf(port.getWidth()).toString();
    } catch (IllegalActionException ex) {
      width = "Failed to get width of port " + port.getFullName() + ex;
    }

    String description = "";
    try {
      description = port.description();
    } catch (IllegalActionException ex) {
      description = "Failed to get the description of port " + port.getFullName() + ": " + ex;
    }
    String msg = "Port Info: \n";

    msg += "    getName():         " + port.getName() + "\n";
    msg += "    getWidth():        " + width + "\n";
    msg += "    isInput():         " + port.isInput() + "\n";
    msg += "    isOutput():        " + port.isOutput() + "\n";
    msg += "    isMultiport():     " + port.isMultiport() + "\n";
    msg += "    className():       " + port.getClassName() + "\n";
    msg += "    getDisplayName():  " + port.getDisplayName() + "\n";
    msg += "    getElementName():  " + port.getElementName() + "\n";
    msg += "    getFullName():     " + port.getFullName() + "\n";
    msg += "    getSource():       " + port.getSource() + "\n";
    msg += "    description():     " + description + "\n";
    msg += "    toString():        " + port + "\n";

    return msg;
  }
Ejemplo n.º 2
0
  /**
   * Remove all ports which's name is not in the selected vector
   *
   * @param nonRemovePortName The ports to NOT remove.
   * @throws IllegalActionException When bad things happen.
   */
  void removeOtherOutputPorts(Collection nonRemovePortName) throws IllegalActionException {
    // Use toArray() to make a deep copy of this.portList().
    // Do this to prevent ConcurrentModificationExceptions.
    TypedIOPort[] l = new TypedIOPort[0];
    l = (TypedIOPort[]) this.portList().toArray(l);

    for (TypedIOPort port : l) {
      if (port == null || port.isInput()) {
        continue;
      }
      String currPortName = port.getName();
      if (!nonRemovePortName.contains(currPortName)) {
        try {
          port.setContainer(null);
        } catch (Exception ex) {
          throw new IllegalActionException(this, "Error removing port: " + currPortName);
        }
      }
    }
  }
Ejemplo n.º 3
0
  /**
   * Update the ports to match the arguments. If an Argument has no corresponding port, a Port is
   * added. If a Port does not have a corresponding Argument, then the Port is removed. If a input
   * and/or output nature of a Port does not match the Argument with the same name, then the Port is
   * adjusted.
   *
   * @exception IllegalActionException If there is a problem updating the ports.
   */
  public void updatePorts() throws IllegalActionException {
    Iterator arguments = this.argumentsList().iterator();
    TypedIOPort port;

    while (arguments.hasNext()) {
      Argument argument = (Argument) arguments.next();
      port = (TypedIOPort) this.getPort(argument.getName());

      if (port == null) {
        MoMLChangeRequest request = null;

        try {
          if (argument.isReturn()) {

            request =
                new MoMLChangeRequest(
                    this,
                    this,
                    "<port name=\""
                        + argument.getName()
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + "    <property name=\"output\"/>\n"
                        + "</port>");
          } else if (argument.isInput() && argument.isOutput()) {
            request =
                new MoMLChangeRequest(
                    this,
                    this,
                    "<port name=\""
                        + argument.getName()
                        + "in"
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + "    <property name=\"input\"/>\n"
                        + "</port>\n"
                        + "<port name=\""
                        + argument.getName()
                        + "out"
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + "    <property name=\"output\"/>\n"
                        + "</port>");
          } else {
            request =
                new MoMLChangeRequest(
                    this,
                    this,
                    "<port name=\""
                        + argument.getName()
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + (argument.isInput() ? "    <property name=\"input\"/>\n" : "")
                        + (argument.isOutput() ? "    <property name=\"output\"/>\n" : "")
                        + "</port>");
          }
          request.setUndoable(true);
          requestChange(request);
        } catch (Throwable throwable) {
          throw new IllegalActionException(
              this,
              throwable,
              "MoMLChangeRequest for \""
                  + argument.getName()
                  + "\" failed. Request was:\n"
                  + request);
        }
      } else {
        // We have a preexisting port, synchronized the
        // arguments and the ports.

        if (argument.isReturn()) {
          if (port.isInput()) {
            MoMLChangeRequest request =
                new MoMLChangeRequest(
                    this,
                    this,
                    "<port name=\""
                        + argument.getName()
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + "    <deleteProperty name=\"input\"/>\n"
                        + (port.isOutput() ? "" : "    <property name=\"output\"/>\n")
                        + "</port>");
            request.setUndoable(true);
            requestChange(request);
          }
          if (!port.isOutput()) {
            MoMLChangeRequest request =
                new MoMLChangeRequest(
                    this,
                    this,
                    "<port name=\""
                        + argument.getName()
                        + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                        + "    <property name=\"output\"/>\n"
                        + "</port>");
            request.setUndoable(true);
            requestChange(request);
          }
        } else /*if (port.isInput() != argument.isInput()
               || port.isOutput() != argument.isOutput())*/ {
          MoMLChangeRequest request =
              new MoMLChangeRequest(
                  this,
                  this,
                  "<port name=\""
                      + argument.getName()
                      + "\" class=\"ptolemy.actor.TypedIOPort\">\n"
                      + (port.isInput()
                          ? (argument.isInput() ? "" : "<deleteProperty name=\"input\"/>\n")
                          : (argument.isInput() ? "<property name=\"input\"/>\n" : ""))
                      + (port.isOutput()
                          ? (argument.isOutput() ? "" : "<deleteProperty name=\"output\"/>\n")
                          : (argument.isOutput() ? "<property name=\"output\"/>\n" : ""))
                      + "</port>");
          request.setUndoable(true);
          requestChange(request);
        }
      }
    }

    // Remove any ports that do not have arguments.
    Iterator ports = portList().iterator();

    while (ports.hasNext()) {
      port = (TypedIOPort) ports.next();
      Argument argument = (Argument) _argumentsList.get(port.getName());
      if (argument == null) {
        MoMLChangeRequest request =
            new MoMLChangeRequest(this, this, "<deletePort name=\"" + port.getName() + "\"/>");
        request.setUndoable(true);
        requestChange(request);
      }
    }
  }
Ejemplo n.º 4
0
  /**
   * Read the argument of the function from the ports, call the native method throw the generated
   * interface, and put the results on the corresponding ports.
   *
   * @exception IllegalActionException If a exception occured
   */
  public void fire() throws IllegalActionException {
    super.fire();
    // getting the in/inout parameters
    Iterator ports = this.portList().iterator();
    Vector args = new Vector();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      if (port.isInput() && port.hasToken(0) && !(port.isOutput() && !port.isInput())) {
        Token tok = port.get(0);

        String typ = _methods[_methodIndex].getParameterTypes()[args.size()].toString();

        if (typ.equals("boolean")) {
          args.add(Boolean.valueOf(((BooleanToken) tok).booleanValue()));
        } else if (typ.equals("int")) {
          args.add(Integer.valueOf(((IntToken) tok).intValue()));
        } else if (typ.equals("long")) {
          args.add(Long.valueOf(((ScalarToken) tok).longValue()));
        } else if (typ.equals("double")) {
          args.add(Double.valueOf(((DoubleToken) tok).doubleValue()));
        } else if (typ.equals("class [I")) {
          int siz = ((ArrayToken) tok).arrayValue().length;
          int[] tab = new int[siz];

          for (int j = 0; j < siz; j++) {
            tab[j] = ((IntToken) (((ArrayToken) tok).arrayValue()[j])).intValue();
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else if (typ.equals("class [J")) {
          int siz = ((ArrayToken) tok).length();
          long[] tab = new long[siz];

          for (int j = 0; j < siz; j++) {
            Token element = ((ArrayToken) tok).getElement(j);
            try {
              tab[j] = ((LongToken) element).longValue();
            } catch (Throwable throwable) {
              throw new IllegalActionException(
                  this,
                  throwable,
                  "Failed to create LongToken, element "
                      + j
                      + " was: "
                      + element.getClass().getName()
                      + ", value: "
                      + element
                      + ", port: "
                      + port);
            }
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else {
          System.out.println(
              "The intype \"" + typ + "\" is not convertible " + "with Ptolemy II types.");
        }
      }
    }

    // tBFixed : the out parameter is not in by definition
    // ...so no port in can initialize the param
    // call the native function
    Object obj = null;
    Object ret = null;

    try {
      try {
        obj = _class.newInstance();
      } catch (Error error) {
        // Using JNI to link in a native library
        // can result in a java.lang.UnsatisfiedLinkError
        // which extends Error, not Exception.
        // FIXME: Rethrow the error as an exception
        String libraryPath = StringUtilities.getProperty("java.library.path");

        throw new Exception(
            "Class '"
                + _class
                + "' cannot be instantiated.\n"
                + "If you are running under Windows, "
                + "be sure that the directory containing the library "
                + "is in your PATH.\n"
                + "If you are running under Solaris, "
                + "be sure that the directory containing the library "
                + "is in your LD_LIBRARY_PATH and that the library "
                + "name begin with 'lib' and end with '.so'.\n"
                + "You may need to exit, set your "
                + "PATH or LD_LIBRARY_PATH to include the directory "
                + "that contains the shared library and "
                + "restart.\n"
                + "For example, under Windows "
                + "in a Cygwin bash shell:\n"
                + "PATH=/cygdrive/c/ptII/jni/dll:${PATH}\n"
                + "export PATH\n"
                + "vergil -jni foo.xml\n"
                + "A common error is that "
                + "the class cannot be found in "
                + "property 'java.library.path' "
                + "which is:\n"
                + libraryPath
                + "\nError message was: "
                + error.getMessage(),
            error);
      }
    } catch (Exception ex) {
      throw new IllegalActionException(this, ex, "Class cannot be instantiated");
    }

    try {
      ret = _methods[_methodIndex].invoke(obj, args.toArray());
    } catch (Throwable ex) {
      StringBuffer argumentsDescription = new StringBuffer("");

      try {
        if (args.size() >= 1) {
          argumentsDescription.append(args.elementAt(0).toString());

          for (int i = 1; i < args.size(); i++) {
            argumentsDescription.append(", " + args.elementAt(i).toString());
          }
        }
      } catch (Throwable throwable) {
        // Ignore
      }

      throw new IllegalActionException(
          this,
          ex,
          "Native operation call failed."
              + "Failed to invoke '"
              + obj
              + "' with "
              + args.size()
              + " arg(s) "
              + argumentsDescription.toString());
    }

    ports = portList().iterator();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      // if the argument is return
      if (getArgumentReturn() == null) {
        System.err.println("Warning: GenericJNIActor.java: " + "getArgumentReturn() returns null?");
      }

      if ((port != null)
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && port.getName().equals(this.getArgumentReturn().getName())) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException e) {
          try {
            throw new IllegalActionException(
                this, e, "No return type field '_" + port.getName() + "'");
          } catch (Throwable throwable) {
            getDirector().stop();
          }
        }

        if (typ.equals("boolean")) {
          port.send(0, new BooleanToken(((Boolean) ret).booleanValue()));
        } else if (typ.equals("double")) {
          port.send(0, new DoubleToken(((Double) ret).doubleValue()));
        } else if (typ.equals("int")) {
          port.send(0, new IntToken(((Integer) ret).intValue()));
        } else if (typ.equals("long")) {
          port.send(0, new LongToken(((Long) ret).longValue()));
        } else if (typ.equals("char")) {
          port.send(0, new UnsignedByteToken(((Byte) ret).byteValue()));
        } else {
          System.out.println("The return type is not convertible " + "with Ptolemy II types.");
        }
      }
      // if the argument is output
      else if ((port != null)
          && port.isOutput()
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && !(port.getName().equals(this.getArgumentReturn().getName()))) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException ex) {
          try {
            field =
                _class.getDeclaredField(
                    "_" + port.getName().substring(0, port.getName().length() - 3));
            typ = field.getType().toString();
          } catch (Throwable throwable) {
            try {
              throw new IllegalActionException(
                  this, throwable, "No '+" + port.getName() + "' field !");
            } catch (Throwable throwable2) {
              getDirector().stop();
            }
          }
        }

        if (field == null) {
          throw new InternalErrorException(
              "Field '" + port.getName() + "' in '" + _class + "' is null?");
        } else {
          if (typ.equals("boolean")) {
            try {
              port.send(0, new BooleanToken(field.getBoolean(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("double")) {
            try {
              port.send(0, new DoubleToken(field.getDouble(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("int")) {
            try {
              port.send(0, new IntToken(field.getInt(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("long")) {
            try {
              port.send(0, new LongToken(field.getLong(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("char")) {
            try {
              port.send(0, new UnsignedByteToken(field.getChar(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [I")) {
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              Token[] toks = new Token[((int[]) field.get(obj)).length];

              for (int j = 0; j < ((int[]) field.get(obj)).length; j++) {
                toks[j] = new IntToken(((int[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.INT, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [J")) {
            Token[] toks = null;
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              toks = new Token[((long[]) field.get(obj)).length];

              for (int j = 0; j < ((long[]) field.get(obj)).length; j++) {
                toks[j] = new LongToken(((long[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.LONG, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            } catch (IllegalActionException ex2) {
              throw new IllegalActionException(
                  this,
                  ex2,
                  "Failed to send a Long array token "
                      + (toks == null ? "null" : toks.length)
                      + " to "
                      + port);
            }
          } else if (typ.equals("class [D")) {
            try {
              Token[] toks = new Token[((double[]) field.get(obj)).length];

              for (int j = 0; j < ((double[]) field.get(obj)).length; j++) {
                toks[j] = new DoubleToken(((double[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else {
            // FIXME: for char[] and boolean[], there is
            // no corresponding Token type.
            System.out.println(
                "The outtype '" + typ + "' is not convertible " + "with Ptolemy II types.");
          }
        }
      }
    }
  }
Ejemplo n.º 5
0
  /**
   * Transform the graphic block diagram to text expression. Assume container only contains atomic
   * actors.
   *
   * @param container contains actors.
   * @return txtExpression of graphic block diagram.
   */
  private String _graphToText(CompositeActor container) throws IllegalActionException {
    // It is not trivial to transform graph to text.
    // Here, we assume there is only one Integrator and one expression actor.
    String txtString = "";
    LinkedList actors = new LinkedList(container.entityList());
    ListIterator actorIterator = actors.listIterator();

    // we begin with Integrator.
    AtomicActor beginActor = new AtomicActor();

    while (actorIterator.hasNext()) {
      Actor actor = (Actor) actorIterator.next();

      if (Integrator.class.isInstance(actor)) {
        beginActor = (AtomicActor) actor;
        break;
      }
    }

    if (beginActor == null) {
      throw new IllegalActionException("Integrator is needed!");
    } else {
      // we trace the output of the Integrator
      // we assume the output of the integrator is connectted
      // to the container output directly and they have same names
      // for simplicity at this time.
      // FIXME: we really need to reconsider the methods of ports.
      List outputs = beginActor.outputPortList();
      ListIterator outputIterator = outputs.listIterator();
      String outputName = "";

      if (outputs.size() != 1) {
        throw new IllegalActionException("Integrator only have one output!  " + outputs.size());
      } else {
        TypedIOPort output = (TypedIOPort) outputIterator.next();
        ListIterator sinkIterator = output.connectedPortList().listIterator();

        while (sinkIterator.hasNext()) {
          TypedIOPort sink = (TypedIOPort) sinkIterator.next();

          if (sink.isOutput()) {
            // FIXME: we need to consider depth in hierarchy
            // to avoid two outputs connected to same output
            // of composite actor
            outputName = sink.getName();
          }
        }

        txtString += ("diff { d(" + outputName + ") == ");
      }

      // we trace the input of the integrator
      List inputs = beginActor.inputPortList();
      ListIterator inputIterator = inputs.listIterator();

      if (inputs.size() != 1) {
        throw new IllegalActionException("Integrator only have one input!");
      } else {
        TypedIOPort input = (TypedIOPort) inputIterator.next();
        List sources = input.connectedPortList();

        if (sources.size() != 1) {
          throw new IllegalActionException("There is only one connection to the input!");
        } else {
          TypedIOPort source = (TypedIOPort) sources.get(0);

          // if there is just an integrator
          if (source.isInput()) {
            txtString += (source.getName() + " ; }" + _endLine);
          }
          // if there is some expression actor
          else {
            AtomicActor expressionActor = (AtomicActor) source.getContainer();

            if (Expression.class.isInstance(expressionActor)) {
              Parameter expPara = (Parameter) expressionActor.getAttribute("expression");
              txtString += (expPara.getExpression() + " ; } " + _endLine);
            } else {
              throw new IllegalActionException("This should be Expression Atomic Actor!");
            }
          }
        }
      }
    }

    return txtString;
  }