Example usage for java.util ListIterator previous

List of usage examples for java.util ListIterator previous

Introduction

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

Prototype

E previous();

Source Link

Document

Returns the previous element in the list and moves the cursor position backwards.

Usage

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Searches the finger table for the closest id to the id being searched for (closest in terms of being {@code <=} to), but skips
 * certain ids./*w w  w  .  j  a  v a2 s.  co m*/
 *
 * @param id id being searched for
 * @param skipIds ids being skipped
 * @return closest pointer (closest in terms of being {@code <=} to)
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code id}'s has a different limit bit size than base pointer's id
 */
public Pointer findClosest(Id id, Id... skipIds) {
    Validate.notNull(id);
    Validate.noNullElements(skipIds);
    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);

    List<Id> skipIdList = Arrays.asList(skipIds);
    Id selfId = basePtr.getId();

    InternalEntry foundEntry = null;
    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();
        Id fingerId = ie.pointer.getId();
        // if finger should be skipped, ignore it
        if (skipIdList.contains(fingerId)) {
            continue;
        }
        // if finger[i] exists between n (exclusive) and id (exclusive)
        // then return it
        if (fingerId.isWithin(selfId, false, id, true)) {
            foundEntry = ie;
            break;
        }
    }

    return foundEntry == null ? basePtr : foundEntry.pointer;
}

From source file:com.offbynull.peernetic.playground.chorddht.model.FingerTable.java

/**
 * Removes a pointer in to the finger table. If the pointer doesn't exist in the finger table, does nothing. See the
 * constraints/guarantees mentioned in the class Javadoc: {@link FingerTable}.
 * @param ptr pointer to put in as finger
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if {@code ptr}'s id has a different limit bit size than the base pointer's id, or if {@code ptr} has
 * an id that matches the base pointer's id
 *///from  w w w .  j a v  a  2s .  c  o  m
public void remove(ExternalPointer<A> ptr) {
    Validate.notNull(ptr);
    Validate.isTrue(IdUtils.getBitLength(ptr.getId()) == bitCount);

    Id id = ptr.getId();
    A address = ptr.getAddress();
    Id baseId = basePtr.getId();

    Validate.isTrue(IdUtils.getBitLength(id) == bitCount);
    Validate.isTrue(!id.equals(baseId));

    ListIterator<InternalEntry> lit = table.listIterator(table.size());
    while (lit.hasPrevious()) {
        InternalEntry ie = lit.previous();

        if (ie.pointer instanceof InternalPointer) { // don't bother inspecting internal pointers since we can only remove
                                                     // external pointers
            continue;
        }

        ExternalPointer<A> testPtr = (ExternalPointer<A>) ie.pointer;
        Id testId = testPtr.getId();
        A testAddress = testPtr.getAddress();

        if (id.equals(testId) && address.equals(testAddress)) {
            remove(lit.previousIndex() + 1);
            break;
        }
    }
}

From source file:org.apache.ambari.server.scheduler.ExecutionScheduleManager.java

private JobDetail persistBatch(RequestExecution requestExecution) throws AmbariException {

    Batch batch = requestExecution.getBatch();
    JobDetail jobDetail = null;//from w  ww.j  ava  2 s . c  o m

    if (batch != null) {
        List<BatchRequest> batchRequests = batch.getBatchRequests();
        if (batchRequests != null) {
            Collections.sort(batchRequests);
            ListIterator<BatchRequest> iterator = batchRequests.listIterator(batchRequests.size());
            String nextJobName = null;
            while (iterator.hasPrevious()) {
                BatchRequest batchRequest = iterator.previous();

                String jobName = getJobName(requestExecution.getId(), batchRequest.getOrderId());

                Integer separationSeconds = requestExecution.getBatch().getBatchSettings()
                        .getBatchSeparationInSeconds();

                // Create Job and store properties to get next batch request details
                jobDetail = newJob(BatchRequestJob.class)
                        .withIdentity(jobName, ExecutionJob.LINEAR_EXECUTION_JOB_GROUP)
                        .usingJobData(ExecutionJob.NEXT_EXECUTION_JOB_NAME_KEY, nextJobName)
                        .usingJobData(ExecutionJob.NEXT_EXECUTION_JOB_GROUP_KEY,
                                ExecutionJob.LINEAR_EXECUTION_JOB_GROUP)
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_EXECUTION_ID_KEY, requestExecution.getId())
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_BATCH_ID_KEY, batchRequest.getOrderId())
                        .usingJobData(BatchRequestJob.BATCH_REQUEST_CLUSTER_NAME_KEY,
                                requestExecution.getClusterName())
                        .usingJobData(BatchRequestJob.NEXT_EXECUTION_SEPARATION_SECONDS,
                                separationSeconds != null ? separationSeconds : 0)
                        .storeDurably().build();

                try {
                    executionScheduler.addJob(jobDetail);
                } catch (SchedulerException e) {
                    LOG.error("Failed to add job detail. " + batchRequest, e);
                }

                nextJobName = jobName;
            }
        }
    }
    return jobDetail;
}

From source file:org.jahia.services.content.JCRContentUtils.java

public static <T> Map<String, T> reverse(Map<String, T> orderedMap) {
    if (orderedMap == null || orderedMap.isEmpty()) {
        return orderedMap;
    }/*w ww . j  a va2  s.c  om*/
    LinkedHashMap<String, T> reversed = new LinkedHashMap<String, T>(orderedMap.size());
    ListIterator<String> li = new LinkedList<String>(orderedMap.keySet()).listIterator(orderedMap.size());
    while (li.hasPrevious()) {
        String key = li.previous();
        reversed.put(key, orderedMap.get(key));
    }
    return reversed;
}

From source file:at.pagu.soldockr.core.query.Criteria.java

/**
 * get the QueryString used for executing query
 * //from w w  w .j a  v a2s . c om
 * @return
 */
public String createQueryString() {
    StringBuilder query = new StringBuilder(StringUtils.EMPTY);

    ListIterator<Criteria> chainIterator = this.criteriaChain.listIterator();
    while (chainIterator.hasNext()) {
        Criteria chainedCriteria = chainIterator.next();

        query.append(createQueryFragmentForCriteria(chainedCriteria));

        if (chainIterator.hasNext()) {
            query.append(chainIterator.next().getConjunctionOperator());
            chainIterator.previous();
        }
    }

    return query.toString();
}

From source file:org.rifidi.emulator.reader.thingmagic.commandobjects.UpdateCommand.java

private void parseKeyValuePairs(ListIterator<String> tokenIterator)
        throws CommandCreationException, NoSuchElementException {
    // TODO Auto-generated method stub
    String token;//from  w w w  . j  a  va 2s. c o m
    do {
        token = tokenIterator.next();

        if (!token.matches(A_WORD))
            throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

        String key = token;

        token = tokenIterator.next();

        if (!token.matches(EQUALS_WITH_WS))
            throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

        StringBuffer valueBuffer = new StringBuffer();
        token = tokenIterator.next();

        if (!token.equals("'")) {
            token = tokenIterator.previous().trim();
            throw new CommandCreationException("Error 0100:     syntax error at '" + token + "'");

        }

        token = tokenIterator.next();
        while (!token.equals("'")) {
            valueBuffer.append(token);
            token = tokenIterator.next();
        }
        logger.debug("key: " + key + " value: '" + valueBuffer.toString() + "'");
        keyValuePairs.put(key, valueBuffer.toString());

        /*
         * if we have no more tokens. it is valid.. and we should break
         * here.
         */
        if (!tokenIterator.hasNext())
            break;

        token = tokenIterator.next();
    } while (token.matches(COMMA_WITH_WS));
}

From source file:org.jahia.services.content.ConflictResolver.java

private Map<String, String> getOrdering(ListOrderedMap uuids1, List<String> removed) {
    Map<String, String> previousMap = new LinkedHashMap<String, String>();
    ListIterator<?> it = uuids1.keyList().listIterator(uuids1.size());
    String previous = "";
    while (it.hasPrevious()) {
        String uuid = (String) it.previous();
        if (!removed.contains(uuid)) {
            previousMap.put(uuid, previous);
            previous = uuid;//ww w.  ja  v a 2  s  .  c om
        }
    }
    return previousMap;
}

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

public ActivityChangeSet touch(Instant time, Node node, boolean allowLinkMismatch) {
    Validate.notNull(time);//  w ww  . j a  v a2s  . co 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();
    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:es.tid.fiware.rss.service.SettlementManager.java

/**
 * Get files from path.//from   ww  w  . j a  v a2s .  co 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.SplitTransactionImpl.java

@Override
public boolean rollback(final Server server, final RegionServerServices services) throws IOException {
    this.server = server;
    this.rsServices = services;
    // Coprocessor callback
    if (this.parent.getCoprocessorHost() != null) {
        this.parent.getCoprocessorHost().preRollBackSplit();
    }//from w ww .j a  v  a2s . co m

    boolean result = true;
    ListIterator<JournalEntry> iterator = this.journal.listIterator(this.journal.size());
    // Iterate in reverse.
    while (iterator.hasPrevious()) {
        JournalEntry je = iterator.previous();

        transition(je.getPhase(), true);

        switch (je.getPhase()) {

        case SET_SPLITTING:
            if (services != null && !services.reportRegionStateTransition(TransitionCode.SPLIT_REVERTED,
                    parent.getRegionInfo(), hri_a, hri_b)) {
                return false;
            }
            break;

        case CREATE_SPLIT_DIR:
            this.parent.writestate.writesEnabled = true;
            this.parent.getRegionFileSystem().cleanupSplitsDir();
            break;

        case CLOSED_PARENT_REGION:
            try {
                // So, this returns a seqid but if we just closed and then reopened, we
                // should be ok. On close, we flushed using sequenceid obtained from
                // hosting regionserver so no need to propagate the sequenceid returned
                // out of initialize below up into regionserver as we normally do.
                // TODO: Verify.
                this.parent.initialize();
            } catch (IOException e) {
                LOG.error("Failed rollbacking CLOSED_PARENT_REGION of region "
                        + parent.getRegionInfo().getRegionNameAsString(), e);
                throw new RuntimeException(e);
            }
            break;

        case STARTED_REGION_A_CREATION:
            this.parent.getRegionFileSystem().cleanupDaughterRegion(this.hri_a);
            break;

        case STARTED_REGION_B_CREATION:
            this.parent.getRegionFileSystem().cleanupDaughterRegion(this.hri_b);
            break;

        case OFFLINED_PARENT:
            if (services != null)
                services.addToOnlineRegions(this.parent);
            break;

        case PONR:
            // We got to the point-of-no-return so we need to just abort. Return
            // immediately.  Do not clean up created daughter regions.  They need
            // to be in place so we don't delete the parent region mistakenly.
            // See HBASE-3872.
            return false;

        // Informational only cases
        case STARTED:
        case PREPARED:
        case BEFORE_PRE_SPLIT_HOOK:
        case AFTER_PRE_SPLIT_HOOK:
        case BEFORE_POST_SPLIT_HOOK:
        case AFTER_POST_SPLIT_HOOK:
        case OPENED_REGION_A:
        case OPENED_REGION_B:
        case COMPLETED:
            break;

        default:
            throw new RuntimeException("Unhandled journal entry: " + je);
        }
    }
    // Coprocessor callback
    if (this.parent.getCoprocessorHost() != null) {
        this.parent.getCoprocessorHost().postRollBackSplit();
    }
    return result;
}