Example usage for com.google.common.base Predicates compose

List of usage examples for com.google.common.base Predicates compose

Introduction

In this page you can find the example usage for com.google.common.base Predicates compose.

Prototype

public static <A, B> Predicate<A> compose(Predicate<B> predicate, Function<A, ? extends B> function) 

Source Link

Document

Returns the composition of a function and a predicate.

Usage

From source file:org.apache.brooklyn.entity.nosql.couchbase.CouchbaseClusterImpl.java

public void init() {
    log.info("Initializing the Couchbase cluster...");
    super.init();

    enrichers().add(Enrichers.builder().transforming(COUCHBASE_CLUSTER_UP_NODES).from(this)
            .publishing(COUCHBASE_CLUSTER_UP_NODE_ADDRESSES).computing(new ListOfHostAndPort()).build());
    enrichers()/*from   w  w  w  . ja  v  a 2s.c o m*/
            .add(Enrichers
                    .builder().transforming(COUCHBASE_CLUSTER_UP_NODE_ADDRESSES).from(
                            this)
                    .publishing(
                            COUCHBASE_CLUSTER_CONNECTION_URL)
                    .computing(
                            IfFunctions
                                    .<List<String>>ifPredicate(Predicates.compose(
                                            MathPredicates
                                                    .lessThan(getConfig(CouchbaseCluster.INITIAL_QUORUM_SIZE)),
                                            CollectionFunctionals.sizeFunction(0)))
                                    .value((String) null)
                                    .defaultApply(Functionals.chain(
                                            CollectionFunctionals.<String, List<String>>limit(4),
                                            StringFunctions.joiner(","),
                                            StringFunctions.formatter("http://%s/"))))
                    .build());

    Map<? extends AttributeSensor<? extends Number>, ? extends AttributeSensor<? extends Number>> enricherSetup = ImmutableMap
            .<AttributeSensor<? extends Number>, AttributeSensor<? extends Number>>builder()
            .put(CouchbaseNode.OPS, CouchbaseCluster.OPS_PER_NODE)
            .put(CouchbaseNode.COUCH_DOCS_DATA_SIZE, CouchbaseCluster.COUCH_DOCS_DATA_SIZE_PER_NODE)
            .put(CouchbaseNode.COUCH_DOCS_ACTUAL_DISK_SIZE,
                    CouchbaseCluster.COUCH_DOCS_ACTUAL_DISK_SIZE_PER_NODE)
            .put(CouchbaseNode.EP_BG_FETCHED, CouchbaseCluster.EP_BG_FETCHED_PER_NODE)
            .put(CouchbaseNode.MEM_USED, CouchbaseCluster.MEM_USED_PER_NODE)
            .put(CouchbaseNode.COUCH_VIEWS_ACTUAL_DISK_SIZE,
                    CouchbaseCluster.COUCH_VIEWS_ACTUAL_DISK_SIZE_PER_NODE)
            .put(CouchbaseNode.CURR_ITEMS, CouchbaseCluster.CURR_ITEMS_PER_NODE)
            .put(CouchbaseNode.VB_REPLICA_CURR_ITEMS, CouchbaseCluster.VB_REPLICA_CURR_ITEMS_PER_NODE)
            .put(CouchbaseNode.COUCH_VIEWS_DATA_SIZE, CouchbaseCluster.COUCH_VIEWS_DATA_SIZE_PER_NODE)
            .put(CouchbaseNode.GET_HITS, CouchbaseCluster.GET_HITS_PER_NODE)
            .put(CouchbaseNode.CMD_GET, CouchbaseCluster.CMD_GET_PER_NODE)
            .put(CouchbaseNode.CURR_ITEMS_TOT, CouchbaseCluster.CURR_ITEMS_TOT_PER_NODE).build();

    for (AttributeSensor<? extends Number> nodeSensor : enricherSetup.keySet()) {
        addSummingMemberEnricher(nodeSensor);
        addAveragingMemberEnricher(nodeSensor, enricherSetup.get(nodeSensor));
    }

    enrichers().add(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS)
            .from(IS_CLUSTER_INITIALIZED).computing(IfFunctions.ifNotEquals(true)
                    .value("The cluster is not yet completely initialized").defaultValue(null).build())
            .build());
}

From source file:forge.quest.BoosterUtils.java

private static void populateBalancedFilters(final List<Predicate<CardRules>> colorFilters,
        final List<Byte> preferredColors, final List<PaperCard> cardPool, final boolean includeArtifacts) {

    final List<Byte> otherColors = new ArrayList<>(possibleColors);
    otherColors.removeAll(preferredColors);

    int colorBias = FModel.getQuestPreferences().getPrefInt(QPref.STARTING_POOL_COLOR_BIAS);
    double preferredBias = 0;

    if (preferredColors.isEmpty()) {
        colorBias = 0;/* w  ww .  j a v a 2 s .  co  m*/
    } else {
        preferredBias = (double) colorBias / preferredColors.size();
    }

    int usedMulticolor = 0, usedPhyrexian = 0;

    for (int i = 0; i < MAX_BIAS; i++) {

        if (i < colorBias) {

            int index = (int) ((double) i / preferredBias);
            for (@SuppressWarnings("unused")
            Byte ignored : otherColors) {

                //Add artifacts here if there's no colorless selection
                if (i % 8 == 0 && !preferredColors.contains(MagicColor.COLORLESS) && includeArtifacts) {
                    colorFilters.add(CardRulesPredicates.Presets.IS_ARTIFACT);
                } else if (i % 5 == 0) {

                    //If colorless is the only color selected, add a small chance to get Phyrexian mana cost cards.
                    if (preferredColors.contains(MagicColor.COLORLESS) && preferredColors.size() == 1) {

                        Predicate<CardRules> predicateRules = CardRulesPredicates.cost(StringOp.CONTAINS_IC,
                                "p/");
                        Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules,
                                PaperCard.FN_GET_RULES);

                        int size = Iterables.size(Iterables.filter(cardPool, predicateCard));
                        int totalSize = cardPool.size();

                        double phyrexianAmount = (double) size / totalSize;
                        phyrexianAmount *= 125;

                        if (usedPhyrexian < Math.min(1, phyrexianAmount)) {
                            colorFilters.add(predicateRules);
                            usedPhyrexian++;
                            continue;
                        }

                    }

                    //Try to get multicolored cards that fit into the preferred colors.
                    Predicate<CardRules> predicateRules = Predicates.and(
                            CardRulesPredicates.isColor(preferredColors.get(index)),
                            CardRulesPredicates.Presets.IS_MULTICOLOR);
                    Predicate<PaperCard> predicateCard = Predicates.compose(predicateRules,
                            PaperCard.FN_GET_RULES);

                    //Adjust for the number of multicolored possibilities. This prevents flooding of non-selected
                    //colors if multicolored cards aren't in the selected sets. The more multi-colored cards in the
                    //sets, the more that will be selected.
                    if (usedMulticolor / 8 < Iterables.size(Iterables.filter(cardPool, predicateCard))) {
                        colorFilters.add(predicateRules);
                        usedMulticolor++;
                    } else {
                        //Exceeded multicolor-specific ratio, so here we add a more generic filter.
                        colorFilters.add(CardRulesPredicates.isColor(preferredColors.get(index)));
                    }

                } else {
                    colorFilters.add(CardRulesPredicates.isMonoColor(preferredColors.get(index)));
                }
            }

        } else {

            for (Byte color : otherColors) {
                if (i % 6 == 0) {
                    colorFilters.add(Predicates.and(CardRulesPredicates.isColor(color),
                            CardRulesPredicates.Presets.IS_MULTICOLOR));
                } else {
                    colorFilters.add(CardRulesPredicates.isMonoColor(color));
                }
            }

        }

    }

}

From source file:com.isotrol.impe3.api.DevicesInPortal.java

/**
 * Excludes one device from the collection.
 * @param deviceId Device id to exclude.
 * @return The filtered collection.//  w w  w.j  a va  2  s. com
 */
public final DevicesInPortal excludeDeviceId(UUID deviceId) {
    checkNotNull(deviceId, "Null devices not allowed");
    if (!containsDeviceId(deviceId)) {
        return this;
    }
    if (size() == 1) {
        return EMPTY;
    }
    return new Filter(this,
            Predicates.compose(not(equalTo(deviceId)), Functions.compose(Device.ID, DeviceInPortal.DEVICE)));
}

From source file:forge.deck.generation.DeckGeneratorBase.java

protected void adjustDeckSize(int targetSize) {
    // fix under-sized or over-sized decks, due to integer arithmetic
    int actualSize = tDeck.countAll();
    if (actualSize < targetSize) {
        addSome(targetSize - actualSize, tDeck.toFlatList());
    } else if (actualSize > targetSize) {
        Predicate<PaperCard> exceptBasicLand = Predicates
                .not(Predicates.compose(CardRulesPredicates.Presets.IS_BASIC_LAND, PaperCard.FN_GET_RULES));

        for (int i = 0; i < 3 && actualSize > targetSize; i++) {
            Iterable<PaperCard> matchingCards = Iterables.filter(tDeck.toFlatList(), exceptBasicLand);
            List<PaperCard> toRemove = Aggregates.random(matchingCards, actualSize - targetSize);
            tDeck.removeAllFlat(toRemove);

            for (PaperCard c : toRemove) {
                tmpDeck.append("Removed:").append(c.getName()).append("\n");
            }//  w  w  w.j a va  2s.  c o  m
            actualSize = tDeck.countAll();
        }
    }
}

From source file:org.apache.aurora.scheduler.storage.mem.MemTaskStore.java

private static Predicate<Task> queryFilter(Query.Builder query) {
    return Predicates.compose(Util.queryFilter(query), new Function<Task, IScheduledTask>() {
        @Override/*w  w w .j a  v a2 s.c o  m*/
        public IScheduledTask apply(Task canonicalTask) {
            return canonicalTask.storedTask;
        }
    });
}

From source file:clocker.mesos.entity.framework.MesosFrameworkImpl.java

public List<String> scanTasks(JsonArray frameworks) {
    String frameworkId = sensors().get(FRAMEWORK_ID);
    Entity mesosCluster = sensors().get(MESOS_CLUSTER);
    LOG.debug("Periodic scanning of framework tasks: frameworkId={}, mesosCluster={}", frameworkId,
            mesosCluster);/*from   ww  w  .j av  a2s .  c  o  m*/

    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject framework = frameworks.get(i).getAsJsonObject();
        if (frameworkId.equals(framework.get("id").getAsString())) {
            JsonArray completed = framework.getAsJsonArray("completed_tasks");
            JsonArray tasks = framework.getAsJsonArray("tasks");
            sensors().set(MESOS_COMPLETED_TASKS, completed.size());
            sensors().set(MESOS_RUNNING_TASKS, tasks.size());

            List<String> taskNames = MutableList.<String>of();
            for (int j = 0; j < tasks.size(); j++) {
                JsonObject json = tasks.get(j).getAsJsonObject();
                String id = json.get("id").getAsString();
                String name = json.get("name").getAsString();
                String state = json.get("state").getAsString();

                Optional<Entity> taskEntity = Iterables.tryFind(sensors().get(FRAMEWORK_TASKS).getMembers(),
                        Predicates.compose(Predicates.equalTo(id),
                                EntityFunctions.attribute(MesosTask.TASK_ID)));
                MesosTask task = null;
                if (taskEntity.isPresent()) {
                    // Only interested in tasks for our own use of Marathon.
                    // Tasks that other people create we'll ignore.
                    task = (MesosTask) taskEntity.get();
                }
                if (task != null) {
                    taskNames.add(name);
                    task.sensors().set(MesosTask.TASK_ID, id);
                    task.sensors().set(MesosTask.TASK_STATE, state);
                }
            }

            Set<String> taskNamesSet = Sets.newHashSet(taskNames);
            for (Entity member : ImmutableList.copyOf(getTaskCluster().getMembers())) {
                final String name = member.sensors().get(MesosTask.TASK_NAME);
                if (name != null) {
                    boolean found = taskNamesSet.contains(name);
                    if (found)
                        continue;
                }

                // Stop and then remove the task as it is no longer running, unless ON_FIRE
                //
                // TODO Aled worries about this: if task has gone, then MarathonTask polling
                // the task's URL will fail, setting the serviceUp to false, setting it 
                // on-fire. What will ever remove the task on a graceful shutdown of a container?
                // Or is that handled elsewhere?
                Lifecycle state = member.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    getTaskCluster().removeMember(member);
                    getTaskCluster().removeChild(member);
                    Entities.unmanage(member);
                } else {
                    ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
                }
            }
            return taskNames;
        }
    }
    // not found
    return null;
}

From source file:org.sosy_lab.cpachecker.core.algorithm.precondition.PreconditionHelper.java

private PredicateAbstractState getTargetAbstractionState(final ARGPath pPathToEntryLocation,
        final CFANode pTargetLocation) {

    Preconditions.checkNotNull(pTargetLocation);
    Preconditions.checkNotNull(pPathToEntryLocation);

    final List<ARGState> relevantStates = from(pPathToEntryLocation.asStatesList()).skip(1)
            .filter(Predicates.compose(PredicateAbstractState.FILTER_ABSTRACTION_STATES,
                    toState(PredicateAbstractState.class)))
            .filter(Predicates.compose(equalTo(pTargetLocation), AbstractStates.EXTRACT_LOCATION)).toList();

    Verify.verify(relevantStates.size() == 1);

    return AbstractStates.extractStateByType(relevantStates.get(0), PredicateAbstractState.class);
}

From source file:com.twitter.aurora.scheduler.periodic.Preempter.java

private static Predicate<AssignedTask> greaterPriorityFilter(int priority) {
    return Predicates.compose(greaterThan(priority), GET_PRIORITY);
}

From source file:com.rockhoppertech.music.examples.Guava.java

public static void funpred() {
    MIDITrack track = MIDITrackBuilder.create().noteString("C5 CS F FS E F4").build();

    final Predicate<MIDINote> trebleNote = new Predicate<MIDINote>() {
        public boolean apply(MIDINote n) {
            return n.getMidiNumber() > Pitch.C5;
        }/* w w  w  .j  av  a 2  s .  com*/
    };
    List<MIDINote> highNotes = Lists.newArrayList(Iterables.filter(track, trebleNote));
    // for (MIDINote note : highNotes) {
    // System.out.println(note);
    // }

    Predicate<MIDINote> high = new PitchGreaterThanPredicate(Pitch.C5);
    highNotes = Lists.newArrayList(Iterables.filter(track, high));
    for (MIDINote note : highNotes) {
        System.out.println(note);
    }

    // final List<MIDINote> highNotes =
    // Lists.immutableList(Iterables.filter(list, trebleNote));
    // ImmutableList<MIDINote> imlist =
    // ImmutableList.copyOf(Iterables.filter(list, high));
    //
    //
    final Function<MIDINote, MIDINote> transposeFunction = new Function<MIDINote, MIDINote>() {
        public MIDINote apply(MIDINote n) {
            n.setMidiNumber(n.getMidiNumber() + 1);
            return n;
        }
    };
    // Iterable<MIDINote> mni = Iterables.transform(Iterables.filter(list,
    // high), fun);

    final Function<MIDINote, Integer> tonums = new Function<MIDINote, Integer>() {
        @Override
        public Integer apply(MIDINote n) {
            return n.getMidiNumber();
        }
    };

    ImmutableList<Integer> imInts = ImmutableList
            .copyOf(Iterables.transform(Iterables.filter(track, high), tonums));
    for (Integer in : imInts) {
        System.out.println(in);
    }

    // Iterable i = Iterables.transform(Iterables.filter(Iterables.filter(
    // list, MIDINote.class), high), nameForNumber);

    Predicate<MIDINote> compose = Predicates.compose(new PitchGreaterThanPredicate(Pitch.C5),
            transposeFunction);
}

From source file:forge.deck.generation.DeckGeneratorBase.java

protected void addCmcAdjusted(Iterable<PaperCard> source, int cnt,
        List<ImmutablePair<FilterCMC, Integer>> cmcLevels) {
    int totalWeight = 0;
    for (ImmutablePair<FilterCMC, Integer> pair : cmcLevels) {
        totalWeight += pair.getRight();//w w  w  .  ja va2  s.co  m
    }

    float variability = 0.6f; // if set to 1, you'll get minimum cards to choose from
    float desiredWeight = (float) cnt / (maxDuplicates * variability);
    float desiredOverTotal = desiredWeight / totalWeight;
    float requestedOverTotal = (float) cnt / totalWeight;

    for (ImmutablePair<FilterCMC, Integer> pair : cmcLevels) {
        Iterable<PaperCard> matchingCards = Iterables.filter(source,
                Predicates.compose(pair.getLeft(), PaperCard.FN_GET_RULES));
        int cmcCountForPool = (int) Math.ceil(pair.getRight().intValue() * desiredOverTotal);

        int addOfThisCmc = Math.round(pair.getRight().intValue() * requestedOverTotal);
        tmpDeck.append(String.format("Adding %d cards for cmc range from a pool with %d cards:%n", addOfThisCmc,
                cmcCountForPool));

        final List<PaperCard> curved = Aggregates.random(matchingCards, cmcCountForPool);
        final List<PaperCard> curvedRandomized = Lists.newArrayList();
        for (PaperCard c : curved) {
            cardCounts.put(c.getName(), 0);
            curvedRandomized.add(pool.getCard(c.getName()));
        }

        addSome(addOfThisCmc, curvedRandomized);
    }
}