Ejemplo n.º 1
0
  /**
   * If there is a new token on the <i>input</i> port, then put it on the FIFO.
   *
   * <p>If the queue is not empty, then send the oldest token on the queue to the <i>output</i>
   * port. Send the resulting FIFO size to the <i>size</i> output port.
   *
   * @exception IllegalActionException If getting tokens from input and read ports or sending token
   *     to output throws it.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    // sends copy of the oldest token to the output
    int comp = getDirector().getModelTime().compareTo(nextFlit);
    if (_queue.size() != 0 && (comp == 0 | comp == 1)) {
      output.send(0, (Token) _queue.get(0));
      if (_debugging) _debug("data sent at: " + getDirector().getModelTime());
    }

    // reads input port
    // stores token on the FIFO if there is room
    // sends ack or nack regarding the storage of the token
    if (input.hasToken(0)) {
      Token k = input.get(0);
      if (_queue.size() < _queue.getCapacity()) {
        _queue.put(k);
        ack.send(0, new BooleanToken(true));
      } else {
        ack.send(0, new BooleanToken(false));
      }
    }

    if (_queue.size() != 0) {
      // requests new firing after period
      nextFlit = getDirector().getModelTime();
      DoubleToken per = (DoubleToken) period.getToken();
      nextFlit = nextFlit.add(per.doubleValue());

      getDirector().fireAt(this, nextFlit);
    }

    // sends the FIFO size to the size port
    size.send(0, new IntToken(_queue.size()));
  }
Ejemplo n.º 2
0
 /**
  * Enqueue the token that is being sent and send to the parent whatever is at the end of the
  * queue.
  *
  * @param channelIndex The channel on which to send the token.
  * @param token The token to be sent.
  * @exception IllegalActionException If thrown while sending to the channel.
  * @exception NoRoomException If thrown while sending to the channel.
  */
 public void send(int channelIndex, Token token) throws IllegalActionException, NoRoomException {
   if (latency == 0) {
     super.send(channelIndex, token);
   } else {
     if (token != null) {
       myQueue.add(token);
       super.send(channelIndex, _oldToken);
       _oldToken = myQueue.removeFirst();
     }
   }
 }
Ejemplo n.º 3
0
  /**
   * If the mouse has moved, send the coordinates to the <i>x</i> and <i>y</i> ports. If mouse has
   * not moved, then no data is sent.
   *
   * @exception IllegalActionException If thrown while sending the data to the output ports.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    if (_hasData) {
      x.send(0, new IntToken(_xClicked));
      y.send(0, new IntToken(_yClicked));
      _hasData = false;

      // System.out.println("clicked location -> " + _xClicked
      // + " " + _yClicked);
    }
  }
Ejemplo n.º 4
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.º 5
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));
    }
  }
Ejemplo n.º 6
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.º 7
0
  // Dispatch the given task
  private void dispatchTask(RecordToken token) throws IllegalActionException {
    // IN:  comptime, id, releasetime, period, messagelength, destination
    // OUT: comptime, x, y, id, releasetime, period, messagelength

    // Get source and destination values
    int src = ((IntToken) token.get("id")).intValue();
    int dest = ((IntToken) token.get("destination")).intValue();

    // Replace destination with x and y coordinates
    String[] labels = {"comptime", "x", "y", "id", "releasetime", "period", "messagelength"};
    Token[] newTokens = {
      token.get("comptime"),
      new IntToken(MAPPING_X[dest]),
      new IntToken(MAPPING_Y[dest]),
      token.get("id"),
      token.get("releasetime"),
      token.get("period"),
      token.get("messagelength"),
    };

    RecordToken newToken = new RecordToken(labels, newTokens);

    // Forward to relevant publisher
    output.send(calcEndpointId(src), newToken);
  }
Ejemplo n.º 8
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.º 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
  /**
   * 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.º 11
0
 private void setChannel(int channel) throws IllegalActionException {
   waitTime = getDirector().getModelTime();
   System.out.println("SETTING CHANNEL: " + channel + " at " + waitTime);
   channelOutput.setTypeEquals(BaseType.INT);
   channelOutput.send(0, new IntToken(channel));
   currentChannel = channel;
 }
Ejemplo n.º 12
0
 private void handleFirstTX(SinkData channel, Time currentTime)
     throws NoRoomException, IllegalActionException {
   // Method to handle the third stage, transmitting the first packet to a sink
   IntToken token = new IntToken(currentChannel); // Create a token to send
   output.send(0, token); // Send the token
   if (channel.n
       != null) { // If we have already calculated n in a previous stage (if n is 1) we can skip
                  // straight to the next transmission period
     setNextFireTime(channel, currentTime.getDoubleValue() + (channel.t.getDoubleValue() * 12));
     channel.state = states.SECONDTX;
   } else { // If we do not know n then we need to next fire at the beginning of the next
            // synchronisation phase so we can receive the first pulse and find n
     setNextFireTime(
         channel, currentTime.getDoubleValue() + (channel.t.getDoubleValue() * 11) - 0.02);
     channel.state = states.NCALC;
   }
   System.out.println(
       "FIRSTTX on channel "
           + currentChannel
           + ". t is "
           + channel.t
           + ". nextFireTime is "
           + channel.nextFireTime
           + " currentTime is "
           + currentTime);
 }
Ejemplo n.º 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
Ejemplo n.º 14
0
  /**
   * According to an arbitration scheme, peeks the It also requests write permission on file.
   * * @exception IllegalActionException If there is no director.
   */
  public boolean prefire() throws IllegalActionException {

    // reads rx signal, if available an state is selected

    if (data_in.getWidth() > 0) {
      // boolean ata_token = data_in.hasToken(0);
      // data_token = data_in.hasToken(0);
      if (state == RECEIVING_ADD) {
        accept = BooleanToken.TRUE;
        ack.send(0, accept);
      } else if (state == RECEIVING_SIZE) {
        accept = BooleanToken.TRUE;
        ack.send(0, accept);
      } else if (state == SENDING) {
        accept = BooleanToken.TRUE;
        ack.send(0, accept);
      }
    }
    return true;
  }
Ejemplo n.º 15
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.º 16
0
 private void handleSecondTX(SinkData channel, Time currentTime) throws IllegalActionException {
   IntToken token = new IntToken(currentChannel);
   output.send(0, token);
   channel.state = states.FINISHED;
   System.out.println(
       "SECONDTX on channel "
           + currentChannel
           + ". t is "
           + channel.t
           + " currentTime is "
           + currentTime);
   System.out.println(channelQueue.toString());
 }
Ejemplo n.º 17
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.º 18
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.º 19
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.º 20
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.º 21
0
  /**
   * State machine responsable by receiving the traffic from the input port, disassembly the package
   * and send its flits to the output ports (file). If the input does not have a token, suspend
   * firing and return.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    accept = BooleanToken.FALSE;

    // **************Receiving file**************************** //
    if (state == RECEIVING_ADD) {
      if (data_in.hasToken(0)) {

        cont = 0;
        // get the timestamp of the first flit received from the NoC
        timestamp_ff = (int) getDirector().getCurrentTime();
        // timestap_f_flit = timestamp_ff;

        // get the xy adress
        record = ((RecordToken) data_in.get(0));
        x = ((IntToken) record.get("x")).intValue();
        y = ((IntToken) record.get("y")).intValue();
        s_xy = (Integer.toString(x)) + (Integer.toString(y));
        for (int i = s_xy.length(); i < 4; i++) s_xy = "0" + s_xy;

        printFlit(s_xy);

        debug.send(
            0,
            new StringToken("RECEIVING_ADD " + s_xy + " AT TIME: " + getDirector().getModelTime()));

        // set new state
        state = RECEIVING_SIZE;
      } else {
        state = RECEIVING_ADD;
      }
    } // end if RECEIVING_ADD

    if (state == RECEIVING_SIZE) {

      if (data_in.hasToken(0)) {

        record = ((RecordToken) data_in.get(0));
        size = ((IntToken) record.get("size")).intValue();
        size_s = (Integer.toHexString(size).toUpperCase());
        for (int i = size_s.length(); i < 4; i++) size_s = "0" + size_s;
        cont++;
        printFlit(size_s);

        debug.send(
            0,
            new StringToken(
                "RECEIVING_SIZE " + size + " AT TIME: " + getDirector().getModelTime()));
        state = SENDING;
        cont = 0;
      } else {
        state = RECEIVING_SIZE;
      }
    } // end if RECEIVING_ADD
    else if (state == SENDING) {
      debug.send(0, new StringToken("SENDING "));
      if (data_in.hasToken(0)) {
        record = ((RecordToken) data_in.get(0));
        payload = ((IntToken) record.get("payload")).intValue();
        payload_s = (Integer.toHexString(payload).toUpperCase());
        for (int i = payload_s.length(); i < 4; i++) payload_s = "0" + payload_s;

        cont++;
        if (cont != size) {
          debug.send(
              0,
              new StringToken(
                  "payload_s " + payload + " AT TIME: " + getDirector().getModelTime()));
          printFlit(payload_s);
          state = SENDING;
        } else {
          printFlit(payload_s);
          timestamp_ini = ((IntToken) record.get("timestamp_ini")).intValue();
          timestamp_rede = ((IntToken) record.get("timestamp_sent")).intValue();

          // timestamp of the last flit of the packet
          timestamp_lf = (int) getDirector().getCurrentTime();

          int latency = timestamp_lf - timestamp_rede;

          double ini_simulation_time = ((DoubleToken) record.get("simulation_time")).doubleValue();
          double simu = (new java.util.Date()).getTime();
          simulation_time = (int) ((simu - ini_simulation_time) / 1000);

          debug.send(0, new StringToken("foi "));

          data_out.send(
              0,
              new StringToken(
                  readOutput_file()
                      + timestamp_ini
                      + " "
                      + timestamp_rede
                      + " "
                      + timestamp_lf
                      + " "
                      + latency
                      + " "
                      + simulation_time));
          state = RECEIVING_ADD;
          // wrapup();
        }
      } else {
        state = SENDING;
      }
    }
  } // end public
Ejemplo n.º 22
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.º 23
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()
Ejemplo n.º 24
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);
        }
      }
    }
  }
Ejemplo n.º 25
0
 /**
  * Set up the scene graph connections of this actor.
  *
  * @exception IllegalActionException Always thrown for this base class.
  */
 @Override
 protected void _makeSceneGraphConnection() throws IllegalActionException {
   sceneGraphOut.send(0, new Scene2DToken(_figure));
 }
Ejemplo n.º 26
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));
    }
  }
Ejemplo n.º 27
0
 /**
  * Resend the token from the given channel index.
  *
  * @param channelIndex The given channel index.
  * @exception IllegalActionException If super class throws it.
  * @exception NoRoomException If super class throws it.
  */
 public void resend(int channelIndex) throws IllegalActionException, NoRoomException {
   if (latency != 0) {
     super.send(channelIndex, _oldToken);
   }
 }