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:com.offbynull.voip.kademlia.model.NodeLeastRecentSet.java

public ActivityChangeSet touch(Instant time, Node node, boolean allowLinkMismatch) {
    Validate.notNull(time);//  w  w w.j  a v  a 2 s .c  om
    Validate.notNull(node);

    Id nodeId = node.getId();

    InternalValidate.matchesLength(baseId.getBitLength(), nodeId);
    //        Validate.isTrue(!nodeId.equals(baseId)); // Don't reject adding self

    // TODO: You can make this way more efficient if you used something like MultiTreeSet (guava) and sorted based on entry time

    // Remove existing entry
    Activity oldEntry = null;
    ListIterator<Activity> it = entries.listIterator();
    while (it.hasNext()) {
        Activity entry = it.next();

        Id entryId = entry.getNode().getId();

        if (entryId.equals(nodeId)) {
            if (!allowLinkMismatch) {
                InternalValidate.matchesLink(entry.getNode(), node);
            }

            // remove
            it.remove();
            oldEntry = entry;
            break;
        }
    }

    // Add entry
    Activity newEntry = new Activity(node, time);
    it = entries.listIterator();
    boolean added = false;
    while (it.hasNext()) {
        Activity entry = it.next();

        if (entry.getTime().isAfter(time)) {
            it.previous(); // move back 1 space, we want to add to element just before entry
            it.add(newEntry);
            added = true;
            break;
        }
    }

    if (!added) { // special case where newEntry needs to be added at the end of entries, not handled by loop above
        entries.addLast(newEntry);
    }

    // Set has become too large, remove the item with the latest time
    Activity discardedEntry = null;
    if (entries.size() > maxSize) {
        // if the node removed with the latest time is the one we just added, then report that node couldn't be added
        discardedEntry = entries.removeLast();
        if (discardedEntry.equals(newEntry)) {
            return ActivityChangeSet.NO_CHANGE;
        }
    }

    // Add successful
    if (oldEntry != null) {
        Validate.validState(discardedEntry == null); // sanity check, must not have discarded anything

        // updated existing node
        return ActivityChangeSet.updated(newEntry);
    } else {
        // if block above ensures oldEntry is null if we're in this else block, so sanity check below isn't nessecary
        // Validate.validState(oldEntry == null); // sanity check, node being touched must not have already existed

        // added new node
        Collection<Activity> addedEntries = singletonList(newEntry);
        Collection<Activity> removedEntries = discardedEntry == null ? emptyList()
                : singletonList(discardedEntry);
        Collection<Activity> updatedEntries = emptyList();
        return new ActivityChangeSet(addedEntries, removedEntries, updatedEntries);
    }
}

From source file:com.offbynull.voip.kademlia.model.NodeMostRecentSet.java

public ActivityChangeSet touch(Instant time, Node node, boolean allowLinkMismatch) {
    Validate.notNull(time);//w  ww . j av  a 2 s . c o m
    Validate.notNull(node);

    Id nodeId = node.getId();

    InternalValidate.matchesLength(baseId.getBitLength(), nodeId);
    //        Validate.isTrue(!nodeId.equals(baseId)); // Don't reject adding self

    // TODO: You can make this way more efficient if you used something like MultiTreeSet (guava) and sorted based on entry time

    // Remove existing entry
    Activity oldEntry = null;
    ListIterator<Activity> it = entries.listIterator();
    while (it.hasNext()) {
        Activity entry = it.next();

        Id entryId = entry.getNode().getId();

        if (entryId.equals(nodeId)) {
            if (!allowLinkMismatch) {
                InternalValidate.matchesLink(entry.getNode(), node);
            }

            // remove
            it.remove();
            oldEntry = entry;
            break;
        }
    }

    // Add entry
    Activity newEntry = new Activity(node, time);
    it = entries.listIterator(entries.size());
    boolean added = false;
    while (it.hasPrevious()) {
        Activity entry = it.previous();

        if (entry.getTime().isBefore(time)) {
            it.next(); // move forward 1 space, we want to add to element just after entry
            it.add(newEntry);
            added = true;
            break;
        }
    }

    if (!added) { // special case where newEntry needs to be added at the end of entries, not handled by loop above
        entries.addFirst(newEntry);
    }

    // Set has become too large, remove the item with the earliest time
    Activity discardedEntry = null;
    if (entries.size() > maxSize) {
        // if the node removed with the earliest time is the one we just added, then report that node couldn't be added
        discardedEntry = entries.removeFirst();
        if (discardedEntry.equals(newEntry)) {
            return ActivityChangeSet.NO_CHANGE;
        }
    }

    // Add successful
    if (oldEntry != null) {
        Validate.validState(discardedEntry == null); // sanity check, must not have discarded anything

        // updated existing node
        return ActivityChangeSet.updated(newEntry);
    } else {
        // if block above ensures oldEntry is null if we're in this else block, so sanity check below isn't nessecary
        // Validate.validState(oldEntry == null); // sanity check, node being touched must not have already existed

        // added new node
        Collection<Activity> addedEntries = singletonList(newEntry);
        Collection<Activity> removedEntries = discardedEntry == null ? emptyList()
                : singletonList(discardedEntry);
        Collection<Activity> updatedEntries = emptyList();
        return new ActivityChangeSet(addedEntries, removedEntries, updatedEntries);
    }
}

From source file:at.ofai.music.util.WormFileParseException.java

public void insert(Event newEvent, boolean uniqueTimes) {
    ListIterator<Event> li = l.listIterator();
    while (li.hasNext()) {
        int sgn = newEvent.compareTo(li.next());
        if (sgn < 0) {
            li.previous();//from   w  w w  .  jav a2  s .c  o m
            break;
        } else if (uniqueTimes && (sgn == 0)) {
            li.remove();
            break;
        }
    }
    li.add(newEvent);
}

From source file:org.apache.phoenix.execute.PhoenixTxnIndexMutationGenerator.java

private void processRollback(IndexMaintainer maintainer, byte[] txRollbackAttribute, ResultScanner scanner,
        Set<ColumnReference> mutableColumns, Collection<Mutation> indexUpdates,
        Map<ImmutableBytesPtr, MultiMutation> mutations, boolean replyWrite, final PTable table)
        throws IOException, SQLException {
    if (scanner != null) {
        Result result;//from w ww  .ja v  a2s  .c o  m
        // Loop through last committed row state plus all new rows associated with current transaction
        // to generate point delete markers for all index rows that were added. We don't have Tephra
        // manage index rows in change sets because we don't want to be hit with the additional
        // memory hit and do not need to do conflict detection on index rows.
        ColumnReference emptyColRef = new ColumnReference(maintainer.getDataEmptyKeyValueCF(),
                maintainer.getEmptyKeyValueQualifier());
        while ((result = scanner.next()) != null) {
            Mutation m = mutations.remove(new ImmutableBytesPtr(result.getRow()));
            // Sort by timestamp, type, cf, cq so we can process in time batches from oldest to newest
            // (as if we're "replaying" them in time order).
            List<Cell> cells = result.listCells();
            Collections.sort(cells, new Comparator<Cell>() {

                @Override
                public int compare(Cell o1, Cell o2) {
                    int c = Longs.compare(o1.getTimestamp(), o2.getTimestamp());
                    if (c != 0)
                        return c;
                    c = o1.getTypeByte() - o2.getTypeByte();
                    if (c != 0)
                        return c;
                    c = Bytes.compareTo(o1.getFamilyArray(), o1.getFamilyOffset(), o1.getFamilyLength(),
                            o1.getFamilyArray(), o1.getFamilyOffset(), o1.getFamilyLength());
                    if (c != 0)
                        return c;
                    return Bytes.compareTo(o1.getQualifierArray(), o1.getQualifierOffset(),
                            o1.getQualifierLength(), o1.getQualifierArray(), o1.getQualifierOffset(),
                            o1.getQualifierLength());
                }

            });
            int i = 0;
            int nCells = cells.size();
            Result oldResult = null, newResult;
            long readPtr = phoenixTransactionContext.getReadPointer();
            do {
                boolean hasPuts = false;
                LinkedList<Cell> singleTimeCells = Lists.newLinkedList();
                long writePtr;
                Cell cell = cells.get(i);
                do {
                    hasPuts |= cell.getTypeByte() == KeyValue.Type.Put.getCode();
                    writePtr = cell.getTimestamp();
                    ListIterator<Cell> it = singleTimeCells.listIterator();
                    do {
                        // Add at the beginning of the list to match the expected HBase
                        // newest to oldest sort order (which TxTableState relies on
                        // with the Result.getLatestColumnValue() calls). However, we
                        // still want to add Cells in the expected order for each time
                        // bound as otherwise we won't find it in our old state.
                        it.add(cell);
                    } while (++i < nCells && (cell = cells.get(i)).getTimestamp() == writePtr);
                } while (i < nCells && cell.getTimestamp() <= readPtr);

                // Generate point delete markers for the prior row deletion of the old index value.
                // The write timestamp is the next timestamp, not the current timestamp,
                // as the earliest cells are the current values for the row (and we don't
                // want to delete the current row).
                if (oldResult != null) {
                    TxTableState state = new TxTableState(mutableColumns, writePtr, m, emptyColRef, oldResult);
                    generateDeletes(indexUpdates, txRollbackAttribute, state, maintainer, replyWrite, table);
                }
                // Generate point delete markers for the new index value.
                // If our time batch doesn't have Puts (i.e. we have only Deletes), then do not
                // generate deletes. We would have generated the delete above based on the state
                // of the previous row. The delete markers do not give us the state we need to
                // delete.
                if (hasPuts) {
                    newResult = Result.create(singleTimeCells);
                    // First row may represent the current state which we don't want to delete
                    if (writePtr > readPtr) {
                        TxTableState state = new TxTableState(mutableColumns, writePtr, m, emptyColRef,
                                newResult);
                        generateDeletes(indexUpdates, txRollbackAttribute, state, maintainer, replyWrite,
                                table);
                    }
                    oldResult = newResult;
                } else {
                    oldResult = null;
                }
            } while (i < nCells);
        }
    }
}

From source file:org.jboss.forge.roaster.model.impl.AnnotationImpl.java

@Override
@SuppressWarnings("unchecked")
public AnnotationSource<O> setLiteralValue(final String name, final String value) {
    requireNonNull(value);//ww  w.j  av  a2  s .co m

    if (!isNormal() && !DEFAULT_VALUE.equals(name)) {
        convertTo(AnnotationType.NORMAL);
    } else if (!isSingleValue() && !isNormal() && DEFAULT_VALUE.equals(name)) {
        convertTo(AnnotationType.SINGLE);
    }
    if (isSingleValue() && DEFAULT_VALUE.equals(name)) {
        return setLiteralValue(value);
    }

    NormalAnnotation normalAnnotation = (NormalAnnotation) annotation;

    String stub = "@" + getName() + "(" + name + "=" + value + " ) public class Stub { }";
    JavaClass<?> temp = Roaster.parse(JavaClass.class, stub);

    NormalAnnotation anno = (NormalAnnotation) temp.getAnnotations().get(0).getInternal();
    MemberValuePair pair = (MemberValuePair) anno.values().get(0);

    List<MemberValuePair> values = normalAnnotation.values();
    ListIterator<MemberValuePair> iter = values.listIterator();
    while (iter.hasNext()) {
        if (iter.next().getName().getIdentifier().equals(name)) {
            iter.remove();
            break;
        }
    }
    iter.add((MemberValuePair) ASTNode.copySubtree(annotation.getAST(), pair));

    return this;
}

From source file:org.apache.phoenix.index.PhoenixTransactionalIndexer.java

private void processRollback(RegionCoprocessorEnvironment env, PhoenixIndexMetaData indexMetaData,
        byte[] txRollbackAttribute, ResultScanner scanner, Transaction tx, Set<ColumnReference> mutableColumns,
        Collection<Pair<Mutation, byte[]>> indexUpdates, Map<ImmutableBytesPtr, MultiMutation> mutations)
        throws IOException {
    if (scanner != null) {
        Result result;/*from  w  ww.j a  v  a 2s.com*/
        // Loop through last committed row state plus all new rows associated with current transaction
        // to generate point delete markers for all index rows that were added. We don't have Tephra
        // manage index rows in change sets because we don't want to be hit with the additional
        // memory hit and do not need to do conflict detection on index rows.
        ColumnReference emptyColRef = new ColumnReference(
                indexMetaData.getIndexMaintainers().get(0).getDataEmptyKeyValueCF(),
                indexMetaData.getIndexMaintainers().get(0).getEmptyKeyValueQualifier());
        while ((result = scanner.next()) != null) {
            Mutation m = mutations.remove(new ImmutableBytesPtr(result.getRow()));
            // Sort by timestamp, type, cf, cq so we can process in time batches from oldest to newest
            // (as if we're "replaying" them in time order).
            List<Cell> cells = result.listCells();
            Collections.sort(cells, new Comparator<Cell>() {

                @Override
                public int compare(Cell o1, Cell o2) {
                    int c = Longs.compare(o1.getTimestamp(), o2.getTimestamp());
                    if (c != 0)
                        return c;
                    c = o1.getTypeByte() - o2.getTypeByte();
                    if (c != 0)
                        return c;
                    c = Bytes.compareTo(o1.getFamilyArray(), o1.getFamilyOffset(), o1.getFamilyLength(),
                            o1.getFamilyArray(), o1.getFamilyOffset(), o1.getFamilyLength());
                    if (c != 0)
                        return c;
                    return Bytes.compareTo(o1.getQualifierArray(), o1.getQualifierOffset(),
                            o1.getQualifierLength(), o1.getQualifierArray(), o1.getQualifierOffset(),
                            o1.getQualifierLength());
                }

            });
            int i = 0;
            int nCells = cells.size();
            Result oldResult = null, newResult;
            long readPtr = tx.getReadPointer();
            do {
                boolean hasPuts = false;
                LinkedList<Cell> singleTimeCells = Lists.newLinkedList();
                long writePtr;
                Cell cell = cells.get(i);
                do {
                    hasPuts |= cell.getTypeByte() == KeyValue.Type.Put.getCode();
                    writePtr = cell.getTimestamp();
                    ListIterator<Cell> it = singleTimeCells.listIterator();
                    do {
                        // Add at the beginning of the list to match the expected HBase
                        // newest to oldest sort order (which TxTableState relies on
                        // with the Result.getLatestColumnValue() calls). However, we
                        // still want to add Cells in the expected order for each time
                        // bound as otherwise we won't find it in our old state.
                        it.add(cell);
                    } while (++i < nCells && (cell = cells.get(i)).getTimestamp() == writePtr);
                } while (i < nCells && cell.getTimestamp() <= readPtr);

                // Generate point delete markers for the prior row deletion of the old index value.
                // The write timestamp is the next timestamp, not the current timestamp,
                // as the earliest cells are the current values for the row (and we don't
                // want to delete the current row).
                if (oldResult != null) {
                    TxTableState state = new TxTableState(env, mutableColumns, indexMetaData.getAttributes(),
                            writePtr, m, emptyColRef, oldResult);
                    generateDeletes(indexMetaData, indexUpdates, txRollbackAttribute, state);
                }
                // Generate point delete markers for the new index value.
                // If our time batch doesn't have Puts (i.e. we have only Deletes), then do not
                // generate deletes. We would have generated the delete above based on the state
                // of the previous row. The delete markers do not give us the state we need to
                // delete.
                if (hasPuts) {
                    newResult = Result.create(singleTimeCells);
                    // First row may represent the current state which we don't want to delete
                    if (writePtr > readPtr) {
                        TxTableState state = new TxTableState(env, mutableColumns,
                                indexMetaData.getAttributes(), writePtr, m, emptyColRef, newResult);
                        generateDeletes(indexMetaData, indexUpdates, txRollbackAttribute, state);
                    }
                    oldResult = newResult;
                } else {
                    oldResult = null;
                }
            } while (i < nCells);
        }
    }
}

From source file:org.cloudifysource.usm.launcher.DefaultProcessLauncher.java

private void modifyWindowsCommandLine(final List<String> commandLineParams, final File workingDir) {
    final String firstParam = commandLineParams.get(0);
    if (firstParam.endsWith(".bat") || firstParam.endsWith(".cmd")) {
        for (int i = 0; i < WINDOWS_BATCH_FILE_PREFIX_PARAMS.length; i++) {
            commandLineParams.add(i, WINDOWS_BATCH_FILE_PREFIX_PARAMS[i]);
        }// ww w  . j a va 2s  . c  o m
    }

    // if the file does not exist, this is probably an operating system
    // command
    File file = new File(firstParam);
    if (!file.isAbsolute()) {
        file = new File(workingDir, firstParam);
    }

    if (!file.exists()) {
        // this is not an executable file, so add the cmd interpreter
        // prefix
        for (int i = 0; i < WINDOWS_BATCH_FILE_PREFIX_PARAMS.length; i++) {
            commandLineParams.add(i, WINDOWS_BATCH_FILE_PREFIX_PARAMS[i]);
        }
    }

    // remove quotes
    final ListIterator<String> commandIterator = commandLineParams.listIterator();
    while (commandIterator.hasNext()) {
        final String param = commandIterator.next();
        commandIterator.remove();
        commandIterator.add(StringUtils.replace(param, "\"", ""));
    }

}

From source file:org.jboss.forge.roaster.model.impl.AnnotationImpl.java

@Override
public AnnotationSource<O> setAnnotationValue(String name) {
    if (!isNormal() && DEFAULT_VALUE.equals(name)) {
        return setAnnotationValue();
    }// w  ww.  ja  v  a2 s.c o m
    if (!isNormal()) {
        convertTo(AnnotationType.NORMAL);
    }
    AnnotationSource<O> result = new Nested(this);

    String stub = "@" + getName() + "(" + name + "= 0 ) public class Stub { }";
    JavaClass<?> temp = Roaster.parse(JavaClass.class, stub);

    NormalAnnotation anno = (NormalAnnotation) temp.getAnnotations().get(0).getInternal();
    MemberValuePair pair = (MemberValuePair) anno.values().get(0);

    @SuppressWarnings("unchecked")
    List<MemberValuePair> values = ((NormalAnnotation) annotation).values();
    ListIterator<MemberValuePair> iter = values.listIterator();
    while (iter.hasNext()) {
        if (iter.next().getName().getIdentifier().equals(name)) {
            iter.remove();
            break;
        }
    }
    MemberValuePair mvpCopy = (MemberValuePair) ASTNode.copySubtree(annotation.getAST(), pair);
    mvpCopy.setValue((Expression) result.getInternal());
    iter.add(mvpCopy);

    return result;
}

From source file:net.sf.jabref.bst.VM.java

public String run(Collection<BibEntry> bibtex) {

    // Reset/*from   www  . j  av a  2 s .  c om*/
    bbl = new StringBuilder();

    strings = new HashMap<>();

    integers = new HashMap<>();
    integers.put("entry.max$", Integer.MAX_VALUE);
    integers.put("global.max$", Integer.MAX_VALUE);

    functions = new HashMap<>();
    functions.putAll(buildInFunctions);

    stack = new Stack<>();

    // Create entries
    entries = new ArrayList<>(bibtex.size());
    ListIterator<BstEntry> listIter = entries.listIterator();
    for (BibEntry entry : bibtex) {
        listIter.add(new BstEntry(entry));
    }

    // Go
    for (int i = 0; i < tree.getChildCount(); i++) {
        Tree child = tree.getChild(i);
        switch (child.getType()) {
        case BstParser.STRINGS:
            strings(child);
            break;
        case BstParser.INTEGERS:
            integers(child);
            break;
        case BstParser.FUNCTION:
            function(child);
            break;
        case BstParser.EXECUTE:
            execute(child);
            break;
        case BstParser.SORT:
            sort();
            break;
        case BstParser.ITERATE:
            iterate(child);
            break;
        case BstParser.REVERSE:
            reverse(child);
            break;
        case BstParser.ENTRY:
            entry(child);
            break;
        case BstParser.READ:
            read();
            break;
        case BstParser.MACRO:
            macro(child);
            break;
        default:
            LOGGER.info("Unknown type: " + child.getType());
            break;
        }
    }

    return bbl.toString();
}

From source file:geogebra.common.kernel.implicit.AlgoIntersectImplicitpolys.java

private void insert(double[] pair) {
    ListIterator<double[]> it = valPairs.listIterator();
    double eps = 1E-3; //find good value...
    while (it.hasNext()) {
        double[] p = it.next();
        if (Kernel.isGreater(p[0], pair[0], eps)) {
            it.previous();/*from  ww  w.j  av a2s .  com*/
            break;
        }
        if (Kernel.isEqual(p[0], pair[0], eps)) {
            if (Kernel.isGreater(p[1], pair[1], eps)) {
                it.previous();
                break;
            }
            if (Kernel.isEqual(p[1], pair[1], eps))
                return; //do not add
        }
    }
    it.add(pair);
}