Example usage for java.util ListIterator add

List of usage examples for java.util ListIterator add

Introduction

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

Prototype

void add(E e);

Source Link

Document

Inserts the specified element into the list (optional operation).

Usage

From source file:org.commonjava.maven.ext.core.impl.RESTCollector.java

/**
 * Prescans the Project to build up a list of Project GAs and also the various Dependencies.
 *///from  www.  ja  v  a  2  s .c  om
private void collect(final List<Project> projects) throws ManipulationException {
    final RESTState state = session.getState(RESTState.class);
    final VersioningState vs = session.getState(VersioningState.class);
    final DependencyState ds = session.getState(DependencyState.class);
    final PluginState ps = session.getState(PluginState.class);

    if (!session.isEnabled() || !state.isEnabled()) {
        logger.debug(getClass().getSimpleName() + ": Nothing to do!");
        return;
    }

    final ArrayList<ProjectVersionRef> restParam = new ArrayList<>();
    final ArrayList<ProjectVersionRef> newProjectKeys = new ArrayList<>();

    final String override = vs.getOverride();

    for (final Project project : projects) {
        if (isEmpty(override)) {
            // TODO: Check this : For the rest API I think we need to check every project GA not just inheritance root.
            // Strip SNAPSHOT from the version for matching. DA will handle OSGi conversion.
            ProjectVersionRef newKey = new SimpleProjectVersionRef(project.getKey());

            if (project.getVersion().endsWith("-SNAPSHOT")) {
                if (!vs.preserveSnapshot()) {
                    newKey = new SimpleProjectVersionRef(project.getKey().asProjectRef(),
                            project.getVersion().substring(0, project.getVersion().indexOf("-SNAPSHOT")));
                } else {
                    logger.warn("SNAPSHOT detected for REST call but preserve-snapshots is enabled.");
                }
            }
            newProjectKeys.add(newKey);
        } else if (project.isExecutionRoot()) {
            // We want to manually override the version ; therefore ignore what is in the project and calculate potential
            // matches for that instead.
            Project p = projects.get(0);
            newProjectKeys.add(new SimpleProjectVersionRef(p.getGroupId(), p.getArtifactId(), override));
        }
    }
    restParam.addAll(newProjectKeys);

    // If the dependencyState getRemoteBOMDepMgmt contains suffix then send that to process as well.
    // We only recognise dependencyManagement of the form g:a:version-rebuild not g:a:version-rebuild-<numeric>.
    for (ProjectVersionRef bom : (ds.getRemoteBOMDepMgmt() == null ? Collections.<ProjectVersionRef>emptyList()
            : ds.getRemoteBOMDepMgmt())) {
        if (!Version.hasBuildNumber(bom.getVersionString())
                && bom.getVersionString().contains(PropertiesUtils.getSuffix(session))) {
            // Create the dummy PVR to send to DA (which requires a numeric suffix).
            ProjectVersionRef newBom = new SimpleProjectVersionRef(bom.asProjectRef(),
                    bom.getVersionString() + "-0");
            logger.debug("Adding dependencyManagement BOM {} into REST call.", newBom);
            restParam.add(newBom);
        }
    }

    Set<ArtifactRef> localDeps = establishAllDependencies(session, projects, null);
    // Ok we now have a defined list of top level project plus a unique list of all possible dependencies.
    // Need to send that to the rest interface to get a translation.
    for (ArtifactRef p : localDeps) {
        restParam.add(p.asProjectVersionRef());
    }

    // Call the REST to populate the result.
    logger.debug("Passing {} GAVs following into the REST client api {} ", restParam.size(), restParam);
    logger.info("Calling REST client...");
    long start = System.nanoTime();
    Map<ProjectVersionRef, String> restResult = null;

    try {
        restResult = state.getVersionTranslator().translateVersions(restParam);
    } finally {
        printFinishTime(start, (restResult != null));
    }
    logger.debug("REST Client returned {} ", restResult);

    // Process rest result for boms
    ListIterator<ProjectVersionRef> iterator = (ds.getRemoteBOMDepMgmt() == null
            ? Collections.<ProjectVersionRef>emptyList().listIterator()
            : ds.getRemoteBOMDepMgmt().listIterator());
    while (iterator.hasNext()) {
        ProjectVersionRef pvr = iterator.next();
        // As before, only process the BOMs if they are of the format <rebuild suffix> without a numeric portion.
        if (!Version.hasBuildNumber(pvr.getVersionString())
                && pvr.getVersionString().contains(PropertiesUtils.getSuffix(session))) {
            // Create the dummy PVR to compare with results to...
            ProjectVersionRef newBom = new SimpleProjectVersionRef(pvr.asProjectRef(),
                    pvr.getVersionString() + "-0");
            if (restResult.keySet().contains(newBom)) {
                ProjectVersionRef replacementBOM = new SimpleProjectVersionRef(pvr.asProjectRef(),
                        restResult.get(newBom));
                logger.debug("Replacing BOM value of {} with {}.", pvr, replacementBOM);
                iterator.remove();
                iterator.add(replacementBOM);
            }
        }
    }

    vs.setRESTMetadata(parseVersions(session, projects, state, newProjectKeys, restResult));

    final Map<ArtifactRef, String> overrides = new HashMap<>();

    // Convert the loaded remote ProjectVersionRefs to the original ArtifactRefs
    for (ArtifactRef a : localDeps) {
        if (restResult.containsKey(a.asProjectVersionRef())) {
            overrides.put(a, restResult.get(a.asProjectVersionRef()));
        }
    }
    logger.debug("Setting REST Overrides {} ", overrides);
    ds.setRemoteRESTOverrides(overrides);
    // Unfortunately as everything is just GAVs we have to send everything to the PluginManipulator as well.
    ps.setRemoteRESTOverrides(overrides);
}

From source file:io.swagger.codegen.languages.AbstractJavaCodegen.java

@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
    // recursively add import for mapping one type to multiple imports
    List<Map<String, String>> recursiveImports = (List<Map<String, String>>) objs.get("imports");
    if (recursiveImports == null)
        return objs;

    ListIterator<Map<String, String>> listIterator = recursiveImports.listIterator();
    while (listIterator.hasNext()) {
        String _import = listIterator.next().get("import");
        // if the import package happens to be found in the importMapping (key)
        // add the corresponding import package to the list
        if (importMapping.containsKey(_import)) {
            Map<String, String> newImportMap = new HashMap<String, String>();
            newImportMap.put("import", importMapping.get(_import));
            listIterator.add(newImportMap);
        }/*from   ww  w  .  ja va  2s  .  c o m*/
    }

    return postProcessModelsEnum(objs);
}

From source file:com.edgenius.wiki.render.macro.AlignMacro.java

@Override
protected void replaceHTML(HTMLNode node, ListIterator<HTMLNode> iter, RenderContext context) {
    if (node.getPair() == null) {
        log.warn("Unexpect case: No close tag for " + this.getClass().getName());
        return;//  w  ww  .jav a 2 s  .  c  o  m
    }
    if (node.getStyle() != null && node.getStyle().get(NameConstants.TEXT_ALIGN) != null
            && (node.getAttributes() == null
                    || StringUtils.isBlank(node.getAttributes().get(NameConstants.AID)))) {
        String align = node.getStyle().get(NameConstants.TEXT_ALIGN);
        HTMLNode alignNode = null;

        //what ever the NODE is, such as <td style="align:center;colspan=4"> etc, the align attribute need be remove
        node.removeStyle("text-align", null);
        if ("div".equalsIgnoreCase(node.getTagName()) || "span".equalsIgnoreCase(node.getTagName())
                || "p".equalsIgnoreCase(node.getTagName())) {
            alignNode = node;
        } else {
            //maybe <td> tag,  it can not be simply reset -- otherwise, table will lost one cell.So here will add a paired <span> node
            //!!! don't insert <div> pair as it may broken TableMacro.isSimpleTableSupport()
            //enclose by current node 
            //?? need handle default left?
            if ("center".equalsIgnoreCase(align) || "right".equalsIgnoreCase(align)) {
                //build a proxy tag, their tagname does not matter as it will reset following code
                alignNode = new HTMLNode("<span>", false);
                HTMLNode closeAlignNode = new HTMLNode("</span>", false);
                alignNode.setPair(closeAlignNode);

                iter.add(alignNode);

                //example, go to </td> tag 
                moveIteratorCursorTo(node.getPair(), iter, true);
                //this is that node before </td>, need confirm it is not <td> (basically, it is impossible a <div> insert after <td>) 
                HTMLNode nd = iter.previous();
                if (nd != node) {
                    iter.add(closeAlignNode);
                    //move iterator back to node
                    moveIteratorCursorTo(node, iter, false);
                }
            }
        }

        if (alignNode != null) {
            if ("center".equalsIgnoreCase(align)) {
                alignNode.reset("{align:align=center}", true);
                alignNode.getPair().reset("{align}", true);

            } else if ("right".equalsIgnoreCase(align)) {
                alignNode.reset("{align:align=right}", true);
                alignNode.getPair().reset("{align}", true);
            }
        }
    }

}

From source file:annis.visualizers.component.grid.EventExtractor.java

/**
* Splits events of a row if they contain a gap. Gaps are found using the
* token index (provided as ANNIS specific {@link SFeature}. Inserted events
* have a special style to mark them as gaps.
*
* @param row/*from w ww .j a  v  a  2s .c  om*/
* @param graph
* @param startTokenIndex token index of the first token in the match
* @param endTokenIndex token index of the last token in the match
*/
private static void splitRowsOnGaps(Row row, final SDocumentGraph graph, long startTokenIndex,
        long endTokenIndex) {
    ListIterator<GridEvent> itEvents = row.getEvents().listIterator();
    while (itEvents.hasNext()) {
        GridEvent event = itEvents.next();

        int lastTokenIndex = Integer.MIN_VALUE;

        // sort the coveredIDs
        LinkedList<String> sortedCoveredToken = new LinkedList<String>(event.getCoveredIDs());
        Collections.sort(sortedCoveredToken, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                SNode node1 = graph.getSNode(o1);
                SNode node2 = graph.getSNode(o2);

                if (node1 == node2) {
                    return 0;
                }
                if (node1 == null) {
                    return -1;
                }
                if (node2 == null) {
                    return +1;
                }

                long tokenIndex1 = node1.getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();
                long tokenIndex2 = node2.getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();

                return ((Long) (tokenIndex1)).compareTo(tokenIndex2);
            }
        });

        // first calculate all gaps
        List<GridEvent> gaps = new LinkedList<GridEvent>();
        for (String id : sortedCoveredToken) {

            SNode node = graph.getSNode(id);
            long tokenIndexRaw = node.getSFeature(ANNIS_NS, FEAT_TOKENINDEX).getSValueSNUMERIC();

            tokenIndexRaw = clip(tokenIndexRaw, startTokenIndex, endTokenIndex);

            int tokenIndex = (int) (tokenIndexRaw - startTokenIndex);
            int diff = tokenIndex - lastTokenIndex;

            if (lastTokenIndex >= 0 && diff > 1) {
                // we detected a gap
                GridEvent gap = new GridEvent(event.getId() + "_gap", lastTokenIndex + 1, tokenIndex - 1, "");
                gap.setGap(true);
                gaps.add(gap);
            }

            lastTokenIndex = tokenIndex;
        } // end for each covered token id

        for (GridEvent gap : gaps) {
            // remember the old right value
            int oldRight = event.getRight();

            // shorten last event
            event.setRight(gap.getLeft() - 1);

            // insert the real gap
            itEvents.add(gap);

            // insert a new event node that covers the rest of the event
            GridEvent after = new GridEvent(event.getId() + "_after", gap.getRight() + 1, oldRight,
                    event.getValue());
            after.getCoveredIDs().addAll(event.getCoveredIDs());
            itEvents.add(after);
        }

    }
}

From source file:mondrian.rolap.RolapStar.java

/**
 * Adds an {@link AggStar} to this star.
 *
 * <p>Internally the AggStars are added in sort order, smallest row count
 * to biggest, so that the most efficient AggStar is encountered first;
 * ties do not matter./*from w  w  w .j  a va2 s.com*/
 */
public void addAggStar(AggStar aggStar) {
    // Add it before the first AggStar which is larger, if there is one.
    int size = aggStar.getSize();
    ListIterator<AggStar> lit = aggStars.listIterator();
    while (lit.hasNext()) {
        AggStar as = lit.next();
        if (as.getSize() >= size) {
            lit.previous();
            lit.add(aggStar);
            return;
        }
    }

    // There is no larger star. Add at the end of the list.
    aggStars.add(aggStar);
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/**********************************************
 * /*from  w  ww.java 2  s.  c o m*/
 * insertListInListByDate
 * @param singleArtistEventList
 * 
 **********************************************/
public void insertListInListByDate(LinkedList<ArtistEvent> singleArtistEventList) {
    /*
     * If this artist List is empty just return
     */
    if (singleArtistEventList.isEmpty())
        return;

    /*
     * If the big list is empty just add this one to it
     */
    if (artistEventList.isEmpty()) {
        artistEventList.addAll(singleArtistEventList);
        return;
    }

    /*
     * Insert the items (normal case)
     */
    ListIterator<ArtistEvent> artistEventListIterator = artistEventList.listIterator(0);
    ListIterator<ArtistEvent> singleArtistEventListIterator = singleArtistEventList.listIterator(0);
    ArtistEvent artistEvent;
    ArtistEvent singleArtistEvent;
    while (singleArtistEventListIterator.hasNext()) {
        /*
         * Not yet at the end of the big list
         */
        if (artistEventListIterator.hasNext()) {
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEvent = artistEventListIterator.next();
            while (singleArtistEvent.dateInMillis > artistEvent.dateInMillis) {
                if (artistEventListIterator.hasNext())
                    artistEvent = artistEventListIterator.next();
                else {
                    if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE) {
                        return;
                    } else {
                        break; // TODO: add missing items to the big list
                    }
                }
            }
            artistEventListIterator.previous();
            artistEventListIterator.add(singleArtistEvent);
        }
        /*
         * At the end of the big list (but not of the 'small' list
         */
        else {
            if (artistEventListIterator.previousIndex() >= MAX_EVENT_LIST_SIZE)
                return;
            singleArtistEvent = singleArtistEventListIterator.next();
            artistEventListIterator.add(singleArtistEvent);
            artistEventListIterator.next();
        }
    }

    /*
     * Keep the list size in check
     */
    while (artistEventList.size() > MAX_EVENT_LIST_SIZE)
        artistEventList.removeLast();
}

From source file:com.robonobo.eon.SEONConnection.java

private void storePktForLater(SEONPacket pkt) throws EONException {
    // If the packet is after our last one, put it at the end, otherwise
    // search where to put it
    if (recvdPkts.size() == 0)
        recvdPkts.add(pkt);//from   w  w  w  . j  a v  a2 s .  c o m
    else if (mod.gt(pkt.getSequenceNumber(), recvdPkts.getLast().getSequenceNumber()))
        recvdPkts.addLast(pkt);
    else {
        // TODO If this is still too slow, we could cut out the iterator
        // creation by creating a custom list class with a resettable
        // iterator...
        ListIterator<SEONPacket> iter = recvdPkts.listIterator();
        while (iter.hasNext()) {
            SEONPacket itPkt = iter.next();
            if (pkt.getSequenceNumber() == itPkt.getSequenceNumber()) {
                if (itPkt.getPayloadSize() == 0) {
                    // This is a data pkt coming after a bare ack - replace it with the data pkt
                    iter.remove();
                    iter.add(pkt);
                }
                // Otherwise this is just a duplicate pkt - ignore
                break;
            } else if (mod.lt(pkt.getSequenceNumber(), itPkt.getSequenceNumber())) {
                // Insert the pkt *before* the current pkt
                iter.previous();
                iter.add(pkt);
                break;
            }
        }
    }
}

From source file:com.robonobo.eon.SEONConnection.java

/** All packets in the retrans queue are regarded as lost */
private void markInTransitPktsAsLost() {
    // Add everything in retransQ to lostQ, inserting at the correct places - both lists are already sorted so this
    // isn't too bad
    ListIterator<SEONPacket> lostIter = lostQ.listIterator();
    SEONPacket curLostPkt = lostIter.hasNext() ? lostIter.next() : null;
    while (retransQ.size() > 0) {
        SEONPacket newPkt = retransQ.removeFirst();
        while (true) {
            if (curLostPkt == null) {
                lostQ.addLast(newPkt);// w  w w. j  ava  2s.  c  om
                break;
            }
            // If our newly-added packet comes before this one, add it
            // before
            if (mod.lt(newPkt.getSequenceNumber(), curLostPkt.getSequenceNumber())) {
                lostIter.previous();
                lostIter.add(newPkt);
                lostIter.next();
                break;
            }
            curLostPkt = lostIter.hasNext() ? lostIter.next() : null;
        }
    }
}

From source file:org.apache.fop.layoutmgr.inline.TextLayoutManager.java

/** {@inheritDoc} */
public List addALetterSpaceTo(final List oldList, int depth) {
    // old list contains only a box, or the sequence: box penalty glue box;
    // look at the Position stored in the first element in oldList
    // which is always a box
    ListIterator oldListIterator = oldList.listIterator();
    KnuthElement knuthElement = (KnuthElement) oldListIterator.next();
    Position pos = knuthElement.getPosition();
    LeafPosition leafPos = (LeafPosition) pos.getPosition(depth);
    int index = leafPos.getLeafPos();
    //element could refer to '-1' position, for non-collapsed spaces (?)
    if (index > -1) {
        AreaInfo areaInfo = getAreaInfo(index);
        areaInfo.letterSpaceCount++;//from  ww  w . j  a  v  a 2  s  .  c  om
        areaInfo.addToAreaIPD(letterSpaceIPD);
        if (TextLayoutManager.BREAK_CHARS.indexOf(foText.charAt(tempStart - 1)) >= 0) {
            // the last character could be used as a line break
            // append new elements to oldList
            oldListIterator = oldList.listIterator(oldList.size());
            oldListIterator
                    .add(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true, auxiliaryPosition, false));
            oldListIterator.add(new KnuthGlue(letterSpaceIPD, auxiliaryPosition, false));
        } else if (letterSpaceIPD.isStiff()) {
            // constant letter space: replace the box
            // give it the unwrapped position of the replaced element
            oldListIterator.set(new KnuthInlineBox(areaInfo.areaIPD.getOpt(), alignmentContext, pos, false));
        } else {
            // adjustable letter space: replace the glue
            oldListIterator.next(); // this would return the penalty element
            oldListIterator.next(); // this would return the glue element
            oldListIterator.set(
                    new KnuthGlue(letterSpaceIPD.mult(areaInfo.letterSpaceCount), auxiliaryPosition, true));
        }
    }
    return oldList;
}

From source file:com.apptentive.android.sdk.module.messagecenter.view.MessageCenterActivityContent.java

private void prepareMessages(final List<MessageCenterListItem> originalItems) {
    messages.clear();/*  w w  w.  j  av a 2 s .c om*/
    unsendMessagesCount = 0;
    // Loop through each message item retrieved from database
    for (MessageCenterListItem item : originalItems) {
        if (item instanceof ApptentiveMessage) {
            ApptentiveMessage apptentiveMessage = (ApptentiveMessage) item;
            Double createdAt = apptentiveMessage.getCreatedAt();
            if (apptentiveMessage.isOutgoingMessage() && createdAt == null) {
                unsendMessagesCount++;
            }

            /*
             * Find proper location to insert into the messages list of the listview.
             */
            ListIterator<MessageCenterListItem> listIterator = messages.listIterator();
            ApptentiveMessage next = null;
            while (listIterator.hasNext()) {
                next = (ApptentiveMessage) listIterator.next();
                Double nextCreatedAt = next.getCreatedAt();
                // For unsent and dropped message, move the iterator to the end, and append there
                if (createdAt == null || createdAt <= Double.MIN_VALUE) {
                    continue;
                }
                // next message has not received by server or received, but has a later created_at time
                if (nextCreatedAt == null || nextCreatedAt > createdAt) {
                    break;
                }
            }

            if (next == null || next.getCreatedAt() == null || createdAt == null
                    || next.getCreatedAt() <= createdAt || createdAt <= Double.MIN_VALUE) {
                listIterator.add(item);
            } else {
                // Add in front of the message that has later created_at time
                listIterator.set(item);
                listIterator.add(next);
            }
        }
    }
    // Finally, add greeting message
    messages.add(0, interaction.getGreeting());
}