List of usage examples for com.google.common.base Predicates and
public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second)
From source file:org.apache.brooklyn.entity.stock.BasicStartableImpl.java
private static Iterable<Entity> filterStartableManagedEntities(Iterable<Entity> contenders) { return Iterables.filter(contenders, Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged())); }
From source file:fr.xebia.cocktail.CocktailRepository.java
public Collection<Cocktail> find(@Nullable final String ingredient, @Nullable final String name) { Predicate<Cocktail> ingredientPredicate; if (Strings.isNullOrEmpty(ingredient)) { ingredientPredicate = Predicates.alwaysTrue(); } else {//w w w . jav a2s . co m ingredientPredicate = new Predicate<Cocktail>() { @Override public boolean apply(@Nullable Cocktail cocktail) { for (String cocktailIngredient : cocktail.getIngredientNames()) { if (StringUtils.containsIgnoreCase(cocktailIngredient, ingredient)) { return true; } } return false; } }; } Predicate<Cocktail> namePredicate; if (Strings.isNullOrEmpty(name)) { namePredicate = Predicates.alwaysTrue(); } else { namePredicate = new Predicate<Cocktail>() { @Override public boolean apply(@Nullable Cocktail cocktail) { return StringUtils.containsIgnoreCase(cocktail.getName(), name); } }; } return Lists.newArrayList(Collections2.filter(cocktails.asMap().values(), Predicates.and(namePredicate, ingredientPredicate))); }
From source file:forge.game.phase.Untap.java
/** * <p>/* w w w. j av a 2 s .c o m*/ * doUntap. * </p> */ private void doUntap() { final Player player = game.getPhaseHandler().getPlayerTurn(); final Predicate<Card> tappedCanUntap = Predicates.and(Presets.TAPPED, CANUNTAP); CardCollection list = new CardCollection(player.getCardsIn(ZoneType.Battlefield)); for (Card c : list) { c.setStartedTheTurnUntapped(c.isUntapped()); } CardCollection bounceList = CardLists.getKeyword(list, "During your next untap step, as you untap your permanents, return CARDNAME to its owner's hand."); for (final Card c : bounceList) { game.getAction().moveToHand(c); } list.removeAll((Collection<?>) bounceList); final Map<String, Integer> restrictUntap = new HashMap<String, Integer>(); boolean hasChosen = false; for (String kw : player.getKeywords()) { if (kw.startsWith("UntapAdjust")) { String[] parse = kw.split(":"); if (!restrictUntap.containsKey(parse[1]) || Integer.parseInt(parse[2]) < restrictUntap.get(parse[1])) { restrictUntap.put(parse[1], Integer.parseInt(parse[2])); } } if (kw.startsWith("OnlyUntapChosen") && !hasChosen) { List<String> validTypes = Arrays.asList(kw.split(":")[1].split(",")); List<String> invalidTypes = new ArrayList<String>(CardType.getAllCardTypes()); invalidTypes.removeAll(validTypes); final String chosen = player.getController().chooseSomeType("Card", new SpellAbility.EmptySa(ApiType.ChooseType, null, player), validTypes, invalidTypes); list = CardLists.getType(list, chosen); hasChosen = true; } } final CardCollection untapList = new CardCollection(list); final String[] restrict = restrictUntap.keySet().toArray(new String[restrictUntap.keySet().size()]); list = CardLists.filter(list, new Predicate<Card>() { @Override public boolean apply(final Card c) { if (!Untap.canUntap(c)) { return false; } if (c.isValid(restrict, player, null)) { return false; } return true; } }); for (final Card c : list) { optionalUntap(c); } // other players untapping during your untap phase List<Card> cardsWithKW = CardLists.getKeyword(game.getCardsIn(ZoneType.Battlefield), "CARDNAME untaps during each other player's untap step."); final FCollection<Player> otherPlayers = new FCollection<Player>(game.getPlayers()); otherPlayers.remove(player); cardsWithKW = CardLists.filter(cardsWithKW, CardPredicates.isControlledByAnyOf(otherPlayers)); for (final Card cardWithKW : cardsWithKW) { cardWithKW.untap(); } // end other players untapping during your untap phase CardCollection restrictUntapped = new CardCollection(); CardCollection cardList = CardLists.filter(untapList, tappedCanUntap); cardList = CardLists.getValidCards(cardList, restrict, player, null); while (!cardList.isEmpty()) { Map<String, Integer> remaining = new HashMap<String, Integer>(restrictUntap); for (Entry<String, Integer> entry : remaining.entrySet()) { if (entry.getValue() == 0) { cardList.removeAll( (Collection<?>) CardLists.getValidCards(cardList, entry.getKey(), player, null)); restrictUntap.remove(entry.getKey()); } } Card chosen = player.getController().chooseSingleEntityForEffect(cardList, new SpellAbility.EmptySa(ApiType.Untap, null, player), "Select a card to untap\r\n(Selected:" + restrictUntapped + ")\r\n" + "Remaining cards that can untap: " + remaining); if (chosen != null) { for (Entry<String, Integer> rest : restrictUntap.entrySet()) { if (chosen.isValid(rest.getKey(), player, null)) { restrictUntap.put(rest.getKey(), rest.getValue().intValue() - 1); } } restrictUntapped.add(chosen); cardList.remove(chosen); } } for (Card c : restrictUntapped) { optionalUntap(c); } // Remove temporary keywords for (final Card c : player.getCardsIn(ZoneType.Battlefield)) { c.removeAllExtrinsicKeyword("This card doesn't untap during your next untap step."); c.removeAllExtrinsicKeyword("HIDDEN This card doesn't untap during your next untap step."); if (c.hasKeyword("This card doesn't untap during your next two untap steps.")) { c.removeAllExtrinsicKeyword("HIDDEN This card doesn't untap during your next two untap steps."); c.addHiddenExtrinsicKeyword("HIDDEN This card doesn't untap during your next untap step."); } } }
From source file:com.foundationdb.server.types.mcompat.mfuncs.MIfNull.java
private static void createAsGroup(List<TScalar> resultsList, Collection<? extends TClass> group) { Predicate<List<? extends TPreptimeValue>> containsAny = IsCandidatePredicates.containsOnly(group); Predicate<List<? extends TPreptimeValue>> predicate = Predicates.and(containsAny, IsCandidatePredicates.allTypesKnown); resultsList.add(new MIfNull(null, resultsList.size(), predicate)); }
From source file:org.apache.brooklyn.entity.messaging.kafka.KafkaSupport.java
/** * Retrieve the next message on the given topic from the {@link KafkaCluster}. *///from w ww. ja v a2 s .co m public String getMessage(String topic) { ZooKeeperNode zookeeper = cluster.getZooKeeper(); Optional<Entity> anyBrokerNodeInCluster = Iterables.tryFind(cluster.getCluster().getChildren(), Predicates.and(Predicates.instanceOf(KafkaBroker.class), EntityPredicates.attributeEqualTo(KafkaBroker.SERVICE_UP, true))); if (anyBrokerNodeInCluster.isPresent()) { KafkaBroker broker = (KafkaBroker) anyBrokerNodeInCluster.get(); Properties props = new Properties(); props.put("bootstrap.servers", format("%s:%d", broker.getAttribute(KafkaBroker.HOSTNAME), broker.getKafkaPort())); props.put("zookeeper.connect", format(zookeeper.getHostname(), zookeeper.getZookeeperPort())); props.put("group.id", "brooklyn"); props.put("partition.assignment.strategy", "RoundRobin"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer consumer = new KafkaConsumer(props); consumer.subscribe(topic); // FIXME unimplemented KafkaConsumer.poll // Object consumerRecords = consumer.poll(Duration.seconds(3).toMilliseconds()).get(topic); return "TEST_MESSAGE"; } else { throw new InvalidParameterException("No kafka broker node found"); } }
From source file:org.jon.ivmark.graphit.recommendation.service.ItemBasedRecommendationService.java
private Iterable<Item> getFallback(CompositeRecommendationSettings recommendationSettings, int numItems) { if (numItems == 0) { return Collections.emptyList(); }// ww w. j a v a2 s . c o m Predicate<Properties> commonFilter = recommendationSettings.filter(); FallbackSettings fallbackTo = recommendationSettings.getFallbackTo(); Fallback fallback = fallback(fallbackTo); final Predicate<Properties> fallbackFilter = Predicates.and(commonFilter, fallbackFilter(fallbackTo)); return new Traversable<String>(fallback).transform(new Function<String, Item>() { @Override public Item apply(String itemId) { return items.get(itemId); } }).filter(new Predicate<Item>() { @Override public boolean apply(Item item) { return fallbackFilter.apply(new ImmutableItemProperties(item)); } }).head(numItems); }
From source file:com.twitter.bazel.checkstyle.PythonCheckstyle.java
@SuppressWarnings("unchecked") private static Collection<String> getSourceFiles(String extraActionFile) { ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile); SpawnInfo spawnInfo = info.getExtension(SpawnInfo.spawnInfo); return Collections2.filter(spawnInfo.getInputFileList(), Predicates.and(Predicates.containsPattern(".*/src/.+\\.py[c]{0,1}$"), Predicates.not(Predicates.containsPattern("3rdparty/")))); }
From source file:org.eclipse.sirius.diagram.sequence.ui.business.internal.refresh.VisibilityEventHandler.java
private boolean containsVisibilityEvent(ResourceSetChangeEvent event) { Predicate<Notification> isVisibilityEvent = new Predicate<Notification>() { @Override//from w w w . j a v a 2 s .c om public boolean apply(Notification input) { NotificationQuery nq = new NotificationQuery(input); return nq.isViewBecomingInvisibleEvent() || nq.isHideFilterAddEvent(); } }; Predicate<Notification> isAlwaysVisibleSequenceElement = new Predicate<Notification>() { @Override public boolean apply(Notification input) { Object notifier = input.getNotifier(); if (notifier instanceof DDiagramElement) { DDiagramElement dde = (DDiagramElement) notifier; DDiagram parentDiagram = dde.getParentDiagram(); return parentDiagram instanceof SequenceDDiagram && !(new SequenceDiagramTypeProvider().allowsHideReveal(dde)); } return false; } }; return Iterables.any(Iterables.filter(event.getNotifications(), Notification.class), Predicates.and(isAlwaysVisibleSequenceElement, isVisibilityEvent)); }
From source file:forge.item.SealedProduct.java
protected List<PaperCard> getRandomBasicLands(final String setCode, final int count) { Predicate<PaperCard> cardsRule = Predicates.and(IPaperCard.Predicates.printedInSet(setCode), Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES)); return Aggregates.random(Iterables.filter(StaticData.instance().getCommonCards().getAllCards(), cardsRule), count);//w w w .j a v a 2s . co m }
From source file:org.auraframework.util.ServiceLoaderImpl.java
@SuppressWarnings("unchecked") private <T> T get(Class<T> type, Set<Class<?>> classes, boolean primary, Predicate<? super Method> predicate) { Set<Method> beanMethods = Sets.newHashSet(); Predicate<Method> pred; pred = Predicates.and(predicate, ReflectionUtils.withReturnTypeAssignableTo(type)); if (primary) { pred = Predicates.and(pred, ReflectionUtils.withAnnotation(PrimaryImpl.class)); }/* w w w . j av a2 s.c o m*/ /* * This is a better way to do it, but hits a runtime dep on Guava 12, so * until we upgrade to Guava 12, working around this. */ for (Class<?> clazz : classes) { for (Method meth : clazz.getDeclaredMethods()) { if (pred.apply(meth)) { beanMethods.add(meth); } } } T ret = null; try { for (Method meth : beanMethods) { T tmp = (T) meth.invoke(null); if (tmp != null) { if (ret != null) { throw new ServiceLocatorException( "More than one implementation found (primary=" + primary + ")."); } ret = tmp; } } } catch (Exception e) { throw new ServiceLocatorException(e); } return ret; }