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:org.eclipse.xtext.ui.editor.outline.impl.BackgroundOutlineTreeProvider.java

protected boolean isLeaf(final EObject modelElement) {
    return !Iterables.any(modelElement.eClass().getEAllContainments(), new Predicate<EReference>() {
        @Override/*from w w  w  .j a v  a2s.c  o m*/
        public boolean apply(EReference containmentRef) {
            return modelElement.eIsSet(containmentRef);
        }
    });
}

From source file:com.facebook.presto.sql.analyzer.AggregationAnalyzer.java

public boolean analyze(int fieldIndex) {
    return Iterables.any(fieldIndexes, equalTo(fieldIndex));
}

From source file:org.richfaces.cdk.generate.freemarker.ModelElementBaseTemplateModel.java

public TemplateModel hasBindingAttribute() throws TemplateModelException {
    return wrapper.wrap(Iterables.any(model.getAttributes(), new Predicate<PropertyBase>() {
        @Override//from   w ww.j a  va 2  s  .  c om
        public boolean apply(PropertyBase input) {
            return input.isBindingAttribute();
        }
    }));
}

From source file:org.onosproject.cli.net.ResourcesCommand.java

private void printResource(Resource resource, int level) {
    // workaround to preserve the original behavior of ResourceService#getRegisteredResources
    Set<Resource> children;
    if (resource instanceof DiscreteResource) {
        children = resourceService.getRegisteredResources(((DiscreteResource) resource).id());
    } else {//from   ww w.j  a  v  a 2s . co  m
        children = Collections.emptySet();
    }

    if (resource.equals(Resource.ROOT)) {
        print("ROOT");
    } else {
        String resourceName = resource.simpleTypeName();
        if (resource instanceof ContinuousResource) {
            print("%s%s: %f", Strings.repeat(" ", level), resourceName,
                    ((ContinuousResource) resource).value());
            // Continuous resource is terminal node, stop here
            return;
        } else {
            String availability = "";
            if (availablesOnly && !children.isEmpty()) {
                // intermediate nodes cannot be omitted, print availability
                if (resourceService.isAvailable(resource)) {
                    availability = " ";
                } else {
                    availability = " ";
                }
            }
            String toString = String.valueOf(resource.valueAs(Object.class).orElse(""));
            if (toString.startsWith(resourceName)) {
                print("%s%s%s", Strings.repeat(" ", level), toString, availability);
            } else {
                print("%s%s: %s%s", Strings.repeat(" ", level), resourceName, toString, availability);
            }
        }
    }

    // Classify children into aggregatable terminal resources and everything else

    Set<Class<?>> aggregatableTypes = ImmutableSet.<Class<?>>builder().add(VlanId.class).add(MplsLabel.class)
            .build();
    // (last() resource name) -> { Resource }
    Multimap<String, Resource> aggregatables = ArrayListMultimap.create();
    List<Resource> nonAggregatable = new ArrayList<>();

    for (Resource r : children) {
        if (!isPrintTarget(r)) {
            continue;
        }

        if (r instanceof ContinuousResource) {
            // non-aggregatable terminal node
            nonAggregatable.add(r);
        } else if (Iterables.any(aggregatableTypes, r::isTypeOf)) {
            // aggregatable & terminal node
            String simpleName = r.simpleTypeName();
            aggregatables.put(simpleName, r);
        } else {
            nonAggregatable.add(r);
        }
    }

    // print aggregated (terminal)
    aggregatables.asMap().entrySet().forEach(e -> {
        // for each type...
        String resourceName = e.getKey();

        RangeSet<Long> rangeSet = TreeRangeSet.create();

        // aggregate into RangeSet
        e.getValue().stream().map(res -> {
            if (res.isTypeOf(VlanId.class)) {
                return (long) res.valueAs(VlanId.class).get().toShort();
            } else if (res.isTypeOf(MplsLabel.class)) {
                return (long) res.valueAs(MplsLabel.class).get().toInt();
            } else if (res.isTypeOf(TributarySlot.class)) {
                return res.valueAs(TributarySlot.class).get().index();
            }
            // TODO support Lambda (OchSignal types)
            return 0L;
        }).map(Range::singleton).map(range -> range.canonical(DiscreteDomain.longs())).forEach(rangeSet::add);

        print("%s%s: %s", Strings.repeat(" ", level + 1), resourceName, rangeSet);
    });

    // print non-aggregatables (recurse)
    if (sort) {
        nonAggregatable.stream().sorted((o1, o2) -> String.valueOf(o1.id()).compareTo(String.valueOf(o2.id())))
                .forEach(r -> printResource(r, level + 1));
    } else {
        nonAggregatable.forEach(r -> printResource(r, level + 1));
    }
}

From source file:gg.uhc.flagcommands.commands.OptionCommand.java

protected List<String> tabCompleteFlags(String toComplete, String[] others) {
    // filter the args to only ones starting with a dash
    final Set<String> parameters = Sets
            .newHashSet(Iterables.filter(Lists.newArrayList(others), STARTS_WITH_DASH));

    Set<String> available = Sets.newHashSet();

    for (OptionSpec<?> spec : parser.recognizedOptions().values()) {
        // add the dash onto each of the options in the spec
        Iterable<String> params = Iterables.transform(spec.options(), PREPEND_DASH);

        // add to the available set if all of it's options are not in the not-to-complete list
        // and it wasn't already provided in the command
        boolean add = !Iterables.any(params, new Predicate<String>() {
            @Override// w ww .  ja v a2 s  . c  om
            public boolean apply(String input) {
                return argumentsNotToTabComplete.contains(input) || parameters.contains(input);
            }
        });

        if (add) {
            Iterables.addAll(available, params);
        }
    }

    // return applicable ones
    return StringUtil.copyPartialMatches(toComplete, available, Lists.<String>newArrayList());
}

From source file:com.eucalyptus.vmtypes.VmTypes.java

public static boolean isUnorderedType(VmType vmType) {
    return Iterables.any(VmTypes.list(), vmType.orderedPredicate());
}

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

private void reportDuplicateBindings(ImmutableSet<Binding> duplicateBindings, BindingGraph bindingGraph,
        DiagnosticReporter diagnosticReporter) {
    Binding oneBinding = duplicateBindings.asList().get(0);
    diagnosticReporter.reportBinding(ERROR, oneBinding,
            Iterables.any(duplicateBindings, binding -> binding.kind().isMultibinding())
                    ? incompatibleBindingsMessage(oneBinding.key(), duplicateBindings, bindingGraph)
                    : duplicateBindingMessage(oneBinding.key(), duplicateBindings, bindingGraph));
}

From source file:org.eclipse.incquery.validation.runtime.annotation.ConstraintAnnotationValidator.java

private List<String> validateKeys(Annotation annotation, IIssueCallback validator, final Pattern pattern) {
    List<String> keyList = Lists.newArrayList();
    ValueReference locationRef = CorePatternLanguageHelper.getFirstAnnotationParameter(annotation, "location");
    ValueReference keyRef = CorePatternLanguageHelper.getFirstAnnotationParameter(annotation, "key");
    if (locationRef != null && keyRef != null) {
        validator.error("Cannot use both location and key!", keyRef, null, SEVERITY_ISSUE_CODE);
    }/*from www .j a va2s.  c  o m*/
    if (locationRef instanceof VariableValue) {
        String locationVarName = ((VariableValue) locationRef).getValue().getVariable().getName();
        keyList.add(locationVarName);
    }
    if (keyRef instanceof ListValue) {
        Iterable<String> keyParamList = transformStringList(keyRef);

        List<String> invalidKeys = Lists.newArrayList();
        for (String key : keyParamList) {
            Variable parameterByName = CorePatternLanguageHelper.getParameterByName(pattern, key);
            if (parameterByName == null) {
                invalidKeys.add(key);
            } else {
                keyList.add(key);
            }
        }
        if (!invalidKeys.isEmpty()) {
            validator.error("Keys " + invalidKeys.toString() + " are not pattern parameters!", keyRef, null,
                    SEVERITY_ISSUE_CODE);
        }
    }
    if (keyList.isEmpty()) {
        validator.error("No key defined!", keyRef, null, SEVERITY_ISSUE_CODE);
    } else {
        boolean atLeastOneEClassKey = Iterables.any(keyList, new Predicate<String>() {
            @Override
            public boolean apply(String key) {
                Variable firstKeyParameter = CorePatternLanguageHelper.getParameterByName(pattern, key);
                Type sourceType = firstKeyParameter.getType();
                if (!(sourceType instanceof ClassType)
                        || !(((ClassType) sourceType).getClassname() instanceof EClass)) {
                    return false;
                } else {
                    return true;
                }
            }
        });
        if (!atLeastOneEClassKey) {
            validator.warning("At least one key should be EClass to make location possible!", keyRef, null,
                    SEVERITY_ISSUE_CODE);
        }
    }
    return keyList;
}

From source file:org.gradle.api.internal.tasks.execution.DefaultTaskProperties.java

private DefaultTaskProperties(final String name, Factory<Map<String, Object>> inputPropertyValues,
        final ImmutableSortedSet<TaskInputFilePropertySpec> inputFileProperties,
        final ImmutableSortedSet<TaskOutputFilePropertySpec> outputFileProperties, boolean hasDeclaredOutputs,
        FileCollection localStateFiles, FileCollection destroyableFiles,
        List<ValidatingTaskPropertySpec> validatingPropertySpecs) {
    this.validatingPropertySpecs = validatingPropertySpecs;

    this.inputPropertyValues = inputPropertyValues;
    this.inputFileProperties = inputFileProperties;
    this.outputFileProperties = outputFileProperties;
    this.hasDeclaredOutputs = hasDeclaredOutputs;

    this.inputFiles = new CompositeFileCollection() {
        @Override/* w  w w  .  j ava2  s  .c om*/
        public String getDisplayName() {
            return name + " input files";
        }

        @Override
        public void visitContents(FileCollectionResolveContext context) {
            for (TaskInputFilePropertySpec filePropertySpec : inputFileProperties) {
                context.add(filePropertySpec.getPropertyFiles());
            }
        }
    };
    this.sourceFiles = new CompositeFileCollection() {
        @Override
        public String getDisplayName() {
            return name + " source files";
        }

        @Override
        public void visitContents(FileCollectionResolveContext context) {
            for (TaskInputFilePropertySpec filePropertySpec : inputFileProperties) {
                if (filePropertySpec.isSkipWhenEmpty()) {
                    context.add(filePropertySpec.getPropertyFiles());
                }
            }
        }
    };
    this.hasSourceFiles = Iterables.any(inputFileProperties, new Predicate<TaskInputFilePropertySpec>() {
        @Override
        @SuppressWarnings("NullableProblems")
        public boolean apply(TaskInputFilePropertySpec property) {
            return property.isSkipWhenEmpty();
        }
    });
    this.outputFiles = new CompositeFileCollection() {
        @Override
        public String getDisplayName() {
            return "output files";
        }

        @Override
        public void visitContents(FileCollectionResolveContext context) {
            for (TaskFilePropertySpec propertySpec : outputFileProperties) {
                context.add(propertySpec.getPropertyFiles());
            }
        }
    };
    this.localStateFiles = localStateFiles;
    this.destroyableFiles = destroyableFiles;
}

From source file:org.eclipse.emf.compare.uml2.ide.ui.internal.accessor.UMLStereotypeApplicationChangeFeatureAccessor.java

/**
 * When computing the insertion index of a stereotype in the list of applied stereotypes, we need to
 * ignore all stereotypes that feature unresolved Diffs.
 * /* ww  w  . j ava2 s .c  o  m*/
 * @param candidates
 *            The sequence in which we need to compute an insertion index.
 * @param diff
 *            The diff we are computing an insertion index for.
 * @param <E>
 *            Type of the list's content.
 * @return The list of elements that should be ignored when computing the insertion index for a new
 *         element in {@code candidates}.
 */
private static <E> Iterable<E> computeIgnoredElements(Iterable<E> candidates,
        final StereotypeApplicationChange diff) {
    return Iterables.filter(candidates, new Predicate<Object>() {
        public boolean apply(final Object element) {
            if (element instanceof EObject) {
                final Comparison comparison = diff.getMatch().getComparison();
                final Match match = comparison.getMatch((EObject) element);

                return Iterables.any(match.getDifferences(), and(instanceOf(StereotypeApplicationChange.class),
                        hasState(DifferenceState.UNRESOLVED)));
            }
            return false;
        }
    });
}