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

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

Introduction

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

Prototype

public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

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

private void reportDuplicateBindings(DependencyRequest dependencyRequest,
        Set<DependencyEdge> duplicateDependencies, BindingGraph bindingGraph,
        DiagnosticReporter diagnosticReporter) {
    ImmutableSet<BindingNode> duplicateBindings = duplicateDependencies.stream()
            .map(edge -> bindingGraph.incidentNodes(edge).target()).flatMap(instancesOf(BindingNode.class))
            .collect(toImmutableSet());/*w ww .  ja v  a  2  s  .  c o m*/
    diagnosticReporter.reportDependency(ERROR, Iterables.get(duplicateDependencies, 0),
            Iterables.any(duplicateBindings, node -> node.binding().kind().isMultibinding())
                    ? incompatibleBindingsMessage(dependencyRequest, duplicateBindings, bindingGraph)
                    : duplicateBindingMessage(dependencyRequest, duplicateBindings, bindingGraph));
}

From source file:org.gradle.api.internal.tasks.testing.junit.result.AggregateTestResultsProvider.java

public boolean hasOutput(long id, final TestOutputEvent.Destination destination) {
    return Iterables.any(classOutputProviders.get(id), new Predicate<DelegateProvider>() {
        public boolean apply(DelegateProvider delegateProvider) {
            return delegateProvider.provider.hasOutput(delegateProvider.id, destination);
        }// w  w w . jav  a 2 s.  c om
    });
}

From source file:org.eclipse.xtext.parsetree.reconstr.impl.CrossReferenceSerializer.java

@Override
public String serializeCrossRef(EObject context, CrossReference grammarElement, final EObject target,
        INode node) {//from  w  w  w. java 2s  .  co  m
    final EReference ref = GrammarUtil.getReference(grammarElement, context.eClass());
    String text = null;
    if (node != null) {
        List<EObject> objects = linkingService.getLinkedObjects(context, ref, node);
        if (Iterables.any(objects, new Predicate<EObject>() {
            private final URI targetURI = EcoreUtil.getURI(target);

            @Override
            public boolean apply(EObject input) {
                return input == target || EcoreUtil.getURI(input).equals(targetURI);
            }
        }))
            return ITokenSerializer.KEEP_VALUE_FROM_NODE_MODEL;
    }
    text = getUnconvertedLinkText(target, ref, context);
    if (text != null)
        return getConvertedValue(text, grammarElement);
    if (node != null) {
        return linkingHelper.getCrossRefNodeAsString(node, false);
    }
    return null;
}

From source file:brooklyn.location.waratek.WaratekLocation.java

@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    synchronized (mutex) {
        // Check context for entitiy implementing UsesJava interface
        Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
        if (context instanceof Entity) {
            List<Class<?>> implementations = Reflections.getAllInterfaces(context.getClass());
            boolean usesJava = Iterables.any(implementations, Predicates.<Class>equalTo(UsesJava.class));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Context {}: UsesJava {}", context.toString(), Boolean.toString(usesJava));
            }// www.  j av  a2 s.c om
            if (!usesJava) {
                // Return an SshMachineLocation from the provisioner
                SshMachineLocation machine = provisioner.obtain(flags);
                obtained.add(machine);
                return machine;
            }
        } else {
            throw new IllegalStateException("Invalid location context: " + context);
        }

        // Use the waratek strategy to add a single JVM
        List<Location> jvms = getExtension(AvailabilityZoneExtension.class).getAllSubLocations();
        List<Location> added = strategy.locationsForAdditions(null, jvms, 1);
        WaratekMachineLocation machine = (WaratekMachineLocation) Iterables.getOnlyElement(added);
        JavaVirtualMachine jvm = machine.getOwner();

        // Now wait until the JVM has started up
        Entities.waitForServiceUp(jvm);

        // Obtain a new JVC location, save and return it
        WaratekContainerLocation container = machine.obtain(MutableMap.of("entity", context));

        Maybe<SshMachineLocation> deployed = Machines.findUniqueSshMachineLocation(jvm.getLocations());
        if (deployed.isPresent()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Storing container mapping {} to {}", deployed.toString(), container.getId());
            }
            machines.put(deployed.get(), container.getId());
            containers.put(container.getId(), deployed.get());
        }
        return container;
    }
}

From source file:com.twitter.aurora.scheduler.thrift.aop.AopModule.java

@Override
protected void configure() {
    requireBinding(CapabilityValidator.class);

    // Layer ordering:
    // Log -> CapabilityValidator -> FeatureToggle -> StatsExporter -> APIVersion ->
    // SchedulerThriftInterface

    // TODO(Sathya): Consider using provider pattern for constructing interceptors to facilitate
    // unit testing without the creation of Guice injectors.
    bindThriftDecorator(new LoggingInterceptor());

    // Note: it's important that the capability interceptor is only applied to AuroraAdmin.Iface
    // methods, and does not pick up methods on AuroraSchedulerManager.Iface.
    MethodInterceptor authInterceptor = new UserCapabilityInterceptor();
    requestInjection(authInterceptor);//from ww w  .  ja  va  2s .c  om
    bindInterceptor(THRIFT_IFACE_MATCHER, GuiceUtils.interfaceMatcher(AuroraAdmin.Iface.class, true),
            authInterceptor);

    install(new PrivateModule() {
        @Override
        protected void configure() {
            // Ensure that the provided methods exist on the decorated interface.
            List<Method> methods = ImmutableList.copyOf(AuroraSchedulerManager.Iface.class.getMethods());
            for (String toggledMethod : toggledMethods.keySet()) {
                Preconditions.checkArgument(
                        Iterables.any(methods, Predicates.compose(Predicates.equalTo(toggledMethod), GET_NAME)),
                        String.format("Method %s was not found in class %s", toggledMethod,
                                AuroraSchedulerManager.Iface.class));
            }

            bind(new TypeLiteral<Map<String, Boolean>>() {
            }).toInstance(toggledMethods);
            bind(IsFeatureEnabled.class).in(Singleton.class);
            Key<Predicate<Method>> predicateKey = Key.get(new TypeLiteral<Predicate<Method>>() {
            });
            bind(predicateKey).to(IsFeatureEnabled.class);
            expose(predicateKey);
        }
    });
    bindThriftDecorator(new FeatureToggleInterceptor());
    bindThriftDecorator(new ThriftStatsExporterInterceptor());
    bindThriftDecorator(new APIVersionInterceptor());
}

From source file:com.proofpoint.cloudmanagement.service.InstancesResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//ww  w  .  j av a2s . c  o  m
@Produces(MediaType.APPLICATION_JSON)
public Response createInstance(final InstanceCreationRequest request, @Context UriInfo uriInfo) {
    checkNotNull(request);
    checkNotNull(uriInfo);

    if (!instanceConnectorMap.containsKey(request.getProvider())) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new InstanceCreationFailedResponse(request, PROVIDER_UNAVAILABLE)).build();
    }

    if (instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation()) == null) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new InstanceCreationFailedResponse(request, LOCATION_UNAVAILABLE)).build();
    }

    if (!Iterables.any(instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation())
            .getAvailableSizes(), new Predicate<Size>() {
                @Override
                public boolean apply(@Nullable Size size) {
                    return size.getSize().equals(request.getSize());
                }
            })) {
        return Response.status(Status.BAD_REQUEST)
                .entity(new InstanceCreationFailedResponse(request, SIZE_UNAVAILABLE)).build();
    }

    String instanceId = instanceConnectorMap.get(request.getProvider()).createInstance(request.getSize(),
            request.getNamePrefix(), request.getLocation());

    for (InstanceCreationNotifier instanceCreationNotifier : instanceCreationNotifiers) {
        instanceCreationNotifier.notifyInstanceCreated(instanceId);
    }

    return Response.created(InstanceResource.constructSelfUri(uriInfo, instanceId)).build();
}

From source file:org.killbill.billing.jaxrs.resources.ComboPaymentResource.java

protected UUID getOrCreatePaymentMethod(final Account account,
        @Nullable final PaymentMethodJson paymentMethodJson, final Iterable<PluginProperty> pluginProperties,
        final CallContext callContext) throws PaymentApiException {

    // No info about payment method was passed, we default to null payment Method ID (which is allowed to be overridden in payment control plugins)
    if (paymentMethodJson == null || paymentMethodJson.getPluginName() == null) {
        return null;
    }//  w w w .  j a va 2s. c o m

    // Get all payment methods for account
    final List<PaymentMethod> accountPaymentMethods = paymentApi.getAccountPaymentMethods(account.getId(),
            false, ImmutableList.<PluginProperty>of(), callContext);

    // If we were specified a paymentMethod id and we find it, we return it
    if (paymentMethodJson.getPaymentMethodId() != null) {
        final UUID match = UUID.fromString(paymentMethodJson.getPaymentMethodId());
        if (Iterables.any(accountPaymentMethods, new Predicate<PaymentMethod>() {
            @Override
            public boolean apply(final PaymentMethod input) {
                return input.getId().equals(match);
            }
        })) {
            return match;
        }
        throw new PaymentApiException(ErrorCode.PAYMENT_NO_SUCH_PAYMENT_METHOD, match);
    }

    // If we were specified a paymentMethod externalKey and we find it, we return it
    if (paymentMethodJson.getExternalKey() != null) {
        final PaymentMethod match = Iterables.tryFind(accountPaymentMethods, new Predicate<PaymentMethod>() {
            @Override
            public boolean apply(final PaymentMethod input) {
                return input.getExternalKey().equals(paymentMethodJson.getExternalKey());
            }
        }).orNull();
        if (match != null) {
            return match.getId();
        }
    }

    // Only set as default if this is the first paymentMethod on the account
    final boolean isDefault = accountPaymentMethods.isEmpty();
    final PaymentMethod paymentData = paymentMethodJson.toPaymentMethod(account.getId().toString());
    return paymentApi.addPaymentMethod(account, paymentMethodJson.getExternalKey(),
            paymentMethodJson.getPluginName(), isDefault, paymentData.getPluginDetail(), pluginProperties,
            callContext);
}

From source file:org.gradle.model.internal.registry.RuleBinder.java

public Iterable<ModelPath> getUnboundPaths() {
    Set<ModelPath> subjectUnboundPath = Collections.emptySet();
    if (subjectReference != null && subjectReference.getPath() != null && subjectBinding == null) {
        subjectUnboundPath = Collections.singleton(subjectReference.getPath());
    }// w w  w .  j a  v  a2  s  .  c o  m

    return Iterables.concat(subjectUnboundPath,
            FluentIterable.from(getInputReferences()).filter(new Predicate<ModelReference<?>>() {
                public boolean apply(final ModelReference<?> reference) {
                    return reference.getPath() != null
                            && !Iterables.any(getInputBindings(), new Predicate<ModelBinding<?>>() {
                                public boolean apply(@Nullable ModelBinding<?> binding) {
                                    return binding != null && binding.getReference() == reference;
                                }
                            });
                }
            }).transform(new Function<ModelReference<?>, ModelPath>() {
                public ModelPath apply(ModelReference<?> input) {
                    return input.getPath();
                }
            })

    );
}

From source file:org.opentestsystem.authoring.testauth.publish.CompletePublisherHelper.java

@Override
public TestSpecification<Complete> createTestSpec(final Assessment assessment, final DateTime publishDate,
        final String version, final Purpose purpose,
        final TestSpecification<? extends PurposeBaseContent> seedingTestSpec) {
    final long start = System.currentTimeMillis();
    final TestSpecification<Complete> testSpec = doGeneralTestSpecificationSetup(assessment, publishDate,
            version, purpose, Complete.class);

    final Complete specContent = new Complete();
    // administration.setComment("comment");
    final String assessmentId = assessment.getId();
    final List<Item> itemList = retrieveItemsForAssessment(assessmentId);
    final List<Segment> segmentList = retrieveSegmentList(assessmentId);
    final List<BlueprintElement> blueprintElementList = getActiveBlueprintElements(assessmentId);
    specContent.setBlueprintElementList(blueprintElementList);
    final List<AffinityGroup> affinityGroupList = getActiveAffinityGroups(assessmentId);
    final long dataRetrieval = System.currentTimeMillis();
    final Map<BlueprintReferenceType, Map<String, String>> blueprintReferenceMap = buildBlueprintReferenceMap(
            assessment, segmentList, blueprintElementList, affinityGroupList);
    specContent.setBlueprintReferenceMap(blueprintReferenceMap);
    final long blueprintReferenceMapCreation = System.currentTimeMillis();

    // ITEMPOOL// w  w  w. j av a2 s .  com
    specContent.setItemPool(setupItemPoolData(assessment, itemList, segmentList, affinityGroupList, version));
    final Map<String, TestItem> testItemMap = buildTestItemMap(specContent.getItemPool().getTestItemList());
    final long itemPoolCreation = System.currentTimeMillis();

    // BLUEPRINT (counts, different levels of the hierarchy)
    specContent.setTestBlueprintList(
            setupBlueprintData(assessment, itemList, segmentList, blueprintElementList, affinityGroupList));
    final long blueprintCreation = System.currentTimeMillis();

    // SEGMENT
    specContent.setAdministrationSegmentList(setupAdminSegmentData(assessment, itemList, segmentList,
            specContent.getTestBlueprintList(), blueprintElementList, affinityGroupList));
    final long segmentCreation = System.currentTimeMillis();

    // FORM
    long formCreation = segmentCreation;
    if (Iterables.any(segmentList, FIXEDFORM_SEGMENT_FILTER)) {
        specContent.setTestFormList(setupTestFormData(assessment, segmentList, itemList, testItemMap));
        formCreation = System.currentTimeMillis();
    }

    // top-level pool property
    specContent.setPoolPropertyList(
            buildTopLevelPoolPropertyList(assessmentId, itemList, segmentList, testItemMap));
    final long poolCreation = System.currentTimeMillis();

    // PERFORMANCE LEVELS
    specContent.setTestPerformanceLevelList(setupPerformanceLevelData(assessmentId, blueprintReferenceMap));
    final long performanceCreation = System.currentTimeMillis();

    // SCORING RULES
    final List<ScoringRule> scoringRuleList = retrieveScoringRules(assessmentId);
    specContent.setScoringRuleData(setupScoringRuleData(assessmentId, blueprintReferenceMap, scoringRuleList,
            blueprintElementList, true));
    final Map<String, Collection<TestComputationRule>> scoringRuleReferenceMap = buildScoringRuleReferenceMap(
            specContent.getScoringRuleData().getComputationRuleList());
    final long scoringCreation = System.currentTimeMillis();

    // REPORTING MEASURES
    specContent.setTestReportingMeasureList(
            setupReportingMeasureData(assessmentId, blueprintReferenceMap, scoringRuleReferenceMap));
    final long reportingCreation = System.currentTimeMillis();
    logStats(start, dataRetrieval, blueprintReferenceMapCreation, itemPoolCreation, blueprintCreation,
            segmentCreation, formCreation, poolCreation, performanceCreation, scoringCreation,
            reportingCreation);

    testSpec.setContent(specContent);
    return testSpec;
}

From source file:org.eclipse.sirius.ui.tools.internal.actions.copy.CopyRepresentationAction.java

/**
 * Test if the selection is valid./*w  w  w  .java 2s  .c  om*/
 *
 * @return true if the selection is valid
 */
private boolean isValidSelection() {

    boolean anyInvalidCopy = Iterables.any(representations, new Predicate<DRepresentation>() {

        @Override
        public boolean apply(DRepresentation input) {
            EObject container = input.eContainer();
            if (container instanceof DView) {
                IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault()
                        .getPermissionAuthority(container);
                if (permissionAuthority != null && !permissionAuthority.canCreateIn(container)) {
                    return true;
                }
            }
            return false;
        }
    });

    return !anyInvalidCopy;
}