Example usage for com.google.common.collect PeekingIterator next

List of usage examples for com.google.common.collect PeekingIterator next

Introduction

In this page you can find the example usage for com.google.common.collect PeekingIterator next.

Prototype

@Override
E next();

Source Link

Document

The objects returned by consecutive calls to #peek() then #next() are guaranteed to be equal to each other.

Usage

From source file:edu.sdsc.scigraph.neo4j.HierarchyVisitor.java

void traverse(Node... roots) {
    TraversalDescription description = graph.traversalDescription().uniqueness(Uniqueness.RELATIONSHIP_PATH)
            .depthFirst().expand(new PathExpander<Void>() {

                @Override/*w  w  w. j av a  2s.c o m*/
                public Iterable<Relationship> expand(Path path, BranchState<Void> state) {
                    Set<Relationship> relationships = new HashSet<>();
                    addAll(relationships, path.endNode().getRelationships(Direction.INCOMING,
                            OwlRelationships.RDFS_SUBCLASS_OF));
                    if (includeEquivalentClasses && null != path.lastRelationship()
                            && !path.lastRelationship().isType(OwlRelationships.OWL_EQUIVALENT_CLASS)) {
                        addAll(relationships,
                                path.endNode().getRelationships(OwlRelationships.OWL_EQUIVALENT_CLASS));
                    }
                    return relationships;
                }

                @Override
                public PathExpander<Void> reverse() {
                    return null;
                }
            });

    try (Transaction tx = graph.beginTx()) {
        for (Path position : description.traverse(roots)) {
            List<Node> path = new ArrayList<>();
            PeekingIterator<PropertyContainer> iter = Iterators.peekingIterator(position.iterator());
            while (iter.hasNext()) {
                PropertyContainer container = iter.next();
                if (container instanceof Node) {
                    if (((Node) container).hasLabel(OwlLabels.OWL_ANONYMOUS)) {
                        // Ignore paths with anonymous nodes
                    } else if (iter.hasNext()
                            && ((Relationship) iter.peek()).isType(OwlRelationships.OWL_EQUIVALENT_CLASS)) {
                        // Ignore the path hop representing the equivalence
                    } else {
                        path.add((Node) container);
                    }
                }
            }
            callback.processPath(path);
        }
    }
}

From source file:com.cloudera.crash.Main.java

@Override
public int run(String[] args) throws Exception {
    // generic options parsing...
    HashMultimap<String, String> options = HashMultimap.create();
    List<String> targets = Lists.newArrayList();
    PeekingIterator<String> strings = Iterators.peekingIterator(Iterators.forArray(args));
    while (strings.hasNext()) {
        final String arg = strings.next();
        if (arg.startsWith("--")) {
            final String option = arg.substring(2);
            if (FLAGS.contains(option) || strings.peek().startsWith("--")) {
                options.put(option, "true");
            } else {
                options.putAll(option, Splitter.on(',').split(strings.next()));
            }// w w  w  . j  a v a 2  s  .c om
        } else {
            targets.add(arg);
        }
    }

    // add directories to the distributed cache
    // -libjars doesn't seem to work with vendor/
    if (options.containsKey("vendor")) {
        for (String path : options.get("vendor")) {
            File file = new File(path);
            if (file.isDirectory()) {
                DistCache.addJarDirToDistributedCache(getConf(), file);
            } else if (file.isFile()) {
                DistCache.addJarToDistributedCache(getConf(), file);
            }
        }
    }

    if (targets.isEmpty()) {
        // TODO: usage
        System.err.println("No script provided!");
        return 1;
    }
    final String scriptName = targets.get(0);

    Script script = new Script(scriptName, Files.toByteArray(new File(scriptName)));
    script.setPipeline(getPipeline());
    script.getAnalytic();

    PipelineResult result = this.run();

    return result.succeeded() ? 0 : 1;
}

From source file:google.registry.backup.RestoreCommitLogsAction.java

@Override
public void run() {
    checkArgument( // safety
            RegistryEnvironment.get() == RegistryEnvironment.ALPHA
                    || RegistryEnvironment.get() == RegistryEnvironment.UNITTEST,
            "DO NOT RUN ANYWHERE ELSE EXCEPT ALPHA OR TESTS.");
    if (dryRun) {
        logger.info("Running in dryRun mode");
    }/*from  w  ww.j ava  2 s .c  o m*/
    List<GcsFileMetadata> diffFiles = diffLister.listDiffFiles(fromTime);
    if (diffFiles.isEmpty()) {
        logger.info("Nothing to restore");
        return;
    }
    Map<Integer, DateTime> bucketTimestamps = new HashMap<>();
    CommitLogCheckpoint lastCheckpoint = null;
    for (GcsFileMetadata metadata : diffFiles) {
        logger.info("Restoring: " + metadata.getFilename().getObjectName());
        try (InputStream input = Channels
                .newInputStream(gcsService.openPrefetchingReadChannel(metadata.getFilename(), 0, BLOCK_SIZE))) {
            PeekingIterator<ImmutableObject> commitLogs = peekingIterator(createDeserializingIterator(input));
            lastCheckpoint = (CommitLogCheckpoint) commitLogs.next();
            saveOfy(asList(lastCheckpoint)); // Save the checkpoint itself.
            while (commitLogs.hasNext()) {
                CommitLogManifest manifest = restoreOneTransaction(commitLogs);
                bucketTimestamps.put(manifest.getBucketId(), manifest.getCommitTime());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    // Restore the CommitLogCheckpointRoot and CommitLogBuckets.
    saveOfy(FluentIterable.from(bucketTimestamps.entrySet())
            .transform(new Function<Entry<Integer, DateTime>, ImmutableObject>() {
                @Override
                public ImmutableObject apply(Entry<Integer, DateTime> entry) {
                    return new CommitLogBucket.Builder().setBucketNum(entry.getKey())
                            .setLastWrittenTime(entry.getValue()).build();
                }
            }).append(CommitLogCheckpointRoot.create(lastCheckpoint.getCheckpointTime())));
}

From source file:com.google.errorprone.bugpatterns.AbstractExpectedExceptionChecker.java

@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
    if (tree.getBody() == null) {
        return NO_MATCH;
    }//from www.  j a  v  a  2s . 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: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 ww w  .j  a va  2 s.c o  m
    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:com.github.zhongl.index.Merger.java

public IndicesFile merge(PeekingIterator<Index> base, PeekingIterator<Index> delta) throws IOException {
    IndicesFile file = new IndicesFile(dir, encoder);

    while (base.hasNext() && delta.hasNext()) {

        Index a = base.peek();//from  w ww  . j  a v a  2s.  c  om
        Index b = delta.peek();
        Index c;

        int result = a.compareTo(b);

        if (result < 0)
            c = base.next(); // a <  b, use a
        else if (result > 0)
            c = delta.next(); // a >  b, use b
        else { // a == b, use b
            c = b;
            delta.next();
            base.next();
        }

        if (c.isRemoved())
            continue; // remove this entry
        file.append(c);
    }

    mergeRestOf(base, file);
    mergeRestOf(delta, file);

    return file;
}

From source file:com.github.rinde.rinsim.ui.renderers.WarehouseRenderer.java

private void drawNodes() {
    // draw node connectors
    for (final Point p : graph.getNodes()) {
        if (showNodes) {
            adapter.setBackgroundSysCol(SWT.COLOR_RED);
            adapter.fillCircle(p, 2);/* w w w  .j  a va 2 s.c om*/
        }

        final Set<Point> conns = new LinkedHashSet<>();
        conns.addAll(graph.getIncomingConnections(p));
        conns.addAll(graph.getOutgoingConnections(p));

        if (conns.size() == 1) {
            // dead end is a special case
            final Point n = conns.iterator().next();
            final Point c1 = PointUtil.perp(p, n, -vehicleLength, -halfRoadWidth);
            final Point c2 = PointUtil.perp(p, n, -vehicleLength, halfRoadWidth);
            final Point o1 = PointUtil.perp(p, n, vehicleLength, -halfRoadWidth);
            final Point o2 = PointUtil.perp(p, n, vehicleLength, halfRoadWidth);
            adapter.setForegroundSysCol(SWT.COLOR_GRAY);
            adapter.drawPolyline(o1, c1, c2, o2);
        } else {
            final List<Point> neighbors = new ArrayList<>(conns);
            Collections.sort(neighbors, new Comparator<Point>() {
                @Override
                public int compare(@Nullable Point o1, @Nullable Point o2) {
                    assert o1 != null;
                    assert o2 != null;
                    return Double.compare(PointUtil.angle(p, o1), PointUtil.angle(p, o2));
                }
            });

            neighbors.add(neighbors.get(0));
            final PeekingIterator<Point> it = Iterators.peekingIterator(neighbors.iterator());

            for (Point n = it.next(); it.hasNext(); n = it.next()) {
                if (!it.hasNext()) {
                    break;
                }
                final Point a = PointUtil.perp(p, n, vehicleLength, -halfRoadWidth);
                final Point a2 = PointUtil.perp(p, n, vehicleLength + 1, -halfRoadWidth);
                final Point b = PointUtil.perp(p, it.peek(), vehicleLength, halfRoadWidth);
                final Point b2 = PointUtil.perp(p, it.peek(), vehicleLength + 1, halfRoadWidth);
                final Optional<Point> intersect = PointUtil.intersectionPoint(a, a2, b, b2);

                if (intersect.isPresent()) {
                    final Point control = intersect.get();
                    adapter.setForegroundSysCol(SWT.COLOR_GRAY);
                    adapter.drawCurve(a, b, control);
                } else {
                    adapter.setForegroundSysCol(SWT.COLOR_GRAY);
                    adapter.drawLine(a, b);
                }
            }
        }
    }
}

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;// w w  w. java2s . com
    }

    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);/*from w w  w. j a  v  a  2s  .  c o 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.apache.hadoop.hbase.regionserver.CompactorScanner.java

private void skipToNextColumn(Cell cell, PeekingIterator<Map.Entry<Cell, Optional<Cell>>> iter) {
    while (iter.hasNext() && CellUtil.matchingFamily(iter.peek().getKey(), cell)
            && CellUtil.matchingQualifier(iter.peek().getKey(), cell)) {
        iter.next();
    }/*from ww w  .j  a  v a2  s  .  c  o  m*/
}