Java Code Examples for java.util.Iterator.remove()

The following are Jave code examples for showing how to use remove() of the java.util.Iterator class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lib-commons-httpclient   File: PostMethod.java   View Source Code Vote up 7 votes
/**
 * Removes all parameters with the given paramName. If there is more than
 * one parameter with the given paramName, all of them are removed.  If
 * there is just one, it is removed.  If there are none, then the request
 * is ignored.
 *
 * @param paramName The parameter name to remove.
 *
 * @return true if at least one parameter was removed
 *
 * @throws IllegalArgumentException When the parameter name passed is null
 *
 * @since 2.0
 */
public boolean removeParameter(String paramName) 
throws IllegalArgumentException {
    LOG.trace("enter PostMethod.removeParameter(String)");

    if (paramName == null) {
        throw new IllegalArgumentException(
            "Argument passed to removeParameter(String) cannot be null");
    }
    boolean removed = false;
    Iterator iter = this.params.iterator();

    while (iter.hasNext()) {
        NameValuePair pair = (NameValuePair) iter.next();

        if (paramName.equals(pair.getName())) {
            iter.remove();
            removed = true;
        }
    }
    return removed;
}
 
Example 2
Project: GitHub   File: CacheTest.java   View Source Code Vote up 6 votes
@Test public void iteratorRemoveFromCache() throws Exception {
  // Put a response in the cache.
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .setBody("a"));
  HttpUrl url = server.url("/a");
  assertEquals("a", get(url).body().string());

  // Remove it with iteration.
  Iterator<String> i = cache.urls();
  assertEquals(url.toString(), i.next());
  i.remove();

  // Confirm that subsequent requests suffer a cache miss.
  server.enqueue(new MockResponse()
      .setBody("b"));
  assertEquals("b", get(url).body().string());
}
 
Example 3
Project: CustomWorldGen   File: StructureVillagePieces.java   View Source Code Vote up 6 votes
public static List<StructureVillagePieces.PieceWeight> getStructureVillageWeightedPieceList(Random random, int size)
{
    List<StructureVillagePieces.PieceWeight> list = Lists.<StructureVillagePieces.PieceWeight>newArrayList();
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House4Garden.class, 4, MathHelper.getRandomIntegerInRange(random, 2 + size, 4 + size * 2)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Church.class, 20, MathHelper.getRandomIntegerInRange(random, 0 + size, 1 + size)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House1.class, 20, MathHelper.getRandomIntegerInRange(random, 0 + size, 2 + size)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.WoodHut.class, 3, MathHelper.getRandomIntegerInRange(random, 2 + size, 5 + size * 3)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Hall.class, 15, MathHelper.getRandomIntegerInRange(random, 0 + size, 2 + size)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field1.class, 3, MathHelper.getRandomIntegerInRange(random, 1 + size, 4 + size)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field2.class, 3, MathHelper.getRandomIntegerInRange(random, 2 + size, 4 + size * 2)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House2.class, 15, MathHelper.getRandomIntegerInRange(random, 0, 1 + size)));
    list.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House3.class, 8, MathHelper.getRandomIntegerInRange(random, 0 + size, 3 + size * 2)));
    net.minecraftforge.fml.common.registry.VillagerRegistry.addExtraVillageComponents(list, random, size);
    Iterator<StructureVillagePieces.PieceWeight> iterator = list.iterator();

    while (iterator.hasNext())
    {
        if (((StructureVillagePieces.PieceWeight)iterator.next()).villagePiecesLimit == 0)
        {
            iterator.remove();
        }
    }

    return list;
}
 
Example 4
Project: monarch   File: JCAManagedConnection.java   View Source Code Vote up 6 votes
public void cleanup() throws ResourceException {
  if (DEBUG) {
    try {
      throw new NullPointerException("Asif:JCAManagedConnection:cleanup");
    } catch (NullPointerException npe) {
      npe.printStackTrace();
    }
  }
  synchronized (this.connections) {
    Iterator<GFConnectionImpl> connsItr = this.connections.iterator();
    while (connsItr.hasNext()) {
      GFConnectionImpl conn = connsItr.next();
      conn.invalidate();
      connsItr.remove();
    }
  }
  if (this.localTran == null || this.localTran.transactionInProgress()) {
    if (this.initDone && !this.cache.isClosed()) {
      this.localTran = new JCALocalTransaction(cache, gfTxMgr);
    } else {
      this.localTran = new JCALocalTransaction();
    }
  }

}
 
Example 5
Project: fresco_floodlight   File: InMemoryStorageEngine.java   View Source Code Vote up 6 votes
@Override
public void cleanupTask() {
    // Remove tombstones that are older than the tombstone deletion
    // threshold.  If a value is deleted and the tombstone has been 
    // cleaned up before the cluster is fully synchronized, then there
    // is a chance that deleted values could be resurrected
    Iterator<Entry<K, List<Versioned<V>>>> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<K, List<Versioned<V>>> e = iter.next();
        List<Versioned<V>> items = e.getValue();

        synchronized (items) {
            if (StoreUtils.canDelete(items, tombstoneDeletion))
                iter.remove();
        }
    }
}
 
Example 6
Project: guava-mock   File: FilteredEntryMultimap.java   View Source Code Vote up 6 votes
@Override
public int remove(@Nullable Object key, int occurrences) {
  checkNonnegative(occurrences, "occurrences");
  if (occurrences == 0) {
    return count(key);
  }
  Collection<V> collection = unfiltered.asMap().get(key);
  if (collection == null) {
    return 0;
  }
  @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself
  K k = (K) key;
  int oldCount = 0;
  Iterator<V> itr = collection.iterator();
  while (itr.hasNext()) {
    V v = itr.next();
    if (satisfies(k, v)) {
      oldCount++;
      if (oldCount <= occurrences) {
        itr.remove();
      }
    }
  }
  return oldCount;
}
 
Example 7
Project: avr-bootloader   File: MemoryRegions.java   View Source Code Vote up 6 votes
public void compact() {
    Collections.sort(regions);

    Iterator<Region> iter = regions.iterator();
    Region prev = null;
    while (iter.hasNext()) {
        Region curr = iter.next();
        if (prev == null) {
            prev = curr;
        } else {
            // check for chaining
            if (curr.getAddressStart() == (prev.getAddressStart() + prev.getLength())) {
                prev.incLength(curr.getLength());
                iter.remove();
            } else {
                prev = curr;
            }
        }
    }
}
 
Example 8
Project: openjdk-jdk10   File: InMemoryCookieStore.java   View Source Code Vote up 6 votes
/**
 * Get all URIs, which are associated with at least one cookie
 * of this cookie store.
 */
public List<URI> getURIs() {
    List<URI> uris = new ArrayList<>();

    lock.lock();
    try {
        Iterator<URI> it = uriIndex.keySet().iterator();
        while (it.hasNext()) {
            URI uri = it.next();
            List<HttpCookie> cookies = uriIndex.get(uri);
            if (cookies == null || cookies.size() == 0) {
                // no cookies list or an empty list associated with
                // this uri entry, delete it
                it.remove();
            }
        }
    } finally {
        uris.addAll(uriIndex.keySet());
        lock.unlock();
    }

    return uris;
}
 
Example 9
Project: L2J-Global   File: TimerExecutor.java   View Source Code Vote up 6 votes
/**
 * @param event
 * @param npc
 * @param player
 * @return {@code true} if timer for the given event, npc, player were stopped, {@code false} otheriwse
 */
public boolean cancelTimer(T event, L2Npc npc, L2PcInstance player)
{
	final Set<TimerHolder<T>> timers = _timers.get(event);
	if ((timers == null) || timers.isEmpty())
	{
		return false;
	}
	
	final Iterator<TimerHolder<T>> holders = timers.iterator();
	while (holders.hasNext())
	{
		final TimerHolder<T> holder = holders.next();
		if (holder.isEqual(event, npc, player))
		{
			holders.remove();
			return holder.cancelTimer();
		}
	}
	return false;
}
 
Example 10
Project: lustre-connector-for-hadoop   File: LustreFsMergeThread.java   View Source Code Vote up 6 votes
public void startMerge(Set<T> inputs) {
  if (!closed) {
    numPending.incrementAndGet();
    List<T> toMergeInputs = new ArrayList<T>();
    Iterator<T> iter=inputs.iterator();
    for (int ctr = 0; iter.hasNext() && ctr < mergeFactor; ++ctr) {
      toMergeInputs.add(iter.next());
      iter.remove();
    }
    LOG.info(getName() + ": Starting merge with " + toMergeInputs.size() + 
             " segments, while ignoring " + inputs.size() + " segments");
    synchronized(pendingToBeMerged) {
      pendingToBeMerged.addLast(toMergeInputs);
      pendingToBeMerged.notifyAll();
    }
  }
}
 
Example 11
Project: googles-monorepo-demo   File: FilteredEntryMultimap.java   View Source Code Vote up 6 votes
@Override
public int remove(@Nullable Object key, int occurrences) {
  checkNonnegative(occurrences, "occurrences");
  if (occurrences == 0) {
    return count(key);
  }
  Collection<V> collection = unfiltered.asMap().get(key);
  if (collection == null) {
    return 0;
  }
  @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself
  K k = (K) key;
  int oldCount = 0;
  Iterator<V> itr = collection.iterator();
  while (itr.hasNext()) {
    V v = itr.next();
    if (satisfies(k, v)) {
      oldCount++;
      if (oldCount <= occurrences) {
        itr.remove();
      }
    }
  }
  return oldCount;
}
 
Example 12
Project: ats-framework   File: SkipIniMatcher.java   View Source Code Vote up 5 votes
private void processSections( String snapshot, Map<String, Map<String, String>> props ) {

        // remove sections that are marked for removal

        Iterator<Map.Entry<String, Map<String, String>>> it = props.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Map<String, String>> entry = it.next();
            String section = entry.getKey();

            if (isSectionSkipped(snapshot, section)) {
                it.remove();
                continue;
            }
        }
    }
 
Example 13
Project: springboot-shiro-cas-mybatis   File: CentralAuthenticationServiceImpl.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Timed(name = "GET_TICKETS_TIMER")
@Metered(name = "GET_TICKETS_METER")
@Counted(name="GET_TICKETS_COUNTER", monotonic=true)
@Override
public Collection<Ticket> getTickets(final Predicate predicate) {
    final Collection<Ticket> c = new HashSet<>(this.ticketRegistry.getTickets());
    final Iterator<Ticket> it = c.iterator();
    while (it.hasNext()) {
        if (!predicate.evaluate(it.next())) {
            it.remove();
        }
    }
    return c;
}
 
Example 14
Project: sentimental-analyzer   File: SingleWordTermFilter.java   View Source Code Vote up 5 votes
@Override
public void filter(Map<String, Term> terms) {
	Iterator<Entry<String, Term>> iter = terms.entrySet().iterator();
	while(iter.hasNext()) {
		Entry<String, Term> entry = iter.next();
		if(entry.getValue().getWord() == null 
				|| entry.getValue().getWord().length() <= 1) {
			iter.remove();
		}
	}
}
 
Example 15
Project: ProjectAres   File: GhostSquadronMatchModule.java   View Source Code Vote up 5 votes
@EventHandler
public void landmineExplode(final PlayerMoveEvent event) {
    MatchPlayer player = this.getMatch().getPlayer(event.getPlayer());
    if(!MatchPlayers.canInteract(player)) return;

    Location to = event.getTo();
    Iterator<Entry<Location, PlayerId>> iterator = this.landmines.entrySet().iterator();

    while(iterator.hasNext()) {
        Map.Entry<Location, PlayerId> entry = iterator.next();
        Location landmine = entry.getKey();
        MatchPlayer placer = this.getMatch().getPlayer(entry.getValue());

        if(placer == null || !placer.isParticipating()) {
            iterator.remove();
            continue;
        }

        Competitor placerTeam = this.landmineTeams.get(landmine);
        if(placerTeam == player.getParty()) continue;

        if(to.distanceSquared(landmine) < GhostSquadron.LANDMINE_ACTIVATION_DISTANCE_SQ) {
            TNTPrimed tnt = (TNTPrimed) landmine.getWorld().spawnEntity(landmine.clone().add(0, 1, 0), EntityType.PRIMED_TNT);
            tnt.setFuseTicks(0);
            tnt.setYield(1);

            this.reveal(player.getBukkit());
            getMatch().callEvent(new ExplosionPrimeByEntityEvent(tnt, placer.getBukkit()));
            iterator.remove();
            this.landmineTeams.remove(landmine);
        }
    }
}
 
Example 16
Project: hadoop   File: NodeStatusUpdaterImpl.java   View Source Code Vote up 5 votes
@VisibleForTesting
@Private
public void removeOrTrackCompletedContainersFromContext(
    List<ContainerId> containerIds) throws IOException {
  Set<ContainerId> removedContainers = new HashSet<ContainerId>();

  pendingContainersToRemove.addAll(containerIds);
  Iterator<ContainerId> iter = pendingContainersToRemove.iterator();
  while (iter.hasNext()) {
    ContainerId containerId = iter.next();
    // remove the container only if the container is at DONE state
    Container nmContainer = context.getContainers().get(containerId);
    if (nmContainer == null) {
      iter.remove();
    } else if (nmContainer.getContainerState().equals(
      org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerState.DONE)) {
      context.getContainers().remove(containerId);
      removedContainers.add(containerId);
      iter.remove();
    }
  }

  if (!removedContainers.isEmpty()) {
    LOG.info("Removed completed containers from NM context: "
        + removedContainers);
  }
  pendingCompletedContainers.clear();
}
 
Example 17
Project: DecompiledMinecraft   File: GuiNewChat.java   View Source Code Vote up 5 votes
/**
 * finds and deletes a Chat line by ID
 */
public void deleteChatLine(int p_146242_1_)
{
    Iterator<ChatLine> iterator = this.field_146253_i.iterator();

    while (iterator.hasNext())
    {
        ChatLine chatline = (ChatLine)iterator.next();

        if (chatline.getChatLineID() == p_146242_1_)
        {
            iterator.remove();
        }
    }

    iterator = this.chatLines.iterator();

    while (iterator.hasNext())
    {
        ChatLine chatline1 = (ChatLine)iterator.next();

        if (chatline1.getChatLineID() == p_146242_1_)
        {
            iterator.remove();
            break;
        }
    }
}
 
Example 18
Project: rmq4note   File: RouteInfoManager.java   View Source Code Vote up 5 votes
/**
 * 这里定时关闭不活跃的broker连接,默认时间为两分钟。
 * 这里,broker会定时向nameser注册broker信息时,会更新BrokerLiveInfo.lastUpdateTimestamp
 */
public void scanNotActiveBroker() {
    log.info("schedule topicQueueTable,{}", topicQueueTable);
    Iterator<Entry<String, BrokerLiveInfo>> it = this.brokerLiveTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, BrokerLiveInfo> next = it.next();
        long last = next.getValue().getLastUpdateTimestamp();
        if ((last + BROKER_CHANNEL_EXPIRED_TIME) < System.currentTimeMillis()) {
            RemotingUtil.closeChannel(next.getValue().getChannel());
            it.remove();
            log.warn("The broker channel expired, {} {}ms", next.getKey(), BROKER_CHANNEL_EXPIRED_TIME);
            this.onChannelDestroy(next.getKey(), next.getValue().getChannel());
        }
    }
}
 
Example 19
Project: lams   File: ResourceServiceImpl.java   View Source Code Vote up 4 votes
@Override
   @SuppressWarnings("unchecked")
   public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException {
if (ResourceServiceImpl.log.isDebugEnabled()) {
    ResourceServiceImpl.log.debug(
	    "Removing Share Resources content for user ID " + userId + " and toolContentId " + toolContentId);
}

Resource resource = resourceDao.getByContentId(toolContentId);
if (resource == null) {
    ResourceServiceImpl.log
	    .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content");
    return;
}

Iterator<ResourceItem> itemIterator = resource.getResourceItems().iterator();
while (itemIterator.hasNext()) {
    ResourceItem item = itemIterator.next();
    ResourceItemVisitLog visitLog = resourceItemVisitDao.getResourceItemLog(item.getUid(), userId.longValue());
    if (visitLog != null) {
	resourceItemVisitDao.removeObject(ResourceItemVisitLog.class, visitLog.getUid());
    }

    if (!item.isCreateByAuthor() && item.getCreateBy().getUserId().equals(userId.longValue())) {
	if (item.getFileUuid() != null) {
	    try {
		resourceToolContentHandler.deleteFile(item.getFileUuid());
	    } catch (Exception e) {
		throw new ToolException("Error while removing Share Resources file UUID " + item.getFileUuid(),
			e);
	    }
	}
	resourceItemDao.removeObject(ResourceItem.class, item.getUid());
	itemIterator.remove();
    }
}

List<ResourceSession> sessions = resourceSessionDao.getByContentId(toolContentId);
for (ResourceSession session : sessions) {
    ResourceUser user = resourceUserDao.getUserByUserIDAndSessionID(userId.longValue(), session.getSessionId());
    if (user != null) {
	NotebookEntry entry = getEntry(session.getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL,
		ResourceConstants.TOOL_SIGNATURE, userId);
	if (entry != null) {
	    resourceDao.removeObject(NotebookEntry.class, entry.getUid());
	}

	resourceUserDao.removeObject(ResourceUser.class, user.getUid());
    }
}
   }
 
Example 20
Project: lams   File: ImageGalleryServiceImpl.java   View Source Code Vote up 4 votes
@Override
   @SuppressWarnings("unchecked")
   public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException {
if (ImageGalleryServiceImpl.log.isDebugEnabled()) {
    ImageGalleryServiceImpl.log.debug(
	    "Removing Image Gallery content for user ID " + userId + " and toolContentId " + toolContentId);
}
ImageGallery gallery = imageGalleryDao.getByContentId(toolContentId);
if (gallery == null) {
    ImageGalleryServiceImpl.log
	    .warn("Did not find activity with toolContentId: " + toolContentId + " to remove learner content");
    return;
}

Iterator<ImageGalleryItem> itemIterator = gallery.getImageGalleryItems().iterator();
while (itemIterator.hasNext()) {
    ImageGalleryItem item = itemIterator.next();

    ImageVote vote = imageVoteDao.getImageVoteByImageAndUser(item.getUid(), userId.longValue());
    if (vote != null) {
	imageVoteDao.removeObject(ImageVote.class, vote.getUid());
    }

    if (!item.isCreateByAuthor() && item.getCreateBy().getUserId().equals(userId.longValue())) {
	try {
	    if (item.getOriginalFileUuid() != null) {
		imageGalleryToolContentHandler.deleteFile(item.getOriginalFileUuid());
	    }
	    if (item.getMediumFileUuid() != null) {
		imageGalleryToolContentHandler.deleteFile(item.getMediumFileUuid());
	    }
	    if (item.getThumbnailFileUuid() != null) {
		imageGalleryToolContentHandler.deleteFile(item.getThumbnailFileUuid());
	    }
	} catch (Exception e) {
	    throw new ToolException("Error while removing a file in Image Gallery", e);
	}

	imageGalleryItemDao.removeObject(ImageGalleryItem.class, item.getUid());
	itemIterator.remove();
    }
}

ImageGalleryUser user = imageGalleryUserDao.getUserByUserIDAndContentID(userId.longValue(), toolContentId);
if (user != null) {
    NotebookEntry entry = getEntry(user.getSession().getSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL,
	    ImageGalleryConstants.TOOL_SIGNATURE, userId);
    if (entry != null) {
	imageGalleryDao.removeObject(NotebookEntry.class, entry.getUid());
    }

    imageGalleryUserDao.removeObject(ImageGalleryUser.class, user.getUid());
}

   }