Example #1
0
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    Token t = input.get(0);

    if (r.nextInt(100) > Integer.parseInt(discardage.getValueAsString())) output.send(0, t);
  }
Example #2
0
  public void fire() throws IllegalActionException {
    super.fire();

    try {
      if (trigQuery.hasToken(0)) {
        trigQuery.get(0);

        System.out.println("Send peer discovery message...");

        // send a query message that is
        // - propagated within the group
        // - for peer discovery
        // - no attribute/value matching
        // - each response contains at most 5 peers
        _discoveryService.getRemoteAdvertisements(null, DiscoveryService.PEER, null, null, 5);

        System.out.println("Send actor query message...");
        _actorQueryMessage.setQueryId(_actorQueryMessage.getQueryId() + 1);
        _resolverService.sendQuery(null, _actorQueryMessage);
      }

      if (_inToken != null) {
        queryResult.send(0, _inToken);
        _inToken = null;
        System.out.println("send data ");
      }
    } catch (Exception e) {
      System.out.println("Error : " + e);
    }
  }
Example #3
0
  /**
   * Read one RecordToken from the input port and send its fields to the output ports. If the input
   * does not have a token, suspend firing and return.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Director director = getDirector();

    if (director == null) {
      throw new IllegalActionException(this, "No director!");
    }

    if (input.hasToken(0)) {
      RecordToken record = (RecordToken) input.get(0);
      Iterator labels = record.labelSet().iterator();

      while (labels.hasNext()) {
        String label = (String) labels.next();
        Token value = record.get(label);
        IOPort port = (IOPort) getPort(label);

        // since the record received may contain more fields than the
        // output ports, some fields may not have a corresponding
        // output port.
        if (port != null) {
          port.send(0, value);
        }
      }
    }
  }
  /**
   * Does up to three things, in this order: Set new remote address value, Set new remote socket
   * number, transmit data as a UDP packet over the ethernet. The first two can, of course, affect
   * where the datagram goes. Any remote address/socket values supplied are saved and become the
   * defaults for next time.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    String address = null;

    for (int jj = 0; jj < remoteAddress.getWidth(); jj++) {
      if (remoteAddress.hasToken(jj)) {
        address = ((StringToken) (remoteAddress.get(jj))).stringValue();
      }
    }

    if (address != null) {
      try {
        _address = InetAddress.getByName(address);
      } catch (UnknownHostException ex) {
        throw new IllegalActionException(
            this, ex, "The input remote " + "address specifies an unknown host");
      }
    }

    for (int jj = 0; jj < remoteSocketNumber.getWidth(); jj++) {
      if (remoteSocketNumber.hasToken(jj)) {
        // Valid socket numbers are 0..65535,
        // so keep only lower 16 bits.
        _remoteSocketNumber = 65535 & ((IntToken) remoteSocketNumber.get(jj)).intValue();
      }
    }

    if (data.hasToken(0)) {
      ArrayToken dataArrayToken = (ArrayToken) data.get(0);

      byte[] dataBytes = new byte[dataArrayToken.length()];

      for (int j = 0; j < dataArrayToken.length(); j++) {
        UnsignedByteToken token = (UnsignedByteToken) dataArrayToken.getElement(j);
        dataBytes[j] = token.byteValue();
      }

      DatagramPacket packet =
          new DatagramPacket(dataBytes, dataBytes.length, _address, _remoteSocketNumber);

      try {
        _socket.send(packet);
      } catch (IOException ex) {
        // ignore, UDP does not guarantee success
        // throw new InternalErrorException("socket.send failed");
        // FIXME  I don't believe that!  I think send guarantees that
        // it will send!!  Just not that anyone is listening.
        //    (yet when I ran it with 'throw...' uncommented
        //     then it threw it right away!? )
        // Would TCP stall here awaiting reply??  I doubt it!
      }

      triggerOutput.broadcast(new Token());
    }
  }
Example #5
0
  /**
   * Reap one packet from the ORB, unstuff it as an OrbImagePacket, and output the resulting
   * ImageToken (containing a java.awt.Image object). Note that this whole actor can be implemented
   * as a composite actor utilizing ObjectToRecord, RecordDisassembler, and something that forms
   * ImageTokens from java.awt.Image.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    try {
      OrbRawPacket pkt = (OrbRawPacket) (_orb.reap(false));
      OrbImagePacket imgPkt = (OrbImagePacket) (OrbImagePacket.unstuff(pkt));
      output.broadcast(new AWTImageToken(imgPkt.image));

    } catch (Exception e) {
      throw new IllegalActionException(this, e.getMessage());
    }
  }
  /**
   * Consume one double token from each of the two input ports (x and y), and output one new double
   * token on each of the two output ports (magnitude and angle). The output is a polar form
   * representation of the Cartesian pair given at the inputs. The angle is in radians.
   *
   * @exception IllegalActionException If there is no director.
   */
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    double xValue = ((DoubleToken) x.get(0)).doubleValue();
    double yValue = ((DoubleToken) y.get(0)).doubleValue();

    double magnitudeValue = Math.sqrt(xValue * xValue + yValue * yValue);
    double angleValue = Math.atan2(yValue, xValue);

    magnitude.send(0, new DoubleToken(magnitudeValue));
    angle.send(0, new DoubleToken(angleValue));
  }
Example #7
0
  /**
   * If the <i>enable</i> input is connected, then if it has a true token, produce the next output.
   * If it is not connected, produce the next output unconditionally. Whether it is connected is
   * determined by checking the width of the port.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if ((!enable.isOutsideConnected())
        || (enable.hasToken(0) && ((BooleanToken) enable.get(0)).booleanValue())) {
      ArrayToken valuesArray = (ArrayToken) values.getToken();

      if (_currentIndex < valuesArray.length()) {
        output.send(0, valuesArray.getElement(_currentIndex));
        _outputProduced = true;
      }
    }
  }
Example #8
0
  /**
   * Perform pattern matching and substring replacement, and output the modified string. If no match
   * is found, output the unmodified stringToEdit string.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    replacement.update();
    stringToEdit.update();
    pattern.update();

    String replacementValue = ((StringToken) replacement.getToken()).stringValue();
    String stringToEditValue = ((StringToken) stringToEdit.getToken()).stringValue();
    boolean replaceAllTokens = ((BooleanToken) replaceAll.getToken()).booleanValue();
    boolean regularExpressionValue = ((BooleanToken) regularExpression.getToken()).booleanValue();

    if (regularExpressionValue) {
      if (_pattern == null) {
        try {
          String patternValue = ((StringToken) pattern.getToken()).stringValue();
          _pattern = Pattern.compile(patternValue);
        } catch (PatternSyntaxException ex) {
          String patternValue = ((StringToken) pattern.getToken()).stringValue();
          throw new IllegalActionException(
              this, ex, "Failed to compile regular expression \"" + patternValue + "\"");
        }
      }
      Matcher match = _pattern.matcher(stringToEditValue);
      String outputString = "";

      // Unfortunately, the String class throws runtime exceptions
      // if something goes wrong, so we have to catch them.
      try {
        if (replaceAllTokens) {
          outputString = match.replaceAll(replacementValue);
        } else {
          outputString = match.replaceFirst(replacementValue);
        }
      } catch (Exception ex) {
        throw new IllegalActionException(this, ex, "String replace failed.");
      }

      output.send(0, new StringToken(outputString));
    } else {
      // No regular expression.
      String outputString;
      if (replaceAllTokens) {
        outputString = stringToEditValue.replaceAll(_patternValue, replacementValue);
      } else {
        outputString = stringToEditValue.replace(_patternValue, replacementValue);
      }
      output.send(0, new StringToken(outputString));
    }
  }
Example #9
0
  /**
   * Read the search parameter, if it matches "Search 50" then we've "got" data. Let the Loop Actor
   * know it can stop searching
   */
  public void fire() throws IllegalActionException {
    super.fire();

    if (search.getWidth() > 0 && search.hasToken(0)) {
      String searchStr = ((StringToken) search.get(0)).stringValue();
      if (searchStr.equals("Search 50")) {
        System.out.println("Found DATA!");
        resultsOutput.broadcast(new StringToken("Results Found"));

      } else {
        System.out.println("Didn't Match! " + searchStr);
        resultsOutput.broadcast(new StringToken("No Data"));
      }
    }
  }
Example #10
0
  /**
   * Read a token from each input port. If the token from the <i>control</i> input is true, then
   * output the token consumed from the <i>input</i> port on the <i>trueOutput</i> port, otherwise
   * output the token on the <i>falseOutput</i> port.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if (control.hasToken(0)) {
      _control = ((BooleanToken) control.get(0)).booleanValue();
    }

    if (input.hasToken(0)) {
      Token token = input.get(0);

      if (_control) {
        trueOutput.send(0, token);
      } else {
        falseOutput.send(0, token);
      }
    }
  }
  /**
   * If there is at least one token on the input ports, multiply tokens from the <i>multiply</i>
   * port, divide by tokens from the <i>divide</i> port, and send the result to the output port. At
   * most one token is read from each channel, so if more than one token is pending, the rest are
   * left for future firings. If none of the input channels has a token, do nothing. If none of the
   * multiply channels have tokens, then the tokens on the divide channels are divided into a one
   * token of the same type as the denominator.
   *
   * @exception IllegalActionException If there is no director, or if multiplication and division
   *     are not supported by the available tokens.
   */
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    Token numerator = null;
    try {
      for (int i = 0; i < multiply.getWidth(); i++) {
        if (multiply.hasToken(i)) {
          if (numerator == null) {
            numerator = multiply.get(i);
          } else {
            numerator = numerator.multiply(multiply.get(i));
          }
        }
      }

      Token denominator = null;

      for (int i = 0; i < divide.getWidth(); i++) {
        if (divide.hasToken(i)) {
          if (denominator == null) {
            denominator = divide.get(i);
          } else {
            denominator = denominator.multiply(divide.get(i));
          }
        }
      }

      if (numerator == null) {
        if (denominator == null) {
          return;
        }

        // For the benefit of copernicus, this means that
        // numerator always has the same type.
        numerator = multiply.getType().convert(denominator.one());
      }

      if (denominator != null) {
        numerator = numerator.divide(denominator);
      }
    } catch (Exception e) {
      throw new IllegalActionException(this, e.getCause(), e.getMessage());
    }

    output.send(0, numerator);
  }
Example #12
0
 /**
  * Perform a conditional rendezvous on any <i>input</i> channel, and then take the resulting token
  * and send it via rendezvous on the <i>output</i>.
  *
  * @exception IllegalActionException If an error occurs during executing the process.
  * @exception TerminateProcessException If the process termination is requested by the director.
  */
 public void fire() throws IllegalActionException {
   super.fire();
   Director director = getDirector();
   if (!(director instanceof RendezvousDirector)) {
     throw new IllegalActionException(this, "Barrier can only be used with RendezvousDirector.");
   }
   if (_debugging) {
     _debug("Ready to rendezvous with an input.");
   }
   /*Token received = RendezvousReceiver.getFromAny(
   input.getReceivers(), (RendezvousDirector)director);
   if (_debugging) {
   _debug("Received input: " + received);
   _debug("Sending to the output.");
   }
   output.send(0, received);*/
   RendezvousReceiver.getFromAnyPutToAll(
       input.getReceivers(), output.getRemoteReceivers(), (RendezvousDirector) director);
 }
Example #13
0
  /**
   * State machine responsable by receiving the traffic from the data_in port, disassembly the
   * pcredit_outage and send its flits to the output ports (file). If the data_in does not have a
   * token, suspend firing and return.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if (_debugging) _debug("fire current_time: " + getDirector().getModelTime());

    // getting current Time
    current_time = getDirector().getModelTime();
    compare_time = current_time.getDoubleValue();

    // if(firstSend.compareTo(compare_time) == 0.0){
    if (compare_time == init_tim) {
      send_msg.send(0, new IntToken("1"));

      if (_debugging) _debug("FIRST sent at: " + compare_time);
      if (compare_time <= stop_time) {
        new_send = ((DoubleToken) interval.getToken()).doubleValue();

        nextSend = current_time.add(new_send);

        getDirector().fireAt(this, nextSend);

        if (_debugging) _debug("after first send at: " + nextSend);
        // Requests to the director to be fire() at the window sample
      }
    } else if (compare_time < init_tim) {
      firstSend = current_time.add(init_tim);

      getDirector().fireAt(this, firstSend);

      if (_debugging) _debug("init_tim at: " + init_tim + " first send at " + firstSend);
    } else if (current_time.getDoubleValue() == nextSend.getDoubleValue()) {
      nextSend = nextSend.add(new_send);
      send_msg.send(0, new IntToken("2"));

      if (_debugging) _debug("msg sent at: " + compare_time);
      if (_debugging) _debug("NEXT SEND AT: " + nextSend);

      getDirector().fireAt(this, nextSend);

    } else if (current_time.getDoubleValue() != nextSend.getDoubleValue()) {
      if (_debugging) _debug("NAO ROLOU " + compare_time);
    }
  } // end public
Example #14
0
  /**
   * Send the token in the input to the output.
   *
   * @exception IllegalActionException If it is thrown by the send() method sending out the token.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Token sum = null;
    if (input.hasToken(0)) {
      sum = input.get(0);
    }

    for (int i = 0; i < multiportInput.getWidth(); i++) {
      if (multiportInput.hasToken(i)) {
        if (sum == null) {
          sum = multiportInput.get(i);
        } else {
          sum = sum.add(multiportInput.get(i));
        }
      }
    }
    if (sum != null) {
      output.send(0, sum);
    }
  }
Example #15
0
  // NOTE: No clone() method, so don't clone this.
  public void fire() throws IllegalActionException {
    super.fire();
    double increment = 0.0;

    if ((input.getWidth() > 0) && input.hasToken(0)) {
      DoubleToken in = (DoubleToken) input.get(0);
      increment = in.doubleValue();
    }

    output.broadcast(new DoubleToken(value + increment));
    value += 1.0;

    Director director = getDirector();
    Time time = director.getModelTime();
    count++;

    if (count >= 5) {
      director.fireAt(this, time.add(1.0));
      count = 0;
    } else {
      director.fireAt(this, time);
    }
  }
Example #16
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.");
          }
        }
      }
    }
  }
Example #17
0
  /**
   * Perform a multiway rendezvous with all input channels, collect one input token from each
   * channel, and then perform a multiway rendezvous with the output channels, providing that data.
   *
   * @exception IllegalActionException If the input width is zero.
   * @exception TerminateProcessException If the process termination is requested by the director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if (_debugging && _VERBOSE_DEBUGGING) {
      if (!_listeningToBranchController) {
        _branchController.addDebugListener(this);
        _listeningToBranchController = true;
      }
    } else {
      _branchController.removeDebugListener(this);
      _listeningToBranchController = false;
    }
    if (!input.isOutsideConnected()) {
      throw new IllegalActionException(this, "Barrier requires at least one input.");
    }
    ConditionalBranch[] branches = new ConditionalBranch[input.getWidth()];
    for (int i = 0; i < input.getWidth(); i++) {
      // The branch has channel i and ID i.
      branches[i] = new ConditionalReceive(input, i, i);
      if (_debugging && _VERBOSE_DEBUGGING) {
        branches[i].addDebugListener(this);
      }
    }
    if (_debugging) {
      _debug("Performing multiway rendezvous on the input channels.");
    }
    if (!_branchController.executeBranches(branches)) {
      if (_debugging) {
        _debug("At least one input rendezvous was terminated.");
      }
      _terminate = true;
      return;
    }
    if (_debugging) {
      _debug("Input channels completed.");
      if (_VERBOSE_DEBUGGING) {
        for (ConditionalBranch branche : branches) {
          branche.removeDebugListener(this);
        }
      }
    }
    Token[] data = new Token[input.getWidth()];
    for (int i = 0; i < input.getWidth(); i++) {
      data[i] = branches[i].getToken();
      if (_debugging) {
        _debug("Completed read input from channel " + i + ": " + data[i]);
      }
      if (data[i] == null) {
        throw new InternalErrorException("Input data is null!");
      }
    }

    if (output.isOutsideConnected()) {
      branches = new ConditionalBranch[output.getWidth()];
      Token token = null;
      for (int i = 0; i < output.getWidth(); i++) {
        if (i < input.getWidth()) {
          token = data[i];
        }
        if (_debugging) {
          _debug("Sending output to channel " + i + ": " + token);
        }
        branches[i] = new ConditionalSend(output, i, i, token);
        if (_debugging && _VERBOSE_DEBUGGING) {
          branches[i].addDebugListener(this);
        }
      }
      if (_debugging) {
        _debug("Performing multiway rendezvous on the output channels.");
      }
      if (_branchController.executeBranches(branches)) {
        if (_debugging) {
          _debug("Output channels completed.");
        }
      } else {
        if (_debugging) {
          _debug("Output channels failed.");
        }
      }
      if (_debugging && _VERBOSE_DEBUGGING) {
        for (ConditionalBranch branche : branches) {
          branche.removeDebugListener(this);
        }
      }
    }
  }
Example #18
0
  public void fire() throws IllegalActionException {
    super.fire();

    // first, checks for acks from remote buffers, updating the
    // values within txack[].

    for (int i = 0; i < 5; i++) {
      if (ack[i].getWidth() > 0) {
        while (ack[i].hasToken(0)) {
          // consumes the token

          BooleanToken ackt = (BooleanToken) ack[i].get(0);
          if (_debugging) _debug("Consuming ack from " + ack[i]);

          if (ackt.booleanValue()) txack[i] = true;
          else txack[i] = false;
          if (_debugging) _debug("ack: " + txack[i]);
        }
      }
    }

    // second, handle the current request from the arbiter

    if (hasRequest()) {
      // get the index of the port with the request

      int j = nextRequest();
      if (_debugging) _debug("Arbiter gives turn to input " + j);

      if (j != -1) {
        // packet header flit
        RecordToken record = (RecordToken) inputreq[j].get(0);
        // calculate route information
        int dir = route(record);
        // verify if the output port is free, otherwise
        // do nothing and wait for another request
        boolean isfree = freeoutput[dir];
        boolean hasspace = txack[dir];
        if (isfree & hasspace) {
          // allocate outputport
          direction[j] = new IntToken(dir);
          freeoutput[dir] = false;

          if (_debugging) _debug("Input " + j + " connected to output " + dir);

          // deletes original header flit from buffer
          read[j].send(0, new Token());
          // signalize state machine to prepare for size
          state[j] = SIZE;

          // sends copy of the header flit to output
          output[dir].send(0, record);
          txack[dir] = false;

          // updates the last granted input port
          sel = j;
        }
      }
    }

    // clear all unatended requests (they will be asked again next cycle)
    clearRequests();

    // third, handle tokens on the inputs

    for (int i = 0; i < 5; i++) {
      if (inputreq[i].getWidth() > 0 & inputreq[i].hasToken(0)) {
        if (state[i] == SIZE | state[i] == PAYLOAD) {
          if (_debugging) _debug(inputreq[i] + " has size/payload token");
          // payload flit

          // get the direction assigned to this input port
          int dir = direction[i].intValue();

          // check if the remote buffer in that direction is free
          if (txack[dir]) {

            // check if it is a size flit or a regular flit

            if (state[i] == SIZE) {
              // set the size of the packet
              RecordToken record = (RecordToken) inputreq[i].get(0);
              packetsize[i] = ((IntToken) record.get("size")).intValue();
              if (_debugging) _debug("Packet size " + packetsize[i]);

              // prepare for payload
              state[i] = PAYLOAD;

              // deletes original header flit from buffer
              read[i].send(0, new Token());

              // send the token to the remote output buffer
              output[dir].send(0, record);

              if (_debugging) _debug(inputreq[i] + " sent size token to " + output[dir]);

              txack[dir] = false;

            } else if (state[i] == PAYLOAD) {

              // send the token to the remote output buffer
              output[dir].send(0, inputreq[i].get(0));
              txack[dir] = false;

              // deletes original header flit from buffer
              read[i].send(0, new Token());
              if (_debugging) _debug(inputreq[i] + " sent token to " + output[dir]);

              packetsize[i]--;
              if (_debugging) _debug("packet size " + packetsize[i]);

              // if package is finished,
              // release output port and prepare for new header
              if (packetsize[i] == 0) {
                freeoutput[dir] = true;
                state[i] = REQUESTING;
                if (_debugging) _debug("packet is over");
              }
            }
          } // end if direction is free
          else {
            inputreq[i].get(0);
          }
        } // end if state
      } // end if width > 1
    } // end for

    if (clocked) {

      // fourth: requests write on all inputs with packet payload or size
      // and whose respective output ports received acks

      for (int i = 0; i < 5; i++) {
        if (state[i] == PAYLOAD | state[i] == SIZE) {
          if (txack[direction[i].intValue()]) peek[i].send(0, new Token());
        }
      }

      // fifth: requests write on remote buffers
      for (int i = 0; i < 5; i++) {
        // if(!txack[i]){
        outputtx[i].send(0, new Token());
        // }
        txack[i] = false; // consumes unused acks
      }

      // requests copy of request from all requesting input buffers

      for (int i = 0; i < 5; i++) {
        if (state[i] == REQUESTING) {
          peek[i].send(0, new Token());
          if (_debugging) {
            _debug("Peek for request on direction " + i);
          }
        }
      }

      clocked = false;
    }
  }
Example #19
0
  /**
   * If a new message is available at the inputs, record it in the list indexed with the time that
   * the message shall be completed, and loop through the list to check whether there is collision.
   * If the current time matches one of the times that we have previously recorded as the completion
   * time for a transmission, then output the received message to the <i>received</i> output port if
   * it is not lost to a collision; otherwise, output it to the <i>collided</i> output port.
   *
   * @exception IllegalActionException If an error occurs reading or writing inputs or outputs.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    Time currentTime = getDirector().getModelTime();

    if (_debugging) {
      _debug("---------------------------------");
      _debug("Current time is: " + currentTime);
    }

    if (message.hasToken(0) && power.hasToken(0) && duration.hasToken(0)) {
      double powerValue = ((DoubleToken) power.get(0)).doubleValue();

      if (_debugging) {
        _debug("Received message with power: " + powerValue);
      }

      if (powerValue < _powerThreshold) {
        // The signal it too weak to be detected, simply drop it.
        message.get(0);
        duration.get(0);

        if (_debugging) {
          _debug("Message power is below threshold. Ignoring.");
        }
      } else {
        // Record the reception.
        Reception reception = new Reception();
        reception.data = message.get(0);
        reception.power = powerValue;
        reception.arrivalTime = currentTime.getDoubleValue();
        reception.collided = false;
        reception.duration = ((DoubleToken) duration.get(0)).doubleValue();

        if (_debugging) {
          _debug("Message is above threshold and has duration: " + reception.duration);
        }

        // Update the total power density.
        _totalPower = _totalPower + reception.power;

        // Put the new reception into the list of prior receptions.
        Time time = currentTime.add(reception.duration);
        reception.expiration = time.getDoubleValue();

        _receptions.add(reception);

        // Schedule this actor to be fired at the end of
        // the duration of the message.
        _fireAt(time);
      }
    }

    // Loop through the prior receptions (and the new one)
    // to mark whether a message is collided according to the new total
    // power density. Also, any prior receptions that are now
    // expiring are sent to one of the two outputs.
    Iterator priorReceptions = _receptions.listIterator();

    while (priorReceptions.hasNext()) {
      Reception priorReception = (Reception) priorReceptions.next();

      if (_debugging) {
        _debug("Checking reception with arrival time: " + priorReception.arrivalTime);
      }

      // If the reception is now expiring, send it to one of the two
      // output ports.
      if (priorReception.expiration == currentTime.getDoubleValue()) {
        if (_debugging) {
          _debug(
              "Current time matches expiration "
                  + "time of a prior message that arrived at: "
                  + priorReception.arrivalTime);
        }

        // The time matches a pending reception.
        priorReceptions.remove();

        // Update the total power.
        _totalPower = _totalPower - priorReception.power;

        // Quantization errors may take this negative. Do not allow.
        if (_totalPower < 0.0) {
          _totalPower = 0.0;
        }

        if (!priorReception.collided) {
          received.send(0, priorReception.data);

          if (_debugging) {
            _debug("Message has been received: " + priorReception.data);
          }
        } else {
          collided.send(0, priorReception.data);

          if (_debugging) {
            _debug("Message has been lost: " + priorReception.data);
          }
        }

        continue;
      }

      // Check the snr to see whether to mark this prior reception
      // collided.
      double powerWithoutThisOne = _totalPower - priorReception.power;

      // Quantization errors may make this negative.
      if (powerWithoutThisOne < 0.0) {
        powerWithoutThisOne = 0.0;
      }

      double snr = priorReception.power / powerWithoutThisOne;

      if (!priorReception.collided && (snr <= _SNRThresholdInDB)) {
        priorReception.collided = true;

        if (_debugging) {
          _debug(
              "Message now has a collision. SNR is: " + snr + ". Total power is: " + _totalPower);
        }
      }
    }
  }
  /**
   * 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));
    }
  }
Example #21
0
  /**
   * Execute the filter model on each input array element until it gets as many elements as
   * specified by the <i>maxOutputLength</i> parameter. If there are no enough elements satisfying
   * the filter model, then only output all the satisfied elements. Before running the filter model,
   * this method update the filter model's <i>inputArrayElement</i> parameter for each array
   * element. After running the filter model, this method looks for the <i>evaluatedValue</i>
   * parameter and keep the input element if the evaluated value is ture, otherwise, skip the
   * element.
   *
   * @exception IllegalActionException If there is no director, or if the director's action methods
   *     throw it.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    if (_model instanceof CompositeActor) {
      CompositeActor executable = (CompositeActor) _model;

      _manager = executable.getManager();

      if (_manager == null) {
        throw new InternalErrorException("No manager!");
      }

      if (_debugging) {
        _manager.addDebugListener(this);

        Director director = executable.getDirector();

        if (director != null) {
          director.addDebugListener(this);
        }
      } else {
        _manager.removeDebugListener(this);

        Director director = executable.getDirector();

        if (director != null) {
          director.removeDebugListener(this);
        }
      }

      int i = 0;
      int j = 0;
      LinkedList list = new LinkedList();
      ArrayToken array = (ArrayToken) inputArray.get(0);

      while ((i < _outputLength) && (j < array.length())) {
        Token t = array.getElement(j);
        _updateParameter(t);

        if (_debugging) {
          _debug("** Executing filter model.");
        }

        try {
          _manager.execute();
        } catch (KernelException ex) {
          throw new IllegalActionException(this, ex, "Execution failed.");
        }

        if (_getResult()) {
          i++;
          list.add(t);
        }

        j++;
      }

      Token[] result = new Token[list.size()];

      for (i = 0; i < list.size(); i++) {
        result[i] = (Token) list.get(i);
      }

      outputArray.send(0, new ArrayToken(array.getElementType(), result));
    }
  }
Example #22
0
  /** Create and send the request, and send the response to the appropriate output ports. */
  public void fire() throws IllegalActionException {
    super.fire();

    _updateFilePortParameters();
    String commandLine = _makeCmd();
    if (commandLine == null) {
      log.error("Command line is null.");
      throw new IllegalActionException("Unable to built the command line.");
    }
    int cpuNumber = _getCpuNumber();

    // let's invoke the remote opal service
    JobInputType jobInputType = new JobInputType();
    jobInputType.setArgList(commandLine);
    if (cpuNumber != 0) {
      jobInputType.setNumProcs(new Integer(cpuNumber));
    }
    // preparing the input files
    InputFileType[] files = _getInputFiles();
    if (files != null) {
      log.info(files.length + " files have been submitted");
      String names = "";
      for (int i = 0; i < files.length; i++) names += files[i].getName() + " ";
      log.info("their names are: " + names);
      jobInputType.setInputFile(files);
    } else {
      log.info("No file has been submitted.");
    }

    // finally invoke opal service!
    JobSubOutputType subOut = null;
    AppServicePortType appServicePort = null;
    try {
      AppServiceLocator asl = new AppServiceLocator();
      appServicePort = asl.getAppServicePort(new java.net.URL(_appMetadata.getURL()));
      subOut = appServicePort.launchJob(jobInputType); // TODO check for null
      // Let's wait for the job to finish
      log.info("Job has been sumitted waiting for its completition: " + subOut.getJobID());
      StatusOutputType status = subOut.getStatus();
      int code = status.getCode();
      while (code != 4 && code != 8) {
        // sleep
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        status = appServicePort.queryStatus(subOut.getJobID());
        log.info(
            "Remote job status for job "
                + subOut.getJobID()
                + " from server is: "
                + status.getMessage());
        code = status.getCode();
      }
      if (code == 8) {
        // success
        JobOutputType out = null;
        out = appServicePort.getOutputs(subOut.getJobID());
        // send base Url
        baseUrl.send(0, new StringToken(status.getBaseURL().toString()));
        // send stdout and error
        output.send(0, new StringToken(out.getStdOut().toString()));
        output.send(0, new StringToken(out.getStdErr().toString()));
        OutputFileType[] outfiles = out.getOutputFile();
        if (outfiles != null) {
          for (int i = 0; i < outfiles.length; i++)
            output.send(0, new StringToken(outfiles[i].getUrl().toString()));
        } // if
      } else {
        // failure
        throw new IllegalActionException(
            "The exectuion of the OpalClient failed with the following error: "
                + status.getMessage()
                + "the application ID is "
                + status.getBaseURL());
      }
    } catch (FaultType e) {
      log.error("Remote exception in OpalClient: " + e.getMessage1(), e);
      throw new IllegalActionException(this, "Remote exception in OpalClient: " + e.getMessage1());
    } catch (RemoteException e) {
      log.error("Exception while invoking OpalClient: " + e.getMessage(), e);
      throw new IllegalActionException(
          this, "Excetion while invoking OpalClient: " + e.getMessage());
    } catch (java.net.MalformedURLException e) {
      log.error("Exception while invoking OpalClient: " + e.getMessage(), e);
      throw new IllegalActionException(
          this, "Excetion while invoking OpalClient: " + e.getMessage());
    } catch (javax.xml.rpc.ServiceException e) {
      log.error("Exception while invoking OpalClient: " + e.getMessage(), e);
      throw new IllegalActionException(
          this, "Excetion while invoking OpalClient: " + e.getMessage());
    }
  } // fire()
Example #23
0
  /**
   * If the input width is greater than zero and it has not already been done, start a thread to
   * read a token from the <i>release</i> input port and store it in the pool. Then, in the calling
   * thread, if there is at least one resource in the pool, write the first resource in the pool to
   * any <i>grant</i> output channel.
   *
   * @exception IllegalActionException If an error occurs during executing the process.
   * @exception TerminateProcessException If the process termination is requested by the director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    final RendezvousDirector director = (RendezvousDirector) getDirector();
    final Thread writeThread = Thread.currentThread();

    if (!(getDirector() instanceof RendezvousDirector)) {
      throw new IllegalActionException(
          this, "ResourcePool actor can only be used with RendezvousDirector.");
    }
    _postfireReturns = true;
    if (release.isOutsideConnected() && _readThread == null) {
      _readThread =
          new Thread(getFullName() + "_readThread") {
            public void run() {
              try {
                while (!_stopRequested) {
                  // Synchronize on the director since all read/write
                  // operations do.
                  synchronized (director) {
                    if (_debugging) {
                      _debug("Resources available: " + _pool);
                    }
                    Token resource =
                        RendezvousReceiver.getFromAny(release.getReceivers(), director);
                    _pool.add(resource);
                    director.threadUnblocked(writeThread, null);
                    director.notifyAll();
                  }
                }
              } catch (TerminateProcessException ex) {
                // OK, just exit
                _postfireReturns = false;
              } finally {
                director.removeThread(_readThread);
              }
            }
          };
      director.addThread(_readThread);
      _readThread.start();
    } else if (!release.isOutsideConnected() && _readThread != null) {
      // A mutation has eliminated the sources.
      _readThread.interrupt();
    }
    // Synchronize on the director since all read/write
    // operations do.
    synchronized (director) {
      while (_pool.size() == 0) {
        if (_stopRequested || !_postfireReturns) {
          _postfireReturns = false;
          return;
        }
        try {
          director.threadBlocked(writeThread, null);
          RendezvousReceiver.waitForChange(director);
        } catch (TerminateProcessException ex) {
          _postfireReturns = false;
          return;
        } finally {
          director.threadUnblocked(writeThread, null);
        }
      }
      // There is a token.
      Token token = (Token) _pool.get(0);
      // If this put blocks for any reason, it will block on
      // a director.wait(), so the lock will not be held.
      try {
        RendezvousReceiver.putToAny(token, grant.getRemoteReceivers(), director);
      } catch (TerminateProcessException e) {
        _postfireReturns = false;
        return;
      }
      _pool.remove(0);
    }
  }