Example usage for com.google.common.collect Iterables any

List of usage examples for com.google.common.collect Iterables any

Introduction

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

Prototype

public static <T> boolean any(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns true if any element in iterable satisfies the predicate.

Usage

From source file:com.gnapse.metric.Quantity.java

private static void checkAdditiveQuantities(Iterable<Quantity> quantities) throws MetricException {
    final int size = Iterables.size(quantities);
    if (size > 1) {
        final boolean hasOffset = Iterables.any(quantities, new Predicate<Quantity>() {
            @Override/*  ww  w.  j a  v a2s  .  c  om*/
            public boolean apply(Quantity q) {
                return q.getUnit().hasOffset();
            }
        });
        if (hasOffset) {
            throw MetricException.withMessage("Cannot sum non-absolute quantities");
        }
    }
}

From source file:org.splevo.jamopp.refactoring.java.ifelse.optxor.IfStaticConfigClassOPTXOR.java

/**
 * Checks if the given variation point can be refactored without the use of the RefactoringUtil.
 * This implies that all features offered by the {@link IfElseRefactoringUtil} are not used in
 * these refactorings./*from w  w  w  .  j  av  a2  s  .c  om*/
 * 
 * @param variationPoint The variation point to be refactored.
 * @return True if the variation point can be refactored, False otherwise.
 */
public boolean canBeRefactoredWithoutRefactoringUtil(final VariationPoint variationPoint) {
    return Iterables.any(availableRefactorings, new Predicate<VariabilityRefactoring>() {
        @Override
        public boolean apply(VariabilityRefactoring input) {
            if (input instanceof RequiresIfRefactoringUtil) {
                return false;
            }
            return input.canBeAppliedTo(variationPoint).getSeverity() == Diagnostic.OK;
        }
    });

}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.export.template.ExcelTemplateGeneratorServiceImpl.java

/**
 * Generate sheets for the {@link SubstantialTypeExpression}s and {@link RelationshipTypeExpression}s.
 *
 * @param metamodel the metamodel//from  w  w  w  .ja  va 2  s  .  com
 * @param wbContext the workbook context
 */
private void generateSheets(Metamodel metamodel, WorkbookContext wbContext) {
    List<UniversalTypeExpression> universalTypes = Lists.newArrayList();
    universalTypes.addAll(metamodel.getSubstantialTypes());
    universalTypes.addAll(metamodel.getRelationshipTypes());

    Collections.sort(universalTypes, new Comparator<UniversalTypeExpression>() {
        private UniversalTypeExpressionOrder order = new UniversalTypeExpressionOrderFix();

        public int compare(UniversalTypeExpression type1, UniversalTypeExpression type2) {
            return order.compareNames(type1.getPersistentName(), type2.getPersistentName());
        }
    });

    List<TypeSheetGenerator> generators = Lists.newArrayList();
    for (UniversalTypeExpression ute : universalTypes) {
        LOGGER.debug("Generating sheet for type: {0}", ute);
        TypeSheetGenerator generator = new TypeSheetGenerator(wbContext, ute);
        generators.add(generator);
        SheetContext sheetContext = generator.generateSheet();
        wbContext.addSheetContext(sheetContext);
    }

    for (TypeSheetGenerator generator : generators) {
        LOGGER.debug("Adding dropdowns to sheet for type: {0}", generator.getTypeExpression());
        generator.addDropdowns();
    }

    List<RelationshipExpression> relationships = metamodel.getRelationships();
    for (RelationshipExpression re : relationships) {
        List<RelationshipEndExpression> relationshipEnds = re.getRelationshipEnds();
        if (Iterables.any(relationshipEnds, ToOneRelationFilter.INSTANCE)) {
            continue;
        }

        LOGGER.debug("Generating sheet for relation: {0}", re);
        RelationshipSheetGenerator relationSheetGenerator = new RelationshipSheetGenerator(wbContext, re);
        SheetContext sheetContext = relationSheetGenerator.generateSheet();
        wbContext.addSheetContext(sheetContext);
    }

    List<EnumerationExpression> enums = metamodel.getEnumerationTypes();
    for (EnumerationExpression ete : enums) {
        LOGGER.debug("Generating sheet for enum: {0}: {1} ", ete, ete.getLiterals().toString());
        if (ete.getPersistentName() != null) {
            EnumSheetGenerator enumSheetGenerator = new EnumSheetGenerator(wbContext, ete);
            SheetContext sheetContext = enumSheetGenerator.generateSheet();
            wbContext.addSheetContext(sheetContext);
        }
    }

    adjustSheetColumnWidths(wbContext);
}

From source file:org.eclipse.elk.alg.layered.p3order.LayerSweepTypeDecider.java

private boolean hasNoEasternPorts(final LNode node) {
    List<LPort> eastPorts = node.getPortSideView(PortSide.EAST);
    return eastPorts.isEmpty() || !Iterables.any(eastPorts, p -> p.getConnectedEdges().iterator().hasNext());
}

From source file:org.sosy_lab.cpachecker.cpa.bam.BAMTransferRelation.java

@Override
public Collection<? extends AbstractState> getAbstractSuccessors(final AbstractState pState,
        final Precision pPrecision) throws CPATransferException, InterruptedException {
    try {//from   w w  w.j  av  a2 s.c  o m

        final Collection<? extends AbstractState> successors = getAbstractSuccessorsWithoutWrapping(pState,
                pPrecision);

        assert !Iterables.any(successors, IS_TARGET_STATE)
                || successors.size() == 1 : "target-state should be returned as single-element-collection";

        return attachAdditionalInfoToCallNodes(successors);

    } catch (CPAException e) {
        throw new RecursiveAnalysisFailedException(e);
    }
}

From source file:org.opentestsystem.authoring.testauth.validation.ScoringRuleValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ScoringRule scoringRule = (ScoringRule) obj;

    // parameterDataMap can only be evaluated if corresponding ComputationRule is passed along
    if (StringUtils.isNotBlank(scoringRule.getComputationRuleId())
            && scoringRule.getComputationRule() != null) {
        validateFileUploads(errors, scoringRule);

        if (!CollectionUtils.isEmpty(scoringRule.getParameters())) {
            // check for duplicate parameter names
            final Map<String, Collection<ScoringRuleParameter>> duplicates = Maps.filterEntries(
                    Multimaps.index(scoringRule.getParameters(), RULE_PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                    PARAMETER_DUPLICATE_FILTER);
            if (!duplicates.isEmpty()) {
                rejectValue(errors, PARAMETERS,
                        getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_DUPLICATES,
                        duplicates.keySet().toString());
            }/*from  w  w w. j  av a2  s  . c om*/

            for (int i = 0; i < scoringRule.getParameters().size(); i++) {
                final ScoringRuleParameter scoringRuleParameter = scoringRule.getParameters().get(i);
                try {
                    errors.pushNestedPath(PARAMETERS + "[" + i + "]");
                    final ComputationRuleParameter computationRuleParameter = Iterables
                            .find(scoringRule.getComputationRule().getParameters(), FUNCTION_PARAMETER_FINDER
                                    .getInstance(scoringRuleParameter.getComputationRuleParameterName()));
                    if (computationRuleParameter == null) {
                        rejectValue(errors, PARAMETER_NAME,
                                getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                                scoringRuleParameter.getComputationRuleParameterName());
                    } else {
                        // evaluate every value within the rule parameter to ensure it adheres to the constraints of the ComputationRuleParameter
                        ValidationUtils.invokeValidator(this.scoringRuleParameterValidator,
                                scoringRuleParameter, errors, computationRuleParameter);
                    }
                } catch (final NoSuchElementException e) {
                    rejectValue(errors, PARAMETER_NAME,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_NOT_FOUND,
                            scoringRuleParameter.getComputationRuleParameterName());
                } finally {
                    errors.popNestedPath();
                }
            }

            for (final ComputationRuleParameter computationRuleParameter : scoringRule.getComputationRule()
                    .getParameters()) {
                if (!Iterables.any(scoringRule.getParameters(),
                        RULE_PARAMETER_FINDER.getInstance(computationRuleParameter.getParameterName()))) {
                    rejectValue(errors, PARAMETERS,
                            getErrorMessageRoot() + PARAMETERS + MSG_PARAMETER_NAME + MSG_MISSING,
                            computationRuleParameter.getParameterName());
                }
            }
        }
    }
}

From source file:gov.nih.nci.firebird.service.task.CoordinatorTasksGenerator.java

private boolean containsCoordinatorRoleAwaitingApproval(FirebirdUser user) {
    Set<ManagedInvestigator> managedInvestigators = user.getRegistrationCoordinatorRole()
            .getManagedInvestigators();/*from   w w w  .  j a va 2 s.  c  om*/
    return Iterables.any(managedInvestigators, new Predicate<ManagedInvestigator>() {
        @Override
        public boolean apply(ManagedInvestigator managedInvestigator) {
            return !managedInvestigator.isApproved();
        }
    });
}

From source file:org.jclouds.aws.s3.filters.RequestAuthorizeSignature.java

@VisibleForTesting
void appendBucketName(HttpRequest req, StringBuilder toSign) {
    checkArgument(req instanceof GeneratedHttpRequest<?>, "this should be a generated http request");
    GeneratedHttpRequest<?> request = GeneratedHttpRequest.class.cast(req);

    String bucketName = null;//from   w w  w .  ja  v a2s .  c o m

    for (int i = 0; i < request.getJavaMethod().getParameterAnnotations().length; i++) {
        if (Iterables.any(Arrays.asList(request.getJavaMethod().getParameterAnnotations()[i]),
                new Predicate<Annotation>() {
                    public boolean apply(Annotation input) {
                        return input.annotationType().equals(Bucket.class);
                    }
                })) {
            bucketName = (String) request.getArgs()[i];
            break;
        }
    }

    if (bucketName != null)
        toSign.append(servicePath).append(bucketName);
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.SynchronizeISequenceEventsSemanticOrderingOperation.java

private void updateSemanticPosition(ISequenceEvent eventToUpdate) {
    DDiagramElement dde = resolveDiagramElement(eventToUpdate);
    if (dde == null || reordered.contains(eventToUpdate)) {
        return;/*from   w w w.  ja v  a  2 s  . c o  m*/
    }

    ReorderTool reorderTool = findReorderTool(dde);
    if (reorderTool == null) {
        return;
    }

    EObject semanticElement = dde.getTarget();
    EList<EventEnd> endsBySemanticOrder = sequenceDiagram.getSemanticOrdering().getEventEnds();
    EList<EventEnd> endsByGraphicalOrder = sequenceDiagram.getGraphicalOrdering().getEventEnds();

    List<EventEnd> ends = EventEndHelper.findEndsFromSemanticOrdering(eventToUpdate);
    List<EventEnd> compoundEnds = getCompoundEnds(eventToUpdate, ends);

    // Ignore the ends of the descendants: they are treated by recursive
    // calls.
    Set<EventEnd> toIgnore = selectEndsToIgnore(eventToUpdate, endsBySemanticOrder, ends, compoundEnds);

    // The semantic ordering contains the state before the move
    EventEnd startingEndPredecessorBefore = findEndPredecessor(semanticElement, STARTING_END,
            endsBySemanticOrder, toIgnore);
    EventEnd finishingEndPredecessorBefore = findEndPredecessor(semanticElement, FINISHING_END,
            endsBySemanticOrder, toIgnore);

    // The graphical ordering contains the state after
    EventEnd startingEndPredecessorAfter = findEndPredecessor(semanticElement, STARTING_END,
            endsByGraphicalOrder, toIgnore);
    EventEnd finishingEndPredecessorAfter = findEndPredecessor(semanticElement, FINISHING_END,
            endsByGraphicalOrder, toIgnore);

    // Handle lost messages
    if (eventToUpdate.isLogicallyInstantaneous() && eventToUpdate instanceof Message && ends.size() == 1
            && !Iterables.any(ends, Predicates.instanceOf(CompoundEventEnd.class))) {
        SingleEventEnd see = (SingleEventEnd) ends.iterator().next();
        if (see.isStart()) {
            finishingEndPredecessorBefore = startingEndPredecessorBefore;
            finishingEndPredecessorAfter = startingEndPredecessorAfter;
        } else {
            startingEndPredecessorBefore = finishingEndPredecessorBefore;
            startingEndPredecessorAfter = finishingEndPredecessorAfter;
        }

    }

    if (!Objects.equal(startingEndPredecessorBefore, startingEndPredecessorAfter)
            || !Objects.equal(finishingEndPredecessorBefore, finishingEndPredecessorAfter)
            || !Iterables.elementsEqual(endsByGraphicalOrder, endsBySemanticOrder)) {
        applySemanticReordering(semanticElement, startingEndPredecessorAfter, finishingEndPredecessorAfter,
                reorderTool);
        applyCompoundReordering(semanticElement, ends, compoundEnds, startingEndPredecessorAfter,
                finishingEndPredecessorAfter, reorderTool);
        reordered.add(eventToUpdate);

        new RefreshSemanticOrderingsOperation(sequenceDiagram).execute();
        updateSubEventsSemanticPositions(eventToUpdate);
    }
}

From source file:org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider.java

protected boolean _isLeaf(final EObject modelElement) {
    return !Iterables.any(modelElement.eClass().getEAllContainments(), new Predicate<EReference>() {
        @Override//from   w ww  .j  a va  2s .c  o  m
        public boolean apply(EReference containmentRef) {
            return modelElement.eIsSet(containmentRef);
        }
    });
}