Java Code Examples for java.util.ListIterator#hasPrevious()

The following examples show how to use java.util.ListIterator#hasPrevious() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * @see org.apache.uima.ResourceFactory#produceResource(java.lang.Class,
 *      org.apache.uima.resource.ResourceSpecifier, java.util.Map)
 */
public Resource produceResource(Class<? extends Resource> aResourceClass, ResourceSpecifier aSpecifier,
        Map<String, Object> aAdditionalParams) throws ResourceInitializationException {
  // check for factories registered for this resource specifier type
  // (most recently registered first)
  ListIterator<Registration> it = mRegisteredFactories.listIterator(mRegisteredFactories.size());
  Resource result = null;
  while (it.hasPrevious()) {
    Registration reg = it.previous();
    if (reg.resourceSpecifierInterface.isAssignableFrom(aSpecifier.getClass())) {
      result = reg.factory.produceResource(aResourceClass, aSpecifier, aAdditionalParams);
      if (result != null) {
        return result;
      }
    }
  }
  return null;
}
 
Example 2
/** {@inheritDoc} */
@Override
public @Nullable ViewManager createViewManager(
    ReactApplicationContext reactContext, String viewManagerName) {
  ListIterator<ReactPackage> iterator =
      mChildReactPackages.listIterator(mChildReactPackages.size());
  while (iterator.hasPrevious()) {
    ReactPackage reactPackage = iterator.previous();
    if (reactPackage instanceof ViewManagerOnDemandReactPackage) {
      ViewManager viewManager =
          ((ViewManagerOnDemandReactPackage) reactPackage)
              .createViewManager(reactContext, viewManagerName);
      if (viewManager != null) {
        return viewManager;
      }
    }
  }
  return null;
}
 
Example 3
private void collapseTargetEvents(String cameraName, EventType type, Target target) {
	final ListIterator<Event> it = getCameraEvents(cameraName).listIterator(getCameraEvents(cameraName).size());

	while (it.hasPrevious()) {
		final Event e = it.previous();

		if (e.getType() != EventType.TARGET_RESIZED && e.getType() != EventType.TARGET_MOVED) {
			break;
		}

		if (e.getType() == type) {
			if (type == EventType.TARGET_RESIZED
					&& ((TargetResizedEvent) e).getTargetIndex() == target.getTargetIndex()) {
				it.remove();
			} else if (type == EventType.TARGET_MOVED
					&& ((TargetMovedEvent) e).getTargetIndex() == target.getTargetIndex()) {
				it.remove();
			}
		}
	}
}
 
Example 4
Source Project: glowroot   File: Traverser.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void traverse() throws E {
    while (!stack.isEmpty()) {
        Object popped = stack.pop();
        if (popped == ALREADY_TRAVERSED_MARKER) {
            revisitAfterChildren((T) stack.pop());
            depth--;
            continue;
        }
        T unprocessed = (T) popped;
        List<T> childNodes = visit(unprocessed, depth);
        if (childNodes.isEmpty()) {
            // optimization for no children
            revisitAfterChildren(unprocessed);
        } else {
            stack.push(unprocessed);
            stack.push(ALREADY_TRAVERSED_MARKER);
            ListIterator<T> i = childNodes.listIterator(childNodes.size());
            while (i.hasPrevious()) {
                stack.push(i.previous());
            }
            depth++;
        }
    }
}
 
Example 5
List<ModelNode> getReverseList() {
    //This is the opposite order. Due to how the steps get added, once run we will do them in the following order:
    //  extension removes, extension adds, non-extension composite
    //  The non-extension composite in turn will do removes first, and then adds
    final List<ModelNode> result = new ArrayList<>();
    final ModelNode nonExtensionComposite = Util.createEmptyOperation(COMPOSITE, PathAddress.EMPTY_ADDRESS);
    final ModelNode nonExtensionSteps = nonExtensionComposite.get(STEPS).setEmptyList();
    final ListIterator<ModelNode> it = nonExtensionRemoves.listIterator(nonExtensionRemoves.size());
    while (it.hasPrevious()) {
        nonExtensionSteps.add(it.previous());
    }
    for (ModelNode op : nonExtensionAdds) {
        nonExtensionSteps.add(op);
    }
    if (nonExtensionSteps.asList().size() > 0) {
        result.add(nonExtensionComposite);
    }
    result.addAll(extensionAdds);
    result.addAll(extensionRemoves);
    return result;
}
 
Example 6
@Override
public UiSelector parse() throws UiSelectorSyntaxException, UiObjectNotFoundException {
    resetCurrentIndex();
    UiObject self = consumeConstructor();
    List<Object> results = new ArrayList<>();
    while (hasMoreDataToParse()) {
        consumePeriod();
        Object result = consumeMethodCall();
        if (result == null) {
            continue;
        }

        results.add(result);
        if (result instanceof UiScrollable) {
            setTarget((UiScrollable) result);
        }
    }

    ListIterator<Object> resultsIterator = results.listIterator(results.size());
    while (resultsIterator.hasPrevious()) {
        Object item = resultsIterator.previous();
        if (item instanceof UiObject) {
            // assign the result to the last method in the chain
            // that returns UiObject
            uiSelector = ((UiObject) item).getSelector();
            break;
        }
    }
    if (uiSelector == null && self != null) {
        // if none of the methods in the chain return UiObject instance
        // the assign the result to self instance
        uiSelector = self.getSelector();
    }
    if (uiSelector == null) {
        throw new UiSelectorSyntaxException(expression.toString(),
                "At least one method called on a UiScrollable object must return an UiObject instance");
    }
    return uiSelector;
}
 
Example 7
@Override
protected void executeActualProcessAction(String user, String superProcessInstanceId) {
    List<String> subProcessIds = getActiveExecutionIds(superProcessInstanceId);
    ListIterator<String> subProcessesIdsIterator = subProcessIds.listIterator(subProcessIds.size());

    updateUserIfNecessary(user, superProcessInstanceId);
    while (subProcessesIdsIterator.hasPrevious()) {
        String subProcessId = subProcessesIdsIterator.previous();
        retryProcess(subProcessId);
    }
    historicOperationEventPersister.add(superProcessInstanceId, EventType.RETRIED);
}
 
Example 8
/**
 * @param loaders Loaders for the sources to try, in descending order of
 *                preference.
 */
public FallbackJSBundleLoader(List<JSBundleLoader> loaders) {
  mLoaders = new Stack();
  ListIterator<JSBundleLoader> it = loaders.listIterator(loaders.size());
  while (it.hasPrevious()) {
    mLoaders.push(it.previous());
  }
}
 
Example 9
private void readCalData(String baseUrl, String key) {

        NsRestApiReader nsRestApiReader = new NsRestApiReader();
        Long LastReportedTime = 0L;

        Calibration lastCalibration = Calibration.last();

        if(lastCalibration != null) {
            LastReportedTime = (long)lastCalibration.timestamp;
        }
        Log.e(TAG, "readCalData  LastReportedTime = " + LastReportedTime);

        List<NightscoutMbg> nightscoutMbgs = nsRestApiReader.readCalDataFromNs(baseUrl, key, LastReportedTime, 10 );
        if(nightscoutMbgs == null) {
            Log.e(TAG, "readCalDataFromNs returned null");
            return;
        }

        ListIterator<NightscoutMbg> li = nightscoutMbgs.listIterator(nightscoutMbgs.size());
        long lastInserted = 0;
        while(li.hasPrevious()) {
            NightscoutMbg nightscoutMbg = li.previous();
            Log.e(TAG, "NightscoutMbg " + nightscoutMbg.mbg + " " + nightscoutMbg.date);
            if(nightscoutMbg.date < lastInserted) {
                Log.e(TAG, "not inserting calibratoin, since order is wrong. ");
                continue;
            }
            
            verifyViewerNightscoutMode(mContext, nightscoutMbg);
            
            Calibration.createUpdate(nightscoutMbg.xDrip_sensor_uuid, nightscoutMbg.mbg, nightscoutMbg.date, nightscoutMbg.xDrip_intercept, nightscoutMbg.xDrip_slope, nightscoutMbg.xDrip_estimate_raw_at_time_of_calibration,
                    nightscoutMbg.xDrip_slope_confidence , nightscoutMbg.xDrip_sensor_confidence, nightscoutMbg.xDrip_raw_timestamp);
            lastInserted = nightscoutMbg.date;
        }
    }
 
Example 10
private void addMethodEntries(int threadId, List<StackTraceElement> elements, long timestamp, long threadtimestamp, boolean asRoot) throws IllegalStateException {
    boolean inRoot = false;
    ListIterator<StackTraceElement> reverseIt = elements.listIterator(elements.size());
    
    while(reverseIt.hasPrevious()) {
        StackTraceElement element = reverseIt.previous();
        MethodInfo mi = new MethodInfo(element);
        Integer mId = methodInfoMap.get(mi);
        if (mId == null) {
            mId = registerNewMethodInfo(mi);
            if (status != null) {
                String method = mi.methodName;
                int index = method.indexOf('(');
                if (index > 0) {
                    method = method.substring(0,index);
                }
                status.updateInstrMethodsInfo(mi.className,0,method,mi.signature);
            }
        }
        
        if (asRoot && !inRoot) {
            inRoot = true;
            ccgb.methodEntry(mId.intValue(), threadId, CPUCallGraphBuilder.METHODTYPE_ROOT, timestamp, threadtimestamp, null, null);
        } else {
            ccgb.methodEntry(mId.intValue(), threadId, CPUCallGraphBuilder.METHODTYPE_NORMAL, timestamp, threadtimestamp, null, null);
        }
        
    }
}
 
Example 11
Source Project: DotCi   File: BranchHistoryWidgetModel.java    License: MIT License 5 votes vote down vote up
public OffsetBuild<T> getNextBuildToFetch(final Iterable<T> builds, final HistoryWidget.Adapter<? super T> adapter) {
    final ArrayList<T> list = Lists.newArrayList(builds);
    if (!list.isEmpty()) {
        final ListIterator<T> listIterator = list.listIterator(list.size());

        while (listIterator.hasPrevious()) {
            final T record = listIterator.previous();
            if (adapter.isBuilding(record))
                return new OffsetBuild<>(record, 0);
        }

        return new OffsetBuild(list.get(0), 1);
    }
    return new OffsetBuild<>(null, 0);
}
 
Example 12
Source Project: BrokenView   File: BrokenView.java    License: MIT License 5 votes vote down vote up
@Override
protected void onDraw(Canvas canvas) {
    ListIterator<BrokenAnimator> iterator = animList.listIterator(animList.size());
    while(iterator.hasPrevious()) {
        iterator.previous().draw(canvas);
    }
}
 
Example 13
Source Project: scipio-erp   File: SeoCatalogUrlWorker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Last index of, with starting index (inclusive - .get(startIndex) is compared - like String interface).
 */
static <T> int lastIndexOf(List<T> list, T object, int startIndex) {
    ListIterator<T> it = list.listIterator(startIndex + 1);
    while(it.hasPrevious()) {
        if (object.equals(it.previous())) {
            return it.nextIndex();
        }
    }
    return -1;
}
 
Example 14
@Override
public boolean incrementToken() throws IOException {
  while (!done && queue.size() < windowSize) {
    if (!input.incrementToken()) {
      done = true;
      break;
    }

    // reverse iterating for better efficiency since we know the
    // list is already sorted, and most token start offsets will be too.
    ListIterator<OrderedToken> iter = queue.listIterator(queue.size());
    while (iter.hasPrevious()) {
      if (offsetAtt.startOffset() >= iter.previous().startOffset) {
        // insertion will be before what next() would return (what
        // we just compared against), so move back one so the insertion
        // will be after.
        iter.next();
        break;
      }
    }
    OrderedToken ot = new OrderedToken();
    ot.state = captureState();
    ot.startOffset = offsetAtt.startOffset();
    iter.add(ot);
  }

  if (queue.isEmpty()) {
    return false;
  } else {
    restoreState(queue.removeFirst().state);
    return true;
  }
}
 
Example 15
/**
 * Releases for normal dispatching to the current focus owner all
 * KeyEvents which were enqueued because of a call to
 * <code>enqueueKeyEvents</code> with the same timestamp and Component.
 * If the given timestamp is less than zero, the outstanding enqueue
 * request for the given Component with the <b>oldest</b> timestamp (if
 * any) should be cancelled.
 *
 * @param after the timestamp specified in the call to
 *        <code>enqueueKeyEvents</code>, or any value &lt; 0
 * @param untilFocused the Component specified in the call to
 *        <code>enqueueKeyEvents</code>
 * @see #enqueueKeyEvents
 * @see #discardKeyEvents
 */
protected synchronized void dequeueKeyEvents(long after,
                                             Component untilFocused) {
    if (untilFocused == null) {
        return;
    }

    if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
        focusLog.finer("Dequeue at {0} for {1}",
                   after, untilFocused);
    }

    TypeAheadMarker marker;
    ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator
        ((after >= 0) ? typeAheadMarkers.size() : 0);

    if (after < 0) {
        while (iter.hasNext()) {
            marker = iter.next();
            if (marker.untilFocused == untilFocused)
            {
                iter.remove();
                return;
            }
        }
    } else {
        while (iter.hasPrevious()) {
            marker = iter.previous();
            if (marker.untilFocused == untilFocused &&
                marker.after == after)
            {
                iter.remove();
                return;
            }
        }
    }
}
 
Example 16
Source Project: jadx   File: CodeShrinkVisitor.java    License: Apache License 2.0 5 votes vote down vote up
private static void shrinkBlock(MethodNode mth, BlockNode block) {
	if (block.getInstructions().isEmpty()) {
		return;
	}
	InsnList insnList = new InsnList(block.getInstructions());
	int insnCount = insnList.size();
	List<ArgsInfo> argsList = new ArrayList<>(insnCount);
	for (int i = 0; i < insnCount; i++) {
		argsList.add(new ArgsInfo(insnList.get(i), argsList, i));
	}
	List<WrapInfo> wrapList = new ArrayList<>();
	for (ArgsInfo argsInfo : argsList) {
		List<RegisterArg> args = argsInfo.getArgs();
		if (!args.isEmpty()) {
			ListIterator<RegisterArg> it = args.listIterator(args.size());
			while (it.hasPrevious()) {
				RegisterArg arg = it.previous();
				checkInline(mth, block, insnList, wrapList, argsInfo, arg);
			}
		}
	}
	if (!wrapList.isEmpty()) {
		for (WrapInfo wrapInfo : wrapList) {
			inline(mth, wrapInfo.getArg(), wrapInfo.getInsn(), block);
		}
	}
}
 
Example 17
Source Project: activemq-artemis   File: BridgeImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void cancelRefs() {
   LinkedList<MessageReference> list = new LinkedList<>();

   synchronized (refs) {
      list.addAll(refs.values());
      refs.clear();
   }

   if (logger.isTraceEnabled()) {
      logger.trace("BridgeImpl::cancelRefs cancelling " + list.size() + " references");
   }

   if (logger.isTraceEnabled() && list.isEmpty()) {
      logger.trace("didn't have any references to cancel on bridge " + this);
      return;
   }

   ListIterator<MessageReference> listIterator = list.listIterator(list.size());

   Queue refqueue;

   long timeBase = System.currentTimeMillis();

   while (listIterator.hasPrevious()) {
      MessageReference ref = listIterator.previous();

      if (logger.isTraceEnabled()) {
         logger.trace("BridgeImpl::cancelRefs Cancelling reference " + ref + " on bridge " + this);
      }

      refqueue = ref.getQueue();

      try {
         refqueue.cancel(ref, timeBase, false);
      } catch (Exception e) {
         // There isn't much we can do besides log an error
         ActiveMQServerLogger.LOGGER.errorCancellingRefOnBridge(e, ref);
      }
   }
}
 
Example 18
Source Project: testgrid   File: StackCreationWaiter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Boolean call() throws Exception {
    //Stack details
    DescribeStacksRequest describeStacksRequest = new DescribeStacksRequest().withStackName(stackName);
    DescribeStacksResult describeStacksResult = cloudFormation.describeStacks(describeStacksRequest);
    final List<Stack> stacks = describeStacksResult.getStacks();
    if (stacks.size() > 1 || stacks.isEmpty()) {
        String stackNames = stacks.stream().map(Stack::getStackName).collect(Collectors.joining(", "));
        final String msg = "More than one stack found or stack list is empty for the stack name: " +
                stackName + ": " + stackNames;
        logger.error(msg);
        throw new IllegalStateException(msg);
    }

    Stack stack = stacks.get(0);
    StackStatus stackStatus = StackStatus.fromValue(stack.getStackStatus());

    // Event details of the stack
    DescribeStackEventsRequest describeStackEventsRequest = new DescribeStackEventsRequest()
            .withStackName(stackName);
    DescribeStackEventsResult describeStackEventsResult = cloudFormation.
            describeStackEvents(describeStackEventsRequest);

    //Print a log of the current state of the resources
    StringBuilder stringBuilder = new StringBuilder();
    final List<StackEvent> originalStackEvents = describeStackEventsResult.getStackEvents();
    final List<StackEvent> newStackEvents = new ArrayList<>(originalStackEvents);
    newStackEvents.removeAll(prevStackEvents);
    ListIterator<StackEvent> li = newStackEvents.listIterator(newStackEvents.size());
    while (li.hasPrevious()) {
        StackEvent stackEvent = li.previous();
        stringBuilder.append(StringUtil.concatStrings(
                "Status: ", stackEvent.getResourceStatus(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Resource Type: ", stackEvent.getResourceType(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Logical ID: ", stackEvent.getLogicalResourceId(), ", "));
        stringBuilder.append(StringUtil.concatStrings(
                "Status Reason: ", Optional.ofNullable(stackEvent.getResourceStatusReason()).orElse("-")));
        stringBuilder.append("\n");
    }
    logger.info(StringUtil.concatStrings("\n", stringBuilder.toString()));
    prevStackEvents = originalStackEvents;

    //Determine the steps to execute based on the status of the stack
    switch (stackStatus) {
    case CREATE_COMPLETE:
        return true;
    case CREATE_IN_PROGRESS:
        break;
    default:
        throw new TestGridInfrastructureException(StringUtil.concatStrings(
                "Stack creation transitioned to ", stackStatus.toString(), " state."));
    }
    return false;
}
 
Example 19
public void printRightToLeft() {
  ListIterator<Book> it = contents.listIterator(contents.size());
  while (it.hasPrevious()) {
    System.out.println(it.previous());
  }
}
 
Example 20
/**
 * Check if the job has a timing constraint, and if so determine where to insert it in our
 * list.
 */
@Override
public void maybeStartTrackingJobLocked(JobStatus job, JobStatus lastJob) {
    if (job.hasTimingDelayConstraint() || job.hasDeadlineConstraint()) {
        maybeStopTrackingJobLocked(job, null, false);

        // First: check the constraints now, because if they are already satisfied
        // then there is no need to track it.  This gives us a fast path for a common
        // pattern of having a job with a 0 deadline constraint ("run immediately").
        // Unlike most controllers, once one of our constraints has been satisfied, it
        // will never be unsatisfied (our time base can not go backwards).
        final long nowElapsedMillis = sElapsedRealtimeClock.millis();
        if (job.hasDeadlineConstraint() && evaluateDeadlineConstraint(job, nowElapsedMillis)) {
            return;
        } else if (job.hasTimingDelayConstraint() && evaluateTimingDelayConstraint(job,
                nowElapsedMillis)) {
            if (!job.hasDeadlineConstraint()) {
                // If it doesn't have a deadline, we'll never have to touch it again.
                return;
            }
        }

        boolean isInsert = false;
        ListIterator<JobStatus> it = mTrackedJobs.listIterator(mTrackedJobs.size());
        while (it.hasPrevious()) {
            JobStatus ts = it.previous();
            if (ts.getLatestRunTimeElapsed() < job.getLatestRunTimeElapsed()) {
                // Insert
                isInsert = true;
                break;
            }
        }
        if (isInsert) {
            it.next();
        }
        it.add(job);
        job.setTrackingController(JobStatus.TRACKING_TIME);
        maybeUpdateAlarmsLocked(
                job.hasTimingDelayConstraint() ? job.getEarliestRunTime() : Long.MAX_VALUE,
                job.hasDeadlineConstraint() ? job.getLatestRunTimeElapsed() : Long.MAX_VALUE,
                deriveWorkSource(job.getSourceUid(), job.getSourcePackageName()));
    }
}