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.nes.correlation.NesPersonRoleIntegrationServiceBean.java

private Set<Correlation> filterByOrganization(Correlation[] correlations, final String organizationNesId) {
    if (correlations == null) {
        return Collections.emptySet();
    }/*from  w  w w . j a va 2s  . c o  m*/
    Set<Correlation> correlationSet = Sets.newHashSet(correlations);
    return Sets.filter(correlationSet, new Predicate<Correlation>() {
        @Override
        public boolean apply(Correlation correlation) {
            return isIdMatch(organizationNesId, getScoperIdentifier(correlation));
        }
    });
}

From source file:module.siadap.domain.util.SiadapProcessCounter.java

public Set<Siadap> getOrCreateSiadapsNotListed() {
    final int year = configuration.getYear();
    Set<Siadap> notListedSiadapsForGivenYear = notListedSiadaps.get(year);
    if (notListedSiadapsForGivenYear == null) {
        notListedSiadapsForGivenYear = new TreeSet<Siadap>(
                Siadap.COMPARATOR_BY_EVALUATED_PRESENTATION_NAME_FALLBACK_YEAR_THEN_OID);

        notListedSiadapsForGivenYear//  ww w  . ja  v a  2s .co  m
                .addAll(Sets.filter(SiadapRootModule.getInstance().getSiadapsSet(), new Predicate<Siadap>() {

                    @Override
                    public boolean apply(Siadap input) {
                        if (input == null) {
                            return false;
                        }
                        return input.getYear() == year;
                    }
                }));

        notListedSiadapsForGivenYear.removeAll(getSiadaps());
        notListedSiadaps.put(year, notListedSiadapsForGivenYear);
        return notListedSiadapsForGivenYear;

    } else {
        return notListedSiadapsForGivenYear;
    }
}

From source file:org.sosy_lab.cpachecker.util.templates.TemplatePrecision.java

/**
 * Get templates associated with the given node.
 *//*from  www.  j  av a 2 s  . c om*/
public Collection<Template> getTemplatesForNode(final CFANode node) {
    if (cache.containsKey(node)) {
        return cache.get(node);
    }

    Builder<Template> out = ImmutableSet.builder();
    out.addAll(extractTemplatesForNode(node)::iterator);
    out.addAll(extraTemplates);
    out.addAll(extractedFromAssertTemplates);

    out.addAll(generateTemplates(node));
    Set<Template> outBuild = out.build();

    if (varFiltering == VarFilteringStrategy.ONE_LIVE) {

        // Filter templates to make sure at least one is alive.
        outBuild = Sets.filter(outBuild, input -> shouldUseTemplate(input, node));
    }

    // Sort.
    List<Template> sortedTemplates = Ordering
            .from(Comparator.<Template>comparingInt((template) -> template.getLinearExpression().size())
                    .thenComparingInt(t -> t.toString().trim().startsWith("-") ? 1 : 0)
                    .thenComparing(Template::toString))
            .immutableSortedCopy(outBuild);

    cache.putAll(node, sortedTemplates);
    return cache.get(node);
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint.EndpointManager.java

/**
 * Get the set of nodes//from  w ww .j  av a2  s.  c  om
 *
 * @param egKey - the egKey of the endpoint group to get nodes for
 * @return a collection of {@link NodeId} objects.
 */
public synchronized Set<NodeId> getNodesForGroup(final EgKey egKey) {
    return ImmutableSet.copyOf(Sets.filter(endpointsByGroupByNode.keySet(), new Predicate<NodeId>() {

        @Override
        public boolean apply(NodeId input) {
            Map<EgKey, Set<EpKey>> nodeEps = endpointsByGroupByNode.get(input);
            return (nodeEps != null && nodeEps.containsKey(egKey));
        }

    }));
}

From source file:org.gradle.plugins.ide.idea.IdeaPlugin.java

private void configureIdeaProject(final Project project) {
    if (isRoot(project)) {
        final GenerateIdeaProject task = project.getTasks().create("ideaProject", GenerateIdeaProject.class);
        task.setDescription("Generates IDEA project file (IPR)");
        XmlFileContentMerger ipr = new XmlFileContentMerger(task.getXmlTransformer());
        IdeaProject ideaProject = instantiator.newInstance(IdeaProject.class, project, ipr);
        task.setIdeaProject(ideaProject);
        ideaModel.setProject(ideaProject);

        ideaProject.setOutputFile(new File(project.getProjectDir(), project.getName() + ".ipr"));
        ConventionMapping conventionMapping = ((IConventionAware) ideaProject).getConventionMapping();
        conventionMapping.map("jdkName", new Callable<String>() {
            @Override/* w  w  w . j  ava2  s.c  om*/
            public String call() throws Exception {
                return JavaVersion.current().toString();
            }
        });
        conventionMapping.map("languageLevel", new Callable<IdeaLanguageLevel>() {
            @Override
            public IdeaLanguageLevel call() throws Exception {
                JavaVersion maxSourceCompatibility = getMaxJavaModuleCompatibilityVersionFor(
                        SOURCE_COMPATIBILITY);
                return new IdeaLanguageLevel(maxSourceCompatibility);
            }

        });
        conventionMapping.map("targetBytecodeVersion", new Callable<JavaVersion>() {
            @Override
            public JavaVersion call() throws Exception {
                return getMaxJavaModuleCompatibilityVersionFor(TARGET_COMPATIBILITY);
            }

        });

        ideaProject.setWildcards(Sets.newHashSet("!?*.class", "!?*.scala", "!?*.groovy", "!?*.java"));
        conventionMapping.map("modules", new Callable<List<IdeaModule>>() {
            @Override
            public List<IdeaModule> call() throws Exception {
                return Lists.newArrayList(Iterables.transform(
                        Sets.filter(project.getRootProject().getAllprojects(), new Predicate<Project>() {
                            @Override
                            public boolean apply(Project p) {
                                return p.getPlugins().hasPlugin(IdeaPlugin.class);
                            }

                        }), new Function<Project, IdeaModule>() {
                            @Override
                            public IdeaModule apply(Project p) {
                                return ideaModelFor(p).getModule();
                            }
                        }));
            }
        });

        conventionMapping.map("pathFactory", new Callable<PathFactory>() {
            @Override
            public PathFactory call() throws Exception {
                return new PathFactory().addPathVariable("PROJECT_DIR", task.getOutputFile().getParentFile());
            }
        });

        addWorker(task);
    }

}

From source file:com.isotrol.impe3.web20.impl.MigrationServiceImpl.java

private MemberEntity fillMember(MemberEntity entity, MemberDTO dto) {
    final Calendar date = Calendar.getInstance();
    date.setTime(dto.getDate());//from  w  ww.j  a  v  a2  s  .co m
    entity.setDate(date);
    entity.setDisplayName(dto.getDisplayName());
    entity.setEmail(dto.getEmail());
    entity.setMemberCode(dto.getCode());
    entity.setName(dto.getName());
    entity.setBlocked(dto.isBlocked());

    final Set<String> profiles = entity.getProfiles();
    profiles.clear();
    final Set<String> dtopf = dto.getProfiles();
    if (dtopf != null) {
        profiles.addAll(Sets.filter(dtopf, notNull()));
    }
    final Map<String, String> properties = entity.getProperties();
    properties.clear();
    final Map<String, String> dtopr = dto.getProperties();
    if (dtopr != null) {
        properties.putAll(Maps.filterKeys(Maps.filterValues(dtopr, notNull()), notNull()));
    }

    return entity;
}

From source file:org.apache.isis.core.runtime.services.changes.ChangedObjectsServiceInternal.java

private Set<Map.Entry<AdapterAndProperty, PreAndPostValues>> capturePostValuesAndDrain(
        final Map<AdapterAndProperty, PreAndPostValues> changedObjectProperties) {
    final Map<AdapterAndProperty, PreAndPostValues> processedObjectProperties1 = Maps.newLinkedHashMap();

    while (!changedObjectProperties.isEmpty()) {

        final Set<AdapterAndProperty> keys = Sets.newLinkedHashSet(changedObjectProperties.keySet());
        for (final AdapterAndProperty aap : keys) {

            final PreAndPostValues papv = changedObjectProperties.remove(aap);

            final ObjectAdapter adapter = aap.getAdapter();
            if (adapter.isDestroyed()) {
                // don't touch the object!!!
                // JDO, for example, will complain otherwise...
                papv.setPost(IsisTransaction.Placeholder.DELETED);
            } else {
                papv.setPost(aap.getPropertyValue());
            }//from w  w  w  .ja  v a 2s .  co m

            // if we encounter the same objectProperty again, this will simply overwrite it
            processedObjectProperties1.put(aap, papv);
        }
    }

    return Collections.unmodifiableSet(
            Sets.filter(processedObjectProperties1.entrySet(), PreAndPostValues.Predicates.CHANGED));
}

From source file:org.kaaproject.kaa.server.common.nosql.cassandra.dao.EndpointProfileCassandraDao.java

private CassandraEndpointProfile updateProfile(CassandraEndpointProfile profile) {
    LOG.debug("Updating endpoint profile with id {}", profile.getId());
    ByteBuffer epKeyHash = profile.getEndpointKeyHash();
    byte[] keyHash = getBytes(epKeyHash);
    CassandraEndpointProfile storedProfile = findByKeyHash(keyHash);
    if (storedProfile != null) {
        profile = super.save(profile);
        List<Statement> statementList = new ArrayList<>();

        Set<String> oldEndpointGroupIds = getEndpointProfilesGroupIdSet(storedProfile);
        Set<String> newEndpointGroupIds = getEndpointProfilesGroupIdSet(profile);

        Set<String> removeEndpointGroupIds = Sets.filter(oldEndpointGroupIds,
                Predicates.not(Predicates.in(newEndpointGroupIds)));

        Set<String> addEndpointGroupIds = Sets.filter(newEndpointGroupIds,
                Predicates.not(Predicates.in(oldEndpointGroupIds)));
        if (addEndpointGroupIds != null) {
            for (String id : addEndpointGroupIds) {
                statementList.add(cassandraEpByEndpointGroupIdDao
                        .getSaveQuery(new CassandraEpByEndpointGroupId(id, epKeyHash)));
            }/*from   ww  w  .  j  a  va2  s  .  c o  m*/

            if (removeEndpointGroupIds != null) {
                for (String id : removeEndpointGroupIds) {
                    statementList.add(delete().from(EP_BY_ENDPOINT_GROUP_ID_COLUMN_FAMILY_NAME)
                            .where(eq(EP_BY_ENDPOINT_GROUP_ID_ENDPOINT_GROUP_ID_PROPERTY, id))
                            .and(eq(EP_BY_ENDPOINT_GROUP_ID_ENDPOINT_KEY_HASH_PROPERTY, epKeyHash)));
                }
            }
            executeBatch(statementList.toArray(new Statement[statementList.size()]));
        } else {
            LOG.error("[{}] Can't update endpoint profile with version {}. "
                    + "Endpoint profile already changed!", profile.getId(), profile.getVersion());
            throw new KaaOptimisticLockingFailureException(
                    "Can't update endpoint profile with" + " version . Endpoint profile already changed!");
        }

        String accessToken = profile.getAccessToken();
        if (storedProfile.getAccessToken() != null && !storedProfile.getAccessToken().equals(accessToken)) {
            cassandraEpByAccessTokenDao.removeById(storedProfile.getAccessToken());
        }
        if (accessToken != null) {
            statementList.add(cassandraEpByAccessTokenDao
                    .getSaveQuery(new CassandraEpByAccessToken(accessToken, epKeyHash)));
        }
        executeBatch(statementList.toArray(new Statement[statementList.size()]));
        LOG.debug("[{}] Endpoint profile updated", profile.getId());
    } else {
        LOG.error("[{}] Stored profile is null. Can't update endpoint profile.", profile.getId());
        throw new DatabaseProcessingException("Stored profile is null. " + "Can't update endpoint profile.");
    }
    return profile;
}

From source file:org.jclouds.cleanup.doclet.ClassDocParser.java

public Bean parseBean(ClassDoc element, ParseOptions options, boolean asSuperClass) {
    checkNotNull(element, "element");
    checkNotNull(options, "options");

    ParseOptions.NullableHandling nullableHandling = options.getNullableHandling();
    Bean superClass = null;//www  .j  a v a 2  s.  co m
    if (element.superclassType() != null
            && !Objects.equal(element.superclassType().qualifiedTypeName(), "java.lang.Object")) {
        String superClassQualifiedName = element.superclassType().qualifiedTypeName();
        if (!CACHE.containsKey(superClassQualifiedName)) {
            LOG.debug("Parsing superclass " + superClassQualifiedName);
            parseBean(element.superclassType().asClassDoc(), options, true);
        }
        superClass = checkNotNull(CACHE.get(superClassQualifiedName),
                "oops failed to parse superclass " + superClassQualifiedName + " of " + element.name());
    }

    Bean bean = new Bean(superClass, element.containingPackage().toString(), element.isAbstract(), options,
            element.simpleTypeName(), getAnnotations(element),
            extractComment("Class " + element.name(), null, element));

    LOG.debug("Parsing bean " + bean);

    // Process imports
    List<String> lines = ImmutableList.of();
    try {
        if (element.position() != null && element.position().file() != null) {
            // This is actually helpful (oddly!)
            lines = ImmutableList.copyOf(
                    Strings2.toStringAndClose(new FileInputStream(element.position().file())).split("\n"));
        }
    } catch (IOException ex) {
        if (asSuperClass)
            LOG.debug("Failed to parse imports et al from superclass " + bean);
        else {
            LOG.error("Failed to parse imports et al for " + bean, ex);
            Throwables.propagate(ex);
        }
    }

    bean.addImports(Sets.filter(ImmutableSet.copyOf(lines), new Predicate<String>() {
        @Override
        public boolean apply(String input) {
            return input.trim().startsWith("import ");
        }
    }));

    // TODO this is re-indenting inner classes (sometimes unpleasantly!)
    // Process inner classes
    for (ClassDoc clazz : element.innerClasses()) {
        if (!clazz.simpleTypeName().toLowerCase().endsWith("builder")) {
            List<String> content = Lists.newArrayList();
            IndentedPrintWriter ipw = new IndentedPrintWriter(new NullOutputStream());
            ipw.println("{");
            for (int i = clazz.position().line(); ipw.currentIndent() > 0 && i < lines.size(); i++) {
                ipw.println(lines.get(i));
                content.add(lines.get(i).trim());
            }
            content.remove(content.size() - 1);
            LOG.debug("Processing inner class " + bean.getType() + "." + clazz.name());
            bean.addInnerClass(new InnerClass("public static " + (clazz.isEnum() ? "enum" : "class"),
                    clazz.simpleTypeName(), getAnnotations(clazz), extractComment(clazz), content));
        }
    }

    // Extract these bits of information from the ClassDoc data
    Map<String, String> serializedNames = Maps.newHashMap();
    Set<String> nullableFields = Sets.newHashSet();
    Map<String, MethodDoc> accessors = Maps.newHashMap();

    for (ConstructorDoc constructor : element.constructors()) {
        for (Parameter parameter : constructor.parameters()) {
            // options state field MUST be nullable
            if (nullableHandling.mustBeNullable(parameter.name())) {
                LOG.debug(nullableHandling + " marking " + bean.getType() + "." + parameter + " as nullable");
                nullableFields.add(parameter.name());
            }
            // options state field MAY be nullable
            if (nullableHandling.maybeNullable(parameter.name())) {
                for (AnnotationDesc anno : parameter.annotations()) {
                    if (Objects.equal(anno.annotationType().typeName(), "Nullable")) {
                        LOG.debug(nullableHandling + " marking " + bean.getType() + "." + parameter
                                + " as nullable (constructor annotation)");
                        nullableFields.add(parameter.name());
                    }
                }
            }
        }
    }

    // Inject/Named
    for (ConstructorDoc constructor : element.constructors()) {
        for (AnnotationDesc anno : constructor.annotations()) {
            if (Objects.equal(anno.annotationType().typeName(), "Inject")
                    || Objects.equal(anno.annotationType().typeName(), "ConstructorProperties")) {
                for (Parameter parameter : constructor.parameters()) {
                    // try to pick-up the associations with fields
                    String serializedName = getSerializedName(parameter.annotations());
                    if (serializedName != null) {
                        serializedNames.put(parameter.name(), serializedName);
                    }
                }
            }
        }
    }

    // ConstructorProperties
    for (ConstructorDoc constructor : element.constructors()) {
        Iterable<String> constructorProperties = null;
        for (AnnotationDesc anno : constructor.annotations()) {
            if (Objects.equal(anno.annotationType().typeName(), "ConstructorProperties")) {
                String stuff = anno.elementValues()[0].value().toString();
                constructorProperties = Splitter.on(",").trimResults(CharMatcher.anyOf("\t\n {}\""))
                        .split(stuff);
                break;
            }
        }

        // Try to map to actual field names...
        if (constructorProperties != null) {
            Iterator<String> it = constructorProperties.iterator();
            for (int i = 0; i < constructor.parameters().length && it.hasNext(); i++) {
                serializedNames.put(constructor.parameters()[i].name(), it.next());
            }
            break;
        }
    }

    // Look for accessor and field annotations
    for (FieldDoc field : element.fields()) {

        if (!field.isStatic()) {
            String fieldName = field.name();

            if (nullableHandling.maybeNullable(fieldName) && annotatatedAsNullable(field)) {
                LOG.debug(nullableHandling + " marking " + bean.getType() + "." + fieldName
                        + " as nullable (field annotation)");
                nullableFields.add(fieldName);
            }

            // Accessors first
            for (MethodDoc method : element.methods()) {
                if (Objects.equal(method.name(), getAccessorName(field))
                        || Objects.equal(method.name(), fieldName)) {
                    accessors.put(fieldName, method);
                    String serializedName = getSerializedName(method.annotations());
                    if (serializedName != null) {
                        LOG.debug(bean.getType() + "." + fieldName + " serialized name is " + serializedName
                                + " (getter annotation)");
                        serializedNames.put(fieldName, serializedName);
                    }
                    if (nullableHandling.maybeNullable(fieldName) && annotatatedAsNullable(method)) {
                        LOG.debug(nullableHandling + " marking " + bean.getType() + "." + fieldName
                                + " as nullable (getter annotation)");
                        nullableFields.add(fieldName);
                    }
                }
            }

            // Fields
            String serializedName = getSerializedName(field.annotations());
            if (serializedName != null) {
                LOG.debug(bean.getType() + "." + fieldName + " serialized name is " + serializedName
                        + " (field annotation)");
                serializedNames.put(fieldName, serializedName);
            }
        }
    }

    // Construct the fields
    for (FieldDoc field : element.fields()) {
        if (field.isStatic()) {
            LOG.debug("adding static field " + bean.getType() + "." + field.name());
            bean.addClassField(new ClassField(field.name(), properTypeName(field, bean.rawImports()),
                    getAnnotations(field),
                    extractComment(null, ImmutableMultimap.<String, String>of(), field)));
        } else {
            LOG.debug("adding instance field " + bean.getType() + "." + field.name());
            // Note we need to pick up any stray comments or annotations on accessors
            InstanceField instanceField = new InstanceField(field.name(), serializedNames.get(field.name()),
                    getAccessorName(field), properTypeName(field, bean.rawImports()),
                    nullableFields.contains(field.name()), getAnnotations(field), extractComment(null,
                            ImmutableMultimap.<String, String>of(), field, accessors.get(field.name())));
            bean.addInstanceField(instanceField);
        }
    }

    CACHE.put(element.qualifiedTypeName(), bean);

    return bean;
}

From source file:com.axelor.mail.service.MailServiceImpl.java

/**
 * Get the list of recipient email addresses.
 *
 * <p>/*from w  w  w  .j  a v  a 2s  .c  o m*/
 * The default implementation returns email addresses of all followers.
 * Custom implementation may include more per business requirement. For
 * example, including customer email on sale order is confirmed.
 * </p>
 *
 * @param message
 *            the message to send
 * @param entity
 *            the related entity, can be null if there is no related record
 * @return set of email addresses
 */
protected Set<String> recipients(final MailMessage message, Model entity) {
    final Set<String> recipients = new LinkedHashSet<>();
    final MailFollowerRepository followers = Beans.get(MailFollowerRepository.class);

    if (message.getRecipients() != null) {
        for (MailAddress address : message.getRecipients()) {
            recipients.add(address.getAddress());
        }
    }
    for (MailFollower follower : followers.findAll(message)) {
        if (follower.getEmail() != null && follower.getArchived() != Boolean.TRUE) {
            recipients.add(follower.getEmail().getAddress());
        }
    }

    return Sets.filter(recipients, Predicates.notNull());
}