コード例 #1
1
ファイル: JavaLineStyler.java プロジェクト: abego/java2script
 /**
  * Event.detail line start offset (input) Event.text line text (input) LineStyleEvent.styles
  * Enumeration of StyleRanges, need to be in order. (output) LineStyleEvent.background line
  * background color (output)
  */
 public void lineGetStyle(LineStyleEvent event) {
   Vector styles = new Vector();
   int token;
   StyleRange lastStyle;
   // If the line is part of a block comment, create one style for the entire line.
   if (inBlockComment(event.lineOffset, event.lineOffset + event.lineText.length())) {
     styles.addElement(
         new StyleRange(event.lineOffset, event.lineText.length(), getColor(COMMENT), null));
     event.styles = new StyleRange[styles.size()];
     styles.copyInto(event.styles);
     return;
   }
   Color defaultFgColor = ((Control) event.widget).getForeground();
   scanner.setRange(event.lineText);
   token = scanner.nextToken();
   while (token != EOF) {
     if (token == OTHER) {
       // do nothing for non-colored tokens
     } else if (token != WHITE) {
       Color color = getColor(token);
       // Only create a style if the token color is different than the
       // widget's default foreground color and the token's style is not
       // bold.  Keywords are bolded.
       if ((!color.equals(defaultFgColor)) || (token == KEY)) {
         StyleRange style =
             new StyleRange(
                 scanner.getStartOffset() + event.lineOffset, scanner.getLength(), color, null);
         if (token == KEY) {
           style.fontStyle = SWT.BOLD;
         }
         if (styles.isEmpty()) {
           styles.addElement(style);
         } else {
           // Merge similar styles.  Doing so will improve performance.
           lastStyle = (StyleRange) styles.lastElement();
           if (lastStyle.similarTo(style) && (lastStyle.start + lastStyle.length == style.start)) {
             lastStyle.length += style.length;
           } else {
             styles.addElement(style);
           }
         }
       }
     } else if ((!styles.isEmpty())
         && ((lastStyle = (StyleRange) styles.lastElement()).fontStyle == SWT.BOLD)) {
       int start = scanner.getStartOffset() + event.lineOffset;
       lastStyle = (StyleRange) styles.lastElement();
       // A font style of SWT.BOLD implies that the last style
       // represents a java keyword.
       if (lastStyle.start + lastStyle.length == start) {
         // Have the white space take on the style before it to
         // minimize the number of style ranges created and the
         // number of font style changes during rendering.
         lastStyle.length += scanner.getLength();
       }
     }
     token = scanner.nextToken();
   }
   event.styles = new StyleRange[styles.size()];
   styles.copyInto(event.styles);
 }
コード例 #2
0
 public Vector getParentInterfaceNames() {
   if (parentInterfaceNames.isEmpty() && !parentInterfaces.isEmpty()) {
     for (int i = 0; i < parentInterfaces.size(); i++) {
       parentInterfaceNames.addElement(((Class) parentInterfaces.elementAt(i)).getName());
     }
   }
   return parentInterfaceNames;
 }
コード例 #3
0
ファイル: Whotrules.java プロジェクト: franko4don/programs
 public static int rules(
     String top, Vector<String> first, Vector<String> second, Vector<String> afia) {
   while (!first.isEmpty() && !second.isEmpty()) {
     if (count % 2 == 0) {
       boolean check = false;
       for (int i = 0; i < first.size(); i++) {
         check =
             matcher(
                 top,
                 first.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(first.elementAt(i));
           first.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         first.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     } else {
       boolean check = false;
       for (int i = 0; i < second.size(); i++) {
         check =
             matcher(
                 top,
                 second.elementAt(
                     i)); // performs a linear search on player1's whot to see if any matches the
         // top card
         if (check == true) {
           place.addElement(second.elementAt(i));
           second.removeElementAt(i);
           break;
         }
       }
       if (check == false) {
         Random rd = new Random();
         int pick = Math.abs(rd.nextInt(afia.size() - 1)) % (afia.size() - 1);
         second.addElement(afia.elementAt(pick));
         afia.removeElementAt(pick);
       }
     }
   }
   return 1;
 }
コード例 #4
0
  /** Creates a new instance of AccountPicker */
  public AccountSelect(Display display, boolean enableQuit) {
    super();
    // this.display=display;

    setTitleItem(new Title(SR.MS_ACCOUNTS));

    accountList = new Vector();
    Account a;

    int index = 0;
    activeAccount = Config.getInstance().accountIndex;
    do {
      a = Account.createFromStorage(index);
      if (a != null) {
        accountList.addElement(a);
        a.active = (activeAccount == index);
        index++;
      }
    } while (a != null);
    if (accountList.isEmpty()) {
      a = Account.createFromJad();
      if (a != null) {
        // a.updateJidCache();
        accountList.addElement(a);
        rmsUpdate();
      }
    }
    attachDisplay(display);
    addCommand(cmdAdd);

    if (enableQuit) addCommand(cmdQuit);

    commandState();
    setCommandListener(this);
  }
コード例 #5
0
ファイル: ScoreParser.java プロジェクト: emtwo/piano
  // ParserListener methods
  public void noteEvent(Note note) {
    if (layer >= staves) {
      return;
    }
    // System.out.println(note.getMusicString() + " " + note.getMillisDuration() + " " +
    // note.getDecimalDuration());
    Vector<Chord> currChords = chords[layer];
    Iterator<NotePanel> currNote = currNotes[layer];

    if (!currNote.hasNext()) {
      System.err.println("Received noteEvent, but no PostScript notes are left");
      return;
    }

    if (note.getMillisDuration() > 0) {
      NotePanel notePanel = currNote.next();
      // time the last chord ended
      long tempTime = 0;
      for (int i = currChords.size() - 1; i >= 0; --i) {
        if (!currChords.get(i).isTie()) {
          tempTime = currChords.get(i).getTime() + currChords.get(i).getDuration();
          break;
        }
      }

      if (notePanel.isTie) {
        Chord chord = new Chord();
        // for each note in the last chord, set the next note as a tied note
        for (int i = 0; i < currChords.lastElement().size(); ++i) {
          notePanel.setTie(true).setTime(Math.min(tempTime, time - 1)).setTempo(tempo);
          chord.addNote(notePanel);
          notePanel = currNote.next();
        }
        currChords.add(chord);
      }

      while (notePanel.isRest) {
        notePanel
            .setTime(Math.min(tempTime, time - 1)) // hack, in case the rest should be trimmed
            .setTempo(tempo);
        tempTime += notePanel.getDuration();
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
        // System.out.println("REST: " + notePanel.getMusicString() + " " +
        // notePanel.getDuration());
        notePanel = currNote.next();
      }

      notePanel.setNote(note).setTime(time).setTempo(tempo);
      if (currChords.isEmpty() || currChords.lastElement().getTime() != time) {
        Chord chord = new Chord(notePanel);
        currChords.add(chord);
      } else {
        currChords.lastElement().addNote(notePanel);
      }
    }
  }
コード例 #6
0
ファイル: WMLCompositor.java プロジェクト: iwoj/Maui
  /**
   * This method takes care of some special generic Maui events. It should be called before the Maui
   * application handles the event.
   *
   * @param mauiApp Reference to the MauiApplication associated with the events
   * @param eventVector The same event vector that is passed to the Maui app.
   * @param paramHash Hashtable of HTTP parameters
   * @param response The HTTPResponse object which will be sent back to the client
   */
  private void processEvent(
      MauiApplication mauiApp,
      Vector eventVector,
      Hashtable paramHash,
      HTTPRequest request,
      HTTPResponse response) {
    boolean passEventToMauiApp = true;

    try {
      if (eventVector != null && !eventVector.isEmpty()) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Component events
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        String componentID = (String) eventVector.lastElement();

        // If there are parentheses...
        if (componentID.startsWith("(") && componentID.endsWith(")")) {
          // ... strip them off!
          componentID = componentID.substring(1, componentID.length() - 1);
        }

        //
        //	Strip off prefix - some wml browsers don't like variables that begin with a digit
        //
        if (componentID.startsWith("IDz")) {
          componentID = componentID.substring(3);
        }
        {
          System.err.println("componentID: " + componentID);
        }

        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // Pass events to Maui application
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        // Check for a content-type override
        String contentType = null;
        {
          if ((contentType = request.getQueryValue("contentType")) != null) {
            response.setContentType(contentType);
          } else {
            response.setContentType("x-wap.wml");
          }
        }
        response.setContent(mauiApp.render().getBytes());
      } else {
        response.setContentType("text/vnd.wap.wml");
        response.setContent(mauiApp.render().getBytes());
      }
    } catch (Exception e) {
      response.setContentType(getBaseContentType());
      response.setContent((generateExceptionMessage(e)).getBytes());
      e.printStackTrace(System.err);
    }
  }
コード例 #7
0
  /** Append the string containing the SQL insert string for the given table. */
  protected SQLCall buildCallWithoutReturning(AbstractSession session) {
    SQLCall call = new SQLCall();
    call.returnNothing();

    Writer writer = new CharArrayWriter(200);
    try {
      writer.write("INSERT ");
      if (getHintString() != null) {
        writer.write(getHintString());
        writer.write(" ");
      }
      writer.write("INTO ");
      writer.write(getTable().getQualifiedNameDelimited(session.getPlatform()));
      writer.write(" (");

      Vector fieldsForTable = new Vector();
      for (Enumeration fieldsEnum = getModifyRow().keys(); fieldsEnum.hasMoreElements(); ) {
        DatabaseField field = (DatabaseField) fieldsEnum.nextElement();
        if (field.getTable().equals(getTable()) || (!field.hasTableName())) {
          fieldsForTable.addElement(field);
        }
      }

      if (fieldsForTable.isEmpty()) {
        throw QueryException.objectToInsertIsEmpty(getTable());
      }

      for (int i = 0; i < fieldsForTable.size(); i++) {
        writer.write(
            ((DatabaseField) fieldsForTable.elementAt(i)).getNameDelimited(session.getPlatform()));
        if ((i + 1) < fieldsForTable.size()) {
          writer.write(", ");
        }
      }
      writer.write(") VALUES (");

      for (int i = 0; i < fieldsForTable.size(); i++) {
        DatabaseField field = (DatabaseField) fieldsForTable.elementAt(i);
        call.appendModify(writer, field);
        if ((i + 1) < fieldsForTable.size()) {
          writer.write(", ");
        }
      }
      writer.write(")");

      call.setSQLString(writer.toString());
    } catch (IOException exception) {
      throw ValidationException.fileError(exception);
    }
    return call;
  }
コード例 #8
0
ファイル: PeerWriter.java プロジェクト: marcpawl/vassal
 private synchronized String getLine() {
   while (isOpen && zLines.isEmpty()) {
     try {
       wait(pingInterval);
     } catch (InterruptedException e) {
     }
   }
   String message = isOpen ? "" : null;
   if (isOpen && zLines.size() > 0) {
     message = (String) zLines.elementAt(0);
     zLines.removeElementAt(0);
   }
   return message;
 }
コード例 #9
0
 void commandState() {
   if (accountList.isEmpty()) {
     removeCommand(cmdEdit);
     removeCommand(cmdDel);
     removeCommand(cmdSelect);
     removeCommand(cmdLogin);
     removeCommand(cmdCancel);
   } else {
     addCommand(cmdEdit);
     addCommand(cmdDel);
     addCommand(cmdLogin);
     addCommand(cmdSelect);
     if (activeAccount >= 0) addCommand(cmdCancel); // нельзя выйти без активного аккаунта
   }
 }
コード例 #10
0
 /**
  * Adds the sequence with name <tt>name</tt> and sequence <tt>gas</tt> to the alignment.
  *
  * @param name The name of the sequence to be added
  * @param gas The sequence as a <tt>GappedAlignmentString</tt>
  * @see GappedAlignmentString
  */
 public void addGappedAlignment(String name, GappedAlignmentString gas) {
   if (ordering.isEmpty()) {
     gappedLength = gas.gappedLength();
   } else {
     if (gas.gappedLength() != gappedLength) {
       throw new IllegalArgumentException(
           String.format("Gapped Length %d doesn't match.", gas.gappedLength()));
     }
     if (ordering.contains(name)) {
       throw new IllegalArgumentException(String.format("Duplicate name: %s", name));
     }
   }
   ordering.add(name);
   gappedAlignments.put(name, gas);
 }
コード例 #11
0
ファイル: JSR82Channel.java プロジェクト: elayman/EE149
 /** @see javax.bluetooth.L2CAPConnection#receive(byte[]) */
 public int receive(byte[] inBuf) throws IOException {
   while (incommingPackets.isEmpty()) {
     if (channelState == CLOSED) throw new IOException("L2CAP Channel is closed.");
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
     }
   }
   byte[] packet = (byte[]) incommingPackets.elementAt(0);
   if (packet != null) {
     incommingPackets.removeElementAt(0);
     int length = inBuf.length;
     if (packet.length < length) length = packet.length;
     System.arraycopy(packet, 0, inBuf, 0, length);
     return length;
   }
   throw new InterruptedIOException();
 }
コード例 #12
0
  /**
   * Enumerate the methods of the Clob interface and get the list of methods present in the
   * interface
   *
   * @param LOB an instance of the Clob interface implementation
   */
  void buildMethodList(Object LOB) throws IllegalAccessException, InvocationTargetException {
    // If the given method throws the correct exception
    // set this to true and add it to the
    boolean valid = true;

    // create a list of the methods that fail the test
    Vector<Method> methodList = new Vector<Method>();

    // The class whose methods are to be verified
    Class clazz = Clob.class;

    // The list of the methods in the class that need to be invoked
    // and verified
    Method[] methods = clazz.getMethods();

    // Check each of the methods to ensure that
    // they throw the required exception
    for (int i = 0; i < methods.length; i++) {
      if (!checkIfExempted(methods[i])) {
        valid = checkIfMethodThrowsSQLException(LOB, methods[i]);

        // add the method to the list if the method does
        // not throw the required exception
        if (valid == false) methodList.add(methods[i]);

        // reset valid
        valid = true;
      }
    }

    if (!methodList.isEmpty()) {
      int c = 0;
      String failureMessage = "The Following methods don't throw " + "required exception - ";
      for (Method m : methodList) {
        c = c + 1;
        if (c == methodList.size() && c != 1) failureMessage += " & ";
        else if (c != 1) failureMessage += " , ";
        failureMessage += m.getName();
      }
      fail(failureMessage);
    }
  }
コード例 #13
0
ファイル: ScoreParser.java プロジェクト: emtwo/piano
 private void parseImages() {
   String fileLocation = "data/out/" + name + ".png";
   File file = new File(fileLocation);
   if (file.exists()) {
     imageNames.add(fileLocation);
   } else {
     int p = 1;
     fileLocation = "data/out/" + name + "-page" + p + ".png";
     file = new File(fileLocation);
     while (file.exists()) {
       imageNames.add(fileLocation);
       ++p;
       fileLocation = "data/out/" + name + "-page" + p + ".png";
       file = new File(fileLocation);
     }
   }
   if (imageNames.isEmpty()) {
     System.err.println("Lilypond failed to produce any files");
   }
   pages = imageNames.size();
 }
コード例 #14
0
  /**
   * This will take in the string given at the command line by the user find if it is null and calls
   * readline().
   *
   * @param s[] holds the given command line string
   */
  public CommandLine(String s[]) throws CommandLineException, IndexOutOfBoundsException {
    if (s == null || s.length == 0) { // there are no params
      params = false;
    } else {
      params = true;
      commandLine = s;
      readLine();
      //
      // If no files are specified, default.
      //

      if ((isStdIn() == false) && fileSpecs.isEmpty()) {

        String specs = ResourceHandler.getMessage("converter_gui.lablel2");
        StringTokenizer st = new StringTokenizer(specs, " ,");
        while (st.hasMoreTokens()) {
          fileSpecs.add(st.nextToken());
        }
      }
      checkForProblems();
    }
  }
コード例 #15
0
ファイル: JEP.java プロジェクト: RichardMorris/jep-java-gpl
 /**
  * Returns true if an error occurred during the most recent action (parsing or evaluation).
  *
  * @return Returns <code>true</code> if an error occurred during the most recent action (parsing
  *     or evaluation).
  */
 public boolean hasError() {
   return !errorList.isEmpty();
 }
コード例 #16
0
ファイル: JSR82Channel.java プロジェクト: elayman/EE149
 /** @see javax.bluetooth.L2CAPConnection#ready() */
 public boolean ready() throws IOException {
   return !incommingPackets.isEmpty();
 }
コード例 #17
0
  // Parse cluster info from Clusters table and
  // place all cluster=>plugin info into hashtable
  // Schema :
  // create table Clusters (
  //    Cluster String,
  //    Plugin  String
  // );
  private void parseClusterInfo(
      Hashtable all_clusters, Statement stmt, String community, String node) throws SQLException {

    String sql = null;
    ResultSet rset;
    int number = 0;

    // Grab the plugin groups
    Hashtable plugInGroups = new Hashtable();
    sql = "select GroupName, GroupSequence from GroupMaster";

    number = 0;
    System.out.println(sql);

    rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String groupName = rset.getString("GroupName");
      System.out.println(groupName);
      Integer index = new Integer(rset.getInt("GroupSequence"));
      System.out.println(index);
      plugInGroups.put(index, groupName);
    }
    System.out.println("Query returned " + number + " results");

    // Grab the group definitions
    Hashtable groupDefinitions = new Hashtable();
    for (int ind = 0; ind < plugInGroups.size(); ind++) {

      String group = (String) plugInGroups.get(new Integer(ind));
      if (group != null) {
        sql =
            "select InGroupSequence, Plugin from GroupDefinitions"
                + " where GroupName='"
                + group
                + "'";
        rset = stmt.executeQuery(sql);
        System.out.println(sql);
        groupDefinitions.put(group, new Hashtable());

        number = 0;
        while (rset.next()) {
          number++;
          Hashtable plugins = (Hashtable) groupDefinitions.get(group);
          int index = rset.getInt("InGroupSequence");
          String plugIn = rset.getString("Plugin");
          plugins.put(new Integer(index), plugIn);
        }
        System.out.println("Query returned " + number + " results");
      } else {
        break;
      }
    }

    // Add the plugIn groups per cluster to the plugIn vector
    number = 0;
    sql = "select Cluster, PluginGroup from GroupsInCluster";

    if (community != null && node != null) {
      sql =
          sql
              + ", Organizations where Cluster=Organizations.Name and"
              + " Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql =
          sql
              + ", Organizations where Cluster=Organizations.Name and"
              + " Organizations.Community='"
              + community
              + "'";
    } else if (node != null) {
      sql = sql + ", Organizations where Organizations.Node='" + node + "'";
    }

    System.out.println(sql);

    number = 0;
    rset = stmt.executeQuery(sql);
    while (rset.next()) {
      number++;
      String cluster_name = rset.getString("Cluster");
      String pluginGroup = rset.getString("PluginGroup");

      Vector current_cluster_plugins = (Vector) all_clusters.get(cluster_name);
      if (current_cluster_plugins == null) {
        current_cluster_plugins = new Vector();
        all_clusters.put(cluster_name, current_cluster_plugins);
      }
      Hashtable groupPlugins = (Hashtable) groupDefinitions.get(pluginGroup);
      for (int ind = 0; ind < groupPlugins.size(); ind++) {
        current_cluster_plugins.addElement(groupPlugins.get(new Integer(ind)));
      }
    }
    System.out.println("Query returned " + number + " results");

    // Grab the plugins that go in every community or every cluster within specific communities
    Vector mdbCommunities = new Vector();

    sql = "select Community from CommunityMaster";
    number = 0;
    System.out.println(sql);

    rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String community_name = rset.getString("Community");
      mdbCommunities.addElement(community_name);
    }
    System.out.println("Query returned " + number + " results");

    while (!mdbCommunities.isEmpty()) {
      number = 0;
      String sCommunity = (String) mdbCommunities.firstElement();
      mdbCommunities.removeElementAt(0);

      sql =
          "select Organizations.Name, CommunityPlugins.Plugin from Organizations, CommunityPlugins"
              + " where CommunityPlugins.Community='"
              + sCommunity
              + "'";

      if (!sCommunity.equals("Society")) {
        if (community != null) {
          if (!community.equals(sCommunity)) {
            continue;
          }
        }
        sql = sql + " and Organizations.Community='" + sCommunity + "'";
      } else {
        if (community != null) {
          sql = sql + " and Organizations.Community='" + community + "'";
        }
      }

      if (node != null) {
        sql = sql + " and Organizations.Node='" + node + "'";
      }

      System.out.println(sql);
      number = 0;
      rset = stmt.executeQuery(sql);
      while (rset.next()) {
        number++;
        String cluster_name = rset.getString("Name");
        String plugin = rset.getString("Plugin");

        Vector current_cluster_plugins = (Vector) all_clusters.get(cluster_name);
        if (current_cluster_plugins == null) {
          current_cluster_plugins = new Vector();
          all_clusters.put(cluster_name, current_cluster_plugins);
        }

        current_cluster_plugins.addElement(plugin);
      }
      System.out.println("Query returned " + number + " results");
    }

    // Query for all Cluster/Plugin info and populate 'all_clusters' hashtable

    sql =
        "select Clusters.Cluster, Clusters.Plugin, Clusters.Parameters from Clusters, Organizations"
            + " where Clusters.Cluster=Organizations.Name";

    if (community != null && node != null) {
      sql =
          sql
              + "and Organizations.Node='"
              + node
              + "'"
              + " and Organizations.Community='"
              + community
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);

    number = 0;
    rset = stmt.executeQuery(sql);
    while (rset.next()) {
      number++;
      String cluster_name = rset.getString("Cluster");
      String plugin = rset.getString("Plugin");
      String parameters = rset.getString("Parameters");

      // put the parameters into the plugin
      if (parameters != null) {
        plugin = plugin + "(" + parameters + ")";
      }

      Vector current_cluster_plugins = (Vector) all_clusters.get(cluster_name);
      if (current_cluster_plugins == null) {
        current_cluster_plugins = new Vector();
        all_clusters.put(cluster_name, current_cluster_plugins);
      }

      current_cluster_plugins.addElement(plugin);
    }
    System.out.println("Query returned " + number + " results");
  }
コード例 #18
0
ファイル: Collective.java プロジェクト: swapon15/ecj-1
  /**
   * Initiates an information exchange with a known and living other base if such a base exists.
   *
   * @return true if refresh was succesful, false otherwise.
   */
  private boolean refresh() {

    final String logSender = observer + "#refresh";
    final String contrName = ((contributor != null) ? contributor.getName() : null);

    // --- refreshing local contribution and commands
    updateLocalInfo();

    // --- creating a random permutation of peers
    Vector peers = null;
    synchronized (cache) {
      peers = new Vector(cache.values());
      // just to be sure, shouldn't be there anyway
      if (contrName != null) peers.remove(cache.get(contrName));
    }
    Collections.shuffle(peers);
    if (peers.isEmpty()) {
      Logger.debug(logSender, "no peers in cache");
      return false;
    }

    // --- reset array representations
    cacheCollection = null;
    commandCollection = null;

    // --- trying to talk to random peer
    IRequest answer = null;
    Address peer = null;
    for (int i = 0; i < peers.size(); ++i) {
      if (!shouldLive) return false;

      peer = ((ContributionBox) peers.get(i)).contributor;
      Logger.debug(logSender, "asking " + peer);

      answer = observer.fireMessage(peer, "collectiveUpdate-" + name, this);
      while (answer.getStatus() == IRequest.WAITING) {
        try {
          Thread.sleep(100);
        } catch (Exception e) {
        }
      }
      if (answer.getStatus() == IRequest.DONE) break;
      Logger.debug(logSender, "not accessable: " + peer);
    }

    if (answer.getStatus() != IRequest.DONE) {
      Logger.debug(logSender, "no accessable peers");
      observer.collectiveUpdated(null);
      return false;
    } else {
      Collective c = (Collective) answer.getInfo("reply");

      // --- remove possible garbage
      if (contributor != null) {
        cache.remove(contributor.getName());
        c.cache.remove(contributor.getName());
      }
      cache.remove(peer.name);
      c.cache.remove(peer.name);

      repairSenderAddress(c, peer);
      merge(c);
      observer.collectiveUpdated((ContributionBox) cache.get(c.myContribution.contributor.name));
      return true;
    }
  }
コード例 #19
0
ファイル: ClassWriter.java プロジェクト: rpgoldman/europa-pso
  public static void defineConstructor(IndentWriter writer, IXMLElement constructor)
      throws IOException {
    assert (DebugMsg.debugMsg("ClassWriter", "Begin ClassWriter::defineConstructor"));
    IXMLElement klass = constructor.getParent();
    SharedWriter.generateFileLocation(writer, klass);

    if (klass == null) {
      throw new RuntimeException("missing class for constructor");
    }

    String longname = XMLUtil.nameOf(klass);
    writer.write("void " + longname + "::");
    generateSignature(writer, constructor);
    writer.write(" {\n");
    writer.indent();

    // If the constructor has a call to the super class, invoke it.
    assert (DebugMsg.debugMsg(
        "ClassWriter", "ClassWriter::defineConstructor -  getting children named 'super'"));
    Vector superCalls = constructor.getChildrenNamed("super");
    assert (DebugMsg.debugMsg(
        "ClassWriter",
        "ClassWriter::defineConstructor -  " + superCalls.size() + " children named retrieved"));
    if (!superCalls.isEmpty()) {
      assert (DebugMsg.debugMsg("ClassWriter", "ClassWriter::defineConstructor -  calling super"));

      if (superCalls.size() > 1) writer.write("!ERROR: AT MOST ONE CALL TO SUPER ALLOWED\n");

      IXMLElement superCall = (IXMLElement) superCalls.elementAt(0);
      String superClass = ModelAccessor.getParentClassName(klass);
      String superCppClass = ModelAccessor.getCppClass(superClass);
      writer.write(superCppClass + "::constructor(");
      String comma = "";
      Enumeration arguments = superCall.enumerateChildren();
      while (arguments.hasMoreElements()) {
        IXMLElement argument = (IXMLElement) arguments.nextElement();
        String value = ModelAccessor.getValue(argument);
        if (argument.getName().equals("value")
            && XMLUtil.getAttribute(argument, "type").equals("string"))
          writer.write(comma + "\"" + value + "\"");
        else writer.write(comma + value);
        comma = ", ";
      }
      writer.write(");\n");
    }

    Set allocatedMemberVariables = new HashSet(); // Store names as we go for reference

    /* Now capture names of constructor arguments */
    Set constructorArguments = new HashSet(); // Store for names of constructor arguments
    {
      Vector args = constructor.getChildrenNamed("arg");
      assert (DebugMsg.debugMsg(
          "ClassWriter",
          "ClassWriter::defineConstructor -  getting " + args.size() + " arguments"));
      for (int i = 0; i < args.size(); i++) {
        IXMLElement arg = (IXMLElement) args.elementAt(i);
        String argName = XMLUtil.getAttribute(arg, "name");
        constructorArguments.add(argName);
      }
    }

    Vector constructorAssignments = constructor.getChildrenNamed("assign");
    Vector classVariables = klass.getChildrenNamed("var");

    // Use the set below  to track when an assignment is being made more than once for same variable
    Set assignmentsMade = new HashSet();

    for (int i = 0; i < constructorAssignments.size(); i++) {
      IXMLElement element = (IXMLElement) constructorAssignments.elementAt(i);
      String target = XMLUtil.getAttribute(element, "name");

      if (assignmentsMade.contains(target)) {
        writer.write("!ERROR: Duplicate assignment for " + target + "\n");
      } else {
        assignmentsMade.add(target);
        // String type = getVariableType(classVariables, target);
        // trust in the parser, for it will assign the correct types
        String type = XMLUtil.getAttribute(element, "type");
        IXMLElement sourceElement = element.getChildAtIndex(0);

        if (sourceElement.getName().equals("new")) { // Handle object allocation
          assert (DebugMsg.debugMsg(
              "ClassWriter", "ClassWriter::defineConstructor -  allocating object for " + target));
          String sourceType = XMLUtil.typeOf(sourceElement);
          writer.write(target + " = addVariable(");
          writer.write(
              sourceType
                  + "Domain((new "
                  + sourceType
                  + "(m_id, \""
                  + target
                  + "\"))->getId(), \""
                  + sourceType
                  + "\")");
          writer.write(", " + makeObjectVariableNameString(target) + ");\n");
          writer.write(
              "Id<"
                  + type
                  + ">(singleton("
                  + target
                  + "))->constructor("
                  + buildArguments(
                      classVariables, constructorArguments, allocatedMemberVariables, sourceElement)
                  + ");\n"); // Invoke initialization
          writer.write(
              "Id<"
                  + type
                  + ">(singleton("
                  + target
                  + "))->handleDefaults();\n"); // Default variable setup
        } else { // Handle variable allocation
          String value = ModelAccessor.getValue(sourceElement);

          if (sourceElement.getName().equals("id") && type.equals(NddlXmlStrings.x_string))
            value = XMLUtil.escapeQuotes(value);
          else if (sourceElement.getName().equals(NddlXmlStrings.x_symbol)
              || XMLUtil.getAttribute(sourceElement, "type").equals(NddlXmlStrings.x_string))
            value = "LabelStr(\"" + XMLUtil.escapeQuotes(value) + "\")";
          else if (ModelAccessor.isNumericPrimitive(type)
              && !type.equals(NddlXmlStrings.x_boolean)) {
            // Set both bounds to singleton value
            value = value + ", " + value;
          }

          writer.write(target + " = addVariable(");

          if (allocatedMemberVariables.contains(
              value)) // If we are assigning one member to another, we obtain the base domain for it
          writer.write(value + "->baseDomain()");
          else writer.write(ModelAccessor.getDomain(type) + "(" + value + ", \"" + type + "\")");

          writer.write(", " + makeObjectVariableNameString(target) + ");\n");
        }
        // Add member to the set
        allocatedMemberVariables.add(target);
      }
    }

    writer.unindent();
    writer.write("}\n");
    assert (DebugMsg.debugMsg("ClassWriter", "End ClassWriter::defineConstructor"));
  }
コード例 #20
0
 /** INTERNAL: Check if it is a child descriptor. */
 public boolean isInterfaceChildDescriptor() {
   return ((!(parentInterfaces == null) && !parentInterfaces.isEmpty())
       || (!(parentInterfaceNames == null) && !parentInterfaceNames.isEmpty()));
 }
コード例 #21
0
ファイル: GossipClient.java プロジェクト: ECF/JGroups
  public static void main(String[] args) {
    Vector gossip_hosts = new Vector();
    String host;
    InetAddress ip_addr;
    int port;
    boolean get = false, register = false, keep_running = false;
    String register_host = null;
    int register_port = 0;
    String get_group = null, register_group = null;
    GossipClient gossip_client = null;
    List mbrs;
    long expiry = 20000;

    for (int i = 0; i < args.length; i++) {
      if ("-help".equals(args[i])) {
        usage();
        return;
      }
      if ("-expiry".equals(args[i])) {
        expiry = Long.parseLong(args[++i]);
        continue;
      }
      if ("-host".equals(args[i])) {
        host = args[++i];
        port = Integer.parseInt(args[++i]);
        try {
          ip_addr = InetAddress.getByName(host);
          gossip_hosts.addElement(new IpAddress(ip_addr, port));
        } catch (Exception ex) {
          System.err.println(ex);
        }
        continue;
      }
      if ("-keep_running".equals(args[i])) {
        keep_running = true;
        continue;
      }
      if ("-get".equals(args[i])) {
        get = true;
        get_group = args[++i];
        continue;
      }
      if ("-register".equals(args[i])) {
        register_group = args[++i];
        register_host = args[++i];
        register_port = Integer.parseInt(args[++i]);
        register = true;
        continue;
      }
      usage();
      return;
    }

    if (gossip_hosts.isEmpty()) {
      System.err.println("At least 1 GossipRouter has to be given");
      return;
    }

    if (!register && !get) {
      System.err.println("Neither get nor register command given, will not do anything");
      return;
    }

    try {
      gossip_client = new GossipClient(gossip_hosts, expiry);
      if (register) {
        System.out.println(
            "Registering " + register_group + " --> " + register_host + ':' + register_port);
        gossip_client.register(register_group, new IpAddress(register_host, register_port));
      }

      if (get) {
        System.out.println("Getting members for group " + get_group);
        mbrs = gossip_client.getMembers(get_group);
        System.out.println("Members for group " + get_group + " are " + mbrs);
      }
    } catch (Exception ex) {
      System.err.println(ex);
    }
    if (!keep_running) gossip_client.stop();
  }