Example usage for com.google.common.collect Sets filter

List of usage examples for com.google.common.collect Sets filter

Introduction

In this page you can find the example usage for com.google.common.collect Sets filter.

Prototype

@GwtIncompatible("NavigableSet")
@SuppressWarnings("unchecked")
@CheckReturnValue
public static <E> NavigableSet<E> filter(NavigableSet<E> unfiltered, Predicate<? super E> predicate) 

Source Link

Document

Returns the elements of a NavigableSet , unfiltered , that satisfy a predicate.

Usage

From source file:com.censoredsoftware.infractions.bukkit.origin.Origin.java

/**
 * Set of Evidence from this Origin./*w w w  . j a  va 2s  . c o m*/
 *
 * @return Evidence.
 */
public Set<Evidence> getEvidence() {
    final Origin origin = this;
    return Sets.filter(Infractions.allEvidence(), new Predicate<Evidence>() {
        @Override
        public boolean apply(Evidence evidence) {
            return origin.equals(evidence.getOrigin());
        }
    });
}

From source file:com.b2international.commons.hierarchy.Hierarchy.java

private Collection<M> doGetChildren(M parent) {
    Preconditions.checkArgument(parent != null, "Parent must not be null");

    Set<Entry<M, M>> childEntries = Sets.filter(childToParentMap.entrySet(),
            new EntryValuePredicate<M>(parent));
    return Collections2.transform(childEntries, new EntryToKeyFunction<M>());
}

From source file:ru.org.linux.topic.TopicListDao.java

/**
 *  ?  SQL-?./*from  w ww . jav  a2  s. co m*/
 *
 * @param request , ? ?? 
 * @return ?, ?? ??  SQL-?
 */
private static CharSequence makeConditions(TopicListDto request, Map<String, Object> paramsBuilder) {
    StringBuilder where = new StringBuilder("NOT deleted");

    where.append(request.getCommitMode().getQueryPiece());

    Set<Integer> sections = Sets.filter(request.getSections(), v -> v != 0);

    if (!sections.isEmpty()) {
        where.append(" AND section in (:sections)");
        paramsBuilder.put("sections", sections);
    }

    if (request.getGroup() != 0) {
        where.append(" AND groupid=:groupId");
        paramsBuilder.put("groupId", request.getGroup());
    }

    switch (request.getDateLimitType()) {
    case BETWEEN:
        where.append(" AND postdate>=:fromDate AND postdate<:toDate");
        paramsBuilder.put("fromDate", request.getFromDate());
        paramsBuilder.put("toDate", request.getToDate());
        break;
    case FROM_DATE:
        where.append(" AND postdate>=:fromDate");
        paramsBuilder.put("fromDate", request.getFromDate());
        break;
    default:
    }

    if (request.getUserId() != 0) {
        paramsBuilder.put("userId", request.getUserId());
        if (request.isUserFavs()) {
            where.append(" AND memories.userid=:userId");
        } else {
            where.append(" AND userid=:userId");
        }

        if (request.isUserFavs()) {
            if (request.isUserWatches()) {
                where.append(" AND watch ");
            } else {
                where.append(" AND NOT watch ");
            }
        }
    }

    if (request.isNotalks()) {
        where.append(" AND not topics.groupid=8404");
    }

    if (request.isTech()) {
        where.append(" AND not topics.groupid=8404 AND not topics.groupid=4068 AND groups.section=2");
    }

    switch (request.getMiniNewsMode()) {
    case MAJOR:
        where.append(" AND NOT minor");
        break;
    case MINOR:
        where.append(" AND minor");
        break;
    }

    if (request.getTag() != 0) {
        paramsBuilder.put("tagId", request.getTag());
        where.append(" AND topics.id IN (SELECT msgid FROM tags WHERE tagid=:tagId)");
    }

    if (!request.isShowDraft()) {
        where.append(" AND NOT topics.draft ");
    } else {
        where.append(" AND topics.draft ");
    }

    return where;
}

From source file:com.mingo.query.Query.java

/**
 * Gets query case by id.//from w ww.  j a  v a 2s  .co m
 *
 * @param caseId case id
 * @return query case
 */
public QueryCase getQueryCaseById(final String caseId) {
    Set<QueryCase> filtered = Sets.filter(cases, new Predicate<QueryCase>() {
        @Override
        public boolean apply(QueryCase input) {
            return input.getId().equals(caseId);
        }
    });
    return filtered.iterator().next();
}

From source file:org.eclipse.sirius.diagram.business.internal.componentization.mappings.table.CandidateMappingManager.java

/**
 * Build the available candidate mappings based on activated layers.
 * //from   w  w  w  . j  a v a 2 s .co m
 * @param activatedLayers
 *            the activated layers
 */
public void build(final Collection<Layer> activatedLayers) {
    computeAllMappings();
    sortMappings();
    convertMappingsToCandidate();

    final Predicate<CandidateMapping> availablePredicate = new Predicate<CandidateMapping>() {
        public boolean apply(final CandidateMapping input) {
            final Collection<Layer> layers = input.getParentLayers();
            for (final Layer layer : layers) {
                if (EqualityHelper.contains(activatedLayers, layer)) {
                    return true;
                }
            }
            return false;
        }
    };
    availableCandidates = Sets.filter(availableCandidates, availablePredicate);
}

From source file:eu.lp0.cursus.ui.event.EventAttendeesTab.java

@SuppressWarnings("unchecked")
private void initialise() {
    setLayout(new BorderLayout(0, 0));

    scrollPane = new JScrollPane();
    add(scrollPane, BorderLayout.CENTER);

    table = new JTable();
    scrollPane.setViewportView(table);/*from   ww w . ja  v  a 2  s  .  co  m*/

    model = new DatabaseTableModel<Pilot>(Arrays.<DatabaseColumn<Pilot, ?>>asList( //
            new BooleanDatabaseColumn<Pilot>("pilot.event-attendee", win, pilotDAO) { //$NON-NLS-1$
                @Override
                protected Boolean getValue(Pilot row, boolean editing) {
                    assert (currentEvent != null);
                    return row.getEvents().contains(currentEvent);
                }

                @Override
                protected boolean setValue(Pilot row, Boolean value) {
                    assert (currentEvent != null);
                    if (value) {
                        row.getEvents().add(currentEvent);
                    } else {
                        row.getEvents().remove(currentEvent);
                    }
                    return true;
                }
            }, new StringDatabaseColumn<Pilot>("pilot.race-count") { //$NON-NLS-1$
                @Override
                protected String getValue(Pilot row, boolean editing) {
                    return String.valueOf(Sets
                            .filter(row.getRaces().keySet(), Predicates.in(currentEvent.getRaces())).size());
                }

                @Override
                protected boolean setValue(Pilot row, String value) {
                    return false;
                }
            }, new RaceNumbersDatabaseColumnModel("pilot.race-number"), //$NON-NLS-1$
            new StringDatabaseColumn<Pilot>("pilot.name") { //$NON-NLS-1$
                @Override
                protected String getValue(Pilot row, boolean editing) {
                    return row.getName();
                }

                @Override
                protected boolean setValue(Pilot row, String value) {
                    return false;
                }
            }, new EnumDatabaseColumn<Pilot, Sex>("pilot.sex", Sex.class, true) { //$NON-NLS-1$
                @Override
                protected Sex getEnumValue(Pilot row) {
                    return row.getSex();
                }

                @Override
                protected boolean setEnumValue(Pilot row, Sex value) {
                    return false;
                }
            }, new StringDatabaseColumn<Pilot>("pilot.country") { //$NON-NLS-1$
                @Override
                protected String getValue(Pilot row, boolean editing) {
                    return row.getCountry();
                }

                @Override
                protected boolean setValue(Pilot row, String value) {
                    return false;
                }
            }));
    model.setupModel(table);
    table.getRowSorter().setSortKeys(Arrays.asList(new RowSorter.SortKey(0, SortOrder.DESCENDING),
            new RowSorter.SortKey(1, SortOrder.ASCENDING), new RowSorter.SortKey(2, SortOrder.ASCENDING),
            new RowSorter.SortKey(3, SortOrder.ASCENDING), new RowSorter.SortKey(4, SortOrder.ASCENDING),
            new RowSorter.SortKey(5, SortOrder.ASCENDING)));

    table.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.isConsumed()) {
                return;
            }
            if (ke.getKeyCode() == KeyEvent.VK_INSERT) {
                addSelectedPilots();
                ke.consume();
            } else if (ke.getKeyCode() == KeyEvent.VK_DELETE) {
                removeSelectedPilots();
                ke.consume();
            }
        }
    });
}

From source file:gov.nih.nci.caarray.domain.file.FileTypeRegistryImpl.java

/**
 * {@inheritDoc}/*from  w w  w.  ja  v a  2  s .  co m*/
 */
@Override
public Set<FileType> getParseableArrayDataTypes() {
    return Sets.filter(this.types, new Predicate<FileType>() {
        @Override
        public boolean apply(FileType ft) {
            return ft.isParseableData();
        }
    });
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericOverallPositionData.java

@Override
protected LinkedListMultimap<Integer, Pilot> calculateOverallPositionsWithOrder() {
    // Invert race points with ordered lists of pilots
    Comparator<Pilot> racePlacings = new PilotRacePlacingComparator<T>(scores, placingMethod);
    Comparator<Pilot> fallbackOrdering = new PilotRaceNumberComparator();
    TreeMultimap<Integer, Pilot> invOverallPoints = TreeMultimap.create(Ordering.natural(),
            Ordering.from(racePlacings).compound(fallbackOrdering));
    Multimaps.invertFrom(Multimaps.forMap(scores.getOverallPoints()), invOverallPoints);

    // Calculate overall positions
    LinkedListMultimap<Integer, Pilot> overallPositions = LinkedListMultimap.create();
    List<Pilot> collectedPilots = new ArrayList<Pilot>(scores.getPilots().size());
    LinkedList<SortedSet<Pilot>> pilotPointsOrdering = new LinkedList<SortedSet<Pilot>>();
    int position = 1;

    if (allSimulatedToEnd) {
        final Map<Pilot, ? extends Set<Race>> simulatedPilotPoints = scores.getSimulatedPilotPoints();
        Predicate<Pilot> allSimulatedPilot = new Predicate<Pilot>() {
            private final int raceCount = scores.getRaces().size();

            @Override//from  w ww  .  j av  a 2  s. com
            public boolean apply(Pilot input) {
                return simulatedPilotPoints.get(input).size() == raceCount;
            }
        };

        for (Integer points : invOverallPoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invOverallPoints.get(points),
                    Predicates.not(allSimulatedPilot));
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
        for (Integer points : invOverallPoints.keySet()) {
            SortedSet<Pilot> pilots = Sets.filter(invOverallPoints.get(points), allSimulatedPilot);
            if (!pilots.isEmpty()) {
                pilotPointsOrdering.add(pilots);
            }
        }
    } else {
        for (Integer points : invOverallPoints.keySet()) {
            pilotPointsOrdering.add(invOverallPoints.get(points));
        }
    }

    for (SortedSet<Pilot> pilots : pilotPointsOrdering) {
        switch (equalPositioning) {
        case ALWAYS:
            // Always put pilots with the same points in the same position
            overallPositions.putAll(position, pilots);
            position += pilots.size();
            break;

        case IF_REQUIRED:
            // Try to put pilots with the same points in separate positions
            PeekingIterator<Pilot> it = Iterators.peekingIterator(pilots.iterator());
            while (it.hasNext()) {
                Pilot pilot = it.next();
                collectedPilots.add(pilot);

                // If this pilot compares equally with the next pilot, add them too
                while (it.hasNext() && racePlacings.compare(it.peek(), pilot) == 0) {
                    collectedPilots.add(it.next());
                }

                // Sort them by an arbitrary order
                Collections.sort(collectedPilots, fallbackOrdering);

                // Add them all to this position
                overallPositions.putAll(position, collectedPilots);
                position += collectedPilots.size();

                collectedPilots.clear();
            }
            break;
        }
    }

    return overallPositions;
}

From source file:org.graylog2.periodical.UserPermissionMigrationPeriodical.java

@Override
public void doRun() {
    final List<User> users = userService.loadAll();
    final String adminRoleId = roleService.getAdminRoleObjectId();
    final String readerRoleId = roleService.getReaderRoleObjectId();

    for (User user : users) {
        if (user.isLocalAdmin()) {
            log.debug("Skipping local admin user.");
            continue;
        }/*from   ww  w  .j av a2s .  co  m*/

        final Set<String> fixedPermissions = Sets.newHashSet();
        final Set<String> fixedRoleIds = Sets.newHashSet(user.getRoleIds());

        final Set<String> permissionSet = Sets.newHashSet(user.getPermissions());

        boolean hasWildcardPermission = permissionSet.contains("*");

        if (hasWildcardPermission && !user.getRoleIds().contains(adminRoleId)) {
            // need to add the admin role to this user
            fixedRoleIds.add(adminRoleId);
        }

        final Set<String> basePermissions = permissions.readerPermissions(user.getName());
        final boolean hasCompleteReaderSet = permissionSet.containsAll(basePermissions);

        // only migrate the user if it looks like a pre-1.2 user:
        //   - it has no roles
        //   - it has the base reader permission set
        //   - it has the wildcard permissions
        if (!user.getRoleIds().isEmpty() && hasCompleteReaderSet && hasWildcardPermission) {
            log.debug("Not migrating user {}, it has already been migrated.", user.getName());
            continue;
        }
        if (hasCompleteReaderSet && !user.getRoleIds().contains(readerRoleId)) {
            // need to add the reader role to this user
            fixedRoleIds.add(readerRoleId);
        }
        // filter out the individual permissions to dashboards and streams
        final List<String> dashboardStreamPermissions = Lists
                .newArrayList(Sets.filter(permissionSet, new Predicate<String>() {
                    @Override
                    public boolean apply(String permission) {
                        return !basePermissions.contains(permission) && !permission.equals("*");
                    }
                }));
        // add the minimal permission set back to the user
        fixedPermissions.addAll(permissions.userSelfEditPermissions(user.getName()));
        fixedPermissions.addAll(dashboardStreamPermissions);

        log.info(
                "Migrating permissions to roles for user {} from permissions {} and roles {} to new permissions {} and roles {}",
                user.getName(), permissionSet, user.getRoleIds(), fixedPermissions, fixedRoleIds);

        user.setRoleIds(fixedRoleIds);
        user.setPermissions(Lists.newArrayList(fixedPermissions));
        try {
            userService.save(user);
        } catch (ValidationException e) {
            log.error("Unable to migrate user permissions for user " + user.getName(), e);
        }
    }

    log.info("Marking user permission migration as done.");
    clusterConfigService.write(UserPermissionMigrationState.create(true));

}

From source file:com.censoredsoftware.infractions.bukkit.issuer.Issuer.java

/**
 * Set of Dossiers contributed to./* w w  w  . j  a  v a  2 s.  c  o  m*/
 *
 * @return Dossiers.
 */
public Set<Dossier> getContributedDossiers() {
    return Sets.filter(Infractions.allDossiers(), new Predicate<Dossier>() {
        @Override
        public boolean apply(Dossier dossier) {
            return Iterables.any(dossier.getInfractions(), new Predicate<Infraction>() {
                @Override
                public boolean apply(Infraction infraction) {
                    return getId().equals(infraction.getIssuer().getId())
                            || Iterables.any(infraction.getEvidence(), new Predicate<Evidence>() {
                                @Override
                                public boolean apply(Evidence evidence) {
                                    return getId().equals(evidence.getIssuer().getId());
                                }
                            });
                }
            });
        }
    });
}