Example usage for com.google.common.collect Maps filterValues

List of usage examples for com.google.common.collect Maps filterValues

Introduction

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

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterValues(BiMap<K, V> unfiltered,
        final Predicate<? super V> valuePredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered whose values satisfy a predicate.

Usage

From source file:com.aionemu.gameserver.services.SiegeService.java

public Map<Integer, ArtifactLocation> getFortressArtifacts() {
    return Maps.filterValues(artifacts, new Predicate<ArtifactLocation>() {
        @Override/* ww  w .  j a  v a  2s.c o m*/
        public boolean apply(@Nullable ArtifactLocation input) {
            return input != null && input.getOwningFortress() != null;
        }
    });
}

From source file:com.cinchapi.concourse.server.storage.temp.Limbo.java

/**
 * Calculate the browsable view of {@code record} at {@code timestamp} using
 * prior {@code context} as if it were also a part of the Buffer.
 * //from w  ww  . ja v  a 2 s  .c o m
 * @param key
 * @param timestamp
 * @param context
 * @return a possibly empty Map of data
 */
public Map<String, Set<TObject>> select(long record, long timestamp, Map<String, Set<TObject>> context) {
    if (timestamp >= getOldestWriteTimestamp()) {
        for (Iterator<Write> it = iterator(); it.hasNext();) {
            Write write = it.next();
            if (write.getRecord().longValue() == record && write.getVersion() <= timestamp) {
                Set<TObject> values;
                values = context.get(write.getKey().toString());
                if (values == null) {
                    values = Sets.newHashSet();
                    context.put(write.getKey().toString(), values);
                }
                if (write.getType() == Action.ADD) {
                    values.add(write.getValue().getTObject());
                } else {
                    values.remove(write.getValue().getTObject());
                }
            } else if (write.getVersion() > timestamp) {
                break;
            } else {
                continue;
            }
        }
    }
    return Maps.newTreeMap((SortedMap<String, Set<TObject>>) Maps.filterValues(context, emptySetFilter));
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

@Override
public Map<Cell, byte[]> get(String tableName, Set<Cell> cells) {
    Stopwatch watch = Stopwatch.createStarted();
    checkGetPreconditions(tableName);//  w  w w . j  a va 2 s  .c o  m
    if (Iterables.isEmpty(cells)) {
        return ImmutableMap.of();
    }

    Map<Cell, byte[]> result = Maps.newHashMap();
    SortedMap<Cell, byte[]> writes = writesByTable.get(tableName);
    if (writes != null) {
        for (Cell cell : cells) {
            if (writes.containsKey(cell)) {
                result.put(cell, writes.get(cell));
            }
        }
    }

    // We don't need to read any cells that were written locally.
    result.putAll(getFromKeyValueService(tableName, Sets.difference(cells, result.keySet())));

    if (perfLogger.isDebugEnabled()) {
        perfLogger.debug("get({}, {} cells) found {} cells (some possibly deleted), took {} ms", tableName,
                cells.size(), result.size(), watch.elapsed(TimeUnit.MILLISECONDS));
    }
    validateExternalAndCommitLocksIfNecessary(tableName);
    return Maps.filterValues(result, Predicates.not(Value.IS_EMPTY));
}

From source file:org.opentestsystem.delivery.testadmin.scheduling.SchedulerHelper.java

/**
 * Generic allocation algorithm used when no other affinities or priorities are in effect.
 * Be aware that the actual scheduling modifies the Schedule argument passed into this function
 * /*  w  w w  .  ja  v  a2 s .c  om*/
 * @param scheduled
 */
public void allocateAll(final Schedule scheduled, final List<Assessment> assessments,
        final Map<String, ScheduledStudent> studentsScheduled,
        final HashMultimap<String, Assessment> gradesToAssessments, final boolean reschedule) {
    // look at the students that still need to be scheduled, do any of them require accommodations?
    // -- if so then determine the distinct assessments those students need to be scheduled for
    // ---- get next assessment
    // ------ get next time slot with empty seats
    // -------- are there still students with accommodations to be allocated?
    // ---------- if yes then, are there any empty seats with accessibility equipment?
    // ------------ if yes then run accessibility rules to see if equipment matches up with students that need
    // accommodations
    // -------------- does equipment match up?
    // ---------------- if yes, then allocate the student to the seat, get next seat and repeat
    // ---------------- if no, then get next seat and repeat
    // ------------ if no then get next time slot and repeat
    // ---------- if no, then are there other students for this assessment that need to be scheduled?
    // ------------ if yes then allocate students to any empty seats, loop back to students with accommodations
    // check
    // ------------ if no, then loop back to get next assessment
    // -- when no students are left to schedule, then done

    Map<String, ScheduledStudent> studentsToBeScheduled = null;

    // for assessment in assessments

    for (final Assessment curAssessment : assessments) {

        // guava filter to get ScheduledStudents that need to be scheduled for assessment

        studentsToBeScheduled = ImmutableMap
                .copyOf(Maps.filterValues(studentsScheduled, new Predicate<ScheduledStudent>() {
                    @Override
                    public boolean apply(final ScheduledStudent schedStudent) {
                        return schedStudent.isEligibleForAssessment(curAssessment)
                                && !schedStudent.isStudentScheduled(curAssessment);
                    }
                }));

        // get ordered time slot itr
        final TreeSet<ScheduledTimeSlot> timeSlots = scheduled.getOrderedTimeSlots(reschedule);

        // for each time slot
        for (final ScheduledTimeSlot nextTimeSlot : timeSlots) {
            // if there are no students to schedule for assessment anymore, then break here
            if (allStudentsScheduled(studentsToBeScheduled)) {
                break;
            }

            // if time slot has no affinities we can schedule
            // if time slot has affinities and no strict affinity was scheduled, then we can schedule
            // if time slot has affinities and a strict affinity was scheduled, then if the assessment matches the
            // affinity, we can schedule

            final boolean canSchedule = nextTimeSlot.isStrictAffinityScheduled()
                    && doesAssessmentFulfillAffinity(nextTimeSlot, curAssessment, gradesToAssessments)
                    || !nextTimeSlot.isStrictAffinityScheduled();

            if (canSchedule) {

                // get unscheduled seats with equipment
                final Set<ScheduledSeat> seatsWithEquipment = nextTimeSlot
                        .getUnscheduledSeatsWithAccessbilityEquip();

                // for each seat with equipment
                for (final ScheduledSeat nextSeatWithEquip : seatsWithEquipment) {
                    // for each student
                    for (final ScheduledStudent studentToSchedule : studentsToBeScheduled.values()) {

                        // does the seat have accessiblity equipment objects loaded yet?
                        // if not, load them
                        // if so, skip the load and continue
                        loadAccessibilityEquipmentObj(nextSeatWithEquip);

                        // if not scheduled for assessment && able to use seat equipment?
                        if (!studentToSchedule.isStudentScheduled(curAssessment)
                                && studentToSchedule.canUseAccessibilityEquipment(
                                        nextSeatWithEquip.getAccessibilityEquipmentObjs(), curAssessment)) {
                            // then schedule for seat
                            final boolean assigned = assignStudentToSeat(nextTimeSlot, curAssessment,
                                    nextSeatWithEquip, Lists.newArrayList(studentToSchedule),
                                    scheduled.getId());

                            if (assigned) {
                                studentToSchedule.scheduledToEquipment(curAssessment,
                                        nextSeatWithEquip.getAccessibilityEquipmentObjs());
                            }

                            // break
                            break;
                        }

                    }

                } // end iteration of seats with equipment

                // we have scheduled any students that qualify for seats with equipment
                // now add any student to any seat

                // get all unscheduled seats
                final Set<ScheduledSeat> unscheduledSeats = nextTimeSlot.getAllUnscheduledSeats();

                // for each seat
                for (final ScheduledSeat nextSeat : unscheduledSeats) {
                    // for each student
                    for (final ScheduledStudent studentToSchedule : studentsToBeScheduled.values()) {
                        // if student not scheduled for assessment
                        if (!studentToSchedule.isStudentScheduled(curAssessment)) {
                            // then schedule for seat
                            assignStudentToSeat(nextTimeSlot, curAssessment, nextSeat,
                                    Lists.newArrayList(studentToSchedule), scheduled.getId());
                            // break
                            break;
                        }
                    }
                }
            }
        }
    }
}

From source file:org.tzi.use.uml.mm.MModel.java

/**
 * Returns all loaded invariants.//from  w  ww.  jav  a 2  s  . c  o m
 */
public Collection<MClassInvariant> getLoadedClassInvariants() {
    return Maps.filterValues(fClassInvariants, new Predicate<MClassInvariant>() {
        @Override
        public boolean apply(MClassInvariant inv) {
            return inv.isLoaded();
        }
    }).values();
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

@Override
public Map<Cell, byte[]> getIgnoringLocalWrites(String tableName, Set<Cell> cells) {
    checkGetPreconditions(tableName);//from  w w  w . j av a2s.  c  o m
    if (Iterables.isEmpty(cells)) {
        return ImmutableMap.of();
    }

    Map<Cell, byte[]> result = getFromKeyValueService(tableName, cells);

    return Maps.filterValues(result, Predicates.not(Value.IS_EMPTY));
}

From source file:com.cinchapi.concourse.server.storage.temp.Buffer.java

@Override
public Set<String> describe(long record, long timestamp, Map<String, Set<TObject>> context) {
    for (Iterator<Write> it = iterator(record, timestamp); it.hasNext();) {
        Write write = it.next();//from w ww  .j a v  a  2s  .  co  m
        Set<TObject> values;
        values = context.get(write.getKey().toString());
        if (values == null) {
            values = Sets.newHashSet();
            context.put(write.getKey().toString(), values);
        }
        if (write.getType() == Action.ADD) {
            values.add(write.getValue().getTObject());
        } else {
            values.remove(write.getValue().getTObject());
        }
    }
    return newLinkedHashMap(Maps.filterValues(context, emptySetFilter)).keySet();
}

From source file:brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from  www .  j a v a 2  s  .com
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    setAttribute(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX).objectName(storageServiceMBean)
                    .attributeName("Initialized").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onException(Functions.constant(false)))
            .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Set<BigInteger>>() {
                        @Override
                        public Set<BigInteger> apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            Set<BigInteger> result = Sets.newLinkedHashSet();
                            for (String token : tokens) {
                                result.add(new BigInteger(token));
                            }
                            return result;
                        }
                    }).onException(Functions.<Set<BigInteger>>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<BigInteger>(TOKEN).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, BigInteger>() {
                        @Override
                        public BigInteger apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            // TODO remove duplication from setting TOKENS
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            String token = Iterables.getFirst(tokens, null);
                            return (token != null) ? new BigInteger(token) : null;
                        }
                    }).onException(Functions.<BigInteger>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getDatacenter")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getRack")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                    .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            List input = (List) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .build();

    functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
            .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                    .onException(Functions.constant((Long) null)).callable(new Callable<Long>() {
                        public Long call() {
                            try {
                                long start = System.currentTimeMillis();
                                Socket s = new Socket(getAttribute(Attributes.HOSTNAME), getThriftPort());
                                s.close();
                                long latency = System.currentTimeMillis() - start;
                                computeServiceUp();
                                return latency;
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Cassandra thrift port poll failure: " + e);
                                setAttribute(SERVICE_UP, false);
                                return null;
                            }
                        }

                        public void computeServiceUp() {
                            // this will wait an additional poll period after thrift port is up,
                            // as the caller will not have set yet, but that will help ensure it is really healthy!
                            setAttribute(SERVICE_UP,
                                    getAttribute(THRIFT_PORT_LATENCY) != null
                                            && getAttribute(THRIFT_PORT_LATENCY) >= 0
                                            && Boolean.TRUE.equals(getAttribute(SERVICE_UP_JMX)));
                        }
                    }))
            .build();

    jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
}

From source file:com.android.builder.internal.packaging.DexIncrementalRenameManager.java

/**
 * Updates the state of the manager with file changes.
 *
 * @param files the files that have changed
 * @return the changed in the packaged files
 * @throws IOException failed to process the changes
 *///ww w.ja v  a2  s .c  o  m
@NonNull
Set<PackagedFileUpdate> update(@NonNull ImmutableMap<RelativeFile, FileStatus> files) throws IOException {
    /*
     * This describes the algorithm to update the files. This algorithm:
     * - (1) Generates the minimal number of PackagedFileUpdates
     * - (2) Ensures that the data that results from making the updates does not contain any
     * gaps in the dex sequences as defined by DexFileNameSupplier.
     * - (3) If at least one of the input files is "classes.dex", that input file will be
     * mapped to "classes.dex".
     *
     * To explain the algorithm, we describe all steps and follow 3 different scenarios, whose
     * initial conditions are:
     * == Scenario S1 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex, FileC -> classes3.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     * == Scenario S2 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes3.dex, FileC -> classes3.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     * == Scenario S3 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *
     *
     * 1. We start by getting all names in the order defined by the DexFileNameSupplier and
     * put all names that are in the map in "nameList".
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex, FileC -> classes3.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex, FileC -> classes3.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     * == Scenario S3 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex ]
     *
     *
     * 2. For every deleted file in the set, we remove it from the name map and keep its
     * name in "deletedNames". Put the file/name map in "deletedFiles".
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileC -> classes3.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes.dex, classes2.dex ]
     *     - deletedFiles = { classes.dex -> FileA, classes2 -> FileB }
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes2.dex ]
     *     - deletedFiles = { classes2 -> FileB }
     * == Scenario S3 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *
     *
     * 3. For every added file in the set, we add it to newFiles. If any of the new files is
     * named "classes.dex" is it added to the beginning of newFiles and the addingClassesDex
     * is set to true.
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileC -> classes3.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes.dex, classes2.dex ]
     *     - deletedFiles = { classes.dex -> FileA, classes2 -> FileB }
     *     - newFiles = [ FileD ]
     *     - addingClassesDex = false
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes2.dex ]
     *     - deletedFiles = { classes2 -> FileB }
     *     - newFiles = [ FileD, FileE]
     *     - addingClassesDex = false
     * == Scenario S3 ==
     *     - mNameMap = { FileA -> classes.dex, FileB -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = [ classes.dex ]
     *     - addingClassesDex = true
     *
     *
     * 4.If addingClassesDex is true, mNameMap contains a mapping for classes.dex and the file
     * it is mapped from is not classes.dex, remove it from the mapping and add it to
     * newFiles. Also, add "classes.dex" to "deletedNames".
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileC -> classes3.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes.dex, classes2.dex ]
     *     - deletedFiles = { classes.dex -> FileA, classes2 -> FileB }
     *     - newFiles = [ FileD ]
     *     - addingClassesDex = false
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes2.dex ]
     *     - deletedFiles = { classes2 -> FileB }
     *     - newFiles = []
     *     - addingClassesDex = false
     * == Scenario S3 ==
     *     - mNameMap = { FileB -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex ]
     *     - deletedNames = [ classes.dex ]
     *     - deletedFiles = {}
     *     - newFiles = [ classes.dex, FileA ]
     *     - addingClassesDex = true
     *
     *
     * 5. For every added file in the set, we add it to the name map using names from
     * "deletedNames", if possible. If a name is used from "deletedNames", we remove it from
     * "deletedNames" and add it to "updatedNames". If no name is available in "deletedNames",
     * we fetch a new name and add it to "addedNames". If we need to fetch new names, we also
     * add them to "nameList". If we remove entries from "deletedNames", we also remove it
     * from "deletedFiles".
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileC -> classes3.dex, FileD -> classes.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes2.dex ]
     *     - deletedFiles = { classes2 -> FileB }
     *     - newFiles = [ FileD ]
     *     - addingClassesDex = false
     *     - updatedNames = { classes.dex }
     *     - addedNames = {}
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex, FileD -> classes2.dex,
      *                     FileE -> classes4.dex }
     *     - files = { FileB: removed, FileC: updated, FileD -> new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex, classes4.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = []
     *     - addingClassesDex = false
     *     - updatedNames = { classes2.dex }
     *     - addedNames = { classes4.dex }
     * == Scenario S3 ==
     *     - mNameMap = { FileB -> classes2.dex, classes.dex -> classes.dex,
     *          FileA -> classes3.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = [ classes.dex, FileA ]
     *     - addingClassesDex = true
     *     - updatedNames = { classes.dex }
     *     - addedNames = { classes3.dex }
     *
     *
     * 6. For every updated file in the set, we search for it in the name map
     * and add it to "updatedNames".
     *
     * == Scenario 1 ==
     *     - mNameMap = { FileC -> classes3.dex, FileD -> classes.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = [ classes2.dex ]
     *     - deletedFiles = { classes2 -> FileB }
     *     - newFiles = [ FileD ]
     *     - addingClassesDex = false
     *     - updatedNames = { classes.dex, classes3.dex }
     *     - addedNames = {}
     * == Scenario 2 ==
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex, FileD -> classes2.dex,
      *                     FileE -> classes4.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex, classes4.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = []
     *     - addingClassesDex = false
     *     - updatedNames = { classes2.dex, classes3.dex }
     *     - addedNames = { classes4.dex }
     * == Scenario S3 ==
     *     - mNameMap = { FileB -> classes2.dex, classes.dex -> classes.dex,
     *          FileA -> classes3.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = [ classes.dex, FileA ]
     *     - addingClassesDex = true
     *     - updatedNames = { classes.dex }
     *     - addedNames = { classes3.dex }
     *
     *
     * 7. Do one of the following:
     * 7.1. If "deletedNames" is empty, we end step 5.
     * 7.2. If the last item of "deletedNames" matches the last name in "nameList", we move it
     * to "finalDeletedNames". We also remove the last name in "nameList". Restart step 5.
     * 7.3. Do the following:
     * - Move the last entry in "nameList" to "finallyDeletedNames" and copy the corresponding
     * entry from mNameMap to deletedFiles.
     * - Rename the name of the file in "mNameMap" corresponding to the moved item of
     * "nameList" to the first position of "deletedNames".
     * - Move the name in the first position of "deletedNames" to "updatedNames".
     * - If the last item from "nameList" that was removed existed in "updatedNames", remove it
     * from "updatedNames".
     * - Restart step 7.
     *
     * == Scenario 1 ==
     *     (after executing 7.3 and then 7.1):
     *     - mNameMap = { FileC -> classes2.dex, FileD -> classes.dex }
     *     - files = { FileA: removed, FileB: removed, FileC: updated, FileD: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex ]
     *     - deletedNames = []
     *     - deletedFiles = { classes2 -> FileB, classes3.dex -> FileC }
     *     - newFiles = [ FileD ]
     *     - addingClassesDex = false
     *     - updatedNames = { classes.dex, classes2.dex }
     *     - addedNames = {}
     *     - finallyDeletedNames = { classes3.dex }
     * == Scenario 2 ==
     *     (after executing 7.1):
     *     - mNameMap = { FileA -> classes.dex, FileC -> classes3.dex, FileD -> classes2.dex,
     *                     FileE -> classes4.dex }
     *     - files = { FileB: removed, FileC: updated, FileD: new, FileE: new }
     *     - nameList = [ classes.dex, classes2.dex, classes3.dex, classes4.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = []
     *     - addingClassesDex = false
     *     - updatedNames = { classes2.dex, classes3.dex }
     *     - addedNames = { classes4.dex }
     *     - finallyDeletedNames = {}
     * == Scenario S3 ==
     *     (after executing 7.1):
     *     - mNameMap = { FileB -> classes2.dex, classes.dex -> classes.dex,
     *          FileA -> classes2.dex }
     *     - files = { classes.dex: new, FileB: updated }
     *     - nameList = [ classes.dex, classes2.dex ]
     *     - deletedNames = []
     *     - deletedFiles = {}
     *     - newFiles = [ classes.dex, FileA ]
     *     - addingClassesDex = true
     *     - updatedNames = { classes.dex }
     *     - addedNames = { classes3.dex }
     *
     * 8. Build the final list with the changes defined in "addedNames", "updatedNames" and
     * "finallyDeletedNames".
     */

    /*
     * Step 1.
     */
    Deque<String> nameList = Lists.newLinkedList();
    DexFileNameSupplier nameSupplier = new DexFileNameSupplier();
    for (int i = 0; i < mNameMap.size(); i++) {
        String nextName = nameSupplier.get();
        nameList.add(nextName);
        Verify.verify(mNameMap.containsValue(nextName), "mNameMap does not contain '" + nextName
                + "', but has a total of " + mNameMap.size() + " entries {mNameMap = " + mNameMap + "}");
    }

    /*
     * Step 2.
     *
     * Make sure that classes.dex, if it was removed, is the first in the deletedNames.
     */
    Deque<String> deletedNames = Lists.newLinkedList();
    Map<String, RelativeFile> deletedFiles = Maps.newHashMap();
    for (RelativeFile deletedRf : Maps.filterValues(files, Predicates.equalTo(FileStatus.REMOVED)).keySet()) {
        String deletedName = mNameMap.get(deletedRf);
        if (deletedName == null) {
            throw new IOException("Incremental update refers to relative file '" + deletedRf
                    + "' as deleted, but this file is not known.");
        }

        if (deletedName.equals(SdkConstants.FN_APK_CLASSES_DEX)) {
            deletedNames.addFirst(deletedName);
        } else {
            deletedNames.add(deletedName);
        }

        deletedFiles.put(deletedName, deletedRf);
        mNameMap.remove(deletedRf);
    }

    /*
     * Step 3.
     */
    AtomicBoolean addingClassesDex = new AtomicBoolean(false);
    Deque<RelativeFile> addedFiles = Lists.newLinkedList(
            Maps.filterValues(files, Predicates.equalTo(FileStatus.NEW)).keySet().stream().peek(rf -> {
                if (getOsIndependentFileName(rf).equals(SdkConstants.FN_APK_CLASSES_DEX)) {
                    addingClassesDex.set(true);

                }
            }).sorted(new DexNameComparator()).collect(Collectors.toList()));

    /*
     * Step 4.
     */
    if (addingClassesDex.get()) {
        RelativeFile mappingToClassesDex = mNameMap.inverse().get(SdkConstants.FN_APK_CLASSES_DEX);
        if (mappingToClassesDex != null) {
            if (!getOsIndependentFileName(mappingToClassesDex).equals(SdkConstants.FN_APK_CLASSES_DEX)) {
                /*
                 * If we get here is because we're adding a file named "classes.dex" and the
                 * current file that maps to "classes.dex" is not named "classes.dex". We
                 * prefer having "classes.dex" mapping to "classes.dex".
                 */
                mNameMap.remove(mappingToClassesDex);
                addedFiles.add(mappingToClassesDex);
                deletedNames.add(SdkConstants.FN_APK_CLASSES_DEX);
            }
        }
    }

    /*
     * Step 5.
     */
    Set<String> addedNames = Sets.newHashSet();
    Set<String> updatedNames = Sets.newHashSet();
    Iterator<String> deletedNamesIterator = deletedNames.iterator();
    for (RelativeFile addedRf : addedFiles) {
        if (deletedNamesIterator.hasNext()) {
            String toUse = deletedNamesIterator.next();
            deletedNamesIterator.remove();
            deletedFiles.remove(toUse);
            updatedNames.add(toUse);
            mNameMap.put(addedRf, toUse);
        } else {
            String addedName = nameSupplier.get();
            addedNames.add(addedName);
            nameList.add(addedName);
            mNameMap.put(addedRf, addedName);
        }
    }

    /*
     * Step 6.
     */
    for (RelativeFile updatedRf : Maps.filterValues(files, Predicates.equalTo(FileStatus.CHANGED)).keySet()) {
        String updatedName = mNameMap.get(updatedRf);
        if (updatedName == null) {
            throw new IOException("Incremental update refers to relative file '" + updatedRf
                    + "' as updated, but this file is not known.");
        }

        updatedNames.add(updatedName);
    }

    /*
     * Step 7.
     */
    Set<String> finallyDeletedNames = Sets.newHashSet();
    while (true) {
        /*
         * Step 7.1.
         */
        if (deletedNames.isEmpty()) {
            break;
        }

        /*
         * Step 7.2.
         */
        if (deletedNames.getLast().equals(nameList.getLast())) {
            nameList.removeLast();
            finallyDeletedNames.add(deletedNames.removeLast());
            continue;
        }

        /*
         * Step 7.3.
         */
        String lastInNames = nameList.removeLast();
        String firstInDeleted = deletedNames.remove();

        finallyDeletedNames.add(lastInNames);
        updatedNames.remove(lastInNames);
        updatedNames.add(firstInDeleted);

        RelativeFile file = mNameMap.inverse().get(lastInNames);
        Verify.verifyNotNull(file, "file == null");
        mNameMap.put(file, firstInDeleted);
        deletedFiles.put(lastInNames, file);
    }

    /*
     * Step 8.
     */
    Set<PackagedFileUpdate> updates = Sets.newHashSet();
    for (String addedName : addedNames) {
        RelativeFile file = Verify.verifyNotNull(mNameMap.inverse().get(addedName));
        updates.add(new PackagedFileUpdate(file, addedName, FileStatus.NEW));
    }

    for (String updatedName : updatedNames) {
        RelativeFile file = Verify.verifyNotNull(mNameMap.inverse().get(updatedName));
        updates.add(new PackagedFileUpdate(file, updatedName, FileStatus.CHANGED));

    }

    for (String deletedName : finallyDeletedNames) {
        RelativeFile file = Verify.verifyNotNull(deletedFiles.get(deletedName));
        updates.add(new PackagedFileUpdate(file, deletedName, FileStatus.REMOVED));
    }

    /*
     * Phew! We're done! Yey!
     */
    return updates;
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from  www .  j a  v  a 2 s  .c om
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    sensors().set(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    if (getDriver().isJmxEnabled()) {
        jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
                .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX)
                        .objectName(storageServiceMBean).attributeName("Initialized")
                        .onSuccess(Functions.forPredicate(Predicates.notNull()))
                        .onException(Functions.constant(false)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS)
                        .objectName(storageServiceMBean).attributeName("TokenToEndpointMap")
                        .onSuccess(new Function<Object, Set<BigInteger>>() {
                            @Override
                            public Set<BigInteger> apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return null;
                                // FIXME does not work on aws-ec2, uses RFC1918 address
                                Predicate<String> self = Predicates
                                        .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                                getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                                Set<String> tokens = Maps.filterValues(input, self).keySet();
                                Set<BigInteger> result = Sets.newLinkedHashSet();
                                for (String token : tokens) {
                                    result.add(new BigInteger(token));
                                }
                                return result;
                            }
                        }).onException(Functions.<Set<BigInteger>>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getDatacenter")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getRack")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                        .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                            @Override
                            public Integer apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return 0;
                                return input.size();
                            }
                        }).onException(Functions.constant(-1)))
                .pollAttribute(
                        new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                                .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                                    @Override
                                    public Integer apply(@Nullable Object arg) {
                                        List input = (List) arg;
                                        if (input == null || input.isEmpty())
                                            return 0;
                                        return input.size();
                                    }
                                }).onException(Functions.constant(-1)))
                .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .build();

        jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
    }

    if (Boolean.TRUE.equals(getConfig(USE_THRIFT_MONITORING))) {
        functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
                .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                        .onException(Functions.constant(-1L))
                        .callable(new ThriftLatencyChecker(CassandraNodeImpl.this))
                        .enabled(retrieveUsageMetrics))
                .build();
    }

    connectServiceUpIsRunning();
}