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.google.security.zynamics.binnavi.disassembly.types.TypeInstanceContainerBackend.java

/**
 * Load all type instances from the database.
 *
 * @return A {@link Set} of {@link TypeInstance} associated to the {@link INaviModule} the
 *         {@link TypeInstanceContainerBackend} is associated to.
 *
 * @throws CouldntLoadDataException if the {@link Set} of {@link TypeInstance} could not be loaded
 *         from the database./*  ww  w.  j av a  2 s . c  o  m*/
 */
public Set<TypeInstance> loadTypeInstances() throws CouldntLoadDataException {
    final List<RawTypeInstance> rawInstances = provider.loadTypeInstances(module);
    final HashMap<TypeInstance, Integer> instanceToComment = Maps.newHashMap();

    for (final RawTypeInstance rawInstance : rawInstances) {
        final BaseType baseType = typeManager.getBaseType(rawInstance.getTypeId());
        final Section section = sectionContainer.getSection(rawInstance.getSectionId());
        final TypeInstance typeInstance = new TypeInstance(rawInstance.getId(), rawInstance.getName(), baseType,
                section, rawInstance.getSectionOffset(), module);
        instanceToComment.put(typeInstance, rawInstance.getCommentId());
        instancesById.put(typeInstance.getId(), typeInstance);
    }

    final Map<TypeInstance, Integer> typeInstanceWithComment = Maps.filterValues(instanceToComment,
            new Predicate<Integer>() {
                @Override
                public boolean apply(final Integer commentId) {
                    return commentId != null;
                }
            });

    final CommentManager manager = CommentManager.get(provider);
    final HashMap<Integer, ArrayList<IComment>> typeInstanceTocomments = provider
            .loadMultipleCommentsById(typeInstanceWithComment.values());
    for (final Entry<TypeInstance, Integer> entry : typeInstanceWithComment.entrySet()) {
        manager.initializeTypeInstanceComment(entry.getKey(), typeInstanceTocomments.get(entry.getValue()));
    }

    return instanceToComment.keySet();
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

/**
 * Obtains all changed inputs of a given input set. Given a set of files mapped to their
 * changed status, this method returns a list of changes computed as follows:
 *
 * <ol>//from   w  w  w. ja v a 2s  .c  om
 *     <li>Changed inputs are split into deleted and non-deleted inputs. This separation is
 *     needed because deleted inputs may no longer be mappable to any {@link InputSet} just
 *     by looking at the file path, without using {@link KnownFilesSaveData}.
 *     <li>Deleted inputs are filtered through {@link KnownFilesSaveData} to get only those
 *     whose input set matches {@code inputSet}.
 *     <li>Non-deleted inputs are processed through
 *     {@link IncrementalRelativeFileSets#makeFromBaseFiles(Collection, Map, FileCacheByPath)}
 *     to obtain the incremental file changes.
 *     <li>The results of processed deleted and non-deleted are merged and returned.
 * </ol>
 *
 * @param changedInputs all changed inputs
 * @param saveData the save data with all input sets from last run
 * @param inputSet the input set to filter
 * @param baseFiles the base files of the input set
 * @param cacheByPath where to cache files
 * @return the status of all relative files in the input set
 */
@NonNull
private ImmutableMap<RelativeFile, FileStatus> getChangedInputs(@NonNull Map<File, FileStatus> changedInputs,
        @NonNull KnownFilesSaveData saveData, @NonNull InputSet inputSet, @NonNull Collection<File> baseFiles,
        @NonNull FileCacheByPath cacheByPath) throws IOException {

    /*
     * Figure out changes to deleted files.
     */
    Set<File> deletedFiles = Maps.filterValues(changedInputs, Predicates.equalTo(FileStatus.REMOVED)).keySet();
    Set<RelativeFile> deletedRelativeFiles = saveData.find(deletedFiles, inputSet);

    /*
     * Figure out changes to non-deleted files.
     */
    Map<File, FileStatus> nonDeletedFiles = Maps.filterValues(changedInputs,
            Predicates.not(Predicates.equalTo(FileStatus.REMOVED)));
    Map<RelativeFile, FileStatus> nonDeletedRelativeFiles = IncrementalRelativeFileSets
            .makeFromBaseFiles(baseFiles, nonDeletedFiles, cacheByPath);

    /*
     * Merge everything.
     */
    return new ImmutableMap.Builder<RelativeFile, FileStatus>()
            .putAll(Maps.asMap(deletedRelativeFiles, Functions.constant(FileStatus.REMOVED)))
            .putAll(nonDeletedRelativeFiles).build();
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves an immutable map {@link Map} whose entries come from the provided
 * map where the entries' value is an instance of the provided {@link Class}.
 * /*w  ww . j a  v a  2s  . c o m*/
 * @param m
 *          The map whose entries will be used to construct a filtered map
 *          according to the provided class.
 * @param clazz
 *          The class for filtering the provided map.
 * @return an immutable {@link Map}.
 */
public <V, T> Map<String, T> filter(final Map<String, V> m, final Class<T> clazz) {
    return Maps.transformValues(Maps.filterValues(m, new Predicate<V>() {
        @Override
        public boolean apply(@Nullable final V input) {
            if (input != null) {
                return clazz.isAssignableFrom(input.getClass());
            } else {
                return false;
            }
        }
    }), new Function<V, T>() {
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public T apply(@Nullable final V input) {
            return (T) input;
        }
    });
}

From source file:org.apache.curator.framework.recipes.cache.PathChildrenCache.java

private boolean hasUninitialized(Map<String, ChildData> localInitialSet) {
    if (localInitialSet == null) {
        return false;
    }//from  www .ja va  2 s .co m

    Map<String, ChildData> uninitializedChildren = Maps.filterValues(localInitialSet,
            new Predicate<ChildData>() {
                @Override
                public boolean apply(ChildData input) {
                    return (input == NULL_CHILD_DATA); // check against ref intentional
                }
            });
    return (uninitializedChildren.size() != 0);
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves an immutable map {@link Map} whose entries come from the provided
 * map where the entries' value's second element is an instance of the
 * provided {@link Class}.//from   w  w  w . j  a v a 2s . co m
 * 
 * @param m
 *          The map whose entries will be used to construct a filtered map
 *          according to the provided class.
 * @param clazz
 *          The class for filtering the provided map.
 * @return an immutable {@link Map}.
 */
public <V, T> Map<String, Pair<Feature, T>> filterp(final Map<String, Pair<Feature, V>> m,
        final Class<T> clazz) {
    return Maps.transformValues(Maps.filterValues(m, new Predicate<Pair<Feature, V>>() {
        @Override
        public boolean apply(@Nullable final Pair<Feature, V> input) {
            if (input != null) {
                return clazz.isAssignableFrom(input.getRight().getClass());
            } else {
                return false;
            }
        }
    }), new Function<Pair<Feature, V>, Pair<Feature, T>>() {
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public Pair<Feature, T> apply(@Nullable final Pair<Feature, V> input) {
            return ImmutablePair.of(input.getLeft(), (T) input.getRight());
        }
    });
}

From source file:ibw.updater.common.config.Configuration.java

/**
 * Initialize./*from ww w.j av  a  2s  .co m*/
 *
 * @param props
 *            the props
 * @param clear
 *            the clear
 */
public synchronized void initialize(Map<String, String> props, boolean clear) {
    HashMap<String, String> copy = new HashMap<>(props);
    copy.remove(null);
    if (clear) {
        getBaseProperties().clear();
    } else {
        Map<String, String> nullValues = Maps.filterValues(copy, Predicates.<String>isNull());
        for (String key : nullValues.keySet()) {
            getBaseProperties().remove(key);
        }
    }
    Map<String, String> notNullValues = Maps.filterValues(copy, Predicates.notNull());
    for (Entry<String, String> entry : notNullValues.entrySet()) {
        getBaseProperties().setProperty(entry.getKey(), entry.getValue());
    }
    resolveProperties();
    debug();
}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

private View diffEditorView(final PageReference page, final String customMessage,
        final HttpServletRequest request) throws PageStoreException, InvalidInputException {
    VersionedPageInfo pageInfo = _store.getUnderlying().tryToLock(page);
    String message;//w  w  w. ja  v a 2  s  .  c o m
    final String content = getContent(request);
    final String newContent = pageInfo.getContent();
    pageInfo = pageInfo.withAlternativeContent(content);
    request.setAttribute(ATTR_MARKED_UP_DIFF, _diffGenerator.getDiffMarkup(newContent, content));
    if (pageInfo.isLocked()
            && !pageInfo.isNewOrLockedByUser((String) request.getAttribute(RequestAttributes.USERNAME))) {
        message = "Page was locked by " + pageInfo.getLockedBy() + " on " + pageInfo.getLockedSince() + ".";
        pageInfo = pageInfo.withoutLockToken();
    } else {
        message = "Lock was lost!";
    }
    if (customMessage != null) {
        message = customMessage;
    }
    request.setAttribute(ATTR_ORIGINAL_ATTRIBUTES, pageInfo.getAttributes());
    pageInfo = pageInfo
            .withAlternativeAttributes(Maps.filterValues(getAttributes(request), new Predicate<String>() {
                public boolean apply(final String value) {
                    if (value == null) {
                        return false;
                    }
                    return true;
                }
            }));
    request.setAttribute(ATTR_PAGE_INFO, pageInfo);
    request.setAttribute("flash", message);
    return new JspView("EditPage");
}

From source file:diskCacheV111.srm.dcache.Storage.java

private static <K, V, C extends Iterable<V>> Map<K, Iterable<V>> filterValues(Map<K, C> unfiltered,
        Predicate<V> predicate) {
    return Maps.filterValues(Maps.transformValues(unfiltered, values -> filter(values, predicate)),
            values -> !isEmpty(values));
}

From source file:org.mycore.common.config.MCRConfiguration.java

public synchronized void initialize(Map<String, String> props, boolean clear) {
    checkForDeprecatedProperties(props);
    HashMap<String, String> copy = new HashMap<>(props);
    copy.remove(null);/*from  ww  w.j  av a2s  .c  om*/
    if (clear) {
        getBaseProperties().clear();
    } else {
        Map<String, String> nullValues = Maps.filterValues(copy, Predicates.<String>isNull());
        for (String key : nullValues.keySet()) {
            getBaseProperties().remove(key);
        }
    }
    Map<String, String> notNullValues = Maps.filterValues(copy, Predicates.notNull());
    for (Entry<String, String> entry : notNullValues.entrySet()) {
        getBaseProperties().setProperty(entry.getKey(), entry.getValue());
    }
    resolveProperties();
    debug();
}

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

/**
 * Validate the schedule to ensure that all students that should be scheduled are scheduled and that each time slot
 * with scheduled students has a proctor.
 * TBD whether we should validate everything from scratch or assume that the collections we're passing into this
 * method are good enough that we don't have to re-load all the data.
 * /*from   w  w w.j  a  va2 s.  com*/
 * @param scheduled
 * @param eligibleStudents
 * @param studentsScheduled
 * @return
 */
public ScheduleCreationInfo validateSchedule(final Schedule scheduled,
        final List<EligibleStudent> eligibleStudents, final Map<String, ScheduledStudent> studentsScheduled,
        final boolean reschedule) {

    // the "easy" way to do validation

    // -- iterate through all the time slots in the Schedule
    // ---- for each timeslot, if any seats are scheduled there MUST be a Proctor
    // ------ if there is no proctor, add an error to the list
    // -- iterate through all the ScheduledStudents
    // ---- for each ScheduledStudent ensure that each assessment is marked as scheduled
    // ------ if one is not marked as scheduled, add an error to the list

    // questions that we can answer here to make it easier to get data to the user through the UI:
    // how many test slots do not have a proctor?
    // which student-assessment combinations were unable to be scheduled?

    /*
     * more questions % capacity: # of testing slots, students scheduled, how many unscheduled students and
     * assessments what kind of excess capacity is there if everyone scheduled?
     * 
     * questions of accessibility equipment: did everyone who needs accessibility equipment get allocated?
     */

    int numTimeslots = 0;
    int numEmptyTimeslots = 0;
    int numSeats = 0;
    int numStudentsScheduled = 0;
    int numAssessmentsScheduled = 0;
    int numStudentsNotScheduled = 0;
    int numAssessmentsNotScheduled = 0;
    int numEmptySeats = 0;
    int numSeatsWithAccessEquip = 0;
    int numStudentsNeedingAccessEquipForAssessment = 0;
    int numStudentsCorrectlyAllocatedToEquipForAssessment = 0;
    int numStudentsNotCorrectlyAllocatedToEquipForAssessment = 0;

    boolean hasAccessEquip = false;

    final Set<String> uniqueStudents = new HashSet<String>();

    final ScheduleCreationInfo info = new ScheduleCreationInfo();

    final List<SchedulerValidationError> errors = new ArrayList<SchedulerValidationError>();

    int numNoProctor = 0;

    for (final ScheduledTimeSlot timeSlot : scheduled.getOrderedTimeSlots(reschedule)) {

        numTimeslots++;

        if (timeSlot.getProctor() == null && !timeSlot.isTimeslotCompletelyEmpty()) {
            numNoProctor++;

            errors.add(new SchedulerValidationError(ErrorType.NO_PROCTOR, "No proctor assigned to test slot",
                    String.format(NO_PROCTOR_ERROR_TEMPLATE, timeSlot.getStartTime().toDate(),
                            timeSlot.getEndTime().toDate())));

        }
        if (timeSlot.isTimeslotCompletelyEmpty()) {
            numEmptyTimeslots++;
        }
        for (final ScheduledSeat seat : timeSlot.getSeats()) {
            numSeats++;

            if (seat.getAccessibilityEquipments() != null && !seat.getAccessibilityEquipments().isEmpty()) {
                numSeatsWithAccessEquip++;
                hasAccessEquip = true;
            }

            if (seat.getStudent() != null) {

                if (uniqueStudents.add(seat.getStudent().getEntityId())) {
                    numStudentsScheduled++;
                }

                numAssessmentsScheduled++;

                // if this seat has accessibility equipment
                // then we look at this student's ScheduledStudent object
                // and see if there is an entry for this assessment and the equipment
                // if the value is TRUE, then the student was correctly allocated to the equipment
                if (seat.getStudent().hasAccommodations(seat.getAssessment())) {
                    if (hasAccessEquip) {
                        final ScheduledStudent thisStudent = studentsScheduled
                                .get(seat.getStudent().getEntityId());
                        if (thisStudent != null) {
                            for (final AccessibilityEquipment equip : seat.getAccessibilityEquipmentObjs()) {
                                if (thisStudent.isScheduledForEquipmentInAssessment(seat.getAssessment(),
                                        equip)) {
                                    numStudentsCorrectlyAllocatedToEquipForAssessment++;
                                    break; // only want to count the equipment allocation once per
                                           // student/assessment
                                }
                            }
                        }

                    }
                }

            } else {
                numEmptySeats++;
            }

            hasAccessEquip = false;

        }
    }

    info.setNumTimeslotsWithNoProctor(numNoProctor);
    info.setNumEmptyTestSlots(numEmptyTimeslots);

    final Map<String, ScheduledStudent> studentsScheduledCopy = Maps.newHashMap(studentsScheduled);

    final Map<String, ScheduledStudent> studentsNotScheduled = ImmutableMap
            .copyOf(Maps.filterValues(studentsScheduledCopy, new Predicate<ScheduledStudent>() {

                @Override
                public boolean apply(final ScheduledStudent scheduledStudent) {

                    final List<Assessment> toRemove = new ArrayList<Assessment>();

                    for (final Map.Entry<Assessment, Boolean> entry : scheduledStudent.getScheduledAssessments()
                            .entrySet()) {
                        if (entry.getValue()) {
                            toRemove.add(entry.getKey());
                        }
                    }

                    if (!toRemove.isEmpty()) {
                        for (final Assessment assess : toRemove) {
                            scheduledStudent.getScheduledAssessments().remove(assess);
                        }
                    }

                    if (scheduledStudent.getScheduledAssessments().size() > 0) {

                        for (final Assessment assess : scheduledStudent.getScheduledAssessments().keySet()) {

                            errors.add(new SchedulerValidationError(ErrorType.STUDENT_NOT_SCHEDULED,
                                    "Student not scheduled for an assessment he/she is eligible for",
                                    String.format(NOT_SCHEDULED_FOR_ASSESSMENT_ERROR_TEMPLATE,
                                            scheduledStudent.getStudent().getEntityId(),
                                            assess.getTestName())));
                        }

                        return true;
                    } else {
                        return false;
                    }
                }
            }));

    final Map<String, List<String>> studentsNotScheduledMap = new HashMap<String, List<String>>();

    for (final Map.Entry<String, ScheduledStudent> entry : studentsNotScheduled.entrySet()) {
        numStudentsNotScheduled++;
        final List<String> notScheduledAssessments = new ArrayList<String>();
        for (final Assessment assess : entry.getValue().getScheduledAssessments().keySet()) {
            numAssessmentsNotScheduled++;
            notScheduledAssessments.add(assess.getTestName());
        }
        studentsNotScheduledMap.put(entry.getKey(), notScheduledAssessments);
    }

    // iterate through Students Scheduled
    // get scheduled assessments
    // if TRUE (assessment scheduled for the student)
    // then check assessment equipment association
    // if there is one and the value is false
    // this means that the student was scheduled for the assessment, but was NOT scheduled into a seat
    // that had the proper equipment the student needs

    for (final ScheduledStudent schedStudent : studentsScheduled.values()) {
        for (final Map.Entry<Assessment, Boolean> entry : schedStudent.getScheduledAssessments().entrySet()) {
            boolean scheduledForAllEquip = true;
            if (entry.getValue()) {
                final Map<AccessibilityEquipment, Boolean> equipmentScheduled = schedStudent
                        .getAllScheduledForEquipmentInAssessment(entry.getKey());

                for (final Map.Entry<AccessibilityEquipment, Boolean> accessEquipEntry : equipmentScheduled
                        .entrySet()) {
                    if (!accessEquipEntry.getValue()) {
                        scheduledForAllEquip = false;
                        errors.add(new SchedulerValidationError(ErrorType.NOT_ALLOCATED_TO_REQUIRED_EQUIPMENT,
                                "Student not allocated to necessary accessibility equipment",
                                String.format(ACCESS_EQUIP_ERROR_TEMPLATE,
                                        schedStudent.getStudent().getEntityId(),
                                        accessEquipEntry.getKey().getName(), entry.getKey().getTestName())));
                    }
                }

                if (!scheduledForAllEquip) {
                    numStudentsNotCorrectlyAllocatedToEquipForAssessment++;
                }
            }
        }
    }

    // now just iterate through all the scheduled students
    // and see if any of them is eligible for accessibility equipment
    // in order to generate the count of all students who require equipment

    for (final ScheduledStudent schedStudent : studentsScheduled.values()) {
        numStudentsNeedingAccessEquipForAssessment += schedStudent.numAssessmentsAccessEquipRequiredFor();
    }

    info.setStudentsNotScheduled(studentsNotScheduledMap);

    info.setErrors(errors);

    info.setNumEmptySeats(numEmptySeats);
    info.setNumSeatsWithAccessibilityEquipment(numSeatsWithAccessEquip);
    info.setNumStudentAssessmentsReqAccessEquipScheduled(numStudentsCorrectlyAllocatedToEquipForAssessment);
    info.setNumStudentAssessmentsReqAccessEquipScheduledIncorrect(
            numStudentsNotCorrectlyAllocatedToEquipForAssessment);
    info.setNumStudentAssessmentsRequiringAccessibilityEquipment(numStudentsNeedingAccessEquipForAssessment);
    info.setNumStudentsScheduled(numStudentsScheduled);
    info.setNumUnscheduledAssessments(numAssessmentsNotScheduled);
    info.setNumUnscheduledStudents(numStudentsNotScheduled);
    info.setPercentCapacityUsed((float) numAssessmentsScheduled / (float) numSeats * 100);
    info.setTotalNumSeats(numSeats);
    info.setTotalNumTestSlots(numTimeslots);

    return info;
}