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:chat.viska.commons.pipelines.Pipeline.java

public void addTowardsInboundEnd(final String previous, final String name, final Pipe pipe) {
    Validate.notBlank(previous);/*from  www  .  j a  va2 s .com*/
    Completable.fromAction(() -> {
        pipeLock.writeLock().lockInterruptibly();
        try {
            if (getIteratorOf(name) != null) {
                throw new IllegalArgumentException("Name collision: " + name);
            }
            ListIterator<Map.Entry<String, Pipe>> iterator = getIteratorOf(previous);
            if (iterator == null) {
                throw new NoSuchElementException(previous);
            }
            iterator.next();
            iterator.add(new AbstractMap.SimpleImmutableEntry<>(name, pipe));
            pipe.onAddedToPipeline(this);
        } finally {
            pipeLock.writeLock().unlock();
        }
    }).onErrorComplete().subscribeOn(Schedulers.io()).subscribe();
}

From source file:com.edgenius.wiki.render.filter.HeadingFilter.java

@Override
protected void replaceHTML(HTMLNode node, ListIterator<HTMLNode> nodeIter, RenderContext context) {
    //      if(node.getTagName().length() != 2){
    //         log.error("Unexpectd head tag, should be 2 characters " + node.getTagName());
    //         return;
    //      }// ww  w .  j a v a2 s.  c o  m
    if (node.getPair() == null) {
        log.error("No close tag for heading tag");
        return;
    }

    int head = NumberUtils.toInt("" + (node.getTagName().charAt(1)), -1);
    if (head < 1 || head > 6) {
        log.error("Unexpectd head tag, should be h[1-6]" + node.getTagName());
        return;
    }

    node.reset(HTMLNode.LINE_START_TAG, false);
    //after new line tag, add new text tag for markup 
    nodeIter.add(new HTMLNode("h" + head + ". ", true));
    node.getPair().reset(HTMLNode.LINE_END_TAG, false);

}

From source file:com.projity.pm.graphic.model.transform.NodeCacheTransformer.java

private void placeVoidNodes(ListIterator i, Node node) {
    Node current;//from  ww w . jav a2 s.c  o m
    for (Enumeration e = node.children(); e.hasMoreElements();) {
        current = (Node) e.nextElement();
        if (current.isVoid()) {
            GraphicNode gcurrent = refCache.getGraphicNode(current);
            i.add(gcurrent);
        }
    }
}

From source file:org.xwiki.refactoring.internal.splitter.DefaultDocumentSplitter.java

/**
 * A recursive method for traversing the xdom of the root document and splitting it into sub documents.
 *
 * @param parentDoc the parent {@link WikiDocument} under which the given list of children reside.
 * @param children current list of blocks being traversed.
 * @param depth the depth from the root xdom to current list of children.
 * @param result space for storing the resulting documents.
 * @param splittingCriterion the {@link SplittingCriterion}.
 * @param namingCriterion the {@link NamingCriterion}.
 *///from ww  w  .j ava  2 s. c o  m
private void split(WikiDocument parentDoc, List<Block> children, int depth, List<WikiDocument> result,
        SplittingCriterion splittingCriterion, NamingCriterion namingCriterion) {
    ListIterator<Block> it = children.listIterator();
    while (it.hasNext()) {
        Block block = it.next();
        if (splittingCriterion.shouldSplit(block, depth)) {
            // Split a new document and add it to the results list.
            XDOM xdom = new XDOM(block.getChildren());
            String newDocumentName = namingCriterion.getDocumentName(xdom);
            WikiDocument newDoc = new WikiDocument(newDocumentName, xdom, parentDoc);
            result.add(newDoc);
            // Remove the original block from the parent document.
            it.remove();
            // Place a link from the parent to child.
            it.add(new NewLineBlock());
            it.add(createLink(block, newDocumentName));
            // Check whether this node should be further traversed.
            if (splittingCriterion.shouldIterate(block, depth)) {
                split(newDoc, newDoc.getXdom().getChildren(), depth + 1, result, splittingCriterion,
                        namingCriterion);
            }
        } else if (splittingCriterion.shouldIterate(block, depth)) {
            split(parentDoc, block.getChildren(), depth + 1, result, splittingCriterion, namingCriterion);
        }
    }
}

From source file:net.sf.json.TestUserSubmitted.java

public void testJSONArrayIterator() {
    JSONArray jsonArray = new JSONArray();
    jsonArray.add("1");
    jsonArray.add("2");
    jsonArray.add("3");

    List list = new LinkedList();
    list.add("4");
    list.add("5");
    list.add("6");
    jsonArray.add(list);/*  w w  w .java 2 s  .com*/

    List newList = new LinkedList();
    newList.add("7");
    newList.add("8");
    newList.add("9");

    Assertions.assertEquals(JSONArray.fromObject("['1','2','3',['4','5','6']]"), jsonArray);

    ListIterator listIterator = jsonArray.listIterator();
    listIterator.add(newList);

    Assertions.assertEquals(JSONArray.fromObject("[['7','8','9'],'1','2','3',['4','5','6']]"), jsonArray);
}

From source file:es.tid.fiware.rss.service.SettlementManager.java

/**
 * Get files from path.//from  ww  w .j a v  a 2s.c o m
 * 
 * @param path
 * @return
 */
public List<RSSFile> getSettlementFilesOfPath(String path) {
    // Opening/creating the folder
    File folder = new File(path);
    List<RSSFile> rssFilesList = new ArrayList<RSSFile>();
    RSSFile rssf = new RSSFile();

    if (folder.exists() && folder.isDirectory()) {
        File[] files = folder.listFiles();
        Arrays.sort(files);

        if (files.length > 0) {
            List<File> fileList = new ArrayList<File>(Arrays.asList(files));
            ListIterator<File> lit = fileList.listIterator();

            while (lit.hasNext()) {
                File file = lit.next();
                logger.info(file.getAbsolutePath());

                if (file.isDirectory()) {
                    logger.debug("Is directory. Getting more files...");
                    File[] moreFiles = file.listFiles();
                    Arrays.sort(moreFiles);
                    if (moreFiles.length > 0) {
                        for (File f : moreFiles) {
                            lit.add(f);
                            lit.previous();
                        }
                    }
                } else {
                    rssf = new RSSFile();
                    rssf.setTxName(file.getName());
                    rssf.setTxUrl(file.getAbsolutePath());
                    rssFilesList.add(rssf);
                    logger.debug("File added");
                }
            }
        }
    }
    return rssFilesList;
}

From source file:org.apache.hadoop.hbase.regionserver.transactional.TrxTransactionState.java

public synchronized void addDelete(final Delete delete) {
    WriteAction waction;/*w  ww  .  j  a va  2  s .co  m*/
    WALEdit e1 = new WALEdit();
    long now = EnvironmentEdgeManager.currentTimeMillis();
    updateLatestTimestamp(delete.getFamilyCellMap().values(), now);
    if (delete.getTimeStamp() == HConstants.LATEST_TIMESTAMP) {
        delete.setTimestamp(now);
    }
    deletes.add(delete);

    ListIterator<WriteAction> writeOrderIter = writeOrdering.listIterator();
    writeOrderIter.add(waction = new WriteAction(delete));

    if (this.earlyLogging) {
        for (Cell value : waction.getCells()) {
            KeyValue kv = KeyValue.cloneAndAddTags(value, tagList);
            e1.add(kv);
            e.add(kv);
        }
        try {
            long txid = this.tHLog.appendNoSync(this.regionInfo, this.regionInfo.getTable(), e1,
                    new ArrayList<UUID>(), EnvironmentEdgeManager.currentTimeMillis(), this.tabledescriptor,
                    this.logSeqId, false, HConstants.NO_NONCE, HConstants.NO_NONCE);
            //if (LOG.isTraceEnabled()) LOG.trace("Trafodion Recovery: Y00 write edit to HLOG during delete with txid " + txid + " ts flush id " + this.flushTxId);
            if (txid > this.flushTxId)
                this.flushTxId = txid; // save the log txid into TS object, later sync on largestSeqid during phase 1
        } catch (IOException exp1) {
            LOG.info(
                    "TrxRegionEndpoint coprocessor addDelete writing to HLOG for early logging: Threw an exception");
        }
    } else {
        for (Cell value : waction.getCells()) {
            KeyValue kv = KeyValue.cloneAndAddTags(value, tagList);
            e.add(kv);
        }
    }

    if (LOG.isTraceEnabled())
        LOG.trace("addDelete -- EXIT");
}

From source file:org.apache.fop.layoutmgr.SpaceResolver.java

private void generate(ListIterator iter) {
    MinOptMax spaceBeforeBreak = sum(firstPartLengths);
    MinOptMax spaceAfterBreak = sum(secondPartLengths);

    boolean hasPrecedingNonBlock = false;
    if (breakPoss != null) {
        if (spaceBeforeBreak.isNonZero()) {
            iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true));
            iter.add(new KnuthGlue(spaceBeforeBreak, null, true));
            if (breakPoss.isForcedBreak()) {
                //Otherwise, the preceding penalty and glue will be cut off
                iter.add(new KnuthBox(0, null, true));
            }/*  w ww .ja  v  a  2s. co m*/
        }
        iter.add(new KnuthPenalty(breakPoss.getPenaltyWidth(), breakPoss.getPenaltyValue(), false,
                breakPoss.getBreakClass(), new SpaceHandlingBreakPosition(this, breakPoss), false));
        if (breakPoss.getPenaltyValue() <= -KnuthPenalty.INFINITE) {
            return; //return early. Not necessary (even wrong) to add additional elements
        }

        // No break
        // TODO: We can't use a MinOptMax for glue2,
        // because min <= opt <= max is not always true - why?
        MinOptMax noBreakLength = sum(noBreakLengths);
        MinOptMax spaceSum = spaceBeforeBreak.plus(spaceAfterBreak);
        int glue2width = noBreakLength.getOpt() - spaceSum.getOpt();
        int glue2stretch = noBreakLength.getStretch() - spaceSum.getStretch();
        int glue2shrink = noBreakLength.getShrink() - spaceSum.getShrink();

        if (glue2width != 0 || glue2stretch != 0 || glue2shrink != 0) {
            iter.add(new KnuthGlue(glue2width, glue2stretch, glue2shrink, null, true));
        }
    } else {
        if (spaceBeforeBreak.isNonZero()) {
            throw new IllegalStateException("spaceBeforeBreak should be 0 in this case");
        }
    }
    Position pos = null;
    if (breakPoss == null) {
        pos = new SpaceHandlingPosition(this);
    }
    if (spaceAfterBreak.isNonZero() || pos != null) {
        iter.add(new KnuthBox(0, pos, true));
    }
    if (spaceAfterBreak.isNonZero()) {
        iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true));
        iter.add(new KnuthGlue(spaceAfterBreak, null, true));
        hasPrecedingNonBlock = true;
    }
    if (isLast && hasPrecedingNonBlock) {
        //Otherwise, the preceding penalty and glue will be cut off
        iter.add(new KnuthBox(0, null, true));
    }
}

From source file:org.apache.hadoop.hbase.regionserver.transactional.TrxTransactionState.java

public synchronized void addWrite(final Put write) {
    if (LOG.isTraceEnabled())
        LOG.trace("addWrite -- ENTRY: write: " + write.toString());
    WriteAction waction;//from  www.  ja  va 2s .  c o m
    KeyValue kv;
    WALEdit e1 = new WALEdit();
    updateLatestTimestamp(write.getFamilyCellMap().values(), EnvironmentEdgeManager.currentTimeMillis());
    // Adding read scan on a write action
    addRead(new WriteAction(write).getRow());

    ListIterator<WriteAction> writeOrderIter = writeOrdering.listIterator();
    writeOrderIter.add(waction = new WriteAction(write));

    if (this.earlyLogging) { // immeditaely write edit out to HLOG during DML (actve transaction state)
        for (Cell value : waction.getCells()) {
            //KeyValue kv = KeyValueUtil.ensureKeyValue(value);
            kv = KeyValue.cloneAndAddTags(value, tagList);
            //if (LOG.isTraceEnabled()) LOG.trace("KV hex dump " + Hex.encodeHexString(kv.getValueArray() /*kv.getBuffer()*/));
            e1.add(kv);
            e.add(kv);
        }
        try {
            long txid = this.tHLog.appendNoSync(this.regionInfo, this.regionInfo.getTable(), e1,
                    new ArrayList<UUID>(), EnvironmentEdgeManager.currentTimeMillis(), this.tabledescriptor,
                    this.logSeqId, false, HConstants.NO_NONCE, HConstants.NO_NONCE);
            //if (LOG.isTraceEnabled()) LOG.trace("Trafodion Recovery: Y11 write edit to HLOG during put with txid " + txid + " ts flush id " + this.flushTxId);
            if (txid > this.flushTxId)
                this.flushTxId = txid; // save the log txid into TS object, later sync on largestSeqid during phase 1
        } catch (IOException exp1) {
            LOG.info(
                    "TrxRegionEndpoint coprocessor addWrite writing to HLOG for early logging: Threw an exception");
            //throw exp1;
        }
    } else { // edits are buffered in ts and written out to HLOG in phase 1
        for (Cell value : waction.getCells()) {
            kv = KeyValue.cloneAndAddTags(value, tagList);
            e.add(kv);
        }
    }
    if (LOG.isTraceEnabled())
        LOG.trace("addWrite -- EXIT");
}

From source file:org.eclipse.php.internal.core.documentModel.parser.regions.PhpScriptRegion.java

@Override
public StructuredDocumentEvent updateRegion(Object requester, IStructuredDocumentRegion flatnode,
        String changes, int requestStart, int lengthToReplace) {
    isFullReparsed = true;/* w w  w .j  a va 2s .  c  o m*/
    updatedTokensStart = -1;
    updatedTokensEnd = -1;
    try {
        final int offset = requestStart - flatnode.getStartOffset() - getStart();

        // support the <?php case
        if (offset < 4) {
            return null;
        }
        // checks for odd quotes
        final String deletedText = lengthToReplace == 0 ? "" //$NON-NLS-1$
                : flatnode.getParentDocument().get(requestStart, lengthToReplace);
        final int length = changes.length();
        if (startQuoted(deletedText) || startQuoted(changes)) {
            return null;
        }

        synchronized (tokensContainer) {
            if (ProjectOptions.getPHPVersion(project) != currentPhpVersion) {
                // https://bugs.eclipse.org/bugs/show_bug.cgi?id=510509
                // force full reparse
                return null;
            }

            // get the region to re-parse
            ITextRegion tokenStart = tokensContainer.getToken(offset == 0 ? 0 : offset - 1);
            ITextRegion tokenEnd = tokensContainer.getToken(offset + lengthToReplace);

            // make sure, region to re-parse doesn't start with unknown
            // token
            while (PHPRegionTypes.UNKNOWN_TOKEN.equals(tokenStart.getType()) && (tokenStart.getStart() > 0)) {
                tokenStart = tokensContainer.getToken(tokenStart.getStart() - 1);
            }

            // make sure, region to re-parse doesn't end with unknown token
            while (PHPRegionTypes.UNKNOWN_TOKEN.equals(tokenEnd.getType())
                    && (tokensContainer.getLastToken() != tokenEnd)) {
                tokenEnd = tokensContainer.getToken(tokenEnd.getEnd());
            }

            boolean shouldDeprecatedKeyword = false;
            int previousIndex = tokensContainer.phpTokens.indexOf(tokenStart) - 1;
            if (previousIndex >= 0) {
                ITextRegion previousRegion = tokensContainer.phpTokens.get(previousIndex);
                if (PhpTokenContainer.deprecatedKeywordAfter(previousRegion.getType())) {
                    shouldDeprecatedKeyword = true;
                }
                if (PHPPartitionTypes.isPHPMultiLineCommentRegion(tokenStart.getType())
                        && tokenStart.getLength() == 1
                        && PHPPartitionTypes.isPHPMultiLineCommentStartRegion(previousRegion.getType())) {
                    requestStart = previousRegion.getStart();
                }

            }

            int newTokenOffset = tokenStart.getStart();

            // get start and end states
            final LexerState startState = tokensContainer.getState(newTokenOffset);
            final LexerState endState = tokensContainer.getState(tokenEnd.getEnd());

            final PhpTokenContainer newContainer = new PhpTokenContainer();
            final AbstractPhpLexer phpLexer = getPhpLexer(
                    new DocumentReader(flatnode, changes, requestStart, lengthToReplace, newTokenOffset),
                    startState, currentPhpVersion);

            if (ArrayUtils.contains(phpLexer.getHeredocStates(), startState.getFirstState())) {
                // https://bugs.eclipse.org/bugs/show_bug.cgi?id=498525
                // Fully re-parse when we're in a heredoc/nowdoc section.
                // NB: it's much easier and safer to use the lexer state to
                // determine if we're in a heredoc/nowdoc section,
                // using PHPRegionTypes make us depend on how each PHP
                // lexer version analyzes the heredoc/nowdoc content.
                // In the same way, PHPPartitionTypes.isPhpQuotesState(type)
                // cannot be used here because it's not exclusive to
                // heredoc/nowdoc sections.
                return null;
            }
            if (isMaybeStartingNewHeredocSection(tokenStart)) {
                // In case a user is (maybe) starting to write a brand new
                // heredoc/nowdoc section in a php document, we should fully
                // re-parse the document to update the lexer to
                // distinguish "<<" bitwise shift operators from "<<" and
                // "<<<" operators that are followed by a label.
                // This also allows highlighters to correctly detect and
                // highlight opening and closing heredoc/nowdoc tags asap.
                return null;
            }

            LexerState state = startState;
            try {
                String yylex = phpLexer.getNextToken();
                if (shouldDeprecatedKeyword && PhpTokenContainer.isKeyword(yylex)) {
                    yylex = PHPRegionTypes.PHP_LABEL;
                }
                int yylength;
                final int toOffset = offset + length;
                while (yylex != null && newTokenOffset <= toOffset && yylex != PHPRegionTypes.PHP_CLOSETAG) {
                    yylength = phpLexer.getLength();
                    newContainer.addLast(yylex, newTokenOffset, yylength, yylength, state);
                    newTokenOffset += yylength;
                    state = phpLexer.createLexicalStateMemento();
                    yylex = phpLexer.getNextToken();
                }
                if (yylex == PHPRegionTypes.WHITESPACE) {
                    yylength = phpLexer.getLength();
                    newContainer.adjustWhitespace(yylex, newTokenOffset, yylength, yylength, state);
                }
            } catch (IOException e) {
                Logger.logException(e);
            }

            // if the fast reparser couldn't lex - - reparse all
            if (newContainer.isEmpty()) {
                return null;
            }

            // if the two streams end with the same lexer state -
            // 1. replace the regions
            // 2. adjust next regions start location
            // 3. update state changes
            final int size = length - lengthToReplace;
            final int end = newContainer.getLastToken().getEnd();

            if (!state.equals(endState) || tokenEnd.getEnd() + size != end) {
                return null;
            }

            // 1. replace the regions
            final ListIterator oldIterator = tokensContainer.removeTokensSubList(tokenStart, tokenEnd);

            ITextRegion[] newTokens = newContainer.getPhpTokens(); // now,
            // add
            // the new
            // ones
            for (int i = 0; i < newTokens.length; i++) {
                oldIterator.add(newTokens[i]);
            }

            // 2. adjust next regions start location
            while (oldIterator.hasNext()) {
                final ITextRegion adjust = (ITextRegion) oldIterator.next();
                adjust.adjustStart(size);
            }

            // 3. update state changes
            tokensContainer.updateStateChanges(newContainer, tokenStart.getStart(), end);
            updatedTokensStart = tokenStart.getStart();
            updatedTokensEnd = end;
            isFullReparsed = false;
        }

        return super.updateRegion(requester, flatnode, changes, requestStart, lengthToReplace);

    } catch (BadLocationException e) {
        PHPCorePlugin.log(e);
        return null; // causes to full reparse in this case
    }
}