Example usage for com.google.common.collect Iterables consumingIterable

List of usage examples for com.google.common.collect Iterables consumingIterable

Introduction

In this page you can find the example usage for com.google.common.collect Iterables consumingIterable.

Prototype

public static <T> Iterable<T> consumingIterable(final Iterable<T> iterable) 

Source Link

Document

Returns a view of the supplied iterable that wraps each generated Iterator through Iterators#consumingIterator(Iterator) .

Usage

From source file:dagger.internal.codegen.BindingGraphFactory.java

private BindingGraph create(Optional<Resolver> parentResolver, ComponentDescriptor componentDescriptor) {
    ImmutableSet.Builder<ContributionBinding> explicitBindingsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<DelegateDeclaration> delegatesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<OptionalBindingDeclaration> optionalsBuilder = ImmutableSet.builder();

    if (!componentDescriptor.kind().isForModuleValidation()) {
        // binding for the component itself
        explicitBindingsBuilder.add(bindingFactory.componentBinding(componentDescriptor.typeElement()));
    }/*ww  w  .  j  a  v a2  s .  c om*/

    // Collect Component dependencies.
    for (ComponentRequirement dependency : componentDescriptor.dependencies()) {
        explicitBindingsBuilder.add(bindingFactory.componentDependencyBinding(dependency));
        List<ExecutableElement> dependencyMethods = methodsIn(elements.getAllMembers(dependency.typeElement()));
        for (ExecutableElement method : dependencyMethods) {
            // MembersInjection methods aren't "provided" explicitly, so ignore them.
            if (isComponentContributionMethod(elements, method)) {
                explicitBindingsBuilder
                        .add(bindingFactory.componentDependencyMethodBinding(componentDescriptor, method));
            }
        }
    }

    // Collect bindings on the creator.
    componentDescriptor.creatorDescriptor()
            .ifPresent(creatorDescriptor -> creatorDescriptor.boundInstanceRequirements().stream()
                    .map(requirement -> bindingFactory.boundInstanceBinding(requirement,
                            creatorDescriptor.elementForRequirement(requirement)))
                    .forEach(explicitBindingsBuilder::add));

    componentDescriptor.childComponentsDeclaredByBuilderEntryPoints()
            .forEach((builderEntryPoint, childComponent) -> {
                if (!componentDescriptor.childComponentsDeclaredByModules().contains(childComponent)) {
                    explicitBindingsBuilder.add(bindingFactory.subcomponentCreatorBinding(
                            builderEntryPoint.methodElement(), componentDescriptor.typeElement()));
                }
            });

    ImmutableSet.Builder<MultibindingDeclaration> multibindingDeclarations = ImmutableSet.builder();
    ImmutableSet.Builder<SubcomponentDeclaration> subcomponentDeclarations = ImmutableSet.builder();

    // Collect transitive module bindings and multibinding declarations.
    for (ModuleDescriptor moduleDescriptor : modules(componentDescriptor, parentResolver)) {
        explicitBindingsBuilder.addAll(moduleDescriptor.bindings());
        multibindingDeclarations.addAll(moduleDescriptor.multibindingDeclarations());
        subcomponentDeclarations.addAll(moduleDescriptor.subcomponentDeclarations());
        delegatesBuilder.addAll(moduleDescriptor.delegateDeclarations());
        optionalsBuilder.addAll(moduleDescriptor.optionalDeclarations());
    }

    final Resolver requestResolver = new Resolver(parentResolver, componentDescriptor,
            indexBindingDeclarationsByKey(explicitBindingsBuilder.build()),
            indexBindingDeclarationsByKey(multibindingDeclarations.build()),
            indexBindingDeclarationsByKey(subcomponentDeclarations.build()),
            indexBindingDeclarationsByKey(delegatesBuilder.build()),
            indexBindingDeclarationsByKey(optionalsBuilder.build()));
    for (DependencyRequest entryPoint : componentDescriptor.entryPoints()) {
        if (entryPoint.kind().equals(RequestKind.MEMBERS_INJECTION)) {
            requestResolver.resolveMembersInjection(entryPoint.key());
        } else {
            requestResolver.resolve(entryPoint.key());
        }
    }

    // Resolve all bindings for subcomponents, creating subgraphs for all subcomponents that have
    // been detected during binding resolution. If a binding for a subcomponent is never resolved,
    // no BindingGraph will be created for it and no implementation will be generated. This is
    // done in a queue since resolving one subcomponent might resolve a key for a subcomponent
    // from a parent graph. This is done until no more new subcomponents are resolved.
    Set<ComponentDescriptor> resolvedSubcomponents = new HashSet<>();
    ImmutableList.Builder<BindingGraph> subgraphs = ImmutableList.builder();
    for (ComponentDescriptor subcomponent : Iterables
            .consumingIterable(requestResolver.subcomponentsToResolve)) {
        if (resolvedSubcomponents.add(subcomponent)) {
            subgraphs.add(create(Optional.of(requestResolver), subcomponent));
        }
    }

    ImmutableMap<Key, ResolvedBindings> resolvedContributionBindingsMap = requestResolver
            .getResolvedContributionBindings();
    for (ResolvedBindings resolvedBindings : resolvedContributionBindingsMap.values()) {
        verify(resolvedBindings.owningComponent().equals(componentDescriptor), "%s is not owned by %s",
                resolvedBindings, componentDescriptor);
    }

    return BindingGraph.create(componentDescriptor, resolvedContributionBindingsMap,
            requestResolver.getResolvedMembersInjectionBindings(), subgraphs.build(),
            requestResolver.getOwnedModules(), requestResolver.getFactoryMethod());
}

From source file:com.b2international.snowowl.snomed.importer.rf2.terminology.ComponentLookup.java

public void registerNewComponentStorageKeys() {
    // Consume each element while it is being registered
    if (newComponents != null) {
        for (final Entry<String, C> newComponent : Iterables.consumingIterable(newComponents.entrySet())) {
            registerComponentStorageKey(newComponent.getKey(),
                    CDOIDUtil.getLong(newComponent.getValue().cdoID()));
        }/*from w w w.j a  v a 2s  . co m*/
        newComponents = null;
    }
}

From source file:org.sosy_lab.cpachecker.core.algorithm.CPAAlgorithm.java

private boolean run0(final ReachedSet reachedSet) throws CPAException, InterruptedException {
    final TransferRelation transferRelation = cpa.getTransferRelation();
    final MergeOperator mergeOperator = cpa.getMergeOperator();
    final StopOperator stopOperator = cpa.getStopOperator();
    final PrecisionAdjustment precisionAdjustment = cpa.getPrecisionAdjustment();

    while (reachedSet.hasWaitingState()) {
        shutdownNotifier.shutdownIfNecessary();

        stats.countIterations++;/*w  w w  .j  av a 2  s  .  c  om*/

        // Pick next state using strategy
        // BFS, DFS or top sort according to the configuration
        int size = reachedSet.getWaitlistSize();
        if (size >= stats.maxWaitlistSize) {
            stats.maxWaitlistSize = size;
        }
        stats.countWaitlistSize += size;

        stats.chooseTimer.start();
        final AbstractState state = reachedSet.popFromWaitlist();
        final Precision precision = reachedSet.getPrecision(state);
        stats.chooseTimer.stop();

        logger.log(Level.FINER, "Retrieved state from waitlist");
        logger.log(Level.ALL, "Current state is", state, "with precision", precision);

        if (forcedCovering != null) {
            stats.forcedCoveringTimer.start();
            try {
                boolean stop = forcedCovering.tryForcedCovering(state, precision, reachedSet);

                if (stop) {
                    // TODO: remove state from reached set?
                    continue;
                }
            } finally {
                stats.forcedCoveringTimer.stop();
            }
        }

        stats.transferTimer.start();
        Collection<? extends AbstractState> successors;
        try {
            successors = transferRelation.getAbstractSuccessors(state, precision);
        } finally {
            stats.transferTimer.stop();
        }
        // TODO When we have a nice way to mark the analysis result as incomplete,
        // we could continue analysis on a CPATransferException with the next state from waitlist.

        int numSuccessors = successors.size();
        logger.log(Level.FINER, "Current state has", numSuccessors, "successors");
        stats.countSuccessors += numSuccessors;
        stats.maxSuccessors = Math.max(numSuccessors, stats.maxSuccessors);

        for (AbstractState successor : Iterables.consumingIterable(successors)) {
            logger.log(Level.FINER, "Considering successor of current state");
            logger.log(Level.ALL, "Successor of", state, "\nis", successor);

            stats.precisionTimer.start();
            PrecisionAdjustmentResult precAdjustmentResult;
            try {
                precAdjustmentResult = precisionAdjustment.prec(successor, precision, reachedSet, successor);
            } finally {
                stats.precisionTimer.stop();
            }

            successor = precAdjustmentResult.abstractState();
            Precision successorPrecision = precAdjustmentResult.precision();
            Action action = precAdjustmentResult.action();

            if (action == Action.BREAK) {
                stats.stopTimer.start();
                boolean stop;
                try {
                    stop = stopOperator.stop(successor, reachedSet.getReached(successor), successorPrecision);
                } finally {
                    stats.stopTimer.stop();
                }

                if (AbstractStates.isTargetState(successor) && stop) {
                    // don't signal BREAK for covered states
                    // no need to call merge and stop either, so just ignore this state
                    // and handle next successor
                    stats.countStop++;
                    logger.log(Level.FINER, "Break was signalled but ignored because the state is covered.");
                    continue;

                } else {
                    stats.countBreak++;
                    logger.log(Level.FINER, "Break signalled, CPAAlgorithm will stop.");

                    // add the new state
                    reachedSet.add(successor, successorPrecision);

                    if (!successors.isEmpty()) {
                        // re-add the old state to the waitlist, there are unhandled
                        // successors left that otherwise would be forgotten
                        reachedSet.reAddToWaitlist(state);
                    }

                    return true;
                }
            }
            assert action == Action.CONTINUE : "Enum Action has unhandled values!";

            Collection<AbstractState> reached = reachedSet.getReached(successor);

            // An optimization, we don't bother merging if we know that the
            // merge operator won't do anything (i.e., it is merge-sep).
            if (mergeOperator != MergeSepOperator.getInstance() && !reached.isEmpty()) {
                stats.mergeTimer.start();
                try {
                    List<AbstractState> toRemove = new ArrayList<>();
                    List<Pair<AbstractState, Precision>> toAdd = new ArrayList<>();

                    logger.log(Level.FINER, "Considering", reached.size(), "states from reached set for merge");
                    for (AbstractState reachedState : reached) {
                        AbstractState mergedState = mergeOperator.merge(successor, reachedState,
                                successorPrecision);

                        if (!mergedState.equals(reachedState)) {
                            logger.log(Level.FINER, "Successor was merged with state from reached set");
                            logger.log(Level.ALL, "Merged", successor, "\nand", reachedState, "\n-->",
                                    mergedState);
                            stats.countMerge++;

                            toRemove.add(reachedState);
                            toAdd.add(Pair.of(mergedState, successorPrecision));
                        }
                    }
                    reachedSet.removeAll(toRemove);
                    reachedSet.addAll(toAdd);

                    if (mergeOperator instanceof ARGMergeJoinPredicatedAnalysis) {
                        ((ARGMergeJoinPredicatedAnalysis) mergeOperator).cleanUp(reachedSet);
                    }

                } finally {
                    stats.mergeTimer.stop();
                }
            }

            stats.stopTimer.start();
            boolean stop;
            try {
                stop = stopOperator.stop(successor, reached, successorPrecision);
            } finally {
                stats.stopTimer.stop();
            }

            if (stop) {
                logger.log(Level.FINER, "Successor is covered or unreachable, not adding to waitlist");
                stats.countStop++;

            } else {
                logger.log(Level.FINER, "No need to stop, adding successor to waitlist");

                stats.addTimer.start();
                reachedSet.add(successor, successorPrecision);
                stats.addTimer.stop();
            }
        }

        if (iterationListener != null) {
            iterationListener.afterAlgorithmIteration(this, reachedSet);
        }
    }
    return true;
}

From source file:edu.buaa.satla.analysis.core.algorithm.CPAAlgorithm.java

private boolean run0(final ReachedSet reachedSet) throws CPAException, InterruptedException {
    final TransferRelation transferRelation = cpa.getTransferRelation();
    final MergeOperator mergeOperator = cpa.getMergeOperator();
    final StopOperator stopOperator = cpa.getStopOperator();
    final PrecisionAdjustment precisionAdjustment = cpa.getPrecisionAdjustment();

    while (reachedSet.hasWaitingState()) {
        shutdownNotifier.shutdownIfNecessary();

        stats.countIterations++;//from w w w  .  j a  v  a  2 s. co m

        // Pick next state using strategy
        // BFS, DFS or top sort according to the configuration
        int size = reachedSet.getWaitlistSize();
        if (size >= stats.maxWaitlistSize) {
            stats.maxWaitlistSize = size;
        }
        stats.countWaitlistSize += size;

        stats.chooseTimer.start();
        final AbstractState state = reachedSet.popFromWaitlist();
        final Precision precision = reachedSet.getPrecision(state);
        stats.chooseTimer.stop();

        logger.log(Level.FINER, "Retrieved state from waitlist");
        logger.log(Level.ALL, "Current state is", state, "with precision", precision);

        if (forcedCovering != null) {
            stats.forcedCoveringTimer.start();
            try {
                boolean stop = forcedCovering.tryForcedCovering(state, precision, reachedSet);

                if (stop) {
                    // TODO: remove state from reached set?
                    continue;
                }
            } finally {
                stats.forcedCoveringTimer.stop();
            }
        }

        stats.transferTimer.start();
        Collection<? extends AbstractState> successors;
        try {
            successors = transferRelation.getAbstractSuccessors(state, precision);
        } finally {
            stats.transferTimer.stop();
        }
        // TODO When we have a nice way to mark the analysis result as incomplete,
        // we could continue analysis on a CPATransferException with the next state from waitlist.

        int numSuccessors = successors.size();
        logger.log(Level.FINER, "Current state has", numSuccessors, "successors");
        stats.countSuccessors += numSuccessors;
        stats.maxSuccessors = Math.max(numSuccessors, stats.maxSuccessors);

        for (AbstractState successor : Iterables.consumingIterable(successors)) {
            logger.log(Level.FINER, "Considering successor of current state");
            logger.log(Level.ALL, "Successor of", state, "\nis", successor);

            stats.precisionTimer.start();
            PrecisionAdjustmentResult precAdjustmentResult;
            try {
                precAdjustmentResult = precisionAdjustment.prec(successor, precision, reachedSet);
            } finally {
                stats.precisionTimer.stop();
            }

            successor = precAdjustmentResult.abstractState();
            Precision successorPrecision = precAdjustmentResult.precision();
            Action action = precAdjustmentResult.action();

            if (action == Action.BREAK) {
                stats.stopTimer.start();
                boolean stop;
                try {
                    stop = stopOperator.stop(successor, reachedSet.getReached(successor), successorPrecision);
                } finally {
                    stats.stopTimer.stop();
                }

                if (AbstractStates.isTargetState(successor) && stop) {
                    // don't signal BREAK for covered states
                    // no need to call merge and stop either, so just ignore this state
                    // and handle next successor
                    stats.countStop++;
                    logger.log(Level.FINER, "Break was signalled but ignored because the state is covered.");
                    continue;

                } else {
                    stats.countBreak++;
                    logger.log(Level.FINER, "Break signalled, CPAAlgorithm will stop.");

                    // add the new state
                    reachedSet.add(successor, successorPrecision);

                    if (!successors.isEmpty()) {
                        // re-add the old state to the waitlist, there are unhandled
                        // successors left that otherwise would be forgotten
                        reachedSet.reAddToWaitlist(state);
                    }

                    return true;
                }
            }
            assert action == Action.CONTINUE : "Enum Action has unhandled values!";

            Collection<AbstractState> reached = reachedSet.getReached(successor);

            // An optimization, we don't bother merging if we know that the
            // merge operator won't do anything (i.e., it is merge-sep).
            if (mergeOperator != MergeSepOperator.getInstance() && !reached.isEmpty()) {
                stats.mergeTimer.start();
                try {
                    List<AbstractState> toRemove = new ArrayList<>();
                    List<Pair<AbstractState, Precision>> toAdd = new ArrayList<>();

                    logger.log(Level.FINER, "Considering", reached.size(), "states from reached set for merge");
                    for (AbstractState reachedState : reached) {
                        AbstractState mergedState = mergeOperator.merge(successor, reachedState,
                                successorPrecision);

                        if (!mergedState.equals(reachedState)) {
                            logger.log(Level.FINER, "Successor was merged with state from reached set");
                            logger.log(Level.ALL, "Merged", successor, "\nand", reachedState, "\n-->",
                                    mergedState);
                            stats.countMerge++;

                            toRemove.add(reachedState);
                            toAdd.add(Pair.of(mergedState, successorPrecision));
                        }
                    }
                    reachedSet.removeAll(toRemove);
                    reachedSet.addAll(toAdd);

                    if (mergeOperator instanceof ARGMergeJoinPredicatedAnalysis) {
                        ((ARGMergeJoinPredicatedAnalysis) mergeOperator).cleanUp(reachedSet);
                    }

                } finally {
                    stats.mergeTimer.stop();
                }
            }

            stats.stopTimer.start();
            boolean stop;
            try {
                stop = stopOperator.stop(successor, reached, successorPrecision);
            } finally {
                stats.stopTimer.stop();
            }

            if (stop) {
                logger.log(Level.FINER, "Successor is covered or unreachable, not adding to waitlist");
                stats.countStop++;

            } else {
                logger.log(Level.FINER, "No need to stop, adding successor to waitlist");

                stats.addTimer.start();
                reachedSet.add(successor, successorPrecision);
                stats.addTimer.stop();
            }
        }

        if (iterationListener != null) {
            iterationListener.afterAlgorithmIteration(this, reachedSet);
        }
    }
    return true;
}

From source file:com.twitter.aurora.scheduler.state.StateManagerImpl.java

private void processWorkQueueInWriteOperation(SideEffectWork<?, ?> sideEffectWork,
        MutableStoreProvider storeProvider) {

    for (final WorkEntry work : Iterables.consumingIterable(workQueue)) {
        final TaskStateMachine stateMachine = work.stateMachine;

        if (work.command == WorkCommand.KILL) {
            driver.killTask(stateMachine.getTaskId());
        } else {//  w w  w  .j  av  a2s  .co m
            TaskStore.Mutable taskStore = storeProvider.getUnsafeTaskStore();
            String taskId = stateMachine.getTaskId();
            Query.Builder idQuery = Query.taskScoped(taskId);

            switch (work.command) {
            case RESCHEDULE:
                ScheduledTask builder = Iterables.getOnlyElement(taskStore.fetchTasks(idQuery)).newBuilder();
                builder.getAssignedTask().unsetSlaveId();
                builder.getAssignedTask().unsetSlaveHost();
                builder.getAssignedTask().unsetAssignedPorts();
                builder.unsetTaskEvents();
                builder.setAncestorId(taskId);
                String newTaskId = taskIdGenerator.generate(
                        ITaskConfig.build(builder.getAssignedTask().getTask()),
                        builder.getAssignedTask().getInstanceId());
                builder.getAssignedTask().setTaskId(newTaskId);

                LOG.info("Task being rescheduled: " + taskId);

                IScheduledTask task = IScheduledTask.build(builder);
                taskStore.saveTasks(ImmutableSet.of(task));

                createStateMachine(task).updateState(PENDING, Optional.of("Rescheduled"));
                ITaskConfig taskInfo = task.getAssignedTask().getTask();
                sideEffectWork.addTaskEvent(new PubsubEvent.TaskRescheduled(taskInfo.getOwner().getRole(),
                        taskInfo.getJobName(), task.getAssignedTask().getInstanceId()));
                break;

            case UPDATE_STATE:
                taskStore.mutateTasks(idQuery, new TaskMutation() {
                    @Override
                    public IScheduledTask apply(IScheduledTask task) {
                        return work.mutation.apply(
                                IScheduledTask.build(task.newBuilder().setStatus(stateMachine.getState())));
                    }
                });
                sideEffectWork.addTaskEvent(
                        new PubsubEvent.TaskStateChange(Iterables.getOnlyElement(taskStore.fetchTasks(idQuery)),
                                stateMachine.getPreviousState()));
                break;

            case DELETE:
                deleteTasks(ImmutableSet.of(taskId));
                break;

            case INCREMENT_FAILURES:
                taskStore.mutateTasks(idQuery, new TaskMutation() {
                    @Override
                    public IScheduledTask apply(IScheduledTask task) {
                        return IScheduledTask
                                .build(task.newBuilder().setFailureCount(task.getFailureCount() + 1));
                    }
                });
                break;

            default:
                LOG.severe("Unrecognized work command type " + work.command);
            }
        }
    }
}