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.eclipse.sirius.business.api.control.SiriusUncontrolCommand.java

private Collection<DRepresentation> collectExistingRepresentations(final Resource resource) {
    return Sets.newHashSet(
            Iterators.filter(EcoreUtil.getAllProperContents(resource, true), DRepresentation.class));
}

From source file:org.eclipse.xtext.generator.parser.packrat.PackratParserGenUtil.java

private static List<String> getConflictingKeywordsImpl(final Grammar grammar, TerminalRule rule) {
    final Iterator<Keyword> conflictingKeywords = getConflictingKeywords(rule,
            Iterators.filter(EcoreUtil.getAllContents(grammar, true), Keyword.class));
    Set<String> res = Sets.newLinkedHashSet();
    Iterators.addAll(res, Iterators.transform(conflictingKeywords, new Function<Keyword, String>() {
        @Override/*from   w w  w.  j av  a  2 s .c  o m*/
        public String apply(Keyword param) {
            return param.getValue();
        }
    }));
    return Lists.newArrayList(res);
}

From source file:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

@Transactional
public void updatePrimaryPlateConcentrations(Copy copy) {
    ConcentrationStatistics concentrationStatistics = new ConcentrationStatistics();
    copy.setConcentrationStatistics(concentrationStatistics);
    // update the plates using values from the wells
    Collection<Plate> platesToConsider = Sets.newHashSet(copy.getPlates().values());

    for (Iterator<Plate> iter = platesToConsider.iterator(); iter.hasNext();) {
        Plate p = iter.next();/* w w  w  .j a  v  a  2s.c  o m*/
        p.setConcentrationStatistics(new ConcentrationStatistics());
        updatePrimaryWellConcentration(p);
        // update the copy with the values from the plate
        if (p.getMaxMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(p.getMaxMgMlConcentration());
            else if (p.getMaxMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(p.getMaxMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(p.getMinMgMlConcentration());
            else if (p.getMinMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(p.getMinMgMlConcentration());
        }
        if (p.getMaxMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(p.getMaxMolarConcentration());
            else if (p.getMaxMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(p.getMaxMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(p.getMinMolarConcentration());
            else if (p.getMinMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(p.getMinMolarConcentration());
        }
        if (!isStoredAtFacility.apply(p.getStatus())) // consider only plates stored at this facility
        {
            iter.remove();
            continue;
        }
    }

    Map<BigDecimal, Integer> mgMlCounts = Maps
            .transformValues(
                    Multimaps.index(
                            Lists.newArrayList(Iterators.filter(platesToConsider.iterator(),
                                    Predicates.compose(Predicates.notNull(),
                                            Plate.ToPrimaryWellMgMlConcentration))),
                            Plate.ToPrimaryWellMgMlConcentration).asMap(),
                    CollectionSize);

    if (!mgMlCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMgMlConcentration(findMaxByValueThenKey(mgMlCounts).getKey());

    Map<MolarConcentration, Integer> molarCounts = Maps
            .transformValues(
                    Multimaps.index(
                            Lists.newArrayList(Iterators.filter(platesToConsider.iterator(),
                                    Predicates.compose(Predicates.notNull(),
                                            Plate.ToPrimaryWellMolarConcentration))),
                            Plate.ToPrimaryWellMolarConcentration).asMap(),
                    CollectionSize);

    if (!molarCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMolarConcentration(findMaxByValueThenKey(molarCounts).getKey());
}

From source file:org.locationtech.geogig.api.plumbing.DeepMove.java

private void moveTree(final ObjectId treeId, final ObjectDatabase from, final ObjectDatabase to,
        final Set<ObjectId> metadataIds) {
    if (to.exists(treeId)) {
        return;/* w w w. j  a  v  a  2s  . c  o m*/
    }
    Supplier<Iterator<NodeRef>> refs = command(LsTreeOp.class).setReference(treeId.toString())
            .setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES);

    Supplier<Iterator<Node>> nodes = Suppliers.compose(new Function<Iterator<NodeRef>, Iterator<Node>>() {

        @Override
        public Iterator<Node> apply(Iterator<NodeRef> input) {
            return Iterators.transform(input, new Function<NodeRef, Node>() {
                @Override
                public Node apply(NodeRef input) {
                    return input.getNode();
                }
            });
        }
    }, refs);

    // move all features, recursively as given by the LsTreeOp strategy
    moveObjects(from, to, nodes, metadataIds);

    // collect all subtree and bucket ids here to delete them from the origin db
    final Set<ObjectId> alltreeIds = Sets.newTreeSet();
    Predicate<RevTree> collectIds = new Predicate<RevTree>() {
        @Override
        public boolean apply(RevTree input) {
            alltreeIds.add(input.getId());
            return true;
        }
    };

    // iterator that traverses the tree,all its subtrees, an bucket trees
    Iterator<RevTree> allSubtreesAndBuckets = new AllTrees(treeId, from);
    allSubtreesAndBuckets = Iterators.filter(allSubtreesAndBuckets, collectIds);

    to.putAll(allSubtreesAndBuckets);
    from.deleteAll(alltreeIds.iterator());
}

From source file:org.axdt.as3.model.impl.As3OperationImpl.java

/**
 * <!-- begin-user-doc -->/*  w  w  w  . j  ava2  s . c  o  m*/
 * <!-- end-user-doc -->
 */
public Iterable<AvmReferable> getDeclarations() {
    if (body != null)
        return Lists.newArrayList(
                Iterators.filter(EcoreUtil.getAllProperContents(body, false), AvmReferable.class));
    return Collections.emptySet();
}

From source file:org.openscience.cdk.isomorphism.Mappings.java

/**
 * Filter the mappings for those which cover a unique set of bonds in the
 * target.// w ww .  ja va 2  s  .c  o m
 *
 * @return fluent-api instance
 * @see #uniqueAtoms()
 */
public Mappings uniqueBonds() {
    // we need the unique predicate to be reset for each new iterator -
    // otherwise multiple iterations are always filtered (seen before)
    final int[][] g = GraphUtil.toAdjList(query);
    return new Mappings(query, target, new Iterable<int[]>() {

        @Override
        public Iterator<int[]> iterator() {
            return Iterators.filter(iterable.iterator(), new UniqueBondMatches(g));
        }
    });
}

From source file:org.eclipse.sirius.diagram.ui.business.internal.migration.DiagramRepresentationsFileMigrationParticipantV670.java

/**
 * Set width and height of graphical filter of collapsed bordered nodes
 * according to current GMF size and the set the GMF bounds according to
 * there collapsed size and location.//ww w  .  java 2s  .  c o m
 * 
 * @param diagram
 *            GMF Diagram to migrate.
 */
private void migrateGraphicalFiltersAndGMFBounds(Diagram diagram) {
    Iterator<Node> viewIterator = Iterators.filter(Iterators.filter(diagram.eAllContents(), Node.class),
            isBorderedNode);
    while (viewIterator.hasNext()) {
        Node node = viewIterator.next();
        if (node.getElement() instanceof DNode && node.eContainer() instanceof Node) {
            // The element of a bordered node should be a DNode and the
            // parent of a bordered node should be a Node.
            DNode dNode = (DNode) node.getElement();
            if (new DDiagramElementQuery(dNode).isIndirectlyCollapsed()) {
                // This node is collapsed.
                Dimension expectedCollapsedSize = new NodeQuery(node).getCollapsedSize();
                LayoutConstraint layoutConstraint = node.getLayoutConstraint();
                if (layoutConstraint instanceof Bounds) {
                    Bounds bounds = (Bounds) layoutConstraint;
                    Rectangle rectBounds = GMFHelper.getAbsoluteBounds(node);
                    // The GMF node size must be stored in collapse
                    // filter (to can set this size
                    // when this node is expanded).
                    for (GraphicalFilter graphicalFilter : dNode.getGraphicalFilters()) {
                        if (graphicalFilter instanceof CollapseFilter) {
                            ((CollapseFilter) graphicalFilter).setWidth(bounds.getWidth());
                            ((CollapseFilter) graphicalFilter).setHeight(bounds.getHeight());
                        }
                    }
                    // Compute the parent border rectangle
                    Rectangle parentBorder = new NodeQuery((Node) node.eContainer()).getHandleBounds();
                    // Compute the new collapsed bounds
                    Rectangle newCollapsedBounds = PortLayoutHelper
                            .getCollapseCandidateLocation(expectedCollapsedSize, rectBounds, parentBorder);
                    // Translate to relative
                    newCollapsedBounds.translate(parentBorder.getLocation().negate());
                    // // Set new GMF bounds
                    Bounds newBounds = NotationFactory.eINSTANCE.createBounds();
                    newBounds.setX(newCollapsedBounds.x);
                    newBounds.setY(newCollapsedBounds.y);
                    newBounds.setWidth(newCollapsedBounds.width);
                    newBounds.setHeight(newCollapsedBounds.height);
                    node.setLayoutConstraint(newBounds);
                }
            }
        }
    }
}

From source file:org.apache.kylin.cube.cuboid.DefaultCuboidScheduler.java

/**
 * Get all valid cuboids for agg group, ignoring padding
 * @param agg agg group//from   w w w. j a v  a 2s. com
 * @return cuboidId list
 */
public Set<Long> calculateCuboidsForAggGroup(AggregationGroup agg) {
    Set<Long> cuboidHolder = new HashSet<>();

    // build tree structure
    Set<Long> children = getLowestCuboids(agg);
    while (!children.isEmpty()) {
        if (cuboidHolder.size() > cubeDesc.getConfig().getCubeAggrGroupMaxCombination()) {
            throw new TooManyCuboidException("Holder size larger than kylin.cube.aggrgroup.max-combination");
        }
        cuboidHolder.addAll(children);
        children = getOnTreeParentsByLayer(children, agg);
    }

    return Sets.newHashSet(Iterators.filter(cuboidHolder.iterator(), new Predicate<Long>() {
        @Override
        public boolean apply(@Nullable Long cuboidId) {
            return !cubeDesc.isBlackedCuboid(cuboidId);
        }
    }));
}

From source file:com.thinkbiganalytics.metadata.core.feed.InMemoryFeedProvider.java

@Override
public List<Feed> getFeeds(FeedCriteria criteria) {
    Criteria critImpl = (Criteria) criteria;
    Iterator<Feed> filtered = Iterators.filter(this.feeds.values().iterator(), critImpl);
    Iterator<Feed> limited = Iterators.limit(filtered, critImpl.getLimit());

    return ImmutableList.copyOf(limited);
}

From source file:org.janusgraph.core.JanusGraphFactory.java

/**
 * Load a properties file containing a JanusGraph graph configuration.
 * <p/>/*w ww  . jav a2s. c  o m*/
 * <ol>
 * <li>Load the file contents into a {@link org.apache.commons.configuration.PropertiesConfiguration}</li>
 * <li>For each key that points to a configuration object that is either a directory
 * or local file, check
 * whether the associated value is a non-null, non-absolute path. If so,
 * then prepend the absolute path of the parent directory of the provided configuration {@code file}.
 * This has the effect of making non-absolute backend
 * paths relative to the config file's directory rather than the JVM's
 * working directory.
 * <li>Return the {@link ReadConfiguration} for the prepared configuration file</li>
 * </ol>
 * <p/>
 *
 * @param file A properties file to load
 * @return A configuration derived from {@code file}
 */
@SuppressWarnings("unchecked")
private static ReadConfiguration getLocalConfiguration(File file) {
    Preconditions.checkArgument(file != null && file.exists() && file.isFile() && file.canRead(),
            "Need to specify a readable configuration file, but was given: %s", file.toString());

    try {
        PropertiesConfiguration configuration = new PropertiesConfiguration(file);

        final File tmpParent = file.getParentFile();
        final File configParent;

        if (null == tmpParent) {
            /*
             * null usually means we were given a JanusGraph config file path
             * string like "foo.properties" that refers to the current
             * working directory of the process.
             */
            configParent = new File(System.getProperty("user.dir"));
        } else {
            configParent = tmpParent;
        }

        Preconditions.checkNotNull(configParent);
        Preconditions.checkArgument(configParent.isDirectory());

        // TODO this mangling logic is a relic from the hardcoded string days; it should be deleted and rewritten as a setting on ConfigOption
        final Pattern p = Pattern.compile("(" + Pattern.quote(STORAGE_NS.getName()) + "\\..*" + "("
                + Pattern.quote(STORAGE_DIRECTORY.getName()) + "|" + Pattern.quote(STORAGE_CONF_FILE.getName())
                + ")" + "|" + Pattern.quote(INDEX_NS.getName()) + "\\..*" + "("
                + Pattern.quote(INDEX_DIRECTORY.getName()) + "|" + Pattern.quote(INDEX_CONF_FILE.getName())
                + ")" + ")");

        final Iterator<String> keysToMangle = Iterators.filter(configuration.getKeys(),
                new Predicate<String>() {
                    @Override
                    public boolean apply(String key) {
                        if (null == key)
                            return false;
                        return p.matcher(key).matches();
                    }
                });

        while (keysToMangle.hasNext()) {
            String k = keysToMangle.next();
            Preconditions.checkNotNull(k);
            String s = configuration.getString(k);
            Preconditions.checkArgument(StringUtils.isNotBlank(s),
                    "Invalid Configuration: key %s has null empty value", k);
            configuration.setProperty(k, getAbsolutePath(configParent, s));
        }
        return new CommonsConfiguration(configuration);
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException("Could not load configuration at: " + file, e);
    }
}