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.tree.ui.tools.internal.editor.provider.TreePopupMenuContributionSupport.java

private static ImageDescriptor findImageDescriptor(OperationAction createTool) {

    ImageDescriptor descriptor = DTreeViewerManager.getImageRegistry()
            .getDescriptor(DTreeViewerManager.CREATE_TREE_ITEM_IMG);
    EObject created = null;/*  w  w  w  .j a va  2 s  .c o  m*/

    Iterator<CreateInstance> createInstances = Iterators.filter(createTool.eAllContents(),
            CreateInstance.class);
    while (created == null && createInstances.hasNext()) {
        CreateInstance map = createInstances.next();
        created = TreePopupMenuContributionSupport.tryToInstanciateType(createTool, created, map.getTypeName());
    }

    if (created != null) {
        final IItemLabelProvider labelProvider = (IItemLabelProvider) TreeUIPlugin.getPlugin()
                .getItemProvidersAdapterFactory().adapt(created, IItemLabelProvider.class);
        if (labelProvider != null) {
            ImageDescriptor semanticDescriptor = ExtendedImageRegistry.getInstance()
                    .getImageDescriptor(labelProvider.getImage(created));
            if (semanticDescriptor != null) {
                descriptor = semanticDescriptor;
            }

        }
    }

    return descriptor;
}

From source file:org.geogit.api.plumbing.WriteTree2.java

private RevTree applyChanges(@Nullable final NodeRef leftTreeRef, @Nullable final NodeRef rightTreeRef) {

    Preconditions.checkArgument(leftTreeRef != null || rightTreeRef != null,
            "either left or right tree shall be non null");

    final String treePath = rightTreeRef == null ? leftTreeRef.path() : rightTreeRef.path();

    final List<String> strippedPathFilters = stripParentAndFiltersThatDontApply(this.pathFilters, treePath);

    // find the diffs that apply to the path filters
    final ObjectId leftTreeId = leftTreeRef == null ? ObjectId.NULL : leftTreeRef.objectId();
    final ObjectId rightTreeId = rightTreeRef == null ? ObjectId.NULL : rightTreeRef.objectId();

    Supplier<Iterator<DiffEntry>> diffs = command(DiffTree.class).setRecursive(false).setReportTrees(false)
            .setOldTree(leftTreeId).setNewTree(rightTreeId).setFilter(strippedPathFilters);

    // move new blobs from the index to the repository (note: this could be parallelized)
    Supplier<Iterator<Node>> nodesToMove = asNodeSupplierOfNewContents(diffs, strippedPathFilters);
    command(DeepMove.class).setObjects(nodesToMove).call();

    final StagingDatabase stagingDatabase = getIndex().getDatabase();

    final RevTree currentLeftTree = leftTreeId.isNull() ? RevTree.EMPTY : stagingDatabase.getTree(leftTreeId);

    final RevTreeBuilder builder = currentLeftTree.builder(repositoryDatabase);

    Iterator<DiffEntry> iterator = diffs.get();
    if (!strippedPathFilters.isEmpty()) {
        final Set<String> expected = Sets.newHashSet(strippedPathFilters);
        iterator = Iterators.filter(iterator, new Predicate<DiffEntry>() {
            @Override/*  www  .  jav  a2 s. c o m*/
            public boolean apply(DiffEntry input) {
                boolean applies;
                if (input.isDelete()) {
                    applies = expected.contains(input.oldName());
                } else {
                    applies = expected.contains(input.newName());
                }
                return applies;
            }
        });
    }

    for (; iterator.hasNext();) {
        final DiffEntry diff = iterator.next();
        if (diff.isDelete()) {
            builder.remove(diff.oldName());
        } else {
            NodeRef newObject = diff.getNewObject();
            Node node = newObject.getNode();
            builder.put(node);
        }
    }

    final RevTree newTree = builder.build();
    repositoryDatabase.put(newTree);
    return newTree;
}

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

/**
 * Add a {@link IndirectlyCollapsedFilter} to the children of CollapsedNode
 * (to retrieve the same behavior as before). The migration of GMF bounds of
 * this indirectly collapsed nodes, if they are bordered nodes, are deal
 * later in method {{@link #migrateGMFBoundsOfBorderedNodes(List)}.
 * //w  ww.  j av a2 s  . c  o m
 * @param diagram
 *            GMF Diagram to migrate.
 */
private void migrateChildrenOfCollapsedNode(Diagram diagram) {
    List<DDiagramElement> indirectlyCollaspedDDEs = Lists.newArrayList();
    Iterator<Node> viewIterator = Iterators.filter(Iterators.filter(diagram.eAllContents(), Node.class),
            isDirectlyCollapsedNode);
    while (viewIterator.hasNext()) {
        final Node node = viewIterator.next();
        if (node.getElement() instanceof AbstractDNode) {
            AbstractDNode abstractDNode = (AbstractDNode) node.getElement();
            indirectlyCollaspedDDEs.addAll(abstractDNode.getOwnedBorderedNodes());
            if (abstractDNode instanceof DNodeContainer) {
                DNodeContainer dDiagramElementContainer = (DNodeContainer) abstractDNode;
                indirectlyCollaspedDDEs.addAll(dDiagramElementContainer.getOwnedDiagramElements());
            } else if (abstractDNode instanceof DNodeList) {
                DNodeList dNodeList = (DNodeList) abstractDNode;
                indirectlyCollaspedDDEs.addAll(dNodeList.getOwnedElements());
            }
        }
    }
    for (DDiagramElement indirectlyCollaspedDDE : indirectlyCollaspedDDEs) {
        if (!Iterables.any(indirectlyCollaspedDDE.getGraphicalFilters(),
                Predicates.instanceOf(IndirectlyCollapseFilter.class))) {
            IndirectlyCollapseFilter indirectlyCollapseFilter = DiagramFactory.eINSTANCE
                    .createIndirectlyCollapseFilter();
            indirectlyCollaspedDDE.getGraphicalFilters().add(indirectlyCollapseFilter);
        }
    }
}

From source file:org.apache.jackrabbit.oak.spi.security.authentication.external.impl.jmx.Delegatee.java

@Nonnull
private Iterator<String> internalListOrphanedIdentities() {
    try {//from   ww w.  ja  v  a  2s. c om
        Iterator<SyncedIdentity> it = handler.listIdentities(userMgr);
        return Iterators.filter(Iterators.transform(it, new Function<SyncedIdentity, String>() {
            @Nullable
            @Override
            public String apply(@Nullable SyncedIdentity syncedIdentity) {
                if (syncedIdentity != null && isMyIDP(syncedIdentity)) {
                    ExternalIdentityRef ref = syncedIdentity.getExternalIdRef();
                    try {
                        ExternalIdentity extId = (ref == null) ? null : idp.getIdentity(ref);
                        if (extId == null) {
                            return syncedIdentity.getId();
                        }
                    } catch (ExternalIdentityException e) {
                        log.error("Error while fetching external identity {}", syncedIdentity, e);
                    }
                }
                return null;
            }
        }), Predicates.notNull());
    } catch (RepositoryException e) {
        log.error("Error while listing orphaned users", e);
        return Iterators.emptyIterator();
    }
}

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

private void updatePrimaryWellConcentration(Plate plate) {
    Map<String, Object> properties = Maps.newHashMap();
    properties.put("plateNumber", plate.getPlateNumber());
    properties.put("libraryWellType", LibraryWellType.EXPERIMENTAL);
    List<Well> wells = _dao.findEntitiesByProperties(Well.class, properties);
    ConcentrationStatistics concentrationStatistics = plate.getConcentrationStatistics();
    for (Well well : wells) {
        if (well.getMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
        }//ww  w  .  j  a va 2 s. c o m
        if (well.getMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
        }
    }

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

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

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

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

From source file:org.eclipse.sirius.business.api.control.SiriusControlCommand.java

/**
 * Update the models references of all representations files of this
 * session.//from  w  ww  .  j ava2  s .  co m
 * 
 * @param analysisToIgnore
 *            The models references of this DAnalysis will not be updated.
 */
private void updateModelsReferences(DAnalysis analysisToIgnore) {
    for (Resource resource : ((DAnalysisSession) session).getAllSessionResources()) {
        for (EObject content : resource.getContents()) {
            if (content instanceof DAnalysis && !content.equals(analysisToIgnore)) {
                for (final DView view : ((DAnalysis) content).getOwnedViews()) {
                    DAnalysisSessionHelper.updateModelsReferences((DAnalysis) content,
                            Iterators.filter(view.eAllContents(), DSemanticDecorator.class));
                }
            }
        }
    }
}

From source file:org.eclipse.emf.ecoretools.design.service.DesignServices.java

private List<EObject> allValidSessionElements(EObject cur, Predicate<EObject> validForClassDiagram) {
    Session found = SessionManager.INSTANCE.getSession(cur);
    List<EObject> result = Lists.newArrayList();
    if (found != null) {
        for (Resource res : found.getSemanticResources()) {
            if (res.getURI().isPlatformResource() || res.getURI().isPlatformPlugin()) {
                Iterators.addAll(result, Iterators.filter(res.getAllContents(), validForClassDiagram));
            }/*  www  .  ja  va  2  s  . c  o m*/
        }
    }
    return result;
}

From source file:org.eclipse.sirius.editor.tree.tools.internal.menu.TreeWizardMenuBuilder.java

private Option<OperationAction> getAlreadyExistingMenuItem(EClass leaf, String referenceName) {
    OperationAction found = null;//www  .ja  va2  s.  c  o m
    Iterator<OperationAction> it = doneItems.get(leaf).iterator();
    while (it.hasNext() && found == null) {
        OperationAction cur = it.next();
        Iterator<CreateInstance> itNewInstance = Iterators.filter(cur.eAllContents(), CreateInstance.class);
        while (itNewInstance.hasNext()) {
            CreateInstance newInstance = itNewInstance.next();
            if (referenceName.equals(newInstance.getReferenceName())) {
                found = cur;
            }
        }
    }
    return Options.newSome(found);
}

From source file:org.apache.marmotta.commons.sesame.repository.ResourceUtils.java

/**
 * List resources with the given prefix/*from   w ww .  j ava 2  s .  c  o m*/
 *
 * @param prefix the prefix
 * @param offset
 * @param limit
 */
public static Iterable<URI> listResourcesByPrefix(final RepositoryConnection con, final String prefix,
        final int offset, final int limit) {
    final ResourceConnection rcon = getWrappedResourceConnection(con);

    if (rcon != null) {
        return new Iterable<URI>() {
            @Override
            public Iterator<URI> iterator() {
                try {
                    Iterator<URI> result = ResultUtils.unwrap(rcon.getResources(prefix));

                    Iterators.advance(result, offset);

                    if (limit > 0) {
                        return Iterators.limit(result, limit);
                    } else {
                        return result;
                    }
                } catch (RepositoryException e) {
                    ExceptionUtils.handleRepositoryException(e, ResourceUtils.class);
                    return Iterators.emptyIterator();
                }

            }
        };
    } else {
        // no direct prefix listing support, need to filter the listResources result
        return new Iterable<URI>() {
            @Override
            public Iterator<URI> iterator() {
                Iterator<URI> result = Iterators
                        .transform(Iterators.filter(listResources(con).iterator(), new Predicate<Resource>() {
                            @Override
                            public boolean apply(Resource input) {
                                return input instanceof URI && input.stringValue().startsWith(prefix);
                            }
                        }), new Function<Resource, URI>() {
                            @Override
                            public URI apply(Resource input) {
                                return (URI) input;
                            }
                        });

                Iterators.advance(result, offset);

                if (limit > 0) {
                    return Iterators.limit(result, limit);
                } else {
                    return result;
                }
            }
        };
    }
}

From source file:info.magnolia.ui.form.field.MultiField.java

/**
 * Takes care of moving a field up or down. Tries hard not to assume much about the layout, so we're iterating over parents
 * and component types to make sure we're dealing with Fields.
 *///from  w  ww . j a  va  2  s.  c  om
private void onMove(Component layout, Property<?> propertyReference, boolean moveUp) {
    int currentPosition = root.getComponentIndex(layout);
    int switchPosition = currentPosition + (moveUp ? -1 : 1);

    Field[] fields = Iterators
            .toArray(Iterators.filter(Iterators.transform(root.iterator(), new Function<Component, Field>() {
                @Nullable
                @Override
                public Field apply(Component input) {
                    if (input instanceof HasComponents) {
                        Optional<Component> field = Iterators.tryFind(((HasComponents) input).iterator(),
                                Predicates.instanceOf(Field.class));
                        if (field.isPresent()) {
                            return (Field) field.get();
                        }
                    }
                    return null;
                }
            }), Predicates.notNull()), Field.class);

    if (moveUp && currentPosition != 0 || (!moveUp && currentPosition != fields.length - 1)) {

        Field switchField = fields[switchPosition];
        Object currentPropertyId = MultiField.this.findPropertyId(getValue(), propertyReference);
        Object switchPropertyId = MultiField.this.findPropertyId(getValue(),
                switchField.getPropertyDataSource());

        root.replaceComponent(root.getComponent(currentPosition), root.getComponent(switchPosition));
        switchItemProperties(currentPropertyId, switchPropertyId);
    }
}