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.diagram.ui.business.internal.migration.DiagramRepresentationsFileMigrationParticipantV650.java

/**
 * In case of resizeKind == NONE and that DNode.width/height is different
 * this of the GMF Node, before the fix changing the resizeKind to something
 * different of NONE has the effect to resize the bounds of concerned
 * figures to the DNode.width/height and not the GMF Node bounds.
 * /*  w w  w  .  j  a  v  a 2s.  com*/
 * @param view
 *            The view to migrate.
 */
private void migrationForGMFViewSizeForDNodeNotResizable(final DView view) {
    Iterator<EObject> viewIterator = Iterators.filter(view.eAllContents(),
            nonResizableNodeWithDifferentSizePredicate);
    while (viewIterator.hasNext()) {
        final EObject next = viewIterator.next();
        if (next instanceof Node) {
            Node node = (Node) next;
            DNode dNode = (DNode) node.getElement();
            Size size = (Size) node.getLayoutConstraint();
            Dimension dNodeSize = new DNodeQuery(dNode).getDefaultDimension();
            size.setWidth(dNodeSize.width);
            size.setHeight(dNodeSize.height);
        }
    }
}

From source file:org.eclipse.emf.compare.diagram.sirius.internal.SiriusDiffPostProcessor.java

/**
 * {@inheritDoc}/*from  www  .  jav  a 2  s  .  c  o m*/
 */
public void postComparison(Comparison comparison, Monitor monitor) {
    /*
     * We re-refine the refinements already setup by
     * org.eclipse.emf.compare.diagram.internal.CompareDiagramPostProcessor
     */
    Iterator<DiagramDiff> it = Iterators.filter(comparison.eAllContents(), DiagramDiff.class);
    while (it.hasNext()) {
        DiagramDiff next = it.next();
        Set<Diff> refinesToAdd = Sets.newLinkedHashSet();
        for (Diff refined : next.getRefinedBy()) {
            collectDifferenceRefines(comparison, refinesToAdd, refined.getMatch().getLeft());
            collectDifferenceRefines(comparison, refinesToAdd, refined.getMatch().getRight());
        }
        next.getRefinedBy().addAll(filter(refinesToAdd, fromSide(next.getSource())));
    }
}

From source file:org.obeonetwork.dsl.uml2.core.internal.services.NodeInverseRefsServices.java

/**
 * Retrieve the cross references of the given type of all the UML elements displayed as node in a Diagram.
 * Note that a Property cross reference will lead to retrieve the cross references of this property.
 *
 * @param diagram/* w  w  w  .  ja v a 2  s  .  c  om*/
 *            a diagram.
 * @param typeName
 *            the expected type.
 * @return the list of cross reference of the given
 */
@SuppressWarnings("unchecked")
public Collection<EObject> getNodeInverseRefs(DDiagram diagram, String typeName) {
    final Set<EObject> result = Sets.newLinkedHashSet();
    if (diagram instanceof DSemanticDecorator) {
        final Session sess = SessionManager.INSTANCE.getSession(((DSemanticDecorator) diagram).getTarget());

        final Iterator<EObject> it = Iterators.transform(
                Iterators.filter(diagram.eAllContents(), AbstractDNode.class),
                new Function<AbstractDNode, EObject>() {

                    public EObject apply(AbstractDNode input) {
                        return input.getTarget();
                    }
                });
        while (it.hasNext()) {
            final EObject displayedAsANode = it.next();
            if (displayedAsANode != null) {
                for (final Setting xRef : sess.getSemanticCrossReferencer()
                        .getInverseReferences(displayedAsANode)) {
                    final EObject eObject = xRef.getEObject();

                    if (xRef instanceof DerivedUnionEObjectEList) {
                        for (final EObject eObject2 : (List<EObject>) xRef) {
                            if (sess.getModelAccessor().eInstanceOf(eObject2, typeName)) {
                                result.add(eObject2);
                            }
                        }
                    }
                    if (sess.getModelAccessor().eInstanceOf(eObject, typeName)) {
                        result.add(eObject);
                    }
                    /*
                     * In the case of an association the real interesting object is the association linked
                     * to the Property and not the direct cross reference.
                     */
                    if (eObject instanceof Property) {
                        if (((Property) eObject).getAssociation() != null) {
                            if (sess.getModelAccessor().eInstanceOf(((Property) eObject).getAssociation(),
                                    typeName)) {
                                result.add(((Property) eObject).getAssociation());
                            }
                        }
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.eclipse.xtext.ui.editor.validation.AnnotationIssueProcessor.java

protected void updateMarkerAnnotations(IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return;/*from  ww  w  .  j av a 2 s .  com*/
    }

    Iterator<MarkerAnnotation> annotationIterator = Iterators.filter(annotationModel.getAnnotationIterator(),
            MarkerAnnotation.class);

    // every markerAnnotation produced by fast validation can be marked as deleted.
    // If its predicate still holds, the validation annotation will be covered anyway.
    while (annotationIterator.hasNext() && !monitor.isCanceled()) {
        final MarkerAnnotation annotation = annotationIterator.next();
        if (!annotation.isMarkedDeleted())
            try {
                if (isRelevantAnnotationType(annotation.getType())) {
                    boolean markAsDeleted = annotation.getMarker().isSubtypeOf(MarkerTypes.FAST_VALIDATION);
                    if (markAsDeleted) {
                        annotation.markDeleted(true);
                        queueOrFireAnnotationChangedEvent(annotation);
                    }
                }
            } catch (CoreException e) {
                // marker type cannot be resolved - keep state of annotation
            }
    }
    fireQueuedEvents();
}

From source file:org.eclipse.viatra.query.tooling.ui.queryexplorer.adapters.EMFModelConnector.java

protected Collection<EObject> getSelectedEObjects(ISelection selection) {
    if (selection instanceof IStructuredSelection) {
        Iterator<EObject> selectionIterator = Iterators.filter((((IStructuredSelection) selection).iterator()),
                EObject.class);
        return Lists.newArrayList(selectionIterator);
    } else {//w w w .  j a  va  2s.  c o  m
        return Collections.emptyList();
    }
}

From source file:org.openengsb.ui.admin.edb.EdbClient.java

public EdbClient() {
    Form<Object> form = new Form<Object>("form");
    final DropDownChoice<Class<? extends OpenEngSBModel>> modelSelector = new DropDownChoice<Class<? extends OpenEngSBModel>>(
            "modelSelector", new Model<Class<? extends OpenEngSBModel>>(), new DomainModelListModel());
    modelSelector.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        private static final long serialVersionUID = -1516333824153580148L;

        @Override/*from w ww .  j  a v a  2 s . co m*/
        protected void onUpdate(AjaxRequestTarget target) {
            Class<? extends OpenEngSBModel> convertedInput = modelSelector.getConvertedInput();
            queryModel.getObject().setModel(convertedInput);
            queryField.setEnabled(convertedInput != null);
            target.add(queryField);
        }
    });
    modelSelector.setChoiceRenderer(new IChoiceRenderer<Class<?>>() {
        private static final long serialVersionUID = 805430071751617166L;

        @Override
        public Object getDisplayValue(Class<?> object) {
            return object.getSimpleName();
        }

        @Override
        public String getIdValue(Class<?> object, int index) {
            return object.getSimpleName();
        }

    });
    form.add(modelSelector);
    queryField = new AutoCompleteTextField<String>("query") {
        private static final long serialVersionUID = 5028249986331789802L;

        @Override
        protected Iterator<String> getChoices(final String input) {
            Class<? extends OpenEngSBModel> model = queryModel.getObject().getModel();
            BeanInfo beanInfo;
            try {
                beanInfo = Introspector.getBeanInfo(model);
            } catch (IntrospectionException e) {
                LOGGER.warn("error introspecting {}. Auto-completing won't work." + model);
                List<String> emptyList = Collections.emptyList();
                return emptyList.iterator();
            }
            List<String> allKeys = Lists.transform(Arrays.asList(beanInfo.getPropertyDescriptors()),
                    new Function<PropertyDescriptor, String>() {
                        @Override
                        public String apply(PropertyDescriptor input) {
                            return input.getName() + ":";
                        }
                    });
            if (Strings.isNullOrEmpty(input)) {
                return allKeys.iterator();
            }
            return Iterators.filter(allKeys.iterator(), new Predicate<String>() {
                @Override
                public boolean apply(String item) {
                    return item.contains(input);
                }
            });
        }

    };
    queryField.setEnabled(false);
    queryField.setOutputMarkupId(true);
    queryField.setModel(new PropertyModel<String>(queryModel.getObject(), "query"));
    form.add(queryField);

    form.add(new IndicatingAjaxButton("submit") {
        private static final long serialVersionUID = -5425144434508998591L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            EkbQuery query = queryModel.getObject();
            List<? extends OpenEngSBModel> models;
            try {
                models = ekbQueryInterface.queryForModels(query.getModel(), query.getQuery());
                resultModel.setObject(models);
                info(String.format("Found %s results", models.size()));
            } catch (Exception e) {
                error(String.format("Error when querying for models %s (%s)", e.getMessage(),
                        e.getClass().getName()));
            }
            target.add(feedback);
            target.add(resultContainer);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
        }
    });
    add(form);
    List<? extends OpenEngSBModel> emptyList = Collections.emptyList();
    resultModel = Model.ofList(emptyList);
    resultContainer = new WebMarkupContainer("result");
    resultContainer.setOutputMarkupId(true);
    add(resultContainer);
    resultContainer.add(new ListView<OpenEngSBModel>("list", resultModel) {
        private static final long serialVersionUID = 5459114215962851286L;

        @Override
        protected void populateItem(ListItem<OpenEngSBModel> item) {
            String idProperty = "id";
            Class<? extends OpenEngSBModel> modelClass = queryModel.getObject().getModel();
            for (Field m : modelClass.getDeclaredFields()) {
                if (m.getAnnotation(OpenEngSBModelId.class) != null) {
                    idProperty = m.getName();
                    break;
                }
            }
            AjaxLink<String> historyLink = new AjaxLink<String>("id",
                    new PropertyModel<String>(item.getModelObject(), idProperty)) {
                private static final long serialVersionUID = -6539033599615376277L;

                @Override
                public void onClick(AjaxRequestTarget target) {
                    this.setResponsePage(new EdbHistoryPanel(getModel().getObject()));
                }
            };
            historyLink.add(new Label("text", new PropertyModel<String>(item.getModelObject(), idProperty)));
            item.add(historyLink);
            MultiLineLabel multiLineLabel = new MultiLineLabel("entries",
                    item.getModelObject().toOpenEngSBModelEntries().toString());
            item.add(multiLineLabel);
        }
    });
    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    form.add(feedback);
}

From source file:com.google.enterprise.connector.otex.LivelinkAuthorizationManager.java

/**
 * Adds an <code>AuthorizationResponse</code> instance to the
 * collection for each authorized document from the list.
 * These doc IDs come from the GSA, so we filter them to just
 * the integers to avoid SQL injection.//from w ww  . ja  v  a 2  s . c o  m
 *
 * @param iterator Iterator over the list of doc IDs
 * @param username the username for which to check authorization
 * @param authorized the collection to add authorized doc IDs to
 * @throws RepositoryException if an error occurs
 */
private void addAuthorizedDocids(Collection<String> docids, String username,
        Collection<AuthorizationResponse> authorized) throws RepositoryException {
    addAuthorizedDocids(Iterators.filter(docids.iterator(), INTEGER_PREDICATE), username, authorized,
            new AuthzCreator());
}

From source file:name.marmar.gf.greplog.GrepLogCommand.java

private GrepResult grep(File f, Predicate<LogRecord> predicate) throws IOException {
    GrepResult result = new GrepResult(limit);
    InputStream is = null;/*from  ww w  .j  a  v a2 s  .  com*/
    try {
        is = new FileInputStream(f);
        UnmodifiableIterator<LogRecord> iter = Iterators.filter(new LogStreamIterator(is), predicate);
        while (iter.hasNext()) {
            result.add(iter.next().getFullMessage());
        }
    } finally {
        try {
            is.close();
        } catch (Exception exc) {
        }
    }
    return result;
}

From source file:com.temenos.interaction.rimdsl.visualisation.providers.ResourceInteractionContentProvider.java

/**
 * Used internally to build up all transitions and caches. 
 * Must be called after the visualisation options have been changed
 *//*w w  w . j  a va2 s  .c  o  m*/
private void rebuildTransitions() {
    states.clear();
    transitions.clear();

    if (input != null) {
        // Some temporary buffers
        Set<State> allStates = new HashSet<State>();
        Map<State, Set<TransitionDescription>> incomingTransitions = new HashMap<State, Set<TransitionDescription>>();
        Map<State, Set<TransitionDescription>> outgoingTransitions = new HashMap<State, Set<TransitionDescription>>();

        if (input instanceof State) {
            State state = (State) input;

            // Iterate over all elements in model
            Iterator<EObject> iter = state.eResource().getAllContents();
            while (iter.hasNext()) {
                EObject rootContent = iter.next();
                if (rootContent instanceof DomainModel) {
                    DomainModel model = (DomainModel) rootContent;
                    Iterator<ResourceInteractionModel> rims = Iterators.filter(model.eAllContents(),
                            ResourceInteractionModel.class);
                    while (rims.hasNext()) {
                        ResourceInteractionModel rim = rims.next();
                        processRIM(rim, allStates, incomingTransitions, outgoingTransitions);
                    }
                }
            }

            // Then build the visual representation of the part of 
            // the network that is to be shown
            if (showIncomingRelations) {
                retrieveStatesTransitions(state, incomingTransitions, true);
            }

            if (showOutgoingRelations) {
                retrieveStatesTransitions(state, outgoingTransitions, false);
            }
        }
    }
}

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

/**
 * Get all parent for children cuboids, considering dim cap.
 * @param children children cuboids//from w w  w  . j a v  a2 s.c  o m
 * @return all parents cuboids
 */
private Set<Long> getOnTreeParentsByLayer(Collection<Long> children) {
    Set<Long> parents = new HashSet<>();
    for (long child : children) {
        parents.addAll(getOnTreeParents(child));
    }
    parents = Sets.newHashSet(Iterators.filter(parents.iterator(), new Predicate<Long>() {
        @Override
        public boolean apply(@Nullable Long cuboidId) {
            if (cuboidId == Cuboid.getBaseCuboidId(cubeDesc)) {
                return true;
            }

            for (AggregationGroup agg : cubeDesc.getAggregationGroups()) {
                if (agg.isOnTree(cuboidId) && agg.checkDimCap(cuboidId)) {
                    return true;
                }
            }

            return false;
        }
    }));
    return parents;
}