コード例 #1
0
ファイル: ZCM.java プロジェクト: ZeroCM/zcm
  /**
   * Remove this particular regex/subscriber pair (UNTESTED AND API MAY CHANGE). If regex is null,
   * all subscriptions for 'sub' are cancelled. If subscriber is null, any previous subscriptions
   * matching the regular expression will be cancelled. If both 'sub' and 'regex' are null, all
   * subscriptions will be cancelled.
   */
  public void unsubscribe(String regex, ZCMSubscriber sub) {
    if (this.closed) throw new IllegalStateException();

    synchronized (this) {
      for (Provider p : providers) p.unsubscribe(regex);
    }

    // TODO: providers don't seem to use anything beyond first channel

    synchronized (subscriptions) {

      // Find and remove subscriber from list
      for (Iterator<SubscriptionRecord> it = subscriptions.iterator(); it.hasNext(); ) {
        SubscriptionRecord sr = it.next();

        if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
          it.remove();
        }
      }

      // Find and remove subscriber from map
      for (String channel : subscriptionsMap.keySet()) {
        for (Iterator<SubscriptionRecord> it = subscriptionsMap.get(channel).iterator();
            it.hasNext(); ) {
          SubscriptionRecord sr = it.next();

          if ((sub == null || sr.lcsub == sub) && (regex == null || sr.regex.equals(regex))) {
            it.remove();
          }
        }
      }
    }
  }
コード例 #2
0
ファイル: Q2.java プロジェクト: rlishtaba/jPOS
 private void deploy() {
   List startList = new ArrayList();
   Iterator iter = dirMap.entrySet().iterator();
   try {
     while (iter.hasNext() && !shutdown) {
       Map.Entry entry = (Map.Entry) iter.next();
       File f = (File) entry.getKey();
       QEntry qentry = (QEntry) entry.getValue();
       long deployed = qentry.getDeployed();
       if (deployed == 0) {
         if (deploy(f)) {
           if (qentry.isQBean()) startList.add(qentry.getInstance());
           qentry.setDeployed(f.lastModified());
         } else {
           // deploy failed, clean up.
           iter.remove();
         }
       } else if (deployed != f.lastModified()) {
         undeploy(f);
         iter.remove();
         loader.forceNewClassLoaderOnNextScan();
       }
     }
     iter = startList.iterator();
     while (iter.hasNext()) {
       start((ObjectInstance) iter.next());
     }
   } catch (Exception e) {
     log.error("deploy", e);
   }
 }
コード例 #3
0
 /*
   Place all motionless objects (fire stations, police offices, ambulance teams and refuges)
   @param fire An array to be filled with fire stations
   @param police An array to be filled with police offices
   @param ambulance An array to be filled with ambulance centres
   @param refuge An array to be filled with refuges
   @param allBuildings All buildings in the map
   @return All ordinary buildings
 */
 public static Building[] placeMotionlessObjects(
     FireStation[] fire,
     PoliceOffice[] police,
     AmbulanceCenter[] ambulance,
     Refuge[] refuge,
     Building[] allBuildings) {
   List remaining = new ArrayList();
   for (int i = 0; i < allBuildings.length; ++i) remaining.add(allBuildings[i]);
   Collections.shuffle(remaining);
   System.out.println("Placing " + ambulance.length + " ambulance centers");
   Iterator it = remaining.iterator();
   for (int i = 0; i < ambulance.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     AmbulanceCenter a = new AmbulanceCenter(location);
     a.setID(location.getID());
     ambulance[i] = a;
     //			writeFixedObjectData(out,TYPE_AMBULANCE_CENTER,i,location);
   }
   System.out.println("Placing " + fire.length + " fire stations");
   for (int i = 0; i < fire.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     FireStation a = new FireStation(location);
     a.setID(location.getID());
     fire[i] = a;
     //			writeFixedObjectData(out,TYPE_FIRE_STATION,i,location);
     //			System.out.print(".");
   }
   System.out.println("Placing " + police.length + " police stations");
   for (int i = 0; i < police.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     PoliceOffice a = new PoliceOffice(location);
     a.setID(location.getID());
     police[i] = a;
     //			writeFixedObjectData(out,TYPE_POLICE_OFFICE,i,location);
     //			System.out.print(".");
   }
   System.out.println("Placing " + refuge.length + " refuges");
   for (int i = 0; i < refuge.length; ++i) {
     Building location = (Building) it.next();
     it.remove();
     Refuge a = new Refuge(location);
     a.setID(location.getID());
     refuge[i] = a;
     //			writeFixedObjectData(out,TYPE_REFUGE,i,location);
     //			System.out.print(".");
   }
   //		System.out.println();
   return (Building[]) remaining.toArray(new Building[0]);
 }
コード例 #4
0
  /**
   * JUnit.
   *
   * @throws Exception If failed.
   */
  public void testIterator() throws Exception {
    // Random queue name.
    String queueName = UUID.randomUUID().toString();

    IgniteQueue<String> queue = grid(0).queue(queueName, 0, config(false));

    for (int i = 0; i < 100; i++) assert queue.add(Integer.toString(i));

    Iterator<String> iter1 = queue.iterator();

    int cnt = 0;
    for (int i = 0; i < 100; i++) {
      assertNotNull(iter1.next());
      cnt++;
    }

    assertEquals(100, queue.size());
    assertEquals(100, cnt);

    assertNotNull(queue.take());
    assertNotNull(queue.take());
    assertTrue(queue.remove("33"));
    assertTrue(queue.remove("77"));

    assertEquals(96, queue.size());

    Iterator<String> iter2 = queue.iterator();

    try {
      iter2.remove();
    } catch (IllegalStateException e) {
      info("Caught expected exception: " + e);
    }

    iter2.next();
    iter2.remove();

    cnt = 0;
    while (iter2.hasNext()) {
      assertNotNull(iter2.next());
      cnt++;
    }

    assertEquals(95, cnt);
    assertEquals(95, queue.size());

    iter2.remove();
  }
コード例 #5
0
  private void recycleChangeList(
      final ShelvedChangeList listCopy, final ShelvedChangeList newList) {
    if (newList != null) {
      for (Iterator<ShelvedBinaryFile> shelvedChangeListIterator =
              listCopy.getBinaryFiles().iterator();
          shelvedChangeListIterator.hasNext(); ) {
        final ShelvedBinaryFile binaryFile = shelvedChangeListIterator.next();
        for (ShelvedBinaryFile newBinary : newList.getBinaryFiles()) {
          if (Comparing.equal(newBinary.BEFORE_PATH, binaryFile.BEFORE_PATH)
              && Comparing.equal(newBinary.AFTER_PATH, binaryFile.AFTER_PATH)) {
            shelvedChangeListIterator.remove();
          }
        }
      }
      for (Iterator<ShelvedChange> iterator = listCopy.getChanges(myProject).iterator();
          iterator.hasNext(); ) {
        final ShelvedChange change = iterator.next();
        for (ShelvedChange newChange : newList.getChanges(myProject)) {
          if (Comparing.equal(change.getBeforePath(), newChange.getBeforePath())
              && Comparing.equal(change.getAfterPath(), newChange.getAfterPath())) {
            iterator.remove();
          }
        }
      }

      // needed only if partial unshelve
      try {
        final CommitContext commitContext = new CommitContext();
        final List<FilePatch> patches = new ArrayList<FilePatch>();
        for (ShelvedChange change : listCopy.getChanges(myProject)) {
          patches.add(change.loadFilePatch(myProject, commitContext));
        }
        writePatchesToFile(myProject, listCopy.PATH, patches, commitContext);
      } catch (IOException e) {
        LOG.info(e);
        // left file as is
      } catch (PatchSyntaxException e) {
        LOG.info(e);
        // left file as is
      }
    }

    if ((!listCopy.getBinaryFiles().isEmpty()) || (!listCopy.getChanges(myProject).isEmpty())) {
      listCopy.setRecycled(true);
      myRecycledShelvedChangeLists.add(listCopy);
      notifyStateChanged();
    }
  }
コード例 #6
0
  /**
   * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding
   * channel bundle.
   */
  void closeTransportManager(TransportManager transportManager) {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        if (i.next() == transportManager) {
          i.remove();
          // Presumably, we have a single association for
          // transportManager.
          break;
        }
      }

      // Close manager
      try {
        transportManager.close();
      } catch (Throwable t) {
        logger.warn(
            "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t);
        // The whole point of explicitly closing the
        // transportManagers of this Conference is to prevent memory
        // leaks. Hence, it does not make sense to possibly leave
        // TransportManagers open because a TransportManager has
        // failed to close.
        if (t instanceof InterruptedException) Thread.currentThread().interrupt();
        else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
      }
    }
  }
コード例 #7
0
ファイル: DownloadPictures.java プロジェクト: joshhazel/mage
  private void update(int card, int count) {
    this.cardIndex = card;

    if (cardIndex < count) {
      float mb = ((count - card) * cardImageSource.getAverageSize()) / 1024;
      bar.setString(
          String.format("%d of %d cards finished! Please wait! [%.1f Mb]", card, count, mb));
    } else {
      Iterator<CardDownloadData> cardsIterator = DownloadPictures.this.cards.iterator();
      while (cardsIterator.hasNext()) {
        CardDownloadData cardDownloadData = cardsIterator.next();
        TFile file = new TFile(CardImageUtils.generateImagePath(cardDownloadData));
        if (file.exists()) {
          cardsIterator.remove();
        }
      }
      count = DownloadPictures.this.cards.size();

      if (count == 0) {
        bar.setString("0 cards remaining! Please close!");
      } else {
        bar.setString(String.format("%d cards remaining! Please choose another source!", count));
        // executor = Executors.newFixedThreadPool(10);
        startDownloadButton.setEnabled(true);
      }
    }
  }
コード例 #8
0
  private void onFinishWebUITests(ITestContext testContext) {
    // List of test results which we will delete later because of duplication or because the test
    // eventually passed
    List<ITestResult> testsToBeRemoved = new ArrayList<ITestResult>();

    // collect all id's from passed test
    Set<Integer> passedTestIds = new HashSet<Integer>();
    for (ITestResult passedTest : testContext.getPassedTests().getAllResults()) {
      passedTestIds.add(getTestId(passedTest));
    }

    Set<Integer> failedTestIds = new HashSet<Integer>();
    for (ITestResult failedTest : testContext.getFailedTests().getAllResults()) {

      int failedTestId = getTestId(failedTest);
      // if this test failed before mark as to be deleted
      // or delete this failed test if there is at least one passed version
      if (failedTestIds.contains(failedTestId) || passedTestIds.contains(failedTestId)) {
        testsToBeRemoved.add(failedTest);
      } else {
        failedTestIds.add(failedTestId);
      }
    }
    // finally delete all tests that are marked
    for (Iterator<ITestResult> iterator = testContext.getFailedTests().getAllResults().iterator();
        iterator.hasNext(); ) {
      ITestResult testResult = iterator.next();
      if (testsToBeRemoved.contains(testResult)) {
        iterator.remove();
      }
    }
  }
コード例 #9
0
ファイル: CIManagerImpl.java プロジェクト: manoj-s/framework
 private void deleteJsonJobs(ApplicationInfo appInfo, List<CIJob> selectedJobs)
     throws PhrescoException {
   try {
     if (CollectionUtils.isEmpty(selectedJobs)) {
       return;
     }
     Gson gson = new Gson();
     List<CIJob> jobs = getJobs(appInfo);
     if (CollectionUtils.isEmpty(jobs)) {
       return;
     }
     // all values
     Iterator<CIJob> iterator = jobs.iterator();
     // deletable values
     for (CIJob selectedInfo : selectedJobs) {
       while (iterator.hasNext()) {
         CIJob itrCiJob = iterator.next();
         if (itrCiJob.getName().equals(selectedInfo.getName())) {
           iterator.remove();
           break;
         }
       }
     }
     writeJsonJobs(appInfo, jobs, CI_CREATE_NEW_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
コード例 #10
0
ファイル: JobTracker.java プロジェクト: bruthe/hadoop-0.1r
    /**
     * The run method lives for the life of the JobTracker, and removes Jobs that are not still
     * running, but which finished a long time ago.
     */
    public void run() {
      while (shouldRun) {
        try {
          Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);
        } catch (InterruptedException ie) {
        }

        synchronized (jobs) {
          synchronized (jobInitQueue) {
            synchronized (jobsByArrival) {
              for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {
                String jobid = (String) it.next();
                JobInProgress job = (JobInProgress) jobs.get(jobid);

                if (job.getStatus().getRunState() != JobStatus.RUNNING
                    && job.getStatus().getRunState() != JobStatus.PREP
                    && (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {
                  it.remove();

                  jobInitQueue.remove(job);
                  jobsByArrival.remove(job);
                }
              }
            }
          }
        }
      }
    }
コード例 #11
0
ファイル: RESTReservations.java プロジェクト: mksh/jicofo
    @Override
    public void run() {
      synchronized (RESTReservations.this) {
        Iterator<Conference> conferenceIterator = conferenceMap.values().iterator();

        while (conferenceIterator.hasNext()) {
          Conference conference = conferenceIterator.next();
          Date startTimeDate = conference.getStartTime();
          if (startTimeDate == null) {
            logger.error("No 'start_time' for conference: " + conference.getName());
            continue;
          }
          long startTime = startTimeDate.getTime();
          long duration = conference.getDuration();
          // Convert duration to millis
          duration = duration * 1000L;
          long now = System.currentTimeMillis();
          if (now - startTime > duration - EXPIRE_INTERVAL) {
            // Destroy the conference
            String mucRoomName = conference.getMucRoomName();

            deleteConference(conference.getId());

            conferenceIterator.remove();

            focusManager.destroyConference(mucRoomName, "Scheduled conference duration exceeded.");
          }
        }
      }
    }
コード例 #12
0
  /**
   * Remove records telling what entity caps node a contact has.
   *
   * @param contact the contact
   */
  public void removeContactCapsNode(Contact contact) {
    Caps caps = null;
    String lastRemovedJid = null;

    Iterator<String> iter = userCaps.keySet().iterator();
    while (iter.hasNext()) {
      String jid = iter.next();

      if (StringUtils.parseBareAddress(jid).equals(contact.getAddress())) {
        caps = userCaps.get(jid);
        lastRemovedJid = jid;
        iter.remove();
      }
    }

    // fire only for the last one, at the end the event out
    // of the protocol will be one and for the contact
    if (caps != null) {
      UserCapsNodeListener[] listeners;
      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(lastRemovedJid, nodeVer, false);
      }
    }
  }
コード例 #13
0
  public void testRemove() throws IOException {
    int i = 0;
    TextFile tf = new TextFile(TEST_FILE_NAME);

    for (String name : tf) {
      System.out.println("::: " + name);
      assertEquals(names.get(i++), name);
    }

    // testing remove()
    for (Iterator<String> it = tf.iterator(); it.hasNext(); ) {
      String name = it.next();
      if ("Dirk".equals(name)) {
        it.remove();
        System.out.println("removing dirk");
      }
    }

    names.remove("Dirk");

    i = 0;
    for (String name : tf) {
      System.out.println("::: " + name);
      assertEquals(names.get(i++), name);
    }
  }
  /** {@inheritDoc} */
  @Override
  public void explicitUndeploy(UUID nodeId, String rsrcName) {
    Collection<SharedDeployment> undeployed = new LinkedList<SharedDeployment>();

    synchronized (mux) {
      for (Iterator<List<SharedDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) {
        List<SharedDeployment> deps = i1.next();

        for (Iterator<SharedDeployment> i2 = deps.iterator(); i2.hasNext(); ) {
          SharedDeployment dep = i2.next();

          if (dep.hasName(rsrcName)) {
            if (!dep.isUndeployed()) {
              dep.undeploy();

              dep.onRemoved();

              // Undeploy.
              i2.remove();

              undeployed.add(dep);

              if (log.isInfoEnabled()) log.info("Undeployed per-version class loader: " + dep);
            }

            break;
          }
        }

        if (deps.isEmpty()) i1.remove();
      }
    }

    recordUndeployed(null, undeployed);
  }
コード例 #15
0
ファイル: TestApp.java プロジェクト: karanbatra/hazelcast
 protected void handleIterator(String[] args) {
   Iterator it = null;
   String iteratorStr = args[0];
   if (iteratorStr.startsWith("s.")) {
     it = getSet().iterator();
   } else if (iteratorStr.startsWith("m.")) {
     it = getMap().keySet().iterator();
   } else if (iteratorStr.startsWith("q.")) {
     it = getQueue().iterator();
   } else if (iteratorStr.startsWith("l.")) {
     it = getList().iterator();
   }
   if (it != null) {
     boolean remove = false;
     if (args.length > 1) {
       String removeStr = args[1];
       remove = removeStr.equals("remove");
     }
     int count = 1;
     while (it.hasNext()) {
       print(count++ + " " + it.next());
       if (remove) {
         it.remove();
         print(" removed");
       }
       println("");
     }
   }
 }
コード例 #16
0
ファイル: Overlord.java プロジェクト: rf/bitster
  /** Selects on sockets and informs their Communicator when there is something to do. */
  public void communicate(int timeout) {

    try {
      selector.select(timeout);
    } catch (IOException e) {
      // Not really sure why/when this happens yet
      return;
    }

    Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

    while (keys.hasNext()) {
      SelectionKey key = keys.next();
      keys.remove();
      if (!key.isValid()) continue; // WHY
      Communicator communicator = (Communicator) key.attachment();

      if (key.isReadable()) communicator.onReadable();
      if (key.isWritable()) communicator.onWritable();
      if (key.isAcceptable()) communicator.onAcceptable();
    }

    // Go through the queue and handle each communicator
    while (!queue.isEmpty()) {
      Communicator c = queue.poll();
      c.onMemo();
    }
  }
コード例 #17
0
  /** Return all of the neighbors with whom we share the provided range. */
  static Set<InetAddress> getNeighbors(String table, Range<Token> toRepair) {
    StorageService ss = StorageService.instance;
    Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(table);
    Range<Token> rangeSuperSet = null;
    for (Range<Token> range : ss.getLocalRanges(table)) {
      if (range.contains(toRepair)) {
        rangeSuperSet = range;
        break;
      } else if (range.intersects(toRepair)) {
        throw new IllegalArgumentException(
            "Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair");
      }
    }
    if (rangeSuperSet == null || !replicaSets.containsKey(toRepair)) return Collections.emptySet();

    Set<InetAddress> neighbors = new HashSet<InetAddress>(replicaSets.get(rangeSuperSet));
    neighbors.remove(FBUtilities.getBroadcastAddress());
    // Excluding all node with version <= 0.7 since they don't know how to
    // create a correct merkle tree (they build it over the full range)
    Iterator<InetAddress> iter = neighbors.iterator();
    while (iter.hasNext()) {
      InetAddress endpoint = iter.next();
      if (Gossiper.instance.getVersion(endpoint) <= MessagingService.VERSION_07) {
        logger.info(
            "Excluding "
                + endpoint
                + " from repair because it is on version 0.7 or sooner. You should consider updating this node before running repair again.");
        iter.remove();
      }
    }
    return neighbors;
  }
コード例 #18
0
  /**
   * Estimates the mean of array <code>y</code>. <code>robustMu</code> uses a Gaussian model to
   * remove outliers iteratively.
   *
   * @param y an array
   * @return the estimated mean of <code>y</code>
   */
  private double robustMu(double[] y) {

    ArrayList<Double> x = new ArrayList<Double>(y.length);

    for (int i = 0; i < y.length; i++) {
      x.add(y[i]);
    }

    double sigma = 0;
    NormalDist gaussian = new NormalDist();
    double cutoff = 0;
    double cutoff1 = 0;
    double cutoff2 = 0;

    int xSize = x.size();

    sigma = std(x);
    double areaRemoved = 0.5 / xSize;

    cutoff = abs(gaussian.inverseF(areaRemoved));

    cutoff1 = -cutoff * sigma + mean(x);
    cutoff2 = cutoff * sigma + mean(x);

    while (true) {

      Iterator<Double> iter = x.iterator();

      int numRemoved = 0;
      while (iter.hasNext()) {

        double cn = iter.next();
        if (cn < cutoff1 || cn > cutoff2) {
          numRemoved++;
          iter.remove();
        }
      }

      if (numRemoved == 0) {
        break;
      }

      sigma = std(x);
      sigma =
          sigma
              / sqrt(
                  (1 - 2 * areaRemoved - 2 * cutoff * exp(-pow(cutoff, 2) / 2) / sqrt(2 * PI))
                      / (1 - 2 * areaRemoved));

      xSize = x.size();
      areaRemoved = 0.5 / xSize;

      cutoff = abs(gaussian.inverseF(areaRemoved));

      cutoff1 = -cutoff * sigma + mean(x);
      cutoff2 = cutoff * sigma + mean(x);
    }

    return mean(x);
  }
コード例 #19
0
ファイル: MapCheck.java プロジェクト: codehaus/jsr166-mirror
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
コード例 #20
0
 public void testSubMapContents2() {
   ConcurrentNavigableMap map = map5();
   SortedMap sm = map.subMap(two, three);
   assertEquals(1, sm.size());
   assertEquals(two, sm.firstKey());
   assertEquals(two, sm.lastKey());
   assertFalse(sm.containsKey(one));
   assertTrue(sm.containsKey(two));
   assertFalse(sm.containsKey(three));
   assertFalse(sm.containsKey(four));
   assertFalse(sm.containsKey(five));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(two));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(three), null);
   assertEquals(4, map.size());
 }
コード例 #21
0
  public void moveToHistory(Step step) {
    List currentSteps =
        (List) SerializableCache.getInstance().currentStepsCache.get(new Long(step.getEntryId()));

    List historySteps =
        (List) SerializableCache.getInstance().historyStepsCache.get(new Long(step.getEntryId()));

    if (historySteps == null) {
      historySteps = new ArrayList();
      SerializableCache.getInstance()
          .historyStepsCache
          .put(new Long(step.getEntryId()), historySteps);
    }

    SimpleStep simpleStep = (SimpleStep) step;

    for (Iterator iterator = currentSteps.iterator(); iterator.hasNext(); ) {
      Step currentStep = (Step) iterator.next();

      if (simpleStep.getId() == currentStep.getId()) {
        iterator.remove();
        historySteps.add(simpleStep);

        break;
      }
    }

    SerializableCache.store();
  }
コード例 #22
0
ファイル: Env.java プロジェクト: NathanEEvans/api
  static synchronized String sourceLine(Location location, int lineNumber) throws IOException {
    if (lineNumber == -1) {
      throw new IllegalArgumentException();
    }

    try {
      String fileName = location.sourceName();

      Iterator<SourceCode> iter = sourceCache.iterator();
      SourceCode code = null;
      while (iter.hasNext()) {
        SourceCode candidate = iter.next();
        if (candidate.fileName().equals(fileName)) {
          code = candidate;
          iter.remove();
          break;
        }
      }
      if (code == null) {
        BufferedReader reader = sourceReader(location);
        if (reader == null) {
          throw new FileNotFoundException(fileName);
        }
        code = new SourceCode(fileName, reader);
        if (sourceCache.size() == SOURCE_CACHE_SIZE) {
          sourceCache.remove(sourceCache.size() - 1);
        }
      }
      sourceCache.add(0, code);
      return code.sourceLine(lineNumber);
    } catch (AbsentInformationException e) {
      throw new IllegalArgumentException();
    }
  }
コード例 #23
0
 public void testDescendingSubMapContents2() {
   ConcurrentNavigableMap map = dmap5();
   SortedMap sm = map.subMap(m2, m3);
   assertEquals(1, sm.size());
   assertEquals(m2, sm.firstKey());
   assertEquals(m2, sm.lastKey());
   assertFalse(sm.containsKey(m1));
   assertTrue(sm.containsKey(m2));
   assertFalse(sm.containsKey(m3));
   assertFalse(sm.containsKey(m4));
   assertFalse(sm.containsKey(m5));
   Iterator i = sm.keySet().iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   assertFalse(i.hasNext());
   Iterator j = sm.keySet().iterator();
   j.next();
   j.remove();
   assertFalse(map.containsKey(m2));
   assertEquals(4, map.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertSame(sm.remove(m3), null);
   assertEquals(4, map.size());
 }
コード例 #24
0
  /**
   * Determines whether {@code effect} has been paused/stopped by the remote peer. The determination
   * is based on counting frames and is triggered by the receipt of (a piece of) a new (video) frame
   * by {@code cause}.
   *
   * @param cause the {@code SimulcastLayer} which has received (a piece of) a new (video) frame and
   *     has thus triggered a check on {@code effect}
   * @param pkt the {@code RawPacket} which was received by {@code cause} and possibly influenced
   *     the decision to trigger a check on {@code effect}
   * @param effect the {@code SimulcastLayer} which is to be checked whether it looks like it has
   *     been paused/stopped by the remote peer
   * @param endIndexInSimulcastLayerFrameHistory
   */
  private void maybeTimeout(
      SimulcastLayer cause,
      RawPacket pkt,
      SimulcastLayer effect,
      int endIndexInSimulcastLayerFrameHistory) {
    Iterator<SimulcastLayer> it = simulcastLayerFrameHistory.iterator();
    boolean timeout = true;

    for (int ix = 0; it.hasNext() && ix < endIndexInSimulcastLayerFrameHistory; ++ix) {
      if (it.next() == effect) {
        timeout = false;
        break;
      }
    }
    if (timeout) {
      effect.maybeTimeout(pkt);

      if (!effect.isStreaming()) {
        // Since effect has been determined to have been paused/stopped
        // by the remote peer, its possible presence in
        // simulcastLayerFrameHistory is irrelevant now. In other words,
        // remove effect from simulcastLayerFrameHistory.
        while (it.hasNext()) {
          if (it.next() == effect) it.remove();
        }
      }
    }
  }
コード例 #25
0
  private void stepTimeout() {
    boolean updated = false;
    synchronized (channels) {
      Iterator<ChannelInfo> it = channels.values().iterator();
      while (it.hasNext()) {
        ChannelInfo channel = it.next();
        Iterator<UserInfo> removed = channel.stepTimeout(getTimeoutLimit());

        if (removed != null) {
          updated = true;
          String channelName = channel.getChannelName();
          while (removed.hasNext()) {
            UserInfo user = removed.next();
            ServerLogger.getInstance()
                .channelLeaved(channelName, user.getUserName(), user.getInetSocketAddress());
          }
          if (channel.isEmpty()) {
            it.remove();
            ServerLogger.getInstance().channelRemoved(channelName);
          }
        }
      }

      if (updated) {
        updateChannelsCache();
      }
    }
  }
コード例 #26
0
ファイル: Executing.java プロジェクト: rhusar/JGroups
  protected void handleView(View view) {
    this.view = view;
    if (log.isDebugEnabled()) log.debug("view=" + view);
    List<Address> members = view.getMembers();

    _consumerLock.lock();
    try {
      // This removes the consumers that were registered that are now gone
      Iterator<Owner> iterator = _consumersAvailable.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveConsumerRequest(owner);
        }
      }

      // This removes the tasks that those requestors are gone
      iterator = _runRequests.iterator();
      while (iterator.hasNext()) {
        Owner owner = iterator.next();
        if (!members.contains(owner.getAddress())) {
          iterator.remove();
          sendRemoveRunRequest(owner);
        }
      }

      synchronized (_awaitingReturn) {
        for (Entry<Owner, Runnable> entry : _awaitingReturn.entrySet()) {
          // The person currently servicing our request has gone down
          // without completing so we have to keep our request alive by
          // sending ours back to the coordinator
          Owner owner = entry.getKey();
          if (!members.contains(owner.getAddress())) {
            Runnable runnable = entry.getValue();
            // We need to register the request id before sending the request back to the coordinator
            // in case if our task gets picked up since another was removed
            _requestId.put(runnable, owner.getRequestId());
            _awaitingConsumer.add(runnable);
            sendToCoordinator(RUN_REQUEST, owner.getRequestId(), local_addr);
          }
        }
      }
    } finally {
      _consumerLock.unlock();
    }
  }
コード例 #27
0
  /**
   * Notifies this {@code SimulcastReceiver} that a specific {@code SimulcastReceiver} has detected
   * the start of a new video frame in the RTP stream that it represents. Determines whether any of
   * {@link #simulcastLayers} other than {@code source} have been paused/stopped by the remote peer.
   * The determination is based on counting (video) frames.
   *
   * @param source the {@code SimulcastLayer} which is the source of the event i.e. which has
   *     detected the start of a new video frame in the RTP stream that it represents
   * @param pkt the {@code RawPacket} which was received by {@code source} and possibly influenced
   *     the decision that a new view frame was started in the RTP stream represented by {@code
   *     source}
   * @param layers the set of {@code SimulcastLayer}s managed by this {@code SimulcastReceiver}.
   *     Explicitly provided to the method in order to avoid invocations of {@link
   *     #getSimulcastLayers()} because the latter makes a copy at the time of this writing.
   */
  private void simulcastLayerFrameStarted(
      SimulcastLayer source, RawPacket pkt, SimulcastLayer[] layers) {
    // Allow the value of the constant TIMEOUT_ON_FRAME_COUNT to disable (at
    // compile time) the frame-based approach to the detection of layer
    // drops.
    if (TIMEOUT_ON_FRAME_COUNT <= 1) return;

    // Timeouts in layers caused by source may occur only based on the span
    // (of time or received frames) during which source has received
    // TIMEOUT_ON_FRAME_COUNT number of frames. The current method
    // invocation signals the receipt of 1 frame by source.
    int indexOfLastSourceOccurrenceInHistory = -1;
    int sourceFrameCount = 0;
    int ix = 0;

    for (Iterator<SimulcastLayer> it = simulcastLayerFrameHistory.iterator(); it.hasNext(); ++ix) {
      if (it.next() == source) {
        if (indexOfLastSourceOccurrenceInHistory != -1) {
          // Prune simulcastLayerFrameHistory so that it does not
          // become unnecessarily long.
          it.remove();
        } else if (++sourceFrameCount >= TIMEOUT_ON_FRAME_COUNT - 1) {
          // The span of TIMEOUT_ON_FRAME_COUNT number of frames
          // received by source only is to be examined for the
          // purposes of timeouts. The current method invocations
          // signals the receipt of 1 frame by source so
          // TIMEOUT_ON_FRAME_COUNT - 1 occurrences of source in
          // simulcastLayerFrameHistory is enough.
          indexOfLastSourceOccurrenceInHistory = ix;
        }
      }
    }

    if (indexOfLastSourceOccurrenceInHistory != -1) {
      // Presumably, if a SimulcastLayer is active, all SimulcastLayers
      // before it (according to SimulcastLayer's order) are active as
      // well. Consequently, timeouts may occur in SimulcastLayers which
      // are after source.
      boolean maybeTimeout = false;

      for (SimulcastLayer layer : layers) {
        if (maybeTimeout) {
          // There's no point in timing layer out if it's timed out
          // already.
          if (layer.isStreaming()) {
            maybeTimeout(source, pkt, layer, indexOfLastSourceOccurrenceInHistory);
          }
        } else if (layer == source) {
          maybeTimeout = true;
        }
      }
    }

    // As previously stated, the current method invocation signals the
    // receipt of 1 frame by source.
    simulcastLayerFrameHistory.add(0, source);
    // TODO Prune simulcastLayerFrameHistory by forgetting so that it does
    // not become too long.
  }
コード例 #28
0
ファイル: IntSet.java プロジェクト: kamaci/UBL
 public boolean removeUnscoped(List vars) {
   Iterator<Exp> i = exps.iterator();
   while (i.hasNext()) {
     Exp e = i.next();
     if (e.removeUnscoped(vars)) i.remove();
   }
   return false;
 }
コード例 #29
0
 /** iterator.remove removes element */
 public void testIteratorRemove() {
   List full = populatedArray(SIZE);
   Iterator it = full.iterator();
   Object first = full.get(0);
   it.next();
   it.remove();
   assertFalse(full.contains(first));
 }
コード例 #30
0
ファイル: Dispatcher1.java プロジェクト: raviAmlani/java
 private void dispatch() throws IOException {
   sel.select();
   for (Iterator i = sel.selectedKeys().iterator(); i.hasNext(); ) {
     SelectionKey sk = (SelectionKey) i.next();
     i.remove();
     Handler h = (Handler) sk.attachment();
     h.handle(sk);
   }
 }