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:forge.learnedai.LearnedAiController.java

public Card chooseBestLandToPlay(CardCollection landList) {
    if (landList.isEmpty()) {
        return null;
    }/*from   w  w w .  j  a  v  a2  s  . co m*/
    //Skip reflected lands.
    CardCollection unreflectedLands = new CardCollection(landList);
    for (Card l : landList) {
        if (l.isReflectedLand()) {
            unreflectedLands.remove(l);
        }
    }

    if (!unreflectedLands.isEmpty()) {
        landList = unreflectedLands;
    }

    // Choose first land to be able to play a one drop
    if (player.getLandsInPlay().isEmpty()) {
        CardCollection oneDrops = CardLists.filter(player.getCardsIn(ZoneType.Hand), CardPredicates.hasCMC(1));
        for (int i = 0; i < MagicColor.WUBRG.length; i++) {
            byte color = MagicColor.WUBRG[i];
            if (!CardLists.filter(oneDrops, CardPredicates.isColor(color)).isEmpty()) {
                for (Card land : landList) {
                    // Don't play ETB Tapped land if you have a 1 drop can be played
                    // Is this the best way to check if a land ETB Tapped?
                    if (land.hasSVar("ETBTappedSVar")) {
                        continue;
                    }

                    // Glacial Fortress and friends
                    if (land.hasSVar("ETBCheckSVar")
                            && CardFactoryUtil.xCount(land, land.getSVar("ETBCheckSVar")) == 0) {
                        continue;
                    }

                    if (land.getType().hasSubtype(MagicColor.Constant.BASIC_LANDS.get(i))) {
                        return land;
                    }
                    for (final SpellAbility m : ComputerUtilMana.getAIPlayableMana(land)) {
                        AbilityManaPart mp = m.getManaPart();
                        if (mp.canProduce(MagicColor.toShortString(color), m)) {
                            return land;
                        }
                    }
                }
            }
        }
    }

    //play basic lands that are needed the most
    if (Iterables.any(landList, CardPredicates.Presets.BASIC_LANDS)) {
        final CardCollectionView combined = player.getCardsIn(ZoneType.Battlefield);

        final List<String> basics = new ArrayList<String>();

        // what types can I go get?
        for (final String name : CardType.Constant.BASIC_TYPES) {
            if (Iterables.any(landList, CardPredicates.isType(name))) {
                basics.add(name);
            }
        }

        // Which basic land is least available from hand and play, that I still
        // have in my deck
        int minSize = Integer.MAX_VALUE;
        String minType = null;

        for (int i = 0; i < basics.size(); i++) {
            final String b = basics.get(i);
            final int num = CardLists.getType(combined, b).size();
            if (num < minSize) {
                minType = b;
                minSize = num;
            }
        }

        if (minType != null) {
            landList = CardLists.getType(landList, minType);
        }
    }
    return landList.get(0);
}

From source file:net.shibboleth.idp.authn.AbstractValidationAction.java

/**
 * Evaluates a message as a potential match as a "classified" error and if matched, the classification
 * label is attached to an {@link AuthenticationErrorContext} and used as the resulting event for the action.
 * /*from w w w.j a  v a 2s  . co m*/
 * <p>If no match, the supplied eventId is used as the result.</p>
 * 
 * <p>If multiple matches, the first matching label is used as the result, but each match is added to the
 * context.</p>
 * 
 * @param profileRequestContext the current profile request context
 * @param authenticationContext the current authentication context
 * @param message to process
 * @param eventId the event to "return" via an {@link org.opensaml.profile.context.EventContext} if
 *  the message is not classified
 */
protected void handleError(
        @Nonnull final ProfileRequestContext<InboundMessageType, OutboundMessageType> profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext, @Nullable final String message,
        @Nonnull @NotEmpty final String eventId) {

    boolean eventSet = false;

    if (!Strings.isNullOrEmpty(message)) {
        final MessageChecker checker = new MessageChecker(message);

        for (final Map.Entry<String, Collection<String>> entry : classifiedMessages.entrySet()) {
            if (Iterables.any(entry.getValue(), checker)) {
                authenticationContext.getSubcontext(AuthenticationErrorContext.class, true)
                        .getClassifiedErrors().add(entry.getKey());
                if (!eventSet) {
                    eventSet = true;
                    ActionSupport.buildEvent(profileRequestContext, entry.getKey());
                }
            }
        }
    }

    if (!eventSet) {
        ActionSupport.buildEvent(profileRequestContext, eventId);
    }
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.edit.policy.ExecutionSelectionEditPolicy.java

private void addMessageReconnectionCommand(Execution self, CompositeTransactionalCommand cc,
        TransactionalEditingDomain editingDomain, Message message, Range newRange, ChangeBoundsRequest request,
        AbstractNodeEventResizeSelectionValidator validator) {

    Set<Execution> executionsInMove = new RequestQuery(request).getExecutions();
    boolean invalidCommand = false;

    Predicate<EventEnd> filterCompoundEventEnd = new Predicate<EventEnd>() {
        @Override//from  ww  w. j av  a2s .c o  m
        public boolean apply(EventEnd input) {
            return input instanceof CompoundEventEnd;
        }
    };

    SetMessageRangeOperation smrc = new SetMessageRangeOperation((Edge) message.getNotationView(), newRange);

    Lifeline selfLifeline = self.getLifeline().get();
    Rectangle logicalDelta = new RequestQuery(request).getLogicalDelta();
    Rectangle bounds = self.getProperLogicalBounds().getCopy();
    bounds.translate(logicalDelta.getLocation());
    bounds.resize(logicalDelta.getSize());
    Range thisFinalRange = RangeHelper.verticalRange(bounds);

    List<ISequenceEvent> toIgnore = Lists.newArrayList();
    boolean isReplyMessage = message.getKind() == Message.Kind.REPLY;
    boolean isReflective = message.isReflective();
    ISequenceNode sourceElement = message.getSourceElement();
    ISequenceNode targetElement = message.getTargetElement();
    if (!isReplyMessage && isReflective
            && Iterables.any(EventEndHelper.findEndsFromSemanticOrdering(message), filterCompoundEventEnd)
            && targetElement == self) {
        // Avoid target of the return message of a reflexive sync call to
        // reconnect on its execution
        toIgnore.add(self);
    }
    // if a verticalSpaceExpansion will occurs, ignore ISequenceEvent under
    // the insertionPoint
    if (needVerticalSpaceExpansion(validator, request)) {
        Collection<ISequenceEvent> sequenceEventsUpperToInsertionTime = getSequenceEventsUpperToInsertionTime(
                self.getDiagram(), validator.getExpansionZone().getLowerBound());
        sequenceEventsUpperToInsertionTime.removeAll(executionsInMove);
        toIgnore.addAll(sequenceEventsUpperToInsertionTime);
    }

    Option<Lifeline> srcLifeline = message.getSourceLifeline();
    if (srcLifeline.some()) {
        EventFinder srcFinder = new EventFinder(srcLifeline.get());
        srcFinder.setReconnection(true);
        srcFinder.setEventsToIgnore(Predicates.in(toIgnore));
        srcFinder.setExpansionZone(validator.getExpansionZone());
        ISequenceEvent finalSrc = (srcLifeline.get() == selfLifeline && sourceElement == self) ? self
                : srcFinder.findMostSpecificEvent(newRange);
        Range finalSrcRange = (srcLifeline.get() == selfLifeline && sourceElement == self) ? thisFinalRange
                : finalSrc.getVerticalRange();
        smrc.setSource(finalSrc.getNotationView(),
                new Rectangle(0, finalSrcRange.getLowerBound(), 0, finalSrcRange.width()));
    } else {
        Range finalSrcRange = RangeHelper.verticalRange(sourceElement.getProperLogicalBounds());
        smrc.setSource(sourceElement.getNotationView(),
                new Rectangle(0, finalSrcRange.getLowerBound(), 0, finalSrcRange.width()));
    }

    toIgnore.clear();
    if (isReplyMessage && isReflective
            && Iterables.any(EventEndHelper.findEndsFromSemanticOrdering(message), filterCompoundEventEnd)
            && sourceElement == self) {
        // Avoid target of the return message of a reflexive sync call to
        // reconnect on its execution
        toIgnore.add(self);
    }
    // if a verticalSpaceExpansion will occurs, ignore ISequenceEvent under
    // the insertionPoint
    if (needVerticalSpaceExpansion(validator, request)) {
        Collection<ISequenceEvent> sequenceEventsUpperToInsertionTime = getSequenceEventsUpperToInsertionTime(
                self.getDiagram(), validator.getExpansionZone().getLowerBound());
        sequenceEventsUpperToInsertionTime.removeAll(executionsInMove);
        toIgnore.addAll(sequenceEventsUpperToInsertionTime);
    }

    Option<Lifeline> tgtLifeline = message.getTargetLifeline();
    if (tgtLifeline.some()) {
        EventFinder tgtFinder = new EventFinder(tgtLifeline.get());
        tgtFinder.setReconnection(true);
        tgtFinder.setEventsToIgnore(Predicates.in(toIgnore));
        tgtFinder.setExpansionZone(validator.getExpansionZone());
        ISequenceEvent finalTgt = (tgtLifeline.get() == selfLifeline && targetElement == self) ? self
                : tgtFinder.findMostSpecificEvent(newRange);
        if (finalTgt == null) {
            invalidCommand = true;
        } else {
            Range finalTgtRange = (tgtLifeline.get() == selfLifeline && targetElement == self) ? thisFinalRange
                    : finalTgt.getVerticalRange();
            smrc.setTarget(finalTgt.getNotationView(),
                    new Rectangle(0, finalTgtRange.getLowerBound(), 0, finalTgtRange.width()));
        }
    } else {
        Range finalTgtRange = RangeHelper.verticalRange(targetElement.getProperLogicalBounds());
        smrc.setTarget(targetElement.getNotationView(),
                new Rectangle(0, finalTgtRange.getLowerBound(), 0, finalTgtRange.width()));
    }

    if (invalidCommand) {
        cc.compose(org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE);
    } else {
        cc.compose(CommandFactory.createICommand(editingDomain, smrc));
    }

}

From source file:org.summer.dsl.xbase.compiler.XbaseCompiler.java

@SuppressWarnings("deprecation")
@Override//from   w ww.  ja v a  2s .  c o  m
protected void convertFunctionType(JvmTypeReference expectedType, final JvmTypeReference functionType,
        ITreeAppendable appendable, Later expression, XExpression context) {
    if (expectedType.getIdentifier().equals(Object.class.getName())
            || EcoreUtil.equals(expectedType.getType(), functionType.getType())
            || ((expectedType instanceof JvmSynonymTypeReference)
                    && Iterables.any(((JvmSynonymTypeReference) expectedType).getReferences(),
                            new Predicate<JvmTypeReference>() {
                                public boolean apply(@Nullable JvmTypeReference ref) {
                                    if (ref == null) {
                                        throw new IllegalStateException();
                                    }
                                    return EcoreUtil.equals(ref.getType(), functionType.getType());
                                }
                            }))) {
        // same raw type but different type parameters
        // at this point we know that we are compatible so we have to convince the Java compiler about that ;-)
        if (!getTypeConformanceComputer().isConformant(expectedType, functionType)) {
            // insert a cast
            appendable.append("(");
            serialize(expectedType, context, appendable);
            appendable.append(")");
        }
        expression.exec(appendable);
        return;
    }
    JvmOperation operation = getClosures().findImplementingOperation(expectedType, context.eResource());
    if (operation == null) {
        throw new IllegalStateException("expected type " + expectedType + " not mappable from " + functionType);
    }
    appendable.append("new ");
    LightweightTypeReference lightweightExpectedType = new OwnedConverter(newTypeReferenceOwner(context))
            .toLightweightReference(expectedType);
    FunctionTypeReference functionTypeReference = lightweightExpectedType
            .tryConvertToFunctionTypeReference(false);
    if (functionTypeReference == null)
        throw new IllegalStateException("Expected type does not seem to be a SAM type");
    JvmTypeReference convertedExpectedType = functionTypeReference.toInstanceTypeReference().toTypeReference();
    serialize(convertedExpectedType, context, appendable, false, false);
    appendable.append("() {");
    appendable.increaseIndentation().increaseIndentation();
    appendable.newLine().append("public ");
    LightweightTypeReference returnType = functionTypeReference.getReturnType();
    if (returnType == null)
        throw new IllegalStateException("Could not find return type");
    serialize(returnType.toTypeReference(), context, appendable, false, false);
    appendable.append(" ").append(operation.getSimpleName()).append("(");
    List<JvmFormalParameter> params = operation.getParameters();
    for (int i = 0; i < params.size(); i++) {
        if (i != 0)
            appendable.append(",");
        JvmFormalParameter p = params.get(i);
        final String name = p.getName();
        serialize(functionTypeReference.getParameterTypes().get(i).toTypeReference(), context, appendable,
                false, false);
        appendable.append(" ").append(name);
    }
    appendable.append(") {");
    appendable.increaseIndentation();
    try {
        appendable.openScope();
        reassignThisInClosure(appendable, operation.getDeclaringType());
        if (!getTypeReferences().is(operation.getReturnType(), Void.TYPE))
            appendable.newLine().append("return ");
        else
            appendable.newLine();
        expression.exec(appendable);
        appendable.append(".");
        JvmOperation actualOperation = getClosures().findImplementingOperation(functionType,
                context.eResource());
        appendable.append(actualOperation.getSimpleName());
        appendable.append("(");
        for (Iterator<JvmFormalParameter> iterator = params.iterator(); iterator.hasNext();) {
            JvmFormalParameter p = iterator.next();
            final String name = p.getName();
            appendable.append(name);
            if (iterator.hasNext())
                appendable.append(",");
        }
        appendable.append(");");
    } finally {
        appendable.closeScope();
    }
    appendable.decreaseIndentation();
    appendable.newLine().append("}");
    appendable.decreaseIndentation().decreaseIndentation();
    appendable.newLine().append("}");
}

From source file:net.shibboleth.idp.authn.AbstractValidationAction.java

/**
 * Evaluates a message as a potential match as a "classified" warning and if matched, the classification
 * label is attached to an {@link AuthenticationWarningContext} and used as the resulting event for the action.
 * /* w w w  .j av a2s  . c om*/
 * <p>If no match, the supplied eventId is used as the result.</p>
 * 
 * <p>If multiple matches, the first matching label is used as the result, but each match is added to the
 * context.</p>
 * 
 * @param profileRequestContext the current profile request context
 * @param authenticationContext the current authentication context
 * @param message to process
 * @param eventId the event to "return" via an {@link org.opensaml.profile.context.EventContext} if
 *  the message is not classified
 */
protected void handleWarning(
        @Nonnull final ProfileRequestContext<InboundMessageType, OutboundMessageType> profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext, @Nullable final String message,
        @Nonnull @NotEmpty final String eventId) {

    boolean eventSet = false;

    if (!Strings.isNullOrEmpty(message)) {
        final MessageChecker checker = new MessageChecker(message);

        for (Map.Entry<String, Collection<String>> entry : classifiedMessages.entrySet()) {
            if (Iterables.any(entry.getValue(), checker)) {
                authenticationContext.getSubcontext(AuthenticationWarningContext.class, true)
                        .getClassifiedWarnings().add(entry.getKey());
                if (!eventSet) {
                    eventSet = true;
                    ActionSupport.buildEvent(profileRequestContext, entry.getKey());
                }
            }
        }
    }

    if (!eventSet) {
        ActionSupport.buildEvent(profileRequestContext, eventId);
    }
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.mergeviewer.item.impl.MergeViewerItem.java

protected boolean yieldsInsertionPoint(Iterable<Diff> diffs) {
    return Iterables.any(diffs, new Predicate<Diff>() {
        public boolean apply(Diff diff) {
            if (isPseudoAddConflict(diff)) {
                return false;
            }//from ww  w.  j a  v  a 2 s. c  o m

            EObject value = (EObject) MergeViewerUtil.getDiffValue(diff);
            Match match = getComparison().getMatch(value);
            if (isAddOnOppositeSide(diff) || isDeleteOnSameSide(diff) || isInsertOnBothSides(diff, match)) {
                if (match == null && diff.getState() == DifferenceState.MERGED) {
                    EObject bestSideValue = (EObject) getBestSideValue();
                    match = getComparison().getMatch(bestSideValue);
                    match = getMatchWithNullValues(match);
                }

                return match != null && !isRealAddConflict(diff, match);
            }

            return false;
        }
    });
}

From source file:com.google.api.tools.framework.aspects.servicecontrol.ServiceControlConfigValidator.java

private void validateCloudAuditLogName(Location location, final String logName) {
    boolean isAllowed = Iterables.any(allowedCloudAuditLogNamePrefixes, new Predicate<String>() {
        @Override/*  w  w w. j av a  2 s  . co  m*/
        public boolean apply(String allowedPrefix) {
            return logName.startsWith(allowedPrefix);
        }
    });
    if (!isAllowed) {
        error(location, "%s is not a valid Cloud Audit log name. Valid Cloud Audit log name prefixes are: %s.",
                logName, Joiner.on(", ").join(allowedCloudAuditLogNamePrefixes));
    }
}

From source file:com.eucalyptus.binding.JsonDescriptorGenerator.java

public static boolean isIgnored(final Field field) {
    final int mods = field.getModifiers();
    final String name = field.getName();
    final String type = field.getType().getSimpleName();
    if (Modifier.isFinal(mods)) {
        LOG.debug("Ignoring field with bad type: " + field.getDeclaringClass().getCanonicalName() + "." + name
                + " of type " + type + " due to: final modifier");
    } else if (Modifier.isStatic(mods)) {
        LOG.debug("Ignoring field with bad type: " + field.getDeclaringClass().getCanonicalName() + "." + name
                + " of type " + type + " due to: static modifier");
    }/*www .ja  va 2 s  .c om*/
    boolean ret = Iterables.any(badClasses, new Predicate<String>() {
        @Override
        public boolean apply(String arg0) {
            if (type.matches(arg0)) {
                LOG.debug("Ignoring field with bad type: " + field.getDeclaringClass().getCanonicalName() + "."
                        + name + " of type " + type + " due to: " + arg0);
                return true;
            } else {
                return false;
            }
        }
    });
    ret |= Iterables.any(badFields, new Predicate<String>() {
        @Override
        public boolean apply(String arg0) {
            if (name.matches(arg0)) {
                LOG.debug("Ignoring field with bad name: " + field.getDeclaringClass().getCanonicalName() + "."
                        + name + " of type " + type + " due to: " + arg0);
                return true;
            } else {
                return false;
            }
        }
    });

    return ret;
}

From source file:forge.ai.AiController.java

public Card chooseBestLandToPlay(CardCollection landList) {
    if (landList.isEmpty()) {
        return null;
    }/*ww  w .j  a va  2 s  . co  m*/
    //Skip reflected lands.
    CardCollection unreflectedLands = new CardCollection(landList);
    for (Card l : landList) {
        if (l.isReflectedLand()) {
            unreflectedLands.remove(l);
        }
    }
    if (!unreflectedLands.isEmpty()) {
        landList = unreflectedLands;
    }

    CardCollection nonLandsInHand = CardLists.filter(player.getCardsIn(ZoneType.Hand),
            Predicates.not(CardPredicates.Presets.LANDS));

    //try to skip lands that enter the battlefield tapped
    if (!nonLandsInHand.isEmpty()) {
        CardCollection nonTappeddLands = new CardCollection();
        for (Card land : landList) {
            // Is this the best way to check if a land ETB Tapped?
            if (land.hasSVar("ETBTappedSVar")) {
                continue;
            }
            // Glacial Fortress and friends
            if (land.hasSVar("ETBCheckSVar")
                    && CardFactoryUtil.xCount(land, land.getSVar("ETBCheckSVar")) == 0) {
                continue;
            }
            nonTappeddLands.add(land);
        }
        if (!nonTappeddLands.isEmpty()) {
            landList = nonTappeddLands;
        }
    }

    // Choose first land to be able to play a one drop
    if (player.getLandsInPlay().isEmpty()) {
        CardCollection oneDrops = CardLists.filter(nonLandsInHand, CardPredicates.hasCMC(1));
        for (int i = 0; i < MagicColor.WUBRG.length; i++) {
            byte color = MagicColor.WUBRG[i];
            if (!CardLists.filter(oneDrops, CardPredicates.isColor(color)).isEmpty()) {
                for (Card land : landList) {
                    if (land.getType().hasSubtype(MagicColor.Constant.BASIC_LANDS.get(i))) {
                        return land;
                    }
                    for (final SpellAbility m : ComputerUtilMana.getAIPlayableMana(land)) {
                        AbilityManaPart mp = m.getManaPart();
                        if (mp.canProduce(MagicColor.toShortString(color), m)) {
                            return land;
                        }
                    }
                }
            }
        }
    }

    //play lands with a basic type that is needed the most
    final CardCollectionView landsInBattlefield = player.getCardsIn(ZoneType.Battlefield);
    final List<String> basics = new ArrayList<String>();

    // what types can I go get?
    for (final String name : MagicColor.Constant.BASIC_LANDS) {
        if (!CardLists.getType(landList, name).isEmpty()) {
            basics.add(name);
        }
    }
    if (!basics.isEmpty()) {
        // Which basic land is least available
        int minSize = Integer.MAX_VALUE;
        String minType = null;

        for (String b : basics) {
            final int num = CardLists.getType(landsInBattlefield, b).size();
            if (num < minSize) {
                minType = b;
                minSize = num;
            }
        }

        if (minType != null) {
            landList = CardLists.getType(landList, minType);
        }

        // pick dual lands if available
        if (Iterables.any(landList, Predicates.not(CardPredicates.Presets.BASIC_LANDS))) {
            landList = CardLists.filter(landList, Predicates.not(CardPredicates.Presets.BASIC_LANDS));
        }
    }
    return landList.get(0);
}

From source file:forge.game.GameActionUtil.java

private static boolean hasUrzaLands(final Player p) {
    final CardCollectionView landsControlled = p.getCardsIn(ZoneType.Battlefield);
    return Iterables.any(landsControlled,
            Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Mine")))
            && Iterables.any(landsControlled,
                    Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Power-Plant")))
            && Iterables.any(landsControlled,
                    Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Tower")));
}