Example usage for java.util ListIterator remove

List of usage examples for java.util ListIterator remove

Introduction

In this page you can find the example usage for java.util ListIterator remove.

Prototype

void remove();

Source Link

Document

Removes from the list the last element that was returned by #next or #previous (optional operation).

Usage

From source file:org.opennms.netmgt.collectd.Collectd.java

/**
 * This method is responsible for handling serviceDeleted events.
 * //w  ww  .  j  a va 2s .co  m
 * @param event
 *            The event to process.
 * @throws InsufficientInformationException 
 * 
 */
private void handleServiceDeleted(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);
    EventUtils.checkInterface(event);
    EventUtils.checkService(event);

    //INCORRECT; we now support all *sorts* of data collection.  This is *way* out of date
    // Currently only support SNMP data collection.
    //
    //if (!event.getService().equals("SNMP"))
    //    return;

    Long nodeId = event.getNodeid();
    String ipAddr = event.getInterface();
    String svcName = event.getService();

    // Iterate over the collectable services list and mark any entries
    // which match the nodeId/ipAddr of the deleted service
    // for deletion.
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        ListIterator<CollectableService> liter = getCollectableServices().listIterator();
        while (liter.hasNext()) {
            cSvc = liter.next();

            // Only interested in entries with matching nodeId, IP address
            // and service
            InetAddress addr = (InetAddress) cSvc.getAddress();

            //WATCH the brackets; there used to be an extra close bracket after the ipAddr comparison which borked this whole expression
            if (!(cSvc.getNodeId() == nodeId && addr.getHostName().equals(ipAddr)
                    && cSvc.getServiceName().equals(svcName)))
                continue;

            synchronized (cSvc) {
                // Retrieve the CollectorUpdates object associated with
                // this CollectableService if one exists.
                CollectorUpdates updates = cSvc.getCollectorUpdates();

                // Now set the update's deletion flag so the next
                // time it is selected for execution by the scheduler
                // the collection will be skipped and the service will not
                // be rescheduled.
                LOG.debug(
                        "Marking CollectableService for deletion because a service was deleted:  Service nodeid={}, deleted node:{}, service address:{}, deleted interface:{}, service servicename:{}, deleted service name:{}, event source {}",
                        cSvc.getNodeId(), nodeId, addr.getHostName(), ipAddr, cSvc.getServiceName(), svcName,
                        event.getSource());
                updates.markForDeletion();
            }

            // Now safe to remove the collectable service from
            // the collectable services list
            liter.remove();
        }
    }

    LOG.debug("serviceDeletedHandler: processing of serviceDeleted event for {}/{}/{} completed.", nodeId,
            ipAddr, svcName);
}

From source file:com.android.systemui.qs.QSDragPanel.java

public void setTiles(final Collection<QSTile<?>> tilesCollection) {
    // we try to be as efficient as possible here because this can happen while the user
    // is in edit mode, or maybe even while tiles are animating
    // step 1: stop all animations
    // step 2: remove tiles no longer to be used, cache ones that are still valid
    // step 3: remove empty viewpager pages
    // step 4: generate new tiles, re-add cached ones

    if (DEBUG_TILES) {
        Log.i(TAG, "setTiles() called with tiles = [" + tilesCollection + "]");
    }//  w  ww.  j  a v  a2s . c o  m
    if (mLastDragRecord != null && mRecords.indexOf(mLastDragRecord) == -1) {
        // the last removed record might be stored in mLastDragRecord if we just shifted
        // re-add it to the list so we'll clean it up below
        mRecords.add(mLastDragRecord);
        mLastDragRecord = null;
    }

    // step kinda-1
    if (mDraggingRecord != null) {
        // dragging record might be animating back, force it to finished position
        mDraggingRecord.tileView.animate().cancel();
    }

    int currentViewPagerPage = mViewPager.getCurrentItem();
    int removedPages = 0;

    Map<QSTile<?>, DragTileRecord> cachedRecords = new ArrayMap<>();
    ListIterator<TileRecord> iterator = mRecords.listIterator(mRecords.size());

    int recordsRemoved = 0;
    // cleanup current records
    while (iterator.hasPrevious()) { // mRecords
        DragTileRecord dr = (DragTileRecord) iterator.previous();

        // step 1
        dr.tileView.animate().cancel();

        // step 2
        if (tilesCollection.contains(dr.tile)) {
            if (DEBUG_TILES) {
                Log.i(TAG, "caching tile: " + dr.tile);
            }
            cachedRecords.put(dr.tile, dr);
        } else {
            if (dr.page >= 0) {
                if (DEBUG_TILES) {
                    Log.w(TAG, "removed dr.tileView: " + dr.tileView + " from page: " + dr.page
                            + " (dest page: " + dr.destinationPage + ")");
                }

                removeTileView(dr.tileView);
            }
            if (DEBUG_TILES) {
                Log.i(TAG, "removing tile: " + dr.tile);
            }

            // remove record
            iterator.remove();
            recordsRemoved++;

            dr.page = -1;
            dr.destinationPage = -1;
        }
    }

    // at this point cachedRecords should have all retained tiles, no new or old tiles
    int delta = tilesCollection.size() - cachedRecords.size() - recordsRemoved;
    if (DEBUG_TILES) {
        Log.i(TAG, "record map delta: " + delta);
    }

    // step 3
    final Iterator<QSPage> pageIterator = mPages.iterator();
    while (pageIterator.hasNext()) {
        final QSPage page = pageIterator.next();
        final int viewpagerIndex = page.getPageIndex() + (mEditing ? 1 : 0);
        final int childCount = page.getChildCount();

        if (DEBUG_TILES) {
            Log.d(TAG, "page " + viewpagerIndex + " has " + childCount);
        }
        if (page.getPageIndex() >= getCurrentMaxPageCount() - 1) {
            if (DEBUG_TILES) {
                Log.d(TAG, "page : " + page + " has " + childCount + " children");
            }
            if (childCount == 0) {
                removedPages++;

                page.removeAllViews();
                mPagerAdapter.startUpdate(mViewPager);
                mPagerAdapter.destroyItem(mViewPager, viewpagerIndex, page);
                mPagerAdapter.finishUpdate(mViewPager);
                mPagerAdapter.notifyDataSetChanged();
            }
        }
    }

    if (removedPages > 0) {
        // even though we explicitly destroy old pages, without this call,
        // the viewpager doesn't seem to want to pick up the fact that we have less pages
        // and allows "empty" scrolls to the right where there is no page.
        if (DEBUG_TILES) {
            Log.d(TAG, "re-setting adapter, page: " + currentViewPagerPage);
        }
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setCurrentItem(Math.min(currentViewPagerPage, mPagerAdapter.getCount()), false);
        mPagerAdapter.notifyDataSetChanged();
    }

    // step 4
    mRecords.ensureCapacity(tilesCollection.size());
    int runningCount = 0;

    final Iterator<QSTile<?>> newTileIterator = tilesCollection.iterator();
    while (newTileIterator.hasNext()) {
        QSTile<?> tile = newTileIterator.next();
        if (tile instanceof CustomQSTile) {
            if (((CustomQSTile) tile).isUserRemoved() || ((CustomQSTile) tile).getTile() == null) {
                // tile not published yet
                continue;
            }
        }
        final int tileDestPage = getPagesForCount(runningCount + 1) - 1;

        if (DEBUG_TILES) {
            Log.d(TAG, "tile at : " + runningCount + ": " + tile + " to dest page: " + tileDestPage);
        }
        DragTileRecord record;
        if (!cachedRecords.containsKey(tile)) {
            if (DEBUG_TILES) {
                Log.d(TAG, "tile at: " + runningCount + " not cached, adding it to records");
            }
            record = makeRecord(tile);
            record.destinationPage = tileDestPage;
            mRecords.add(runningCount, record);
            mPagerAdapter.notifyDataSetChanged();
        } else {
            record = cachedRecords.get(tile);
            if (DEBUG_TILES) {
                Log.d(TAG, "tile at : " + runningCount + ": cached, restoring: " + record);
            }

            mPages.get(record.page).removeView(record.tileView);

            record.page = -1;
            record.destinationPage = tileDestPage;

            mRecords.remove(record);
            mRecords.add(runningCount, record);
            mPagerAdapter.notifyDataSetChanged();
        }
        if (record.page == -1) {
            // add the view
            mPages.get(record.destinationPage).addView(record.tileView);
            record.page = record.destinationPage;
            if (DEBUG_TILES) {
                Log.d(TAG, "added view " + record);
            }
        }
        runningCount++;
    }

    if (isShowingDetail()) {
        mDetail.bringToFront();
    }
    mPagerAdapter.notifyDataSetChanged();

    refreshAllTiles();
    requestLayout();
}

From source file:com.av.remusic.service.MediaService.java

private int removeTracksInternal(int first, int last) {
    synchronized (this) {
        if (last < first) {
            return 0;
        } else if (first < 0) {
            first = 0;/*  www  .  j  ava2s. c  o  m*/
        } else if (last >= mPlaylist.size()) {
            last = mPlaylist.size() - 1;
        }

        boolean gotonext = false;
        if (first <= mPlayPos && mPlayPos <= last) {
            mPlayPos = first;
            gotonext = true;
        } else if (mPlayPos > last) {
            mPlayPos -= last - first + 1;
        }
        final int numToRemove = last - first + 1;

        if (first == 0 && last == mPlaylist.size() - 1) {
            mPlayPos = -1;
            mNextPlayPos = -1;
            mPlaylist.clear();
            mHistory.clear();
        } else {
            for (int i = 0; i < numToRemove; i++) {
                mPlaylistInfo.remove(mPlaylist.get(first).mId);
                mPlaylist.remove(first);

            }

            ListIterator<Integer> positionIterator = mHistory.listIterator();
            while (positionIterator.hasNext()) {
                int pos = positionIterator.next();
                if (pos >= first && pos <= last) {
                    positionIterator.remove();
                } else if (pos > last) {
                    positionIterator.set(pos - numToRemove);
                }
            }
        }
        if (gotonext) {
            if (mPlaylist.size() == 0) {
                stop(true);
                mPlayPos = -1;
                closeCursor();
            } else {
                if (mShuffleMode != SHUFFLE_NONE) {
                    mPlayPos = getNextPosition(true);
                } else if (mPlayPos >= mPlaylist.size()) {
                    mPlayPos = 0;
                }
                final boolean wasPlaying = isPlaying();
                stop(false);
                openCurrentAndNext();
                if (wasPlaying) {
                    play();
                }
            }
            notifyChange(META_CHANGED);
        }
        return last - first + 1;
    }
}

From source file:com.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * Removes the range of tracks specified from the play list. If a file
 * within the range is the file currently being played, playback will move
 * to the next file after the range./*from  w w w . j  av a2 s . c om*/
 *
 * @param first The first file to be removed
 * @param last  The last file to be removed
 * @return the number of tracks deleted
 */
private int removeTracksInternal(int first, int last) {
    synchronized (this) {
        if (last < first) {
            return 0;
        } else if (first < 0) {
            first = 0;
        } else if (last >= mPlaylist.size()) {
            last = mPlaylist.size() - 1;
        }

        boolean gotonext = false;
        if (first <= mPlayPos && mPlayPos <= last) {
            mPlayPos = first;
            gotonext = true;
        } else if (mPlayPos > last) {
            mPlayPos -= last - first + 1;
        }
        final int numToRemove = last - first + 1;

        if (first == 0 && last == mPlaylist.size() - 1) {
            mPlayPos = -1;
            mNextPlayPos = -1;
            mPlaylist.clear();
            mHistory.clear();
        } else {
            for (int i = 0; i < numToRemove; i++) {
                mPlaylist.remove(first);
            }

            // remove the items from the history
            // this is not ideal as the history shouldn't be impacted by this
            // but since we are removing items from the array, it will throw
            // an exception if we keep it around.  Idealistically with the queue
            // rewrite this should be all be fixed
            // https://cyanogen.atlassian.net/browse/MUSIC-44
            ListIterator<Integer> positionIterator = mHistory.listIterator();
            while (positionIterator.hasNext()) {
                int pos = positionIterator.next();
                if (pos >= first && pos <= last) {
                    positionIterator.remove();
                } else if (pos > last) {
                    positionIterator.set(pos - numToRemove);
                }
            }
        }
        if (gotonext) {
            if (mPlaylist.size() == 0) {
                stop(true);
                mPlayPos = -1;
                closeCursor();
            } else {
                if (mShuffleMode != SHUFFLE_NONE) {
                    mPlayPos = getNextPosition(true);
                } else if (mPlayPos >= mPlaylist.size()) {
                    mPlayPos = 0;
                }
                final boolean wasPlaying = isPlaying();
                stop(false);
                openCurrentAndNext();
                if (wasPlaying) {
                    play();
                }
            }
            notifyChange(META_CHANGED);
        }
        return last - first + 1;
    }
}

From source file:org.trnltk.experiment.morphology.ambiguity.DataDiffUtil.java

/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 *
 * @param diffs LinkedList of Diff objects.
 *//* www . j  av  a 2 s  .  c  o  m*/
public void diff_cleanupSemanticLossless(LinkedList<Diff<T>> diffs) {
    List<T> equality1, edit, equality2;
    List<T> commonString;
    int commonOffset;
    int score, bestScore;
    List<T> bestEquality1, bestEdit, bestEquality2;
    // Create a new iterator at the start.
    ListIterator<Diff<T>> pointer = diffs.listIterator();
    Diff<T> prevDiff = pointer.hasNext() ? pointer.next() : null;
    Diff<T> thisDiff = pointer.hasNext() ? pointer.next() : null;
    Diff<T> nextDiff = pointer.hasNext() ? pointer.next() : null;
    // Intentionally ignore the first and last element (don't need checking).
    while (nextDiff != null) {
        if (prevDiff.operation == Operation.EQUAL && nextDiff.operation == Operation.EQUAL) {
            // This is a single edit surrounded by equalities.
            equality1 = prevDiff.text;
            edit = thisDiff.text;
            equality2 = nextDiff.text;

            // First, shift the edit as far left as possible.
            commonOffset = diff_commonSuffix(equality1, edit);
            if (commonOffset != 0) {
                commonString = edit.subList(edit.size() - commonOffset, edit.size());
                equality1 = equality1.subList(0, equality1.size() - commonOffset);
                edit = ListUtils.union(commonString, edit.subList(0, edit.size() - commonOffset));
                equality2 = ListUtils.union(commonString, equality2);
            }

            // Second, step character by character right, looking for the best fit.
            bestEquality1 = equality1;
            bestEdit = edit;
            bestEquality2 = equality2;
            bestScore = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
            while (edit.size() != 0 && equality2.size() != 0 && edit.get(0).equals(equality2.get(0))) {
                equality1 = ListUtils.union(equality1, Arrays.asList(edit.get(0)));
                edit = ListUtils.union(edit.subList(1, edit.size()), Arrays.asList(equality2.get(0)));
                equality2 = equality2.subList(1, equality2.size());
                score = diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2);
                // The >= encourages trailing rather than leading whitespace on edits.
                if (score >= bestScore) {
                    bestScore = score;
                    bestEquality1 = equality1;
                    bestEdit = edit;
                    bestEquality2 = equality2;
                }
            }

            if (!prevDiff.text.equals(bestEquality1)) {
                // We have an improvement, save it back to the diff.
                if (bestEquality1.size() != 0) {
                    prevDiff.text = bestEquality1;
                } else {
                    pointer.previous(); // Walk past nextDiff.
                    pointer.previous(); // Walk past thisDiff.
                    pointer.previous(); // Walk past prevDiff.
                    pointer.remove(); // Delete prevDiff.
                    pointer.next(); // Walk past thisDiff.
                    pointer.next(); // Walk past nextDiff.
                }
                thisDiff.text = bestEdit;
                if (bestEquality2.size() != 0) {
                    nextDiff.text = bestEquality2;
                } else {
                    pointer.remove(); // Delete nextDiff.
                    nextDiff = thisDiff;
                    thisDiff = prevDiff;
                }
            }
        }
        prevDiff = thisDiff;
        thisDiff = nextDiff;
        nextDiff = pointer.hasNext() ? pointer.next() : null;
    }
}

From source file:com.parse.ParseObject.java

/**
 * Handles the result of {@code save}.//  w  w w .  ja v a  2  s  .  c o  m
 *
 * Should be called on success or failure.
 */
/* package */ Task<Void> handleSaveResultAsync(final ParseObject.State result,
        final ParseOperationSet operationsBeforeSave) {
    Task<Void> task = Task.forResult((Void) null);

    final boolean success = result != null;
    synchronized (mutex) {
        // Find operationsBeforeSave in the queue so that we can remove it and move to the next
        // operation set.
        ListIterator<ParseOperationSet> opIterator = operationSetQueue
                .listIterator(operationSetQueue.indexOf(operationsBeforeSave));
        opIterator.next();
        opIterator.remove();

        if (!success) {
            // Merge the data from the failed save into the next save.
            ParseOperationSet nextOperation = opIterator.next();
            nextOperation.mergeFrom(operationsBeforeSave);
            return task;
        }
    }

    /*
     * If this object is in the offline store, then we need to make sure that we pull in any dirty
     * changes it may have before merging the server data into it.
     */
    final OfflineStore store = Parse.getLocalDatastore();
    if (store != null) {
        task = task.onSuccessTask(new Continuation<Void, Task<Void>>() {
            @Override
            public Task<Void> then(Task<Void> task) throws Exception {
                return store.fetchLocallyAsync(ParseObject.this).makeVoid();
            }
        });
    }

    // fetchLocallyAsync will return an error if this object isn't in the LDS yet and that's ok
    task = task.continueWith(new Continuation<Void, Void>() {
        @Override
        public Void then(Task<Void> task) throws Exception {
            synchronized (mutex) {
                State newState;
                if (result.isComplete()) {
                    // Result is complete, so just replace
                    newState = result;
                } else {
                    // Result is incomplete, so we'll need to apply it to the current state
                    newState = getState().newBuilder().apply(operationsBeforeSave).apply(result).build();
                }
                setState(newState);
            }
            return null;
        }
    });

    if (store != null) {
        task = task.onSuccessTask(new Continuation<Void, Task<Void>>() {
            @Override
            public Task<Void> then(Task<Void> task) throws Exception {
                return store.updateDataForObjectAsync(ParseObject.this);
            }
        });
    }

    task = task.onSuccess(new Continuation<Void, Void>() {
        @Override
        public Void then(Task<Void> task) throws Exception {
            saveEvent.invoke(ParseObject.this, null);
            return null;
        }
    });

    return task;
}

From source file:org.oscm.serviceprovisioningservice.bean.ServiceProvisioningServiceBean.java

private void cleanUpProducts(List<Product> products, Set<Long> prodKeysToBeRemoved,
        Map<Long, Product> prodKeysToBeReplaced) {
    ListIterator<Product> productsIterator = products.listIterator();
    while (productsIterator.hasNext()) {
        Long productKey = Long.valueOf(productsIterator.next().getKey());
        if (prodKeysToBeRemoved.contains(productKey) && !prodKeysToBeReplaced.containsKey(productKey)) {
            // remove obsolete products (only if they won't be replaced)
            productsIterator.remove();
        } else {/*from  w ww .j a v  a 2s. c o m*/
            Product specificCopy = prodKeysToBeReplaced.get(productKey);
            if (specificCopy != null) {
                // replace templates by specific copies
                productsIterator.set(specificCopy);
            }
        }
    }
}

From source file:com.google.bitcoin.core.Wallet.java

private void checkBalanceFuturesLocked(@Nullable BigInteger avail) {
    checkState(lock.isHeldByCurrentThread());
    BigInteger estimated = null;//from  w  w w.j av a  2  s . co m
    final ListIterator<BalanceFutureRequest> it = balanceFutureRequests.listIterator();
    while (it.hasNext()) {
        final BalanceFutureRequest req = it.next();
        BigInteger val = null;
        if (req.type == BalanceType.AVAILABLE) {
            if (avail == null)
                avail = getBalance(BalanceType.AVAILABLE);
            if (avail.compareTo(req.value) < 0)
                continue;
            val = avail;
        } else if (req.type == BalanceType.ESTIMATED) {
            if (estimated == null)
                estimated = getBalance(BalanceType.ESTIMATED);
            if (estimated.compareTo(req.value) < 0)
                continue;
            val = estimated;
        }
        // Found one that's finished.
        it.remove();
        final BigInteger v = checkNotNull(val);
        // Don't run any user-provided future listeners with our lock held.
        Threading.USER_THREAD.execute(new Runnable() {
            @Override
            public void run() {
                req.future.set(v);
            }
        });
    }
}