Ejemplo n.º 1
0
  /**
   * Executes the code in this actor. This actor uses a CDO construct when it is waiting to be used
   * by either of the philosophers next to it. Once one of the philosophers is using it, this actor
   * waits to receive a message that the philosopher is finished eating (using it). It is a good
   * example of using a CDO. This process continues executing until a TerminateProcessException is
   * thrown.
   *
   * @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();
    try {
      boolean guard = true;
      boolean continueCDO = true;
      ConditionalBranch[] branches = new ConditionalBranch[2];
      Token t = new IntToken(0);

      while (continueCDO) {
        // step 1
        branches[0] = new ConditionalSend(guard, leftOut, 0, 0, t);
        branches[1] = new ConditionalSend(guard, rightOut, 0, 1, t);

        // step 2
        int successfulBranch = chooseBranch(branches);

        // step 3
        if (successfulBranch == 0) {
          // Wait for philosopher on left to finish eating.
          leftIn.get(0);
        } else if (successfulBranch == 1) {
          // Wait for philosopher on right to finish eating.
          rightIn.get(0);
        } else if (successfulBranch == -1) {
          // all guards false so exit CDO
          continueCDO = false;
        } else {
          throw new IllegalActionException(
              getName() + ": " + "invalid branch id returned during execution " + "of CDO.");
        }
      }
    } catch (NoTokenException ex) {
      throw new IllegalActionException(getName() + ": cannot " + "get token.");
    }
  }
Ejemplo n.º 2
0
  /**
   * Apply the current scaling transformation to the figure.
   *
   * @param figure The figure the transformation is to be applied to.
   * @exception IllegalActionException If the getToken() method throws such an exception.
   */
  protected void _applyTransform(Figure figure) throws IllegalActionException {
    double scaleFactorXValue = 1.0;
    double scaleFactorYValue = 1.0;

    boolean needsTransform = false;

    if ((scaleFactorX.isOutsideConnected()) && scaleFactorX.hasToken(0)) {
      scaleFactorXValue = ((DoubleToken) scaleFactorX.get(0)).doubleValue();
      needsTransform = true;
    }

    if ((scaleFactorY.isOutsideConnected()) && scaleFactorY.hasToken(0)) {
      scaleFactorYValue = ((DoubleToken) scaleFactorY.get(0)).doubleValue();
      needsTransform = true;
    }

    if (needsTransform) {
      if (_isAccumulating()) {
        scaleFactorXValue *= _oldScaleFactorX;
        scaleFactorYValue *= _oldScaleFactorY;
      }

      _oldScaleFactorX = scaleFactorXValue;
      _oldScaleFactorY = scaleFactorYValue;

      AffineTransform inputTransform =
          AffineTransform.getScaleInstance(scaleFactorXValue, scaleFactorYValue);

      figure.transform(inputTransform);
    }
  }
Ejemplo n.º 3
0
  /**
   * If this firing is triggered by an event at <i>waitee</i>, then output the waiting time for each
   * prior event arrival at <i>waiter</i> since the last arrival of waitee. If there is no event at
   * <i>waitee</i>, then record the time of arrival of the events at <i>waiter</i>, and produce no
   * output.
   *
   * @exception IllegalActionException If get() or send() throws it.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Time currentTime = ((DEDirector) getDirector()).getModelTime();

    while (waiter.hasToken(0)) {
      waiter.get(0);
      _waiting.addElement(currentTime);
    }

    boolean godot = false;

    while (waitee.hasToken(0)) {
      waitee.get(0);
      godot = true;
    }

    if (godot) {
      for (int i = 0; i < _waiting.size(); i++) {
        Time previousTime = (Time) _waiting.elementAt(i);
        DoubleToken outToken = new DoubleToken(currentTime.subtract(previousTime).getDoubleValue());
        output.send(0, outToken);
      }

      _waiting.removeAllElements();
    }
  }
Ejemplo n.º 4
0
  /**
   * 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());
    }
  }
Ejemplo n.º 5
0
  /**
   * 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));
  }
Ejemplo n.º 6
0
 private void handleNCalc(SinkData channel, Time currentTime)
     throws NoTokenException, IllegalActionException {
   // Method to handle the fourth stage, where we listen to the first synchronisation pulse to find
   // the value of n
   System.out.println(channel.nextFireTime.getDoubleValue() >= currentTime.getDoubleValue() + 0.4);
   if (channel.nextFireTime.getDoubleValue() >= currentTime.getDoubleValue()) {
     input.get(0);
     return;
   } else if (channel
       .secondRun) { // If we are on the second run through, we have already transmitted twice so
                     // we can stop here
     channel.state = states.FINISHED;
     return;
   } else if (currentTime.subtract(channel.nextFireTime).getDoubleValue()
       > 2) { // There is a large delta between when we were supposed to fire and when we fired, so
              // we probably have a collision with another channel
     channel.secondRun = true; // Store that we will need to go around again for this channel
     channel.state = states.FIRSTRX; // Set the stage back to the beginning so we can restart
     System.out.println(
         "NCALC on channel "
             + currentChannel
             + " n is: "
             + channel.n
             + ". t is "
             + channel.t
             + ". nextFireTime is "
             + channel.nextFireTime
             + " currentTime is "
             + currentTime);
     nextChannel(currentChannel, currentTime);
   } else {
     channel.n = ((IntToken) input.get(0)).intValue();
     setNextFireTime(
         channel, currentTime.getDoubleValue() + (channel.t.getDoubleValue() * channel.n));
     channel.state = states.SECONDTX;
     System.out.println(
         "NCALC on channel "
             + currentChannel
             + " n is: "
             + channel.n
             + ". t is "
             + channel.t
             + ". nextFireTime is "
             + channel.nextFireTime
             + " currentTime is "
             + currentTime);
     nextChannel(currentChannel, currentTime);
     removeFromQueue(currentChannel);
   }
 }
Ejemplo n.º 7
0
 private void handleFirstRX(SinkData channel, Time currentTime)
     throws NoTokenException, IllegalActionException {
   // Method to handle the first stage, receiving the first synchronisation pulse
   IntToken token = (IntToken) input.get(0); // Retrieve the token from the input
   Time timeDelta =
       currentTime.subtract(
           waitTime); // Calculate a delta between the current time and when the channel was
                      // changed, to find the waiting time
   if (timeDelta.getDoubleValue() <= 1.5
       && token.equals(
           1)) { // Token is 1, and we have been waiting for longer than 1.5s. So we will not have
                 // a follow-up token, so can't be used for determining t
     channelQueue
         .remove(); // Send the current channel to the back of the queue so we can do something
                    // useful while it is in its sleep state
     channelQueue.add(currentChannel);
     return;
   }
   if (!channel
       .secondRun) { // If this is the first time we have received packets on the channel we will
                     // need the current time to calculate a t
     channel.t = currentTime;
   }
   channel.state = states.SECONDRX; // Set the channel state to the next stage
   channel.firstValue = token.intValue(); // Store the value we have received
   System.out.println("FIRSTRX on channel " + currentChannel + " currentTime is " + currentTime);
 }
Ejemplo n.º 8
0
 /**
  * Get the current value of the derivative input port.
  *
  * @return The current value at the derivative input port.
  * @exception NoTokenException If reading the input throws it.
  * @exception IllegalActionException If thrown while reading the input.
  */
 public double getDerivative() throws NoTokenException, IllegalActionException {
   double result = ((DoubleToken) derivative.get(0)).doubleValue();
   if (_debugging) {
     _debug("Read input: " + result);
   }
   return result;
 }
Ejemplo n.º 9
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);
      }
    }
  }
Ejemplo n.º 10
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);
  }
Ejemplo n.º 11
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);
        }
      }
    }
  }
Ejemplo n.º 12
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);
    }
  }
Ejemplo n.º 13
0
  public void fire() throws IllegalActionException {
    ObjectToken obj = (ObjectToken) lsp_old.get(0);
    Short[] arg1 = (Short[]) obj.getValue();

    obj = (ObjectToken) lsp_mid.get(0);
    Short[] arg2 = (Short[]) obj.getValue();

    obj = (ObjectToken) lsp_new.get(0);
    Short[] arg3 = (Short[]) obj.getValue();

    Short[] arg4 = new Short[Cnst.MP1 * 4];

    _int_lpc2(arg1, arg2, arg3, arg4);

    obj = new ObjectToken(arg4);
    A.broadcast(obj);
  }
Ejemplo n.º 14
0
  /**
   * 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);
  }
Ejemplo n.º 15
0
  public void fire() throws IllegalActionException {

    // reads all queue updates
    for (int i = 0; i < nqueues; i++) {

      if (queueUpdate.hasToken(i)) {

        IntToken queuedTasks = (IntToken) queueUpdate.get(i);
        queues[i] = queuedTasks.intValue();
      }
    }

    // sends new task, if any, to the queue with the shortest queue
    if (input.hasToken(0)) {

      output.send(this.getShortestQueue(), input.get(0));
    }
  }
Ejemplo n.º 16
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);
    }
  }
Ejemplo n.º 17
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;
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * Consumes packet header Consumes clock token Checks for buffers requesting arbitration
   *
   * @exception IllegalActionException If there is no director.
   */
  public boolean prefire() throws IllegalActionException {
    super.prefire();

    // reads clock signal, if available

    if (wakeup.hasToken(0)) {
      wakeup.get(0);
      clocked = true;
    }

    return true;
  }
Ejemplo n.º 19
0
  /**
   * If the parameter print is true, print the last consumed token to the stdout.
   *
   * @return true always.
   * @exception IllegalActionException If no token available.
   */
  public boolean postfire() throws IllegalActionException {
    _debug(getName() + " postfire.");
    _lastToken = input.get(0);

    if (((BooleanToken) print.getToken()).booleanValue()) {
      Director dir = getDirector();

      if (dir != null) {
        System.out.println(dir.getModelTime() + " " + ((DoubleToken) _lastToken).doubleValue());
      }
    }

    return true;
  }
Ejemplo n.º 20
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"));
      }
    }
  }
Ejemplo n.º 21
0
  /**
   * Add the key to the keystore.
   *
   * @exception IllegalActionException If there's no director, if there are problems setting the
   *     key.
   */
  public boolean postfire() throws IllegalActionException {
    // See io.LineWriter for an example of an actor that writes to a file.
    if (input.hasToken(0)) {
      KeyToken keyToken = (KeyToken) input.get(0);
      java.security.Key key = keyToken.getValue();

      if (key instanceof java.security.PrivateKey) {
        throw new IllegalActionException(
            this,
            "Key is a PrivateKey, which is not supported because " + "it requires a certificate");
      }

      // Now we add the key to the keystore, protected
      // by the password.
      try {
        _keyStore.setKeyEntry(_alias, key, _keyPassword.toCharArray(), null /* No certificate */);
      } catch (Exception ex) {
        throw new IllegalActionException(
            this, ex, "Failed to set key '" + key + "' to alias '" + alias + "'");
      }

      try {
        FileOutputStream keyStoreOutputStream = null;

        try {
          keyStoreOutputStream = new FileOutputStream(fileOrURL.asFile());
          _keyStore.store(keyStoreOutputStream, _storePassword.toCharArray());
          keyStoreOutputStream.close();
        } finally {
          try {
            if (keyStoreOutputStream != null) {
              keyStoreOutputStream.close();
            }
          } catch (Throwable throwable) {
            System.out.println("Ignoring failure to close stream " + "on " + fileOrURL.asFile());
            throwable.printStackTrace();
          }
        }

        output.broadcast(BooleanToken.TRUE);
      } catch (Throwable throwable) {
        throw new IllegalActionException(
            this, throwable, "Failed to store " + fileOrURLDescription());
      }
    }

    return super.postfire();
  }
Ejemplo n.º 22
0
 /**
  * If the <i>enable</i> input is not known, then return false; if the <i>enable</i> input is known
  * and either absent or false, then also return false; if it is known and true, then invoke the
  * prefire() method of the superclass and return what it returns.
  *
  * @exception IllegalActionException If the superclass throws it.
  */
 public boolean prefire() throws IllegalActionException {
   boolean prefireReturnValue = false;
   if (enable.isKnown(0)) {
     if (enable.hasToken(0)) {
       prefireReturnValue = ((BooleanToken) enable.get(0)).booleanValue();
       if (prefireReturnValue) {
         // This will call prefire() on the contained director.
         prefireReturnValue = super.prefire();
       }
     }
   }
   if (_debugging) {
     _debug("EnabledComposite: prefire() returns " + prefireReturnValue);
   }
   return prefireReturnValue;
 }
Ejemplo n.º 23
0
  /**
   * If there is no input on the <i>trigger</i> port, return false, indicating that this actor does
   * not want to fire. This has the effect of leaving input values in the input ports, if there are
   * any.
   *
   * @exception IllegalActionException If there is no director.
   */
  public boolean prefire() throws IllegalActionException {

    boolean hasReadTrigger = false;

    if (read.getWidth() > 0) {
      hasReadTrigger = (read.hasToken(0));
    }

    // if read notification is received, remove the oldest token
    // from the queue
    if (hasReadTrigger) {
      // Consume the trigger token.
      read.get(0);
      _queue.take();
    }

    return true;
  }
Ejemplo n.º 24
0
  public void fire() throws IllegalActionException {

    ObjectToken ot = (ObjectToken) input.get(0);
    MuxDataFrame mf = (MuxDataFrame) ot.getValue();
    int b;

    if (_frameCounter == 0) {
      b = _processFast(mf.getFastByte());
      mf.setFastByte(b);

      if (!_LS0Map) {
        for (int i = 0; i < _LS0Bytes; i++) {
          b = _processFast(mf.getLS0Byte(i));
          mf.setLS0Byte(b, i);
        }
      }

      if (mf.hasLEX()) {
        b = _processFast(mf.getLEXByte());
        mf.setLEXByte(b);
      }
    } else {
      b = _processInter(mf.getFastByte());
      mf.setFastByte(b);

      if (_LS0Map) {
        for (int i = 0; i < _LS0Bytes; i++) {
          b = _processInter(mf.getLS0Byte(i));
          mf.setLS0Byte(b, i);
        }
      }

      if (mf.hasLEX()) {
        b = _processInter(mf.getLEXByte());
        mf.setLEXByte(b);
      }
    }
    _frameCounter++;
    if (_frameCounter == 1 + _S) _frameCounter = 0;

    ot = new ObjectToken(mf);
    output.broadcast(ot);
  }
Ejemplo n.º 25
0
 private void handleSecondRX(SinkData channel, Time currentTime)
     throws NoTokenException, IllegalActionException {
   // Method to handle the second stage, receiving the second synchronisation pulse
   if (!channel
       .secondRun) { // If this is the second time we have received packets on the channel we
                     // already have t so no need to calculate it
     channel.t = currentTime.subtract(channel.t);
   }
   int currentValue = ((IntToken) input.get(0)).intValue(); // Retrieve the value from the input
   if (channel.firstValue == 1 && currentValue == 1) { // If the first two values are 1 then n is 1
     channel.n = 1;
     channel.t =
         new Time(getDirector())
             .add(
                 channel.t.getDoubleValue()
                     / 12); // Calculate t given that n is 1, i.e divide the period by 12 as per
                            // the protocol
   }
   setNextFireTime(
       channel,
       currentTime.getDoubleValue()
           + (channel.t.getDoubleValue()
               * currentValue)); // Manually set the next fire time for this channel
   channel.state = states.FIRSTTX; // Set the channel state to the next stage
   System.out.println(
       "SECONDRX on channel "
           + currentChannel
           + ". Current value is "
           + currentValue
           + ". t is "
           + channel.t
           + ". nextFireTime is "
           + channel.nextFireTime
           + " currentTime is "
           + currentTime);
   nextChannel(currentChannel, currentTime);
   removeFromQueue(currentChannel); // We can now move onto listening on the next channel
 }
Ejemplo n.º 26
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);
    }
  }
Ejemplo n.º 27
0
  /**
   * Read at most one token from the input port and issue a change request to update variables as
   * indicated by the input.
   *
   * @exception IllegalActionException If thrown reading the input.
   */
  public boolean postfire() throws IllegalActionException {
    if (input.hasToken(0)) {
      final Token value = input.get(0);

      if (delayed.getToken().equals(BooleanToken.TRUE)) {
        ChangeRequest request =
            new ChangeRequest(this, "SetVariable change request") {
              protected void _execute() throws IllegalActionException {
                _setValue(value);
              }
            };

        // To prevent prompting for saving the model, mark this
        // change as non-persistent.
        request.setPersistent(false);
        request.addChangeListener(this);
        requestChange(request);
      } else {
        _setValue(value);
      }
    }

    return true;
  }
Ejemplo n.º 28
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));
    }
  }
Ejemplo n.º 29
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.º 30
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));
    }
  }