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

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

Introduction

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

Prototype

@GwtIncompatible("Class.isInstance")
@CheckReturnValue
public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> desiredType) 

Source Link

Document

Returns all elements in unfiltered that are of the type desiredType .

Usage

From source file:org.jclouds.rimuhosting.miro.compute.strategy.RimuHostingListNodesStrategy.java

@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
    return Iterables.filter(Iterables.transform(client.getServerList(), serverToNodeMetadata), filter);
}

From source file:org.jclouds.internal.FilterStringsBoundToInjectorByName.java

@Override
public Map<String, String> apply(Predicate<String> filter) {
    List<Binding<String>> stringBindings = injector.findBindingsByType(TypeLiteral.get(String.class));
    Iterable<Binding<String>> annotatedWithName = Iterables.filter(stringBindings,
            new Predicate<Binding<String>>() {

                @Override//  w w w  .  j av a 2 s .  c o m
                public boolean apply(Binding<String> input) {
                    Annotation annotation = input.getKey().getAnnotation();
                    if (annotation == null)
                        return false;
                    return (annotation instanceof javax.inject.Named)
                            || (annotation instanceof com.google.inject.name.Named);
                }

            });

    Map<String, Binding<String>> bindingsByName = Maps.uniqueIndex(annotatedWithName,
            new Function<Binding<String>, String>() {

                @Override
                public String apply(Binding<String> input) {
                    Annotation annotation = input.getKey().getAnnotation();
                    return (annotation instanceof javax.inject.Named)
                            ? javax.inject.Named.class.cast(annotation).value()
                            : com.google.inject.name.Named.class.cast(annotation).value();
                }

            });

    Map<String, Binding<String>> filteredBindingsByName = Maps.filterKeys(bindingsByName, filter);

    Map<String, String> stringBoundByName = Maps.transformValues(filteredBindingsByName,
            new Function<Binding<String>, String>() {

                @Override
                public String apply(Binding<String> input) {
                    return input.getProvider().get();
                }
            });
    return stringBoundByName;
}

From source file:org.jclouds.vcloud.domain.internal.TasksListImpl.java

public TasksListImpl(URI location, SortedSet<Task> tasks) {
    this.location = location;
    this.tasks = tasks;
    this.tasksByResult = Multimaps.index(Iterables.filter(tasks, new Predicate<Task>() {

        public boolean apply(Task input) {
            return input.getResult() != null;
        }/*from www  .  j  a  v  a  2s.c  o m*/

    }), new Function<Task, URI>() {

        public URI apply(Task input) {

            return input.getResult().getLocation();
        }

    });
    this.tasksByOwner = Multimaps.index(tasks, new Function<Task, URI>() {

        public URI apply(Task in) {

            return in.getOwner().getLocation();
        }

    });
}

From source file:org.jclouds.ibmdev.compute.strategy.IBMDeveloperCloudListNodesStrategy.java

@Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
    return Iterables.filter(Iterables.transform(client.listInstances(), instanceToNodeMetadata), filter);
}

From source file:org.apache.isis.viewer.wicket.model.models.ServiceActionsModel.java

protected List<ObjectAdapter> load() {
    return Lists.newArrayList(Iterables.filter(getServiceAdapters(), with(menuBar)));
}

From source file:ru.ksu.niimm.cll.mocassin.crawl.analyzer.relation.impl.BasicProvesRelationAnalyzer.java

@Override
public void addRelations(Graph<StructuralElement, Reference> graph, String paperUrl) {

    Iterable<StructuralElement> proofs = Iterables.filter(graph.getVertices(),
            new TypePredicate(MocassinOntologyClasses.PROOF));
    MocassinOntologyClasses[] validDomains = MocassinOntologyRelations
            .getValidRanges(MocassinOntologyRelations.PROVES);
    int refId = -2000; // TODO: more accurate id generation is required; see
    // also GateReferenceSearcherImpl and other restricted relation
    // analyzers//  w  w w .ja v a  2s.co  m
    for (StructuralElement proof : proofs) {
        StructuralElement closestPredecessor = this.structuralElementSearcher.findClosestPredecessor(proof,
                validDomains, graph);
        if (closestPredecessor != null) {
            Reference reference = new ReferenceImpl.Builder(refId--).document(new ParsedDocumentImpl(paperUrl))
                    .build();
            reference.setPredictedRelation(MocassinOntologyRelations.PROVES);
            addEdge(graph, reference, proof, closestPredecessor);
        } else {
            logger.warn(
                    "Failed to add a relation for a proof={}, because the found closest predecessor is null",
                    proof.getUri());
        }
    }

}

From source file:com.jivesoftware.os.tasmo.view.reader.service.LatestTreeNode.java

@Override
public JsonNode merge(JsonViewMerger merger, final Set<Id> permittedIds) throws IOException {
    Ordering<MapTreeNode> timestampOrdering = Ordering.from(new Comparator<MapTreeNode>() {
        @Override//from   w ww.  j av  a2 s .co m
        public int compare(MapTreeNode o1, MapTreeNode o2) {
            long diff = o1.getHighWaterTimestamp() - o2.getHighWaterTimestamp();
            return diff < 0 ? -1 : (diff > 0 ? 1 : 0);
        }
    });

    Iterable permitted = Iterables.filter(arrayTreeNode.values(), new Predicate<MapTreeNode>() {
        @Override
        public boolean apply(MapTreeNode input) {
            return permittedIds.contains(input.getObjectId().getId());
        }
    });

    MapTreeNode latestTreeNode = null;
    if (permitted.iterator().hasNext()) {
        latestTreeNode = timestampOrdering.max(permitted);
    }

    if (latestTreeNode == null) {
        return null;
    }
    return latestTreeNode.merge(merger, permittedIds);
}

From source file:controllers.ModuleController.java

private static List<ModuleModel> getNextModules(String input) {
    // get all the supplied view models.
    List<ViewModel> suppliedViewModels = Lists.newArrayList();
    JsonNode inputJson = Json.parse(input);

    // convert json nodes to view models.
    if (inputJson != null && inputJson.isArray()) {
        suppliedViewModels = Lists//  www.  ja v  a 2  s .  c  o  m
                .newArrayList(Iterators.transform(inputJson.getElements(), new Function<JsonNode, ViewModel>() {
                    @Override
                    @Nullable
                    public ViewModel apply(@Nullable JsonNode input) {
                        if (!input.isTextual()) {
                            return null;
                        }
                        return createViewModelQuietly(
                                fetchResource(UuidUtils.create(input.asText()), PersistentObject.class), null);

                    }
                }));
    } else if (inputJson != null && inputJson.isObject()) {
        suppliedViewModels.add(createViewModelQuietly(inputJson, null));
    }

    suppliedViewModels = Lists.newArrayList(Iterables.filter(suppliedViewModels, Predicates.notNull()));

    // get all the modules that can use these inputs.
    Map<Module, Double> nullModulesMap = Maps.newHashMap();
    Map<Module, Double> modulesMap = Maps.newHashMap();
    Reflections reflections = new Reflections("controllers.modules", Play.application().classloader());
    for (Class<? extends Module> moduleClass : reflections.getSubTypesOf(Module.class)) {
        // we're not interested in abstract classes.
        if (Modifier.isAbstract(moduleClass.getModifiers())) {
            continue;
        }

        // get the Module.Requires/Requireses annotation for each module class.
        // the requirements within each Module.Require are ANDed.
        // the requirements across multiple Module.Require annotations are ORed.
        List<Module.Requires> requireds = Lists.newArrayList();
        if (moduleClass.isAnnotationPresent(Module.Requires.class)) {
            requireds.add(moduleClass.getAnnotation(Module.Requires.class));
        }
        if (moduleClass.isAnnotationPresent(Module.Requireses.class)) {
            Collections.addAll(requireds, moduleClass.getAnnotation(Module.Requireses.class).value());
        }

        if (requireds.size() == 0) {
            requireds.add(null);
        }

        for (Module.Requires required : requireds) {
            final Set<Class<? extends ViewModel>> requiredViewModelClasses = Sets.newHashSet();
            if (required != null) {
                Collections.addAll(requiredViewModelClasses, required.value());
            }

            // get all the supplied view modules that are relevant to this module.
            List<ViewModel> usefulViewModels = Lists
                    .newArrayList(Iterables.filter(suppliedViewModels, new Predicate<ViewModel>() {
                        @Override
                        public boolean apply(@Nullable ViewModel input) {
                            // if this class is required, then return true.
                            if (requiredViewModelClasses.contains(input.getClass())) {
                                return true;
                            }

                            // if any of its super classes are required, that also works.
                            for (Class<?> superClass : ClassUtils.getAllSuperclasses(input.getClass())) {
                                if (requiredViewModelClasses.contains(superClass)) {
                                    return true;
                                }
                            }

                            return false;
                        }
                    }));

            // if all the requirements were satisfied.
            if (usefulViewModels.size() >= requiredViewModelClasses.size()) {
                // try to create an instance of the module.
                Module module = null;
                try {
                    module = moduleClass.newInstance();
                    module.setViewModels(usefulViewModels);
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
                    module = null;
                } finally {
                    // if no module was created, just ignore.
                    if (module == null) {
                        continue;
                    }
                }

                // let's not divide by zero!
                double relevancyScore = suppliedViewModels.size() != 0
                        ? usefulViewModels.size() / (double) suppliedViewModels.size()
                        : 1.0;

                // keep null modules separate.
                Map<Module, Double> targetModulesMap = null;
                if (requiredViewModelClasses.size() > 0) {
                    // if a module of this type does not exist, add it.
                    if (Maps.filterKeys(modulesMap, Predicates.instanceOf(moduleClass)).size() == 0) {
                        targetModulesMap = modulesMap;
                    }
                } else {
                    targetModulesMap = nullModulesMap;
                }
                if (targetModulesMap != null) {
                    targetModulesMap.put(module, relevancyScore);
                }
            }
        }
    }

    // use null modules only if there are no regular ones.
    if (modulesMap.size() == 0) {
        modulesMap = nullModulesMap;
    }

    // convert to view models.
    Set<ModuleModel> moduleViewModels = Sets.newHashSet(
            Iterables.transform(modulesMap.entrySet(), new Function<Entry<Module, Double>, ModuleModel>() {
                @Override
                @Nullable
                public ModuleModel apply(@Nullable Entry<Module, Double> input) {
                    return new ModuleModel(input.getKey()).setRelevancyScore(input.getValue());
                }
            }));

    // order first by relevance and then by name.
    return Ordering.from(new Comparator<ModuleModel>() {
        @Override
        public int compare(ModuleModel o1, ModuleModel o2) {
            int relDiff = (int) Math.round((o2.relevancyScore - o1.relevancyScore) * 1000);
            if (relDiff == 0) {
                return o1.name.compareTo(o2.name);
            }

            return relDiff;
        }
    }).sortedCopy(moduleViewModels);
}

From source file:eu.interedition.collatex.neo4j.Neo4jVariantGraphVertex.java

@Override
public Iterable<? extends VariantGraph.Edge> incoming(Set<Witness> witnesses) {
    return Iterables.filter(
            transform(node.getRelationships(Neo4jGraphRelationships.PATH, INCOMING), graph.edgeWrapper),
            Neo4jVariantGraphEdge.createTraversableFilter(witnesses));
}

From source file:org.jnario.spec.ui.highlighting.SpecHighlightingCalculator.java

@Override
protected void doProvideHighlightingFor(XtextResource resource,
        org.eclipse.xtext.ide.editor.syntaxcoloring.IHighlightedPositionAcceptor acceptor,
        CancelIndicator cancelIndicator) {
    EObject root = resource.getContents().get(0);
    if (!(root instanceof SpecFile)) {
        return;/*from   ww  w. j  a  va 2s . c o  m*/
    }
    SpecFile file = (SpecFile) root;
    for (ExampleGroup exampleGroup : Iterables.filter(file.getXtendTypes(), ExampleGroup.class)) {
        for (XAnnotation annotation : exampleGroup.getAnnotations()) {
            // TODO NO_XTEND
            // highlightDeprecatedXtendAnnotationTarget(acceptor, exampleGroup, annotation);
        }
        provideHighlightingFor(exampleGroup, acceptor);
    }
    super.doProvideHighlightingFor(resource, acceptor, cancelIndicator);
}