List of usage examples for com.google.common.collect PeekingIterator hasNext
boolean hasNext();
From source file:com.google.errorprone.bugpatterns.AbstractExpectedExceptionChecker.java
@Override public Description matchMethod(MethodTree tree, VisitorState state) { if (tree.getBody() == null) { return NO_MATCH; }/* ww w. j av a2s .c o m*/ PeekingIterator<? extends StatementTree> it = Iterators .peekingIterator(tree.getBody().getStatements().iterator()); while (it.hasNext() && !MATCHER.matches(it.peek(), state)) { it.next(); } List<Tree> expectations = new ArrayList<>(); while (it.hasNext() && MATCHER.matches(it.peek(), state)) { expectations.add(it.next()); } if (expectations.isEmpty()) { return NO_MATCH; } List<StatementTree> suffix = new ArrayList<>(); Iterators.addAll(suffix, it); return handleMatch(tree, state, expectations, suffix); }
From source file:org.eclipse.xtext.ide.editor.contentassist.IndentationAwareCompletionPrefixProvider.java
protected INode findBestEndToken(INode root, INode candidate, int completionColumn, boolean candidateIsEndToken) { LinkedList<ILeafNode> sameGrammarElement = Lists.newLinkedList(); PeekingIterator<ILeafNode> iterator = createReversedLeafIterator(root, candidate, sameGrammarElement); if (!iterator.hasNext()) { return candidate; }//from ww w. j av a 2 s.com // collect all candidates that belong to the same offset LinkedList<ILeafNode> sameOffset = candidateIsEndToken ? collectLeafsWithSameOffset((ILeafNode) candidate, iterator) : Lists.newLinkedList(); // continue until we find a paired leaf with length 0 that is at the correct offset EObject grammarElement = tryGetGrammarElementAsRule( candidateIsEndToken || sameGrammarElement.isEmpty() ? candidate : sameGrammarElement.getLast()); ILeafNode result = candidateIsEndToken ? null : (ILeafNode) candidate; int sameOffsetSize = sameOffset.size(); while (iterator.hasNext()) { ILeafNode next = iterator.next(); if (result == null || result.isHidden()) { result = next; } if (next.getTotalLength() == 0) { // potential indentation token EObject rule = tryGetGrammarElementAsRule(next); if (rule != grammarElement) { LineAndColumn lineAndColumn = NodeModelUtils.getLineAndColumn(root, next.getTotalOffset()); if (lineAndColumn.getColumn() <= completionColumn) { return result; } else { if (sameOffset.isEmpty()) { if (sameGrammarElement.isEmpty()) { result = null; } else { result = sameGrammarElement.removeLast(); } } else { if (sameOffsetSize >= sameOffset.size()) { result = sameOffset.removeLast(); } else { sameOffset.removeLast(); } } } } else { sameOffset.add(next); } } } return candidate; }
From source file:org.renjin.eval.Calls.java
/** * Argument matching is done by a three-pass process: * <ol>// w w w. j ava2 s . c om * <li><strong>Exact matching on tags.</strong> For each named supplied argument the list of formal arguments * is searched for an item whose name matches exactly. It is an error to have the same formal * argument match several actuals or vice versa.</li> * * <li><strong>Partial matching on tags.</strong> Each remaining named supplied argument is compared to the * remaining formal arguments using partial matching. If the name of the supplied argument * matches exactly with the first part of a formal argument then the two arguments are considered * to be matched. It is an error to have multiple partial matches. * Notice that if f <- function(fumble, fooey) fbody, then f(f = 1, fo = 2) is illegal, * even though the 2nd actual argument only matches fooey. f(f = 1, fooey = 2) is legal * though since the second argument matches exactly and is removed from consideration for * partial matching. If the formal arguments contain ... then partial matching is only applied to * arguments that precede it. * * <li><strong>Positional matching.</strong> Any unmatched formal arguments are bound to unnamed supplied arguments, * in order. If there is a ... argument, it will take up the remaining arguments, tagged or not. * If any arguments remain unmatched an error is declared. * * @param actuals the actual arguments supplied to the list * @param populateMissing */ public static PairList matchArguments(PairList formals, PairList actuals, boolean populateMissing) { PairList.Builder result = new PairList.Builder(); List<PairList.Node> unmatchedActuals = Lists.newArrayList(); for (PairList.Node argNode : actuals.nodes()) { unmatchedActuals.add(argNode); } List<PairList.Node> unmatchedFormals = Lists.newArrayList(formals.nodes()); // do exact matching for (ListIterator<PairList.Node> formalIt = unmatchedFormals.listIterator(); formalIt.hasNext();) { PairList.Node formal = formalIt.next(); if (formal.hasTag()) { Symbol name = formal.getTag(); Collection<PairList.Node> matches = Collections2.filter(unmatchedActuals, PairList.Predicates.matches(name)); if (matches.size() == 1) { PairList.Node match = first(matches); result.add(name, match.getValue()); formalIt.remove(); unmatchedActuals.remove(match); } else if (matches.size() > 1) { throw new EvalException( String.format("Multiple named values provided for argument '%s'", name.getPrintName())); } } } // do partial matching Collection<PairList.Node> remainingNamedFormals = filter(unmatchedFormals, PairList.Predicates.hasTag()); for (Iterator<PairList.Node> actualIt = unmatchedActuals.iterator(); actualIt.hasNext();) { PairList.Node actual = actualIt.next(); if (actual.hasTag()) { Collection<PairList.Node> matches = Collections2.filter(remainingNamedFormals, PairList.Predicates.startsWith(actual.getTag())); if (matches.size() == 1) { PairList.Node match = first(matches); result.add(match.getTag(), actual.getValue()); actualIt.remove(); unmatchedFormals.remove(match); } else if (matches.size() > 1) { throw new EvalException( String.format("Provided argument '%s' matches multiple named formal arguments: %s", actual.getTag().getPrintName(), argumentTagList(matches))); } } } // match any unnamed args positionally Iterator<PairList.Node> formalIt = unmatchedFormals.iterator(); PeekingIterator<PairList.Node> actualIt = Iterators.peekingIterator(unmatchedActuals.iterator()); while (formalIt.hasNext()) { PairList.Node formal = formalIt.next(); if (Symbols.ELLIPSES.equals(formal.getTag())) { PromisePairList.Builder promises = new PromisePairList.Builder(); while (actualIt.hasNext()) { PairList.Node actual = actualIt.next(); promises.add(actual.getRawTag(), actual.getValue()); } result.add(formal.getTag(), promises.build()); } else if (hasNextUnTagged(actualIt)) { result.add(formal.getTag(), nextUnTagged(actualIt).getValue()); } else if (populateMissing) { result.add(formal.getTag(), Symbol.MISSING_ARG); } } if (actualIt.hasNext()) { throw new EvalException(String.format("Unmatched positional arguments")); } return result.build(); }
From source file:com.google.gerrit.server.mail.receive.TextParser.java
/** * Parses comments from plaintext email. * * @param email MailMessage as received from the email service. * @param comments Comments previously persisted on the change that caused the original * notification email to be sent out. Ordering must be the same as in the outbound email * @param changeUrl Canonical change url that points to the change on this Gerrit instance. * Example: https://go-review.googlesource.com/#/c/91570 * @return List of MailComments parsed from the plaintext part of the email. *//*from w w w . j a v a 2s. com*/ public static List<MailComment> parse(MailMessage email, Collection<Comment> comments, String changeUrl) { String body = email.textContent(); // Replace CR-LF by \n body = body.replace("\r\n", "\n"); List<MailComment> parsedComments = new ArrayList<>(); // Some email clients (like GMail) use >> for enquoting text when there are // inline comments that the users typed. These will then be enquoted by a // single >. We sanitize this by unifying it into >. Inline comments typed // by the user will not be enquoted. // // Example: // Some comment // >> Quoted Text // >> Quoted Text // > A comment typed in the email directly String singleQuotePattern = "\n> "; String doubleQuotePattern = "\n>> "; if (countOccurrences(body, doubleQuotePattern) > countOccurrences(body, singleQuotePattern)) { body = body.replace(doubleQuotePattern, singleQuotePattern); } PeekingIterator<Comment> iter = Iterators.peekingIterator(comments.iterator()); String[] lines = body.split("\n"); MailComment currentComment = null; String lastEncounteredFileName = null; Comment lastEncounteredComment = null; for (String line : lines) { if (line.equals(">")) { // Skip empty lines continue; } if (line.startsWith("> ")) { line = line.substring("> ".length()).trim(); // This is not a comment, try to advance the file/comment pointers and // add previous comment to list if applicable if (currentComment != null) { if (currentComment.type == MailComment.CommentType.CHANGE_MESSAGE) { currentComment.message = ParserUtil.trimQuotation(currentComment.message); } if (!Strings.isNullOrEmpty(currentComment.message)) { parsedComments.add(currentComment); } currentComment = null; } if (!iter.hasNext()) { continue; } Comment perspectiveComment = iter.peek(); if (line.equals(ParserUtil.filePath(changeUrl, perspectiveComment))) { if (lastEncounteredFileName == null || !lastEncounteredFileName.equals(perspectiveComment.key.filename)) { // This is the annotation of a file lastEncounteredFileName = perspectiveComment.key.filename; lastEncounteredComment = null; } else if (perspectiveComment.lineNbr == 0) { // This was originally a file-level comment lastEncounteredComment = perspectiveComment; iter.next(); } } else if (ParserUtil.isCommentUrl(line, changeUrl, perspectiveComment)) { lastEncounteredComment = perspectiveComment; iter.next(); } } else { // This is a comment. Try to append to previous comment if applicable or // create a new comment. if (currentComment == null) { // Start new comment currentComment = new MailComment(); currentComment.message = line; if (lastEncounteredComment == null) { if (lastEncounteredFileName == null) { // Change message currentComment.type = MailComment.CommentType.CHANGE_MESSAGE; } else { // File comment not sent in reply to another comment currentComment.type = MailComment.CommentType.FILE_COMMENT; currentComment.fileName = lastEncounteredFileName; } } else { // Comment sent in reply to another comment currentComment.inReplyTo = lastEncounteredComment; currentComment.type = MailComment.CommentType.INLINE_COMMENT; } } else { // Attach to previous comment currentComment.message += "\n" + line; } } } // There is no need to attach the currentComment after this loop as all // emails have footers and other enquoted text after the last comment // appeared and the last comment will have already been added to the list // at this point. return parsedComments; }
From source file:org.locationtech.geogig.plumbing.merge.CheckMergeScenarioOp.java
@Override protected Boolean _call() { if (commits.size() < 2) { return Boolean.FALSE; }/* w w w . ja v a2s . c o m*/ Optional<ObjectId> ancestor = command(FindCommonAncestor.class).setLeft(commits.get(0)) .setRight(commits.get(1)).call(); Preconditions.checkState(ancestor.isPresent(), "No ancestor commit could be found."); for (int i = 2; i < commits.size(); i++) { ancestor = command(FindCommonAncestor.class).setLeft(commits.get(i)).setRightId(ancestor.get()).call(); Preconditions.checkState(ancestor.isPresent(), "No ancestor commit could be found."); } List<AutoCloseableIterator<DiffEntry>> commitDiffs = new ArrayList<AutoCloseableIterator<DiffEntry>>(); try { // we organize the changes made for each path for (RevCommit commit : commits) { AutoCloseableIterator<DiffEntry> toMergeDiffs = command(DiffTree.class).setReportTrees(true) .setOldTree(ancestor.get()).setNewTree(commit.getId()).setPreserveIterationOrder(true) .call(); commitDiffs.add(toMergeDiffs); } PeekingIterator<DiffEntry> merged = Iterators .peekingIterator(Iterators.mergeSorted(commitDiffs, DiffEntry.COMPARATOR)); long progress = 0; while (merged.hasNext()) { List<DiffEntry> nextPath = nextPath(merged); getProgressListener().setProgress(++progress); if (hasConflicts(nextPath)) { return true; } } } finally { commitDiffs.forEach((iter) -> iter.close()); } return false; }
From source file:com.ardor3d.input.PhysicalLayer.java
private void readKeyboardState() { final PeekingIterator<KeyEvent> eventIterator = _keyboardWrapper.getEvents(); // if no new events, just leave the current state as is if (!eventIterator.hasNext()) { return;/*from ww w . j a va 2 s . c om*/ } final KeyEvent keyEvent = eventIterator.next(); // EnumSet.copyOf fails if the collection is empty, since it needs at least one object to // figure out which type of enum to deal with. Hence the check below. final EnumSet<Key> keysDown = _currentKeyboardState.getKeysDown().isEmpty() ? EnumSet.noneOf(Key.class) : EnumSet.copyOf(_currentKeyboardState.getKeysDown()); if (keyEvent.getState() == KeyState.DOWN) { keysDown.add(keyEvent.getKey()); } else { // ignore the fact that this removal might fail - for instance, at startup, the // set of keys tracked as down will be empty even if somebody presses a key when the // app starts. keysDown.remove(keyEvent.getKey()); } _currentKeyboardState = new KeyboardState(keysDown, keyEvent); }
From source file:fr.loria.parole.artimate.engine.Ardor3DWrapper.java
@Override public void playAnimation(UnitSequence units) { final String layerName = "-ANIMATION_LAYER-"; // remove layer if it exists AnimationLayer layer = animation.findAnimationLayer(layerName); animation.removeAnimationLayer(layer); // create new layer layer = new AnimationLayer(layerName); animation.addAnimationLayer(layer);// w w w .j a va 2s .co m // iterate over units PeekingIterator<Unit> unitIterator = Iterators.peekingIterator(units.iterator()); while (unitIterator.hasNext()) { // get animation state Unit unit = unitIterator.next(); SteadyState state = (SteadyState) unit.getAnimation(); // add end transition so that state jumps to next in sequence at end (except for last) if (unitIterator.hasNext()) { Unit nextUnit = unitIterator.peek(); SteadyState nextState = (SteadyState) nextUnit.getAnimation(); state.setEndTransition(new ImmediateTransitionState(nextState.getName())); } // add state to layer layer.addSteadyState(state); } layer.setCurrentState((SteadyState) units.get(0).getAnimation(), true); }
From source file:org.eclipse.xtext.ide.editor.contentassist.IndentationAwareCompletionPrefixProvider.java
private LinkedList<ILeafNode> collectLeafsWithSameOffset(ILeafNode candidate, PeekingIterator<ILeafNode> iterator) { LinkedList<ILeafNode> sameOffset = Lists.newLinkedList(); sameOffset.add(candidate);/* w ww. j av a 2s . c om*/ int offset = candidate.getTotalOffset(); while (iterator.hasNext()) { ILeafNode peek = iterator.peek(); if (peek.getTotalOffset() == offset) { sameOffset.add(peek); iterator.next(); } else { break; } } return sameOffset; }
From source file:com.google.javascript.jscomp.JsCompiler.java
private int run(Iterable<String> args) throws IOException { // Our flags, which we won't pass along to the compiler. List<ClosureJsLibrary> infos = new ArrayList<>(); List<String> roots = new ArrayList<>(); Set<DiagnosticType> globalSuppressions = new HashSet<>(); Path outputErrors = null;//from w w w . j a v a 2s. com boolean expectFailure = false; boolean expectWarnings = false; boolean exportTestFunctions = false; // Compiler flags we want to read. Path jsOutputFile = null; Path createSourceMap = null; // Parse flags in an ad-hoc manner. List<String> passThroughArgs = new ArrayList<>(1024); PeekingIterator<String> iargs = Iterators.peekingIterator(args.iterator()); while (iargs.hasNext()) { String arg = iargs.next(); switch (arg) { case "--info": infos.add(JsCheckerHelper.loadClosureJsLibraryInfo(Paths.get(iargs.next()))); continue; case "--output_errors": outputErrors = Paths.get(iargs.next()); continue; case "--suppress": globalSuppressions.addAll(Diagnostics.getDiagnosticTypesForSuppressCode(iargs.next())); continue; case "--expect_failure": expectFailure = true; continue; case "--expect_warnings": expectWarnings = true; continue; case "--export_test_functions": // TODO(jart): Remove this when it's added to open source Closure Compiler. exportTestFunctions = true; continue; case "--js_module_root": roots.add(iargs.peek()); break; case "--js_output_file": jsOutputFile = Paths.get(iargs.peek()); break; case "--create_source_map": createSourceMap = Paths.get(iargs.peek()); break; default: break; } passThroughArgs.add(arg); } // Keep track of modules defined *only* in rules that don't have the suppress attribute, // e.g. js_library(). We'll make the compiler much more lax for these sources. Set<String> legacyModules = new HashSet<>(); for (ClosureJsLibrary info : infos) { if (info.getLegacy()) { legacyModules.addAll(info.getModuleList()); } } // We want to be able to turn module names back into labels. Map<String, String> labels = new HashMap<>(); // We also need the set of all (module, suppress) combinations propagated from library rules. Multimap<String, DiagnosticType> suppressions = HashMultimap.create(); for (ClosureJsLibrary info : infos) { if (info.getLegacy()) { continue; } legacyModules.removeAll(info.getModuleList()); for (String module : info.getModuleList()) { labels.put(module, info.getLabel()); for (String suppress : info.getSuppressList()) { suppressions.put(module, verifyNotNull(Diagnostics.DIAGNOSTIC_TYPES.get(suppress), "Bad DiagnosticType from closure_js_library: %s", suppress)); } } } // Run the compiler, capturing error messages. boolean failed = false; Compiler compiler = new Compiler(); JsCheckerErrorFormatter errorFormatter = new JsCheckerErrorFormatter(compiler, roots, labels); errorFormatter.setColorize(true); JsCheckerErrorManager errorManager = new JsCheckerErrorManager(errorFormatter); compiler.setErrorManager(errorManager); JsCompilerWarnings warnings = new JsCompilerWarnings(roots, legacyModules, suppressions, globalSuppressions); JsCompilerRunner runner = new JsCompilerRunner(passThroughArgs, compiler, exportTestFunctions, warnings); if (runner.shouldRunCompiler()) { failed |= runner.go() != 0; } failed |= runner.hasErrors(); // Output error messages based on diagnostic settings. if (!expectFailure && !expectWarnings) { for (String line : errorManager.stderr) { System.err.println(line); } System.err.flush(); } if (outputErrors != null) { Files.write(outputErrors, errorManager.stderr, UTF_8); } if (failed && expectFailure) { // If we don't return nonzero, Bazel expects us to create every output file. if (jsOutputFile != null) { Files.write(jsOutputFile, EMPTY_BYTE_ARRAY); } } // Make sure a source map is always created since Bazel expect that but JsCompiler // may not emit sometimes (e.g compiler_level=BUNLDE) if (createSourceMap != null && !Files.exists(createSourceMap)) { Files.write(createSourceMap, EMPTY_BYTE_ARRAY); } if (!failed && expectFailure) { System.err.println("ERROR: Expected failure but didn't fail."); } return failed == expectFailure ? 0 : 1; }
From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticmi.read.InterfaceInformationFlowConsistencyValidator.java
@Override public boolean validate(Model model, MessageListener messageListener) { if (isSentientMode()) { LOGGER.warn("Can't perform model validation! The metamodel is in invalid state for this validator."); return true; }/* ww w . j a va2 s. c o m*/ boolean result = true; Collection<ObjectExpression> allISIs = informationSystemInterface.apply(model).getMany(); for (ObjectExpression isi : allISIs) { ElasticValue<ObjectExpression> connectedInfoFlowEV = isiToIf.apply(isi); if (connectedInfoFlowEV.isMany()) { PeekingIterator<ObjectExpression> infoFlowsIterator = Iterators .peekingIterator(connectedInfoFlowEV.getMany().iterator()); while (infoFlowsIterator.hasNext()) { ObjectExpression currentInfoFlow = infoFlowsIterator.next(); ElasticValue<ObjectExpression> currentIsr1EV = ifToIsr1.apply(currentInfoFlow); ElasticValue<ObjectExpression> currentIsr2EV = ifToIsr2.apply(currentInfoFlow); // check if exactly two ISR are connected: if (!(currentIsr1EV.isOne() && currentIsr2EV.isOne())) { result = false; String nameOfInterface = getNameOrDefault(informationSystemInterface, isi, "NULL", ","); String nameOfInfoFlow = getNameOrDefault(informationFlow, currentInfoFlow, "NULL", ","); messageListener.onMessage(new InterfaceInformationFlowConsistencyViolationMessage( nameOfInterface, nameOfInfoFlow)); continue; } if (!infoFlowsIterator.hasNext()) { break; // reached last pair } ObjectExpression nextInfoFlow = infoFlowsIterator.peek(); ElasticValue<ObjectExpression> nextIsr1EV = ifToIsr1.apply(nextInfoFlow); ElasticValue<ObjectExpression> nextIsr2EV = ifToIsr2.apply(nextInfoFlow); if (!(nextIsr1EV.isOne() && nextIsr2EV.isOne())) { continue; } // check if connected ISR and/or their order are equal compared to the previous InformationFlow: ImmutableList<ObjectExpression> currentList = ImmutableList.of(currentIsr1EV.getOne(), currentIsr2EV.getOne()); ImmutableList<ObjectExpression> nextList = ImmutableList.of(nextIsr1EV.getOne(), nextIsr2EV.getOne()); if (!currentList.equals(nextList)) { result = false; String nameOfInterface = getNameOrDefault(informationSystemInterface, isi, "NULL", ", "); String nameOfInfoFlow1 = getNameOrDefault(informationFlow, currentInfoFlow, "NULL", ","); String nameOfInfoFlow2 = getNameOrDefault(informationFlow, nextInfoFlow, "NULL", ","); messageListener.onMessage(new InterfaceInformationFlowConsistencyViolationMessage( nameOfInterface, nameOfInfoFlow1, nameOfInfoFlow2)); } } } } return result; }