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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked") 
@GwtIncompatible("Class.isInstance")
@CheckReturnValue
public static <T> UnmodifiableIterator<T> filter(Iterator<?> unfiltered, Class<T> desiredType) 

Source Link

Document

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

Usage

From source file:org.locationtech.geogig.porcelain.AddOp.java

/**
 * Stages the object addressed by {@code pathFilter}, or all unstaged objects if
 * {@code pathFilter == null} to be added, if it is/they are marked as an unstaged change. Does
 * nothing otherwise./*from  w  ww.  j a  va  2  s.  c  o  m*/
 * <p>
 * To stage changes not yet staged, a diff tree walk is performed using the current staged
 * {@link RevTree} as the old object and the current unstaged {@link RevTree} as the new object.
 * Then all the differences are traversed and the staged tree is updated with the changes
 * reported by the diff walk (neat).
 * </p>
 * 
 * @param progress the progress listener for this process
 * @param pathFilter the filter to use
 */
public void stage(final ProgressListener progress, final @Nullable String pathFilter) {

    // short cut for the case where the index is empty and we're staging all changes in the
    // working tree, so it's just a matter of updating the index ref to working tree RevTree id
    final StagingArea index = stagingArea();
    try (AutoCloseableIterator<DiffEntry> staged = index.getStaged(null)) {
        if (null == pathFilter && !staged.hasNext() && !updateOnly && index.countConflicted(null) == 0) {
            progress.started();
            Optional<ObjectId> workHead = command(RevParse.class).setRefSpec(Ref.WORK_HEAD).call();
            if (workHead.isPresent()) {
                command(UpdateRef.class).setName(Ref.STAGE_HEAD).setNewValue(workHead.get()).call();
            }
            progress.setProgress(100f);
            progress.complete();
            return;
        }
    }

    final long numChanges = workingTree().countUnstaged(pathFilter).count();

    try (AutoCloseableIterator<DiffEntry> sourceIterator = workingTree().getUnstaged(pathFilter)) {
        Iterator<DiffEntry> updatedIterator = sourceIterator;
        if (updateOnly) {
            updatedIterator = Iterators.filter(updatedIterator, new Predicate<DiffEntry>() {
                @Override
                public boolean apply(@Nullable DiffEntry input) {
                    // HACK: avoid reporting changed trees
                    if (input.isChange() && input.getOldObject().getType().equals(TYPE.TREE)) {
                        return false;
                    }
                    return input.getOldObject() != null;
                }
            });
        }

        index.stage(progress, updatedIterator, numChanges);

        // if we are staging unmerged files, the conflict should get solved. However, if the
        // working index object is the same as the staging area one (for instance, after running
        // checkout --ours), it will not be reported by the getUnstaged method. We solve that
        // here.
        ConflictsDatabase conflictsDatabase = conflictsDatabase();
        conflictsDatabase.removeByPrefix(null, pathFilter);
    }
}

From source file:org.trancecode.concurrent.ParallelIterators.java

/**
 * @see Iterators#filter(Iterable, Predicate)
 *//*from ww w.j av a  2 s  . c  o m*/
public static <T> Iterator<T> filter(final Iterator<T> unfiltered, final Predicate<? super T> predicate,
        final ExecutorService executor) {
    final Function<? super T, Entry<T, Boolean>> evaluateFunction = (Function<T, Entry<T, Boolean>>) element -> Maps
            .immutableEntry(element, predicate.apply(element));

    final Iterator<Entry<T, Boolean>> unfilteredWithPredicateEvaluated = transform(unfiltered, evaluateFunction,
            executor);
    final Function<Entry<T, Boolean>, Boolean> getValueFunction = MapFunctions.getValue();
    final Iterator<Entry<T, Boolean>> filtered = Iterators.filter(unfilteredWithPredicateEvaluated,
            TcPredicates.asPredicate(getValueFunction));

    final Function<Entry<T, Boolean>, T> getKeyFunction = MapFunctions.getKey();
    return Iterators.transform(filtered, getKeyFunction);
}

From source file:org.richfaces.bootstrap.ui.pickList.PickListRendererBase.java

protected Iterator<ClientSelectItem> getTargetSelectItems(List<ClientSelectItem> clientSelectItems) {
    return Iterators.filter(clientSelectItems.iterator(), SelectManyHelper.SELECTED_PREDICATE);
}

From source file:org.richfaces.renderkit.PickListRendererBase.java

public void encodeSourceItems(FacesContext facesContext, UIComponent component,
        List<ClientSelectItem> clientSelectItems) throws IOException {
    Iterator<ClientSelectItem> sourceItems = Iterators.filter(clientSelectItems.iterator(),
            SelectManyHelper.UNSELECTED_PREDICATE);
    SelectManyHelper.encodeItems(facesContext, component, sourceItems, CSS_PREFIX);
}

From source file:org.apache.jackrabbit.oak.security.user.AbstractGroupPrincipal.java

@Override
public Enumeration<? extends Principal> members() {
    final Iterator<Authorizable> members;
    try {/*  ww  w. j av  a  2 s  .c  o  m*/
        members = getMembers();
    } catch (RepositoryException e) {
        // should not occur.
        String msg = "Unable to retrieve Group members: " + e.getMessage();
        log.error(msg);
        throw new IllegalStateException(msg, e);
    }

    Iterator<Principal> principals = Iterators.transform(members, new Function<Authorizable, Principal>() {
        @Override
        public Principal apply(Authorizable authorizable) {
            if (authorizable == null) {
                return null;
            }
            try {
                return authorizable.getPrincipal();
            } catch (RepositoryException e) {
                String msg = "Internal error while retrieving principal: " + e.getMessage();
                log.error(msg);
                throw new IllegalStateException(msg, e);
            }
        }
    });
    return Iterators.asEnumeration(Iterators.filter(principals, Predicates.<Object>notNull()));
}

From source file:org.summer.dsl.ui.codetemplates.ui.highlighting.SemanticHighlighter.java

public void provideHighlightingFor(XtextResource resource, final IHighlightedPositionAcceptor acceptor) {
    if (resource == null || resource.getContents().isEmpty())
        return;//from   w  w  w  . j  a  v  a2s .c  o m
    Codetemplates templates = (Codetemplates) resource.getContents().get(0);
    Grammar grammar = templates.getLanguage();
    if (grammar != null && !grammar.eIsProxy()) {
        TemplateBodyHighlighter highlighter = getHighlighter(grammar);
        if (highlighter != null) {
            ContextTypeIdHelper helper = registry.getContextTypeIdHelper(grammar);
            ContextTypeRegistry contextTypeRegistry = registry.getContextTypeRegistry(grammar);
            for (Codetemplate template : templates.getTemplates()) {
                if (template.getBody() != null) {
                    final EvaluatedTemplate evaluatedTemplate = new EvaluatedTemplate(template);
                    highlighter.provideHighlightingFor(evaluatedTemplate.getMappedString(),
                            new IHighlightedPositionAcceptor() {
                                public void addPosition(int offset, int length, String... id) {
                                    int beginOffset = evaluatedTemplate.getOriginalOffset(offset);
                                    int endOffset = evaluatedTemplate.getOriginalOffset(offset + length);
                                    int fixedLength = endOffset - beginOffset;
                                    acceptor.addPosition(beginOffset, fixedLength, id);
                                }
                            });
                    String id = null;
                    TemplateContextType contextType = null;
                    if (template.getContext() != null) {
                        id = helper.getId(template.getContext());
                        if (id != null)
                            contextType = contextTypeRegistry.getContextType(id);
                    }
                    Set<String> defaultResolvers = Sets.newHashSet();
                    if (contextType != null) {
                        Iterator<TemplateVariableResolver> resolvers = Iterators.filter(contextType.resolvers(),
                                TemplateVariableResolver.class);
                        while (resolvers.hasNext()) {
                            TemplateVariableResolver resolver = resolvers.next();
                            defaultResolvers.add(resolver.getType());
                        }
                    }
                    for (TemplatePart part : template.getBody().getParts()) {
                        if (part instanceof Variable) {
                            Variable variable = (Variable) part;
                            ICompositeNode node = NodeModelUtils.findActualNodeFor(variable);
                            if (node != null) {
                                for (ILeafNode leafNode : node.getLeafNodes()) {
                                    if (leafNode.getGrammarElement() instanceof Keyword) {
                                        acceptor.addPosition(leafNode.getTotalOffset(),
                                                leafNode.getTotalLength(),
                                                TemplatesHighlightingConfiguration.TEMPLATE_VARIABLE);
                                    }
                                }
                                List<INode> typeNodes = NodeModelUtils.findNodesForFeature(variable,
                                        TemplatesPackage.Literals.VARIABLE__TYPE);
                                if (typeNodes.isEmpty()) {
                                    if (defaultResolvers.contains(variable.getName())) {
                                        List<INode> nameNodes = NodeModelUtils.findNodesForFeature(variable,
                                                TemplatesPackage.Literals.VARIABLE__NAME);
                                        for (INode nameNode : nameNodes) {
                                            highlightNode(nameNode,
                                                    TemplatesHighlightingConfiguration.TEMPLATE_VARIABLE,
                                                    acceptor);
                                        }
                                    }
                                } else {
                                    for (INode typeNode : typeNodes) {
                                        highlightNode(typeNode,
                                                TemplatesHighlightingConfiguration.TEMPLATE_VARIABLE, acceptor);
                                    }
                                }
                                List<INode> parameterNodes = NodeModelUtils.findNodesForFeature(variable,
                                        TemplatesPackage.Literals.VARIABLE__PARAMETERS);
                                for (INode parameterNode : parameterNodes) {
                                    highlightNode(parameterNode,
                                            TemplatesHighlightingConfiguration.TEMPLATE_VARIABLE_ARGUMENT,
                                            acceptor);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.util.EditPartsHelper.java

/**
 * Finds all the lifelines contained inside the specified element or any of
 * its descendant edit parts./*  ww  w . ja  v a 2  s  .  co  m*/
 * 
 * @param element
 *            the element from which to start the search for executions.
 * @return the executions found.
 * 
 */
public static List<LifelineEditPart> getAllLifelines(IGraphicalEditPart element) {
    return Lists.newArrayList(
            Iterators.filter(Iterators.filter(new EditPartsTreeIterator(element), LifelineEditPart.class),
                    EditPartsHelper.isValid()));
}

From source file:ch.ethz.inf.vs.hypermedia.corehal.block.ThingCrawler.java

@Override
public Iterator<ThingDescriptionFuture> iterator() {
    LocationCrawler locationCrawler = new LocationCrawler().withContext(parent);
    if (targetLocation != null) {
        locationCrawler = locationCrawler.matchingPrefix(targetLocation);
    }/*from  www.j  a  v a  2  s.  c o  m*/
    // Use pre order for thing discovery
    locationCrawler.setPostOrder(false);
    Iterator<Iterator<ThingDescriptionFuture>> locationResources = Iterators
            .transform(locationCrawler.iterator(), this::discoverLocation);
    Iterator<ThingDescriptionFuture> flatLocationResources = Iterators.concat(locationResources);
    Iterator<WebLink> links = Collections.emptyIterator();
    if (parent instanceof LinkListFuture) {
        links = getSortedWebLinks((LinkListFuture) parent);
    }
    return Iterators.filter(
            Iterators.concat(Iterators.transform(links, ThingCrawler::transform), flatLocationResources),
            this::filter);
}

From source file:org.eclipse.xtext.ui.codetemplates.ui.validation.TemplateValidator.java

@Check
public void checkParameters(Variable variable) {
    Codetemplate template = EcoreUtil2.getContainerOfType(variable, Codetemplate.class);
    Codetemplates templates = EcoreUtil2.getContainerOfType(template, Codetemplates.class);
    if (templates != null && template != null) {
        Grammar language = templates.getLanguage();
        AbstractRule rule = template.getContext();
        ContextTypeIdHelper helper = languageRegistry.getContextTypeIdHelper(language);
        if (helper != null && rule != null && !rule.eIsProxy() && rule instanceof ParserRule) {
            String contextTypeId = helper.getId(rule);
            ContextTypeRegistry contextTypeRegistry = languageRegistry.getContextTypeRegistry(language);
            TemplateContextType contextType = contextTypeRegistry.getContextType(contextTypeId);
            if (contextType != null) {
                Iterator<TemplateVariableResolver> resolvers = Iterators.filter(contextType.resolvers(),
                        TemplateVariableResolver.class);
                String type = variable.getType();
                if (type == null)
                    type = variable.getName();
                while (resolvers.hasNext()) {
                    final TemplateVariableResolver resolver = resolvers.next();
                    if (resolver.getType().equals(type)) {
                        IInspectableTemplateVariableResolver inspectableResolver = registry
                                .toInspectableResolver(resolver);
                        if (inspectableResolver != null) {
                            inspectableResolver.validateParameters(variable, this);
                        }/*ww w .  j  a  va  2s.c  om*/
                    }
                }
            }
        }
    }
}

From source file:org.apache.giraph.block_app.library.internal.SendMessagePiece.java

/**
 * Stripe message sending computation across multiple stripes, in
 * each stripe only part of the vertices will receive messages.
 *
 * @param stripes Number of stripes//w ww.j  av  a 2  s  .c  om
 * @param stripeSupplier Stripe supplier function, if IDs are Longs, you can
 *                       use StripingUtils::fastHashStripingPredicate
 * @return Resulting block
 */
public Block stripeByReceiver(int stripes, Int2ObjFunction<Int2ObjFunction<Predicate<I>>> stripeSupplier) {
    return StripingUtils.generateStripedBlock(stripes, new Function<Predicate<I>, Block>() {
        @Override
        public Block apply(final Predicate<I> stripePredicate) {
            return FilteringPiece.createReceiveFiltering(new SupplierFromVertex<I, V, E, Boolean>() {
                @Override
                public Boolean get(Vertex<I, V, E> vertex) {
                    return stripePredicate.apply(vertex.getId());
                }
            }, new SendMessagePiece<>(name, messageClass, messageSupplier,
                    new SupplierFromVertex<I, V, E, Iterator<I>>() {
                        @Override
                        public Iterator<I> get(Vertex<I, V, E> vertex) {
                            return Iterators.filter(targetsSupplier.get(vertex),
                                    new com.google.common.base.Predicate<I>() {
                                        @Override
                                        public boolean apply(I targetId) {
                                            return stripePredicate.apply(targetId);
                                        }
                                    });
                        }
                    }, messagesConsumer));
        }
    }, stripeSupplier);
}