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

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

Introduction

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

Prototype

@Nullable
public static <T> T find(Iterator<? extends T> iterator, Predicate<? super T> predicate,
        @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterator that satisfies the given predicate.

Usage

From source file:org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.EdgeChangeItemProviderSpec.java

/**
 * {@inheritDoc}/*from  ww  w .  j a  v  a 2  s.co  m*/
 * 
 * @see org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.ForwardingDiagramDiffItemProvider#getReferenceText(org.eclipse.emf.compare.diagram.internal.extensions.DiagramDiff)
 */
@Override
protected String getReferenceText(DiagramDiff diagramDiff) {
    String result = ""; //$NON-NLS-1$
    Diff diff = null;
    DifferenceKind kind = diagramDiff.getKind();
    switch (kind) {
    case ADD:
    case DELETE:
        diff = Iterators.find(diagramDiff.getRefinedBy().iterator(),
                EdgeChangeFactory.isMainDiffForAddOrDeleteEdge(), null);
        break;
    case CHANGE:
        result = "look"; //$NON-NLS-1$
        break;
    default:
    }
    if (diff instanceof ReferenceChange) {
        result = ((ReferenceChange) diff).getReference().getName();
    }
    return result;
}

From source file:org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.NodeChangeItemProviderSpec.java

/**
 * {@inheritDoc}//from   w  w w  .j av  a 2s  .  com
 * 
 * @see org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.ForwardingDiagramDiffItemProvider#getReferenceText(org.eclipse.emf.compare.diagram.internal.extensions.DiagramDiff)
 */
@Override
protected String getReferenceText(DiagramDiff diagramDiff) {
    String result = ""; //$NON-NLS-1$
    Diff diff = null;
    DifferenceKind kind = diagramDiff.getKind();
    switch (kind) {
    case ADD:
    case DELETE:
        diff = Iterators.find(diagramDiff.getRefinedBy().iterator(),
                NodeChangeFactory.isMainDiffForAddOrDeleteNode(), null);
        break;
    case MOVE:
        diff = Iterators.find(diagramDiff.getRefinedBy().iterator(), NodeChangeFactory.isMainDiffForMoveNode(),
                null);
        break;
    default:
    }
    if (diff instanceof ReferenceChange) {
        result = ((ReferenceChange) diff).getReference().getName();
    }
    return result;

}

From source file:org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.DiagramChangeItemProviderSpec.java

/**
 * {@inheritDoc}// ww w .j a  v  a2  s  .c o m
 * 
 * @see org.eclipse.emf.compare.diagram.internal.extensions.provider.spec.ForwardingDiagramDiffItemProvider#getReferenceText(org.eclipse.emf.compare.diagram.internal.extensions.DiagramDiff)
 */
@Override
protected String getReferenceText(DiagramDiff diagramDiff) {
    String result = ""; //$NON-NLS-1$
    Diff diff = null;
    DifferenceKind kind = diagramDiff.getKind();
    switch (kind) {
    case ADD:
    case DELETE:
        diff = Iterators.find(diagramDiff.getRefinedBy().iterator(),
                DiagramChangeFactory.isMainDiffForAddOrDeleteDiagram(), null);
        break;
    default:
    }
    if (diff instanceof ResourceAttachmentChange) {
        result = "contents";
    }
    return result;

}

From source file:com.addthis.bundle.core.BundleMapView.java

@Nullable
@Override//from w  ww .  j av  a 2  s .  c  o  m
public ValueObject remove(Object key) {
    ValueObject previousValue = get(key);
    if (key instanceof BundleField) {
        bundle.removeValue((BundleField) key);
    } else {
        BundleField equivalentField = Iterators.find(bundle.iterator(), equalTo(key), null);
        if (equivalentField != null) {
            bundle.removeValue(equivalentField);
        }
    }
    return previousValue;
}

From source file:org.eclipse.emf.compare.internal.postprocessor.factories.AbstractChangeFactory.java

/**
 * {@inheritDoc}//w w w  .  j a  v a2 s  . c o  m
 * 
 * @see org.eclipse.emf.compare.internal.postprocessor.factories.IChangeFactory#create(org.eclipse.emf.compare.Diff)
 */
public Diff create(Diff input) {
    Diff ret = createExtension();

    final DifferenceKind extensionKind = getRelatedExtensionKind(input);
    ret.setKind(extensionKind);
    // It's important to set the source before calling setRefiningChanges()
    // because refines/refinedBy EReferences demand diffs on the same side
    ret.setSource(input.getSource());

    setRefiningChanges(ret, extensionKind, input);

    // FIXME: Maybe it would be better to get all conflict objects from all conflicting unit differences
    // and
    // create a new conflict object with these differences, to set on the macroscopic change (ret).
    Diff conflictingDiff = Iterators.find(ret.getRefinedBy().iterator(), new Predicate<Diff>() {
        public boolean apply(Diff difference) {
            return difference.getConflict() != null;
        }
    }, null);
    if (conflictingDiff != null) {
        ret.setConflict(conflictingDiff.getConflict());
    }

    return ret;
}

From source file:org.eclipse.incquery.patternlanguage.emf.ui.quickfix.EMFPatternLanguageQuickfixProvider.java

@Fix(EMFIssueCodes.MISSING_PACKAGE_IMPORT)
public void addMissingPackageImport(final Issue issue, IssueResolutionAcceptor acceptor) {

    acceptor.accept(issue, "Add missing import", "Add missing import", null, new IModification() {

        @Override/*from ww  w. j  a v a2  s.com*/
        public void apply(IModificationContext context) throws BadLocationException {
            final IXtextDocument document = context.getXtextDocument();
            Integer offset = document.readOnly(new IUnitOfWork<Integer, XtextResource>() {

                @Override
                public Integer exec(XtextResource state) {
                    final XImportSection importSection = (XImportSection) Iterators.find(state.getAllContents(),
                            Predicates.instanceOf(XImportSection.class), null);
                    final ICompositeNode node = NodeModelUtils.getNode(importSection);

                    return Integer.valueOf(node.getTotalEndOffset());
                }
            });
            if (offset != null) {
                StringBuilder sb = new StringBuilder();
                sb.append("\n");
                sb.append("import \"");
                sb.append(issue.getData()[0]);
                sb.append("\"");
                document.replace(offset, 0, sb.toString());
            }
        }
    });
}

From source file:com.github.jonross.seq4j.Seq.java

/**
 * Uses {@link Iterators#find}; returns the first element in the sequence that
 * satisfies a predicate, as an {@link Optional<T>}, which contains either the
 * found element or <code>null</code> if not fo und.
 */// w  ww.ja va  2 s. c  o  m

public Optional<T> find(Predicate<? super T> p) {
    return Optional.fromNullable(Iterators.find(this, p, null));
}

From source file:org.polarsys.reqcycle.repository.connector.rmf.ui.RMFRepositoryMappingPage.java

protected void generateMapping() {
    if (getSourceInput() instanceof Collection<?> && getTargetInput() instanceof Collection<?>) {
        for (Object inputElement : (Collection<?>) getSourceInput()) {
            if (inputElement instanceof SpecType) {
                final String inputName = ((SpecType) inputElement).getLongName();

                IRequirementType element = Iterators.find(((Collection) getTargetInput()).iterator(),
                        new Predicate<IRequirementType>() {

                            @Override
                            public boolean apply(IRequirementType arg0) {
                                String ii = inputName;
                                return ii.equalsIgnoreCase(arg0.getName());
                            }/*from  w  w w .j  a v a 2  s.co  m*/
                        }, null);
                if (element != null) {
                    MappingElement elementMapping = MappingModelFactory.eINSTANCE.createMappingElement();
                    Collection<IAttribute> allAttributes = element.getAttributes();
                    Collection<IAttribute> filtered = Collections2.filter(allAttributes,
                            new Predicate<IAttribute>() {

                                @Override
                                public boolean apply(IAttribute arg0) {
                                    if (arg0 instanceof IAttribute) {
                                        return !arg0.isHidden();
                                    }
                                    return false;
                                }
                            });
                    elementMapping.getAttributes()
                            .addAll(mapAttributes(((SpecType) inputElement).getSpecAttributes(), filtered));
                    elementMapping.setSourceQualifier(((SpecType) inputElement).getIdentifier());
                    elementMapping.setDescription(((SpecType) inputElement).getLongName());
                    elementMapping.setTargetElement((EClass) element);
                    if (mappingComposite != null) {
                        mappingComposite.addToResult(elementMapping);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.ui.quickfix.EMFPatternLanguageQuickfixProvider.java

@Fix(IssueCodes.MISSING_PACKAGE_IMPORT)
public void addMissingPackageImport(final Issue issue, IssueResolutionAcceptor acceptor) {

    acceptor.accept(issue, "Add missing import", "Add missing import", null, (IModification) context -> {
        final IXtextDocument document = context.getXtextDocument();
        Integer offset = document.readOnly(state -> {
            final VQLImportSection importSection = (VQLImportSection) Iterators.find(state.getAllContents(),
                    Predicates.instanceOf(VQLImportSection.class), null);
            final ICompositeNode node = NodeModelUtils.getNode(importSection);

            return Integer.valueOf(node.getTotalEndOffset());
        });//from  w w w  .j  a v a 2 s.  c o m
        if (offset != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n");
            sb.append("import \"");
            sb.append(issue.getData()[0]);
            sb.append("\"");
            document.replace(offset, 0, sb.toString());
        }
    });
}

From source file:org.opendaylight.tsdr.datastorage.TSDRStorageServiceImpl.java

@Override
public Future<RpcResult<GetTSDRAggregatedMetricsOutput>> getTSDRAggregatedMetrics(
        final GetTSDRAggregatedMetricsInput input) {

    if (this.metricPersistenceService == null) {
        RpcResultBuilder<GetTSDRAggregatedMetricsOutput> builder = RpcResultBuilder.failed();
        return builder.buildFuture();
    }//from  w w w .jav  a  2  s .  co  m

    // Locate the appropriate aggregation function implementation
    final AggregationFunction aggregationFunction = Iterators.find(aggregationFunctions.iterator(),
            new Predicate<AggregationFunction>() {
                @Override
                public boolean apply(AggregationFunction candidate) {
                    return candidate.getType().equals(input.getAggregation());
                }
            }, null);
    if (aggregationFunction == null) {
        return RpcResultBuilder.<GetTSDRAggregatedMetricsOutput>failed()
                .withError(ErrorType.APPLICATION, String.format(
                        "No aggregation function implementation was found for '%s'.", input.getAggregation()))
                .buildFuture();
    }

    // Gather the metrics for the given time span
    final GetTSDRMetricsInput metricsInput = new GetTSDRMetricsInputBuilder()
            .setTSDRDataCategory(input.getTSDRDataCategory()).setStartTime(input.getStartTime())
            .setEndTime(input.getEndTime()).build();
    final Future<RpcResult<GetTSDRMetricsOutput>> result = getTSDRMetrics(metricsInput);

    //Fix for bug 5655 - Do not aggregate when # of points is less than requested
    long numberOfPoints = (input.getEndTime() - input.getStartTime()) / input.getInterval();
    try {
        //In case of a MEAN aggregation and the number of requested points is larger than what is, just return the original
        //result.
        if (input.getAggregation() == AggregationType.MEAN
                && result.get().getResult().getMetrics().size() <= numberOfPoints) {
            final List<AggregatedMetrics> aggregatedMetrics = Lists.newLinkedList();
            for (Metrics m : result.get().getResult().getMetrics()) {
                // Aggregate the metrics in the interval
                aggregatedMetrics.add(new AggregatedMetricsBuilder().setTimeStamp(m.getTimeStamp())
                        .setMetricValue(m.getMetricValue()).build());
            }
            // We're done
            final GetTSDRAggregatedMetricsOutputBuilder outputBuilder = new GetTSDRAggregatedMetricsOutputBuilder()
                    .setAggregatedMetrics(aggregatedMetrics);
            return RpcResultBuilder.success(outputBuilder).buildFuture();

        }
    } catch (InterruptedException | ExecutionException e) {
        RpcResultBuilder builder = RpcResultBuilder.failed();
        builder.withError(ErrorType.APPLICATION, "Failed to extract data for aggregation");
        return builder.buildFuture();
    }

    // Aggregate the results
    return Futures.lazyTransform(result,
            new Function<RpcResult<GetTSDRMetricsOutput>, RpcResult<GetTSDRAggregatedMetricsOutput>>() {
                @Override
                public RpcResult<GetTSDRAggregatedMetricsOutput> apply(
                        RpcResult<GetTSDRMetricsOutput> metricsOutput) {
                    final List<AggregatedMetrics> aggregatedMetrics = Lists.newLinkedList();
                    final PeekingIterator<Metrics> metricIterator = Iterators
                            .peekingIterator(metricsOutput.getResult().getMetrics().iterator());
                    // Generate and iterate over all the intervals in the given range
                    for (Long intervalStartInclusive : new IntervalGenerator(input.getStartTime(),
                            input.getEndTime(), input.getInterval())) {
                        final Long intervalEndExclusive = intervalStartInclusive + input.getInterval();

                        // Gather the list of metrics that fall within the current interval
                        // We make the assumption that the list of metrics is already sorted by time-stamp
                        final List<Metrics> metricsInInterval = Lists.newLinkedList();
                        while (metricIterator.hasNext()) {
                            if (metricIterator.peek().getTimeStamp() >= intervalEndExclusive) {
                                break;
                            }
                            metricsInInterval.add(metricIterator.next());
                        }

                        // Aggregate the metrics in the interval
                        aggregatedMetrics.add(new AggregatedMetricsBuilder()
                                .setTimeStamp(intervalStartInclusive)
                                .setMetricValue(aggregationFunction.aggregate(metricsInInterval)).build());
                    }

                    // We're done
                    final GetTSDRAggregatedMetricsOutput output = new GetTSDRAggregatedMetricsOutputBuilder()
                            .setAggregatedMetrics(aggregatedMetrics).build();
                    return RpcResultBuilder.success(output).build();
                }
            });
}