Example usage for com.google.common.base Predicates in

List of usage examples for com.google.common.base Predicates in

Introduction

In this page you can find the example usage for com.google.common.base Predicates in.

Prototype

public static <T> Predicate<T> in(Collection<? extends T> target) 

Source Link

Document

Returns a predicate that evaluates to true if the object reference being tested is a member of the given collection.

Usage

From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }/*from  ww  w .  j a va  2  s  .  c  o  m*/
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.b2international.snowowl.datastore.server.CDORepositoryManager.java

@Override
public void sendMessageTo(final String message, final Iterable<String> userIds,
        final ISessionOperationCallback... callbacks) {
    Preconditions.checkNotNull(userIds, "User ID iterable argument cannot be null.");
    sendMessage(Predicates.in(Sets.newHashSet(userIds)), message, callbacks);
}

From source file:co.mitro.core.servlets.MutateOrganization.java

@Override
protected MitroRPC processCommand(MitroRequestContext context)
        throws IOException, SQLException, MitroServletException {
    try {//from   ww w  .  ja  v  a2  s. c  o m
        RPC.MutateOrganizationRequest in = gson.fromJson(context.jsonRequest,
                RPC.MutateOrganizationRequest.class);

        in.promotedMemberEncryptedKeys = MitroServlet.createMapIfNull(in.promotedMemberEncryptedKeys);
        in.newMemberGroupKeys = MitroServlet.createMapIfNull(in.newMemberGroupKeys);
        in.adminsToDemote = MitroServlet.uniquifyCollection(in.adminsToDemote);
        in.membersToRemove = MitroServlet.uniquifyCollection(in.membersToRemove);

        @SuppressWarnings("deprecation")
        AuthenticatedDB userDb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor);
        DBGroup org = userDb.getOrganizationAsAdmin(in.orgId);

        Set<String> adminsToDemote = Sets.newHashSet(in.adminsToDemote);
        Collection<DBAcl> aclsToRemove = new HashSet<>();
        Set<Integer> existingAdmins = new HashSet<>();
        for (DBAcl acl : org.getAcls()) {
            DBIdentity u = acl.loadMemberIdentity(context.manager.identityDao);
            assert (u != null); // toplevel groups should not have group members.
            if (adminsToDemote.contains(u.getName())) {
                aclsToRemove.add(acl);
                adminsToDemote.remove(u.getName());
            } else {
                existingAdmins.add(u.getId());
            }
        }
        // check for an attempt to promote members who are already admins.
        Set<Integer> duplicateAdmins = Sets.intersection(existingAdmins,
                DBIdentity.getUserIdsFromNames(context.manager, in.promotedMemberEncryptedKeys.keySet()));
        if (!duplicateAdmins.isEmpty()) {
            throw new MitroServletException(
                    "Operation would create duplicate admins: " + COMMA_JOINER.join(duplicateAdmins));
        }

        if (!adminsToDemote.isEmpty()) {
            throw new MitroServletException("The following users are not admins and could not be deleted:"
                    + COMMA_JOINER.join(adminsToDemote));
        }
        if (existingAdmins.isEmpty() && in.promotedMemberEncryptedKeys.isEmpty()) {
            throw new UserVisibleException("You cannot remove all admins from an organization");
        }

        // delete ACLs for the admin user on the group. This maybe should be using common code?
        context.manager.aclDao.delete(aclsToRemove);
        Map<Integer, Integer> currentMemberIdsToGroupIds = getMemberIdsAndPrivateGroupIdsForOrg(context.manager,
                org);

        // Promoted members (new admins) must be members after all changes
        Set<String> currentMembers = DBIdentity.getUserNamesFromIds(context.manager,
                currentMemberIdsToGroupIds.keySet());
        Set<String> membersAfterChanges = Sets.difference(
                Sets.union(currentMembers, in.newMemberGroupKeys.keySet()), new HashSet<>(in.membersToRemove));
        Set<String> nonMemberAdmins = Sets.difference(in.promotedMemberEncryptedKeys.keySet(),
                membersAfterChanges);
        if (!nonMemberAdmins.isEmpty()) {
            throw new MitroServletException(
                    "Cannot add admins without them being members: " + COMMA_JOINER.join(nonMemberAdmins));
        }

        // check for duplicate users
        Set<Integer> duplicateMembers = Sets.intersection(currentMemberIdsToGroupIds.keySet(),
                DBIdentity.getUserIdsFromNames(context.manager, in.newMemberGroupKeys.keySet()));
        if (!duplicateMembers.isEmpty()) {
            throw new MitroServletException(
                    "Operation would create duplicate members: " + COMMA_JOINER.join(duplicateMembers));
        }

        // delete all the private groups. This might orphan secrets, which is the intended result.
        Set<Integer> memberIdsToRemove = DBIdentity.getUserIdsFromNames(context.manager, in.membersToRemove);
        if (memberIdsToRemove.size() != in.membersToRemove.size()) {
            throw new MitroServletException("Invalid members to remove.");
        }

        Set<Integer> illegalRemovals = Sets.intersection(existingAdmins, memberIdsToRemove);
        if (!illegalRemovals.isEmpty()) {
            throw new MitroServletException(
                    "Cannot remove members who are admins:" + COMMA_JOINER.join(illegalRemovals));
        }
        Set<Integer> nonOrgUsers = Sets.difference(memberIdsToRemove, currentMemberIdsToGroupIds.keySet());
        if (!nonOrgUsers.isEmpty()) {
            throw new MitroServletException("The following users are not members and cannot be removed:"
                    + COMMA_JOINER.join(nonOrgUsers));
        }
        Set<Integer> deleteGroupIds = Sets.newHashSet(
                Maps.filterKeys(currentMemberIdsToGroupIds, Predicates.in(memberIdsToRemove)).values());
        if (!deleteGroupIds.isEmpty()) {
            context.manager.groupDao.deleteIds(deleteGroupIds);
            DeleteBuilder<DBAcl, Integer> deleter = context.manager.aclDao.deleteBuilder();
            deleter.where().in(DBAcl.GROUP_ID_FIELD_NAME, deleteGroupIds);
            deleter.delete();

            DeleteBuilder<DBGroupSecret, Integer> gsDeleter = context.manager.groupSecretDao.deleteBuilder();
            gsDeleter.where().in(DBGroupSecret.GROUP_ID_NAME, deleteGroupIds);
            gsDeleter.delete();
        }

        // Remove the user from all org-owned group to which he belongs.
        // Note: if the user has access to an org-owned secret via a non-org-owned group, 
        // he will retain access. 
        Set<Integer> allOrgGroupIds = Sets.newHashSet();
        for (DBGroup g : org.getAllOrgGroups(context.manager)) {
            allOrgGroupIds.add(g.getId());
        }
        if (!memberIdsToRemove.isEmpty()) {
            if (!allOrgGroupIds.isEmpty()) {
                // Remove users from organization-owned groups (named or otherwise)
                DeleteBuilder<DBAcl, Integer> deleter = context.manager.aclDao.deleteBuilder();
                deleter.where().in(DBAcl.MEMBER_IDENTITY_FIELD_NAME, memberIdsToRemove).and()
                        .in(DBAcl.GROUP_ID_FIELD_NAME, allOrgGroupIds);
                deleter.delete();
            }

            // Remove users from any org-owned secrets (e.g. via non-org private or named groups)
            HashMap<Integer, SecretToPath> orgSecretsToPath = new HashMap<>();
            ListMySecretsAndGroupKeys.getSecretInfo(context, AdminAccess.FORCE_ACCESS_VIA_TOPLEVEL_GROUPS,
                    orgSecretsToPath, ImmutableSet.of(org.getId()), null,
                    IncludeAuditLogInfo.NO_AUDIT_LOG_INFO);
            if (orgSecretsToPath.size() > 0) {
                // Delete any group secret giving these users access to org secrets
                // strange side effect: personal teams may be mysteriously removed from org secrets
                // TODO: Potential bug: removing the last personal team will "orphan" the secret
                String groupSecretDelete = String.format(
                        "DELETE FROM group_secret WHERE id IN ("
                                + "SELECT group_secret.id FROM group_secret, acl WHERE "
                                + "  group_secret.\"serverVisibleSecret_id\" IN (%s) AND "
                                + "  group_secret.group_id = acl.group_id AND acl.member_identity IN (%s))",
                        COMMA_JOINER.join(orgSecretsToPath.keySet()), COMMA_JOINER.join(memberIdsToRemove));
                context.manager.groupSecretDao.executeRaw(groupSecretDelete);
            }
        }

        List<DBAcl> organizationAcls = CreateOrganization.makeAdminAclsForOrganization(userDb, org,
                in.promotedMemberEncryptedKeys);

        // TODO: move to authdb?
        for (DBAcl acl : organizationAcls) {
            context.manager.aclDao.create(acl);
        }

        // create private groups for each new member
        CreateOrganization.addMembersToOrganization(userDb, org, in.newMemberGroupKeys, context.manager);

        context.manager.addAuditLog(DBAudit.ACTION.MUTATE_ORGANIZATION, null, null, org, null, "");

        MutateOrganizationResponse out = new RPC.MutateOrganizationResponse();
        // TODO: validate the group?
        return out;

    } catch (CyclicGroupError e) {
        throw new MitroServletException(e);
    }
}

From source file:org.splevo.ui.vpexplorer.providers.VPExplorerContentProvider.java

/**
 * @param parentElement/* ww  w  .j  av  a2s . c  o m*/
 * @return
 */
private Object[] getChildren(FileWrapper parentElement) {
    File parentFile = parentElement.getFile();
    List<Object> children = Lists.newArrayList();

    Collection<File> childFileInGroup = (Collections2.filter(subFileIndex.get(parentFile),
            Predicates.in(groupFileIndex.get(parentElement.getGroup()))));

    for (File file : childFileInGroup) {
        children.add(new FileWrapper(parentElement, file, parentElement.getGroup()));
    }
    Collection<VariationPoint> childVPInGroup = (Collections2.filter(fileVPIndex.get(parentFile),
            Predicates.in(parentElement.getGroup().getVariationPoints())));
    children.addAll(childVPInGroup);

    return children.toArray();
}

From source file:org.eclipse.sirius.business.internal.session.danalysis.DanglingRefRemovalTrigger.java

@Override
public Option<Command> localChangesAboutToCommit(Collection<Notification> notifications) {
    final Set<EObject> allDetachedObjects = getChangedEObjectsAndChildren(
            Iterables.filter(notifications, IS_DETACHMENT), null);
    if (allDetachedObjects.size() > 0) {
        DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY);

        // Predicate to ignore attachments to detached elements.
        Predicate<EObject> ignoreNotifierInDetachedObjects = Predicates.in(allDetachedObjects);
        final Set<EObject> allAttachedObjects = getChangedEObjectsAndChildren(
                Iterables.filter(notifications, IS_ATTACHMENT), ignoreNotifierInDetachedObjects);
        final Set<EObject> toRemoveXRefFrom = Sets.difference(allDetachedObjects, allAttachedObjects);
        if (toRemoveXRefFrom.size() > 0) {
            EReferencePredicate refToIgnore = new EReferencePredicate() {
                @Override/*from ww  w . j a v  a  2 s.c  o  m*/
                public boolean apply(EReference ref) {
                    return DSEMANTICDECORATOR_REFERENCE_TO_IGNORE_PREDICATE.apply(ref)
                            || NOTATION_VIEW_ELEMENT_REFERENCE_TO_IGNORE_PREDICATE.apply(ref)
                            || EPACKAGE_EFACTORYINSTANCE_REFERENCE_TO_IGNORE_PREDICATE.apply(ref);
                }
            };

            Command removeDangling = new RemoveDanglingReferencesCommand(
                    session.getTransactionalEditingDomain(), session.getModelAccessor(),
                    session.getSemanticCrossReferencer(), session.getSemanticResources(),
                    session.getRefreshEditorsListener(), toRemoveXRefFrom, refToIgnore);
            DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY);
            return Options.newSome(removeDangling);
        }
        DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CLEANING_REMOVEDANGLING_KEY);
    }
    return Options.newNone();
}

From source file:net.derquinse.common.meta.MetaProperty.java

/**
 * Returns a predicate that evaluates to {@code true} if the property value being tested is a
 * member of the given collection. It does not defensively copy the collection passed in, so
 * future changes to it will alter the behavior of the predicate. This method can technically
 * accept any Collection<?>, but using a typed collection helps prevent bugs. This approach
 * doesn't block any potential users since it is always possible to use
 * {@code Predicates.<Object>in()}.
 * @param target The collection that may contain the property value.
 *//*  www.j  a  v a 2s  . c o  m*/
public final Predicate<C> in(Collection<? extends T> target) {
    return compose(Predicates.in(target));
}

From source file:com.google.caliper.runner.CaliperRun.java

private static Collection<BenchmarkMethod> chooseBenchmarkMethods(BenchmarkClass benchmarkClass,
        Instrument instrument, CaliperOptions options) throws InvalidBenchmarkException {
    ImmutableMap<String, BenchmarkMethod> methodMap = benchmarkClass.findAllBenchmarkMethods(instrument);

    ImmutableSet<String> names = options.benchmarkMethodNames();

    // TODO(kevinb): this doesn't seem to prevent bogus names on cmd line yet
    return names.isEmpty() ? methodMap.values() : Maps.filterKeys(methodMap, Predicates.in(names)).values();
}

From source file:org.gitools.heatmap.AbstractMatrixViewDimension.java

@Override
public IMatrixDimension subset(Set<String> identifiers) {
    return new HashMatrixDimension(getId(), Iterables.filter(visible, Predicates.in(identifiers)));
}

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

private Set<Pilot> filteredPilots(Race race) {
    ImmutableSet.Builder<Pilot> pilots = ImmutableSet.builder();
    for (RaceAttendee attendee : Maps.filterKeys(race.getAttendees(), Predicates.in(scores.getFleet()))
            .values()) {/*from  w w w . j  av  a  2 s.  co  m*/
        if (attendee.getType() == RaceAttendee.Type.PILOT) {
            pilots.add(attendee.getPilot());
        }
    }
    return pilots.build();
}

From source file:org.caleydo.vis.lineup.model.MultiCategoricalRankColumnModel.java

@Override
protected void updateMask(BitSet todo, List<IRow> data, BitSet mask) {
    for (int i = todo.nextSetBit(0); i >= 0; i = todo.nextSetBit(i + 1)) {
        Set<CATEGORY_TYPE> v = this.data.apply(data.get(i));
        if ((v == null || v.isEmpty()) && filterNA)
            mask.set(i, false);//w ww  . ja  va2  s  . c  om
        else
            mask.set(i, v == null ? true : Iterables.any(v, Predicates.in(selection)));
    }
}