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:gov.nih.nci.firebird.data.InvestigatorRegistration.java

/**
 * @return the subinvestigator Registrations
 *//*from ww w .j  a va 2s .c om*/
@Transient
public Set<SubInvestigatorRegistration> getActiveSubinvestigatorRegistrations() {
    return Sets.filter(getSubinvestigatorRegistrations(), AbstractProtocolRegistration.IS_INVITED_PREDICATE);
}

From source file:mysql5.MySQL5ItemStoneListDAO.java

private void store(Set<? extends ItemStone> stones, ItemStoneType ist) {
    if (GenericValidator.isBlankOrNull(stones)) {
        return;/*  w w  w.  ja v  a  2s. c  o  m*/
    }

    Set<? extends ItemStone> stonesToAdd = Sets.filter(stones, itemStoneAddPredicate);
    Set<? extends ItemStone> stonesToDelete = Sets.filter(stones, itemStoneDeletedPredicate);
    Set<? extends ItemStone> stonesToUpdate = Sets.filter(stones, itemStoneUpdatePredicate);

    Connection con = null;
    try {
        con = DatabaseFactory.getConnection();
        con.setAutoCommit(false);

        deleteItemStones(con, stonesToDelete, ist);
        addItemStones(con, stonesToAdd, ist);
        updateItemStones(con, stonesToUpdate, ist);

    } catch (SQLException e) {
        log.error("Can't save stones", e);
    } finally {
        DatabaseFactory.close(con);
    }

    for (ItemStone is : stones) {
        is.setPersistentState(PersistentState.UPDATED);
    }
}

From source file:controllers.SearchController.java

protected Result renderSearch(String q, String rangeType, int relative, String from, String to, String keyword,
        String interval, int page, String savedSearchId, String fields, int displayWidth, SearchSort sort,
        Stream stream, String filter) {
    UniversalSearch search;/*w  ww . j  a v  a 2 s. c  om*/
    try {
        search = getSearch(q, filter, rangeType, relative, from, to, keyword, page, sort);
    } catch (InvalidRangeParametersException e2) {
        return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request()));
    } catch (IllegalArgumentException e1) {
        return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request()));
    }

    SearchResult searchResult;
    DateHistogramResult histogramResult;
    SavedSearch savedSearch = null;
    Set<String> selectedFields = getSelectedFields(fields);
    String formattedHistogramResults;
    Set<StreamDescription> streams;
    Set<InputDescription> inputs = Sets.newHashSet();
    Map<String, NodeDescription> nodes = Maps.newHashMap();

    nodes.putAll(Maps.transformEntries(serverNodes.asMap(),
            new Maps.EntryTransformer<String, Node, NodeDescription>() {
                @Override
                public NodeDescription transformEntry(@Nullable String key, @Nullable Node value) {
                    return new NodeDescription(value);
                }
            }));
    try {
        if (savedSearchId != null && !savedSearchId.isEmpty()) {
            savedSearch = savedSearchService.get(savedSearchId);
        }

        searchResult = search.search();
        // TODO create a bulk call to get stream and input details (and restrict the fields that come back)
        final Set<String> streamIds = Sets.newHashSet();
        final HashMultimap<String, String> usedInputIds = HashMultimap.create();
        final HashMultimap<String, String> usedRadioIds = HashMultimap.create();

        for (MessageResult messageResult : searchResult.getMessages()) {
            streamIds.addAll(messageResult.getStreamIds());
            usedInputIds.put(messageResult.getSourceNodeId(), messageResult.getSourceInputId());
            if (messageResult.getSourceRadioId() != null) {
                usedRadioIds.put(messageResult.getSourceRadioId(), messageResult.getSourceRadioInputId());
            }
        }
        // resolve all stream information in the result set
        final HashSet<Stream> allStreams = Sets.newHashSet(streamService.all().iterator());
        streams = Sets.newHashSet(Collections2.transform(Sets.filter(allStreams, new Predicate<Stream>() {
            @Override
            public boolean apply(Stream input) {
                return streamIds.contains(input.getId());
            }
        }), new Function<Stream, StreamDescription>() {
            @Nullable
            @Override
            public StreamDescription apply(@Nullable Stream stream) {
                return StreamDescription.of(stream);
            }
        }));

        // resolve all used inputs and nodes from the result set
        final Map<String, Node> nodeMap = serverNodes.asMap();
        for (final String nodeId : usedInputIds.keySet()) {
            final Node node = nodeMap.get(nodeId);
            if (node != null) {
                final HashSet<Input> allInputs = Sets.newHashSet(node.getInputs());
                inputs = Sets.newHashSet(Collections2.transform(Sets.filter(allInputs, new Predicate<Input>() {
                    @Override
                    public boolean apply(Input input) {
                        final Set<String> inputIds = usedInputIds.get(nodeId);
                        return inputIds != null && inputIds.contains(input.getId());
                    }
                }), new Function<Input, InputDescription>() {
                    @Nullable
                    @Override
                    public InputDescription apply(Input input) {
                        return new InputDescription(input);
                    }
                }));
            }
        }

        // resolve radio inputs
        for (final String radioId : usedRadioIds.keySet()) {
            try {
                final Radio radio = nodeService.loadRadio(radioId);
                nodes.put(radio.getId(), new NodeDescription(radio));
                final HashSet<Input> allRadioInputs = Sets.newHashSet(radio.getInputs());
                inputs.addAll(Collections2.transform(Sets.filter(allRadioInputs, new Predicate<Input>() {
                    @Override
                    public boolean apply(Input input) {
                        return usedRadioIds.get(radioId).contains(input.getId());
                    }
                }), new Function<Input, InputDescription>() {
                    @Override
                    public InputDescription apply(Input input) {
                        return new InputDescription(input);
                    }
                }));

            } catch (NodeService.NodeNotFoundException e) {
                Logger.warn("Could not load radio node " + radioId, e);
            }
        }

        searchResult.setAllFields(getAllFields());

        // histogram resolution (strangely aka interval)
        if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) {
            interval = determineHistogramResolution(searchResult);
        }
        histogramResult = search.dateHistogram(interval);
        formattedHistogramResults = formatHistogramResults(histogramResult.getResults(), displayWidth);
    } catch (IOException e) {
        return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
    } catch (APIException e) {
        if (e.getHttpCode() == 400) {
            try {
                QueryParseError qpe = objectMapper.readValue(e.getResponseBody(), QueryParseError.class);
                return ok(views.html.search.queryerror.render(currentUser(), q, qpe, savedSearch, fields,
                        stream));
            } catch (IOException ioe) {
                // Ignore
            }
        }

        String message = "There was a problem with your search. We expected HTTP 200, but got a HTTP "
                + e.getHttpCode() + ".";
        return status(504, views.html.errors.error.render(message, e, request()));
    }

    return ok(views.html.search.index.render(currentUser(), q, search, page, savedSearch, selectedFields,
            searchResult, histogramResult, formattedHistogramResults, nodes,
            Maps.uniqueIndex(streams, new Function<StreamDescription, String>() {
                @Nullable
                @Override
                public String apply(@Nullable StreamDescription stream) {
                    return stream == null ? null : stream.getId();
                }
            }), Maps.uniqueIndex(inputs, new Function<InputDescription, String>() {
                @Nullable
                @Override
                public String apply(@Nullable InputDescription input) {
                    return input == null ? null : input.getId();
                }
            }), stream));

}

From source file:org.apache.cassandra.index.sasi.plan.QueryController.java

private Set<SSTableIndex> applyScope(Set<SSTableIndex> indexes) {
    return Sets.filter(indexes, index -> {
        SSTableReader sstable = index.getSSTable();
        return range.startKey().compareTo(sstable.last) <= 0
                && (range.stopKey().isMinimum() || sstable.first.compareTo(range.stopKey()) <= 0);
    });//from  w w  w  . ja v  a 2s  . c o m
}

From source file:org.opendaylight.controller.md.sal.common.impl.service.TwoPhaseCommit.java

private Optional<RootedChangeSet<P, D>> resolveConfigChange(P affectedPath) {
    Map<P, D> originalConfig = dataBroker.deepGetBySubpath(transaction.getOriginalConfigurationData(),
            affectedPath);/* w  w w . j  a  v a2s.c  o m*/
    Map<P, D> createdConfig = dataBroker.deepGetBySubpath(transaction.getCreatedConfigurationData(),
            affectedPath);
    Map<P, D> updatedConfig = dataBroker.deepGetBySubpath(transaction.getUpdatedConfigurationData(),
            affectedPath);
    Set<P> removedConfig = Sets.filter(transaction.getRemovedConfigurationData(),
            dataBroker.createIsContainedPredicate(affectedPath));
    return resolveChanges(affectedPath, originalConfig, createdConfig, updatedConfig, removedConfig);
}

From source file:org.jboss.weld.util.Beans.java

/**
 * Retains only beans which have deployment type X.
 * <p/>/* w w  w  . j ava  2  s.c o m*/
 * The deployment type X is
 *
 * @param beans The beans to filter
 * @param beanManager the bean manager
 * @return The filtered beans
 */
public static <T extends Bean<?>> Set<T> removeDisabledBeans(Set<T> beans, final BeanManagerImpl beanManager,
        final SpecializationAndEnablementRegistry registry) {
    if (beans.size() == 0) {
        return beans;
    } else {
        return Sets.filter(beans, new Predicate<T>() {
            @Override
            @SuppressWarnings("NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE")
            public boolean apply(T bean) {
                Preconditions.checkArgumentNotNull(bean, "bean");
                return isBeanEnabled(bean, beanManager.getEnabled());
            }
        });
    }
}

From source file:com.github.rinde.rinsim.core.model.road.AbstractRoadModel.java

@Override
public Set<RoadUser> getObjects(Predicate<RoadUser> predicate) {
    return Sets.filter(getObjects(), predicate);
}

From source file:org.eclipse.incquery.patternlanguage.emf.specification.SpecificationBuilder.java

protected IQuerySpecification<?> buildSpecification(Pattern pattern, boolean skipPatternValidation,
        List<IQuerySpecification<?>> newSpecifications) throws QueryInitializationException {
    String fqn = CorePatternLanguageHelper.getFullyQualifiedName(pattern);
    Preconditions.checkArgument(!patternMap.containsKey(fqn),
            "Builder already stores query with the name of " + fqn);
    if (sanitizer.admit(pattern, skipPatternValidation)) {
        Set<Pattern> newPatterns = Sets
                .newHashSet(Sets.filter(sanitizer.getAdmittedPatterns(), new Predicate<Pattern>() {

                    @Override//from   w  w  w .  j  a  va2  s.co  m
                    public boolean apply(Pattern pattern) {
                        final String name = CorePatternLanguageHelper.getFullyQualifiedName(pattern);
                        return !pattern.eIsProxy() && !"".equals(name) && !patternMap.containsKey(name);
                    }
                }));
        // Initializing new query specifications
        for (Pattern newPattern : newPatterns) {
            String patternFqn = CorePatternLanguageHelper.getFullyQualifiedName(newPattern);
            GenericQuerySpecification specification = new GenericQuerySpecification(
                    new GenericEMFPatternPQuery(newPattern, true));
            patternMap.put(patternFqn, specification);
            patternNameMap.put(patternFqn, newPattern);
            newSpecifications.add(specification);
        }
        // Updating bodies
        for (Pattern newPattern : newPatterns) {
            String patternFqn = CorePatternLanguageHelper.getFullyQualifiedName(newPattern);
            GenericQuerySpecification specification = (GenericQuerySpecification) patternMap.get(patternFqn);
            GenericEMFPatternPQuery pQuery = specification.getInternalQueryRepresentation();
            try {
                buildAnnotations(newPattern, pQuery);
                buildBodies(newPattern, pQuery);
            } catch (IncQueryException e) {
                pQuery.addError(new PProblem(e, e.getShortMessage()));
            } catch (RewriterException e) {
                pQuery.addError(new PProblem(e, e.getShortMessage()));
            }
            if (!PQueryStatus.ERROR.equals(pQuery.getStatus())) {
                for (PQuery query : pQuery.getDirectReferredQueries()) {
                    dependantQueries.put(query, specification);
                }
            }
        }
    } else {
        for (Pattern rejectedPattern : sanitizer.getRejectedPatterns()) {
            String patternFqn = CorePatternLanguageHelper.getFullyQualifiedName(rejectedPattern);
            if (!patternMap.containsKey(patternFqn)) {
                GenericQuerySpecification rejected = new GenericQuerySpecification(
                        new GenericEMFPatternPQuery(rejectedPattern, true));
                for (PProblem problem : sanitizer.getProblemByPattern(rejectedPattern))
                    rejected.getInternalQueryRepresentation().addError(problem);
                patternMap.put(patternFqn, rejected);
                patternNameMap.put(patternFqn, rejectedPattern);
                newSpecifications.add(rejected);
            }
        }
    }
    IQuerySpecification<?> specification = patternMap.get(fqn);
    if (specification == null) {
        GenericQuerySpecification erroneousSpecification = new GenericQuerySpecification(
                new GenericEMFPatternPQuery(pattern, true));
        erroneousSpecification.getInternalQueryRepresentation()
                .addError(new PProblem("Unable to compile pattern due to an unspecified error"));
        patternMap.put(fqn, erroneousSpecification);
        patternNameMap.put(fqn, pattern);
        newSpecifications.add(erroneousSpecification);
        specification = erroneousSpecification;
    }
    return specification;
}

From source file:gov.nih.nci.firebird.selenium2.pages.sponsor.protocol.review.ReviewRegistrationTabHelper.java

private Set<AbstractRegistrationForm> getFormsRequiringReview(AbstractProtocolRegistration registration) {
    return Sets.filter(registration.getFormsForSponsorReview(), new Predicate<AbstractRegistrationForm>() {
        @Override// w  w w. j  a v a  2  s.  c  o  m
        public boolean apply(AbstractRegistrationForm form) {
            return form.isReviewRequired();
        }
    });
}

From source file:grakn.core.graql.executor.QueryExecutor.java

/**
 * @param commonVars     set of variables of interest
 * @param graqlTraversal graql traversal corresponding to the provided pattern
 * @return resulting answer stream/*from   w w  w  .jav a2 s . com*/
 */
public Stream<ConceptMap> traversal(Set<Variable> commonVars, GraqlTraversal graqlTraversal) {
    Set<Variable> vars = Sets.filter(commonVars, Variable::isReturned);

    GraphTraversal<Vertex, Map<String, Element>> traversal = graqlTraversal.getGraphTraversal(transaction,
            vars);

    return traversal.toStream().map(elements -> createAnswer(vars, elements)).distinct().sequential()
            .map(ConceptMap::new);
}