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:ezbake.security.service.processor.EzSecurityHandler.java

protected Set<String> filterCommunityAuthorizations(Set<String> auths, Set<String> appAuths,
        Set<String> targetAppAuths, List<String> chain) throws AppNotRegisteredException {

    // Set up the filter by intersecting all apps
    if (targetAppAuths != null) {
        appAuths.retainAll(targetAppAuths);
    }//from   w w w . ja  v  a2  s . co  m
    if (chain != null) {
        for (String securityIdLink : chain) {
            appAuths.addAll(Sets.newHashSet(
                    fetchApplication(securityIdLink).getRegistration().getCommunityAuthorizations()));
        }
    }

    auths = Sets.intersection(auths, appAuths);
    return Sets.filter(auths, Predicates.and(Predicates.notNull(), Predicates.not(Predicates.equalTo(""))));
}

From source file:ezbake.security.service.processor.EzSecurityHandler.java

protected Set<String> filterAuthorizations(Set<String> auths, Set<String> appAuths, Set<String> targetAppAuths,
        Set<String> preFiltered, List<String> chain) throws AppNotRegisteredException {

    if (preFiltered != null) {
        appAuths = Sets.intersection(appAuths, preFiltered);
    } else if (chain != null && !chain.isEmpty()) {
        appAuths = getAuthorizationsFromChain(Sets.newHashSet(chain), appAuths);
    }/*  www. j  a  v  a  2 s . com*/

    auths = Sets.intersection(auths, appAuths);
    if (targetAppAuths != null) {
        auths = Sets.intersection(auths, targetAppAuths);
    }

    return Sets.filter(auths, Predicates.and(Predicates.notNull(), Predicates.not(Predicates.equalTo(""))));
}

From source file:dagger2.internal.codegen.ComponentGenerator.java

private void initializeFrameworkTypes(BindingGraph input, ClassWriter componentWriter,
        ConstructorWriter constructorWriter, Optional<ClassName> builderName,
        Map<TypeElement, MemberSelect> componentContributionFields,
        ImmutableMap<BindingKey, MemberSelect> memberSelectSnippets,
        ImmutableMap<ContributionBinding, Snippet> parentMultibindingContributionSnippets,
        ImmutableMap<ContributionBinding, Snippet> multibindingContributionSnippets) throws AssertionError {
    List<List<BindingKey>> partitions = Lists.partition(input.resolvedBindings().keySet().asList(), 100);
    for (int i = 0; i < partitions.size(); i++) {
        MethodWriter initializeMethod = componentWriter.addMethod(VoidName.VOID,
                "initialize" + ((i == 0) ? "" : i));
        initializeMethod.body();//w ww.  ja  v a 2s.  com
        initializeMethod.addModifiers(PRIVATE);
        if (builderName.isPresent()) {
            initializeMethod.addParameter(builderName.get(), "builder").addModifiers(FINAL);
            constructorWriter.body().addSnippet("%s(builder);", initializeMethod.name());
        } else {
            constructorWriter.body().addSnippet("%s();", initializeMethod.name());
        }

        for (BindingKey bindingKey : partitions.get(i)) {
            Snippet memberSelectSnippet = memberSelectSnippets.get(bindingKey)
                    .getSnippetFor(componentWriter.name());
            ResolvedBindings resolvedBindings = input.resolvedBindings().get(bindingKey);
            switch (bindingKey.kind()) {
            case CONTRIBUTION:
                ImmutableSet<? extends ContributionBinding> bindings = resolvedBindings.contributionBindings();

                switch (ContributionBinding.bindingTypeFor(bindings)) {
                case SET:
                    boolean hasOnlyProvisions = Iterables.all(bindings,
                            Predicates.instanceOf(ProvisionBinding.class));
                    ImmutableList.Builder<Snippet> parameterSnippets = ImmutableList.builder();
                    for (ContributionBinding binding : bindings) {
                        if (multibindingContributionSnippets.containsKey(binding)) {
                            Snippet initializeSnippet = initializeFactoryForContributionBinding(binding, input,
                                    componentWriter.name(), componentContributionFields, memberSelectSnippets);
                            Snippet snippet = multibindingContributionSnippets.get(binding);
                            initializeMethod.body().addSnippet("this.%s = %s;", snippet, initializeSnippet);
                            parameterSnippets.add(snippet);
                        } else if (parentMultibindingContributionSnippets.containsKey(binding)) {
                            parameterSnippets.add(parentMultibindingContributionSnippets.get(binding));
                        } else {
                            throw new IllegalStateException(binding + " was not found in");
                        }
                    }
                    Snippet initializeSetSnippet = Snippet.format("%s.create(%s)",
                            hasOnlyProvisions ? ClassName.fromClass(SetFactory.class)
                                    : ClassName.fromClass(SetProducer.class),
                            Snippet.makeParametersSnippet(parameterSnippets.build()));
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeSetSnippet);
                    break;
                case MAP:
                    if (Sets.filter(bindings, Predicates.instanceOf(ProductionBinding.class)).isEmpty()) {
                        @SuppressWarnings("unchecked") // checked by the instanceof filter above
                        ImmutableSet<ProvisionBinding> provisionBindings = (ImmutableSet<ProvisionBinding>) bindings;
                        for (ProvisionBinding provisionBinding : provisionBindings) {
                            if (!isNonProviderMap(provisionBinding)
                                    && multibindingContributionSnippets.containsKey(provisionBinding)) {
                                Snippet snippet = multibindingContributionSnippets.get(provisionBinding);
                                initializeMethod.body().addSnippet("this.%s = %s;", snippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        }
                        if (!provisionBindings.isEmpty()) {
                            Snippet initializeMapSnippet = initializeMapBinding(componentWriter.name(),
                                    memberSelectSnippets,
                                    new ImmutableMap.Builder<ContributionBinding, Snippet>()
                                            .putAll(parentMultibindingContributionSnippets)
                                            .putAll(multibindingContributionSnippets).build(),
                                    provisionBindings);
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeMapSnippet);
                        }
                    } else {
                        // TODO(user): Implement producer map bindings.
                        throw new IllegalStateException("producer map bindings not implemented yet");
                    }
                    break;
                case UNIQUE:
                    if (!resolvedBindings.ownedContributionBindings().isEmpty()) {
                        ContributionBinding binding = Iterables.getOnlyElement(bindings);
                        if (binding instanceof ProvisionBinding) {
                            ProvisionBinding provisionBinding = (ProvisionBinding) binding;
                            if (!provisionBinding.factoryCreationStrategy().equals(ENUM_INSTANCE)
                                    || provisionBinding.scope().isPresent()) {
                                initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                        initializeFactoryForProvisionBinding(provisionBinding,
                                                componentWriter.name(),
                                                input.componentDescriptor().dependencyMethodIndex(),
                                                componentContributionFields, memberSelectSnippets));
                            }
                        } else if (binding instanceof ProductionBinding) {
                            ProductionBinding productionBinding = (ProductionBinding) binding;
                            initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                                    initializeFactoryForProductionBinding(productionBinding, input,
                                            componentWriter.name(),
                                            input.componentDescriptor().dependencyMethodIndex(),
                                            componentContributionFields, memberSelectSnippets));
                        } else {
                            throw new AssertionError();
                        }
                    }
                    break;
                default:
                    throw new IllegalStateException();
                }
                break;
            case MEMBERS_INJECTION:
                MembersInjectionBinding binding = Iterables
                        .getOnlyElement(resolvedBindings.membersInjectionBindings());
                if (!binding.injectionStrategy().equals(MembersInjectionBinding.Strategy.NO_OP)) {
                    initializeMethod.body().addSnippet("this.%s = %s;", memberSelectSnippet,
                            initializeMembersInjectorForBinding(componentWriter.name(), binding,
                                    memberSelectSnippets));
                }
                break;
            default:
                throw new AssertionError();
            }
        }
    }
}

From source file:org.apache.beam.sdk.options.PipelineOptionsFactory.java

/**
 * Validates that getters don't have mixed annotation.
 */// w w  w  .  ja v  a  2  s.com
private static void validateGettersHaveConsistentAnnotation(
        SortedSetMultimap<Method, Method> methodNameToAllMethodMap, List<PropertyDescriptor> descriptors,
        final AnnotationPredicates annotationPredicates) {
    List<InconsistentlyAnnotatedGetters> inconsistentlyAnnotatedGetters = new ArrayList<>();
    for (final PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getReadMethod() == null || IGNORED_METHODS.contains(descriptor.getReadMethod())) {
            continue;
        }

        SortedSet<Method> getters = methodNameToAllMethodMap.get(descriptor.getReadMethod());
        SortedSet<Method> gettersWithTheAnnotation = Sets.filter(getters, annotationPredicates.forMethod);
        Set<Annotation> distinctAnnotations = Sets
                .newLinkedHashSet(FluentIterable.from(gettersWithTheAnnotation)
                        .transformAndConcat(new Function<Method, Iterable<? extends Annotation>>() {
                            @Nonnull
                            @Override
                            public Iterable<? extends Annotation> apply(@Nonnull Method method) {
                                return FluentIterable.of(method.getAnnotations());
                            }
                        }).filter(annotationPredicates.forAnnotation));

        if (distinctAnnotations.size() > 1) {
            throw new IllegalArgumentException(
                    String.format("Property [%s] is marked with contradictory annotations. Found [%s].",
                            descriptor.getName(), FluentIterable.from(gettersWithTheAnnotation)
                                    .transformAndConcat(new Function<Method, Iterable<String>>() {
                                        @Nonnull
                                        @Override
                                        public Iterable<String> apply(final @Nonnull Method method) {
                                            return FluentIterable.of(method.getAnnotations())
                                                    .filter(annotationPredicates.forAnnotation)
                                                    .transform(new Function<Annotation, String>() {
                                                        @Nonnull
                                                        @Override
                                                        public String apply(@Nonnull Annotation annotation) {
                                                            return String.format("[%s on %s]",
                                                                    ReflectHelpers.ANNOTATION_FORMATTER
                                                                            .apply(annotation),
                                                                    ReflectHelpers.CLASS_AND_METHOD_FORMATTER
                                                                            .apply(method));
                                                        }
                                                    });

                                        }
                                    }).join(Joiner.on(", "))));
        }

        Iterable<String> getterClassNames = FluentIterable.from(getters)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);
        Iterable<String> gettersWithTheAnnotationClassNames = FluentIterable.from(gettersWithTheAnnotation)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);

        if (!(gettersWithTheAnnotation.isEmpty() || getters.size() == gettersWithTheAnnotation.size())) {
            InconsistentlyAnnotatedGetters err = new InconsistentlyAnnotatedGetters();
            err.descriptor = descriptor;
            err.getterClassNames = getterClassNames;
            err.gettersWithTheAnnotationClassNames = gettersWithTheAnnotationClassNames;
            inconsistentlyAnnotatedGetters.add(err);
        }
    }
    throwForGettersWithInconsistentAnnotation(inconsistentlyAnnotatedGetters,
            annotationPredicates.annotationClass);
}

From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.java

/**
 * Validates that a given class conforms to the following properties:
 * <ul>/*from  ww w .j  a va  2  s.c  o m*/
 *   <li>Any property with the same name must have the same return type for all derived
 *       interfaces of {@link PipelineOptions}.
 *   <li>Every bean property of any interface derived from {@link PipelineOptions} must have a
 *       getter and setter method.
 *   <li>Every method must conform to being a getter or setter for a JavaBean.
 *   <li>Only getters may be annotated with {@link JsonIgnore @JsonIgnore}.
 *   <li>If any getter is annotated with {@link JsonIgnore @JsonIgnore}, then all getters for
 *       this property must be annotated with {@link JsonIgnore @JsonIgnore}.
 * </ul>
 *
 * @param iface The interface to validate.
 * @param validatedPipelineOptionsInterfaces The set of validated pipeline options interfaces to
 *        validate against.
 * @param klass The proxy class representing the interface.
 * @return A list of {@link PropertyDescriptor}s representing all valid bean properties of
 *         {@code iface}.
 * @throws IntrospectionException if invalid property descriptors.
 */
private static List<PropertyDescriptor> validateClass(Class<? extends PipelineOptions> iface,
        Set<Class<? extends PipelineOptions>> validatedPipelineOptionsInterfaces,
        Class<? extends PipelineOptions> klass) throws IntrospectionException {
    Set<Method> methods = Sets.newHashSet(IGNORED_METHODS);
    // Ignore synthetic methods
    for (Method method : klass.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) || method.isSynthetic()) {
            methods.add(method);
        }
    }
    // Ignore standard infrastructure methods on the generated class.
    try {
        methods.add(klass.getMethod("equals", Object.class));
        methods.add(klass.getMethod("hashCode"));
        methods.add(klass.getMethod("toString"));
        methods.add(klass.getMethod("as", Class.class));
        methods.add(klass.getMethod("cloneAs", Class.class));
        methods.add(klass.getMethod("populateDisplayData", DisplayData.Builder.class));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException(e);
    }

    // Verify that there are no methods with the same name with two different return types.
    Iterable<Method> interfaceMethods = FluentIterable
            .from(ReflectHelpers.getClosureOfMethodsOnInterface(iface)).filter(NOT_SYNTHETIC_PREDICATE)
            .toSortedSet(MethodComparator.INSTANCE);
    SortedSetMultimap<Method, Method> methodNameToMethodMap = TreeMultimap.create(MethodNameComparator.INSTANCE,
            MethodComparator.INSTANCE);
    for (Method method : interfaceMethods) {
        methodNameToMethodMap.put(method, method);
    }
    List<MultipleDefinitions> multipleDefinitions = Lists.newArrayList();
    for (Map.Entry<Method, Collection<Method>> entry : methodNameToMethodMap.asMap().entrySet()) {
        Set<Class<?>> returnTypes = FluentIterable.from(entry.getValue())
                .transform(ReturnTypeFetchingFunction.INSTANCE).toSet();
        SortedSet<Method> collidingMethods = FluentIterable.from(entry.getValue())
                .toSortedSet(MethodComparator.INSTANCE);
        if (returnTypes.size() > 1) {
            MultipleDefinitions defs = new MultipleDefinitions();
            defs.method = entry.getKey();
            defs.collidingMethods = collidingMethods;
            multipleDefinitions.add(defs);
        }
    }
    throwForMultipleDefinitions(iface, multipleDefinitions);

    // Verify that there is no getter with a mixed @JsonIgnore annotation and verify
    // that no setter has @JsonIgnore.
    Iterable<Method> allInterfaceMethods = FluentIterable
            .from(ReflectHelpers.getClosureOfMethodsOnInterfaces(validatedPipelineOptionsInterfaces))
            .append(ReflectHelpers.getClosureOfMethodsOnInterface(iface)).filter(NOT_SYNTHETIC_PREDICATE)
            .toSortedSet(MethodComparator.INSTANCE);
    SortedSetMultimap<Method, Method> methodNameToAllMethodMap = TreeMultimap
            .create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE);
    for (Method method : allInterfaceMethods) {
        methodNameToAllMethodMap.put(method, method);
    }

    List<PropertyDescriptor> descriptors = getPropertyDescriptors(klass);

    List<InconsistentlyIgnoredGetters> incompletelyIgnoredGetters = new ArrayList<>();
    List<IgnoredSetter> ignoredSetters = new ArrayList<>();

    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getReadMethod() == null || descriptor.getWriteMethod() == null
                || IGNORED_METHODS.contains(descriptor.getReadMethod())
                || IGNORED_METHODS.contains(descriptor.getWriteMethod())) {
            continue;
        }
        SortedSet<Method> getters = methodNameToAllMethodMap.get(descriptor.getReadMethod());
        SortedSet<Method> gettersWithJsonIgnore = Sets.filter(getters, JsonIgnorePredicate.INSTANCE);

        Iterable<String> getterClassNames = FluentIterable.from(getters)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);
        Iterable<String> gettersWithJsonIgnoreClassNames = FluentIterable.from(gettersWithJsonIgnore)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);

        if (!(gettersWithJsonIgnore.isEmpty() || getters.size() == gettersWithJsonIgnore.size())) {
            InconsistentlyIgnoredGetters err = new InconsistentlyIgnoredGetters();
            err.descriptor = descriptor;
            err.getterClassNames = getterClassNames;
            err.gettersWithJsonIgnoreClassNames = gettersWithJsonIgnoreClassNames;
            incompletelyIgnoredGetters.add(err);
        }
        if (!incompletelyIgnoredGetters.isEmpty()) {
            continue;
        }

        SortedSet<Method> settersWithJsonIgnore = Sets.filter(
                methodNameToAllMethodMap.get(descriptor.getWriteMethod()), JsonIgnorePredicate.INSTANCE);

        Iterable<String> settersWithJsonIgnoreClassNames = FluentIterable.from(settersWithJsonIgnore)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);

        if (!settersWithJsonIgnore.isEmpty()) {
            IgnoredSetter ignored = new IgnoredSetter();
            ignored.descriptor = descriptor;
            ignored.settersWithJsonIgnoreClassNames = settersWithJsonIgnoreClassNames;
            ignoredSetters.add(ignored);
        }
    }
    throwForGettersWithInconsistentJsonIgnore(incompletelyIgnoredGetters);
    throwForSettersWithJsonIgnore(ignoredSetters);

    List<MissingBeanMethod> missingBeanMethods = new ArrayList<>();
    // Verify that each property has a matching read and write method.
    for (PropertyDescriptor propertyDescriptor : descriptors) {
        if (!(IGNORED_METHODS.contains(propertyDescriptor.getWriteMethod())
                || propertyDescriptor.getReadMethod() != null)) {
            MissingBeanMethod method = new MissingBeanMethod();
            method.property = propertyDescriptor;
            method.methodType = "getter";
            missingBeanMethods.add(method);
            continue;
        }
        if (!(IGNORED_METHODS.contains(propertyDescriptor.getReadMethod())
                || propertyDescriptor.getWriteMethod() != null)) {
            MissingBeanMethod method = new MissingBeanMethod();
            method.property = propertyDescriptor;
            method.methodType = "setter";
            missingBeanMethods.add(method);
            continue;
        }
        methods.add(propertyDescriptor.getReadMethod());
        methods.add(propertyDescriptor.getWriteMethod());
    }
    throwForMissingBeanMethod(iface, missingBeanMethods);

    // Verify that no additional methods are on an interface that aren't a bean property.
    SortedSet<Method> unknownMethods = new TreeSet<>(MethodComparator.INSTANCE);
    unknownMethods.addAll(Sets.filter(Sets.difference(Sets.newHashSet(klass.getMethods()), methods),
            NOT_SYNTHETIC_PREDICATE));
    checkArgument(unknownMethods.isEmpty(), "Methods %s on [%s] do not conform to being bean properties.",
            FluentIterable.from(unknownMethods).transform(ReflectHelpers.METHOD_FORMATTER), iface.getName());

    return descriptors;
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java

@Override
public Set<String> getAllTableNames() {
    final CassandraKeyValueServiceConfig config = configManager.getConfig();
    List<Row> rows = session.execute(cqlStatementCache.NORMAL_QUERY
            .getUnchecked("SELECT columnfamily_name FROM system.schema_columnfamilies WHERE keyspace_name = ?")
            .bind(config.keyspace())).all();

    Set<String> existingTables = Sets.newHashSet(Iterables.transform(rows, new Function<Row, String>() {
        @Override/*from w  w  w.  j  av  a2  s .  c o  m*/
        public String apply(Row row) {
            return row.getString("columnfamily_name");
        }
    }));

    return Sets.filter(existingTables, new Predicate<String>() {
        @Override
        public boolean apply(String tableName) {
            return !tableName.startsWith("_") || tableName.startsWith(AtlasDbConstants.NAMESPACE_PREFIX);
        }
    });
}

From source file:org.apache.beam.sdk.options.PipelineOptionsFactory.java

/**
 * Validates that setters don't have the given annotation.
 *///from   ww w. j  a va 2s . c o m
private static void validateSettersDoNotHaveAnnotation(
        SortedSetMultimap<Method, Method> methodNameToAllMethodMap, List<PropertyDescriptor> descriptors,
        AnnotationPredicates annotationPredicates) {
    List<AnnotatedSetter> annotatedSetters = new ArrayList<>();
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() == null || IGNORED_METHODS.contains(descriptor.getWriteMethod())) {
            continue;
        }
        SortedSet<Method> settersWithTheAnnotation = Sets.filter(
                methodNameToAllMethodMap.get(descriptor.getWriteMethod()), annotationPredicates.forMethod);

        Iterable<String> settersWithTheAnnotationClassNames = FluentIterable.from(settersWithTheAnnotation)
                .transform(MethodToDeclaringClassFunction.INSTANCE).transform(ReflectHelpers.CLASS_NAME);

        if (!settersWithTheAnnotation.isEmpty()) {
            AnnotatedSetter annotated = new AnnotatedSetter();
            annotated.descriptor = descriptor;
            annotated.settersWithTheAnnotationClassNames = settersWithTheAnnotationClassNames;
            annotatedSetters.add(annotated);
        }
    }
    throwForSettersWithTheAnnotation(annotatedSetters, annotationPredicates.annotationClass);
}

From source file:org.apache.beam.sdk.options.PipelineOptionsFactory.java

/**
 * Validates that every non-static or synthetic method is either a known method such as
 * {@link PipelineOptions#as} or a bean property.
 *
 * @param iface The interface to validate.
 * @param klass The proxy class representing the interface.
 *///from w  ww .  ja  va 2  s  . c om
private static void validateMethodsAreEitherBeanMethodOrKnownMethod(Class<? extends PipelineOptions> iface,
        Class<? extends PipelineOptions> klass, List<PropertyDescriptor> descriptors) {
    Set<Method> knownMethods = Sets.newHashSet(IGNORED_METHODS);
    // Ignore synthetic methods
    for (Method method : klass.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) || method.isSynthetic()) {
            knownMethods.add(method);
        }
    }
    // Ignore methods on the base PipelineOptions interface.
    try {
        knownMethods.add(iface.getMethod("as", Class.class));
        knownMethods.add(iface.getMethod("outputRuntimeOptions"));
        knownMethods.add(iface.getMethod("populateDisplayData", DisplayData.Builder.class));
    } catch (NoSuchMethodException | SecurityException e) {
        throw new RuntimeException(e);
    }
    for (PropertyDescriptor descriptor : descriptors) {
        knownMethods.add(descriptor.getReadMethod());
        knownMethods.add(descriptor.getWriteMethod());
    }
    final Set<String> knownMethodsNames = Sets.newHashSet();
    for (Method method : knownMethods) {
        knownMethodsNames.add(method.getName());
    }

    // Verify that no additional methods are on an interface that aren't a bean property.
    // Because methods can have multiple declarations, we do a name-based comparison
    // here to prevent false positives.
    SortedSet<Method> unknownMethods = new TreeSet<>(MethodComparator.INSTANCE);
    unknownMethods.addAll(Sets.filter(Sets.difference(Sets.newHashSet(iface.getMethods()), knownMethods),
            Predicates.and(NOT_SYNTHETIC_PREDICATE, new Predicate<Method>() {
                @Override
                public boolean apply(@Nonnull Method input) {
                    return !knownMethodsNames.contains(input.getName());
                }
            })));
    checkArgument(unknownMethods.isEmpty(), "Methods %s on [%s] do not conform to being bean properties.",
            FluentIterable.from(unknownMethods).transform(ReflectHelpers.METHOD_FORMATTER), iface.getName());
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

/**
 * This will throw if we have a value changed conflict.  This means that either we changed the
 * value and anyone did a write after our start timestamp, or we just touched the value (put the
 * same value as before) and a changed value was written after our start time.
 *//*from w  w  w  .ja v  a 2  s. com*/
private void throwIfValueChangedConflict(String table, Map<Cell, byte[]> writes,
        Set<CellConflict> spanningWrites, Set<CellConflict> dominatingWrites,
        LockRefreshToken commitLocksToken) {
    Map<Cell, CellConflict> cellToConflict = Maps.newHashMap();
    Map<Cell, Long> cellToTs = Maps.newHashMap();
    for (CellConflict c : Sets.union(spanningWrites, dominatingWrites)) {
        cellToConflict.put(c.cell, c);
        cellToTs.put(c.cell, c.theirStart + 1);
    }

    Map<Cell, byte[]> oldValues = getIgnoringLocalWrites(table, cellToTs.keySet());
    Map<Cell, Value> conflictingValues = keyValueService.get(table, cellToTs);

    Set<Cell> conflictingCells = Sets.newHashSet();
    for (Entry<Cell, Long> cellEntry : cellToTs.entrySet()) {
        Cell cell = cellEntry.getKey();
        if (!writes.containsKey(cell)) {
            Validate.isTrue(false,
                    "Missing write for cell: " + cellToConflict.get(cell) + " for table " + table);
        }
        if (!conflictingValues.containsKey(cell)) {
            // This error case could happen if our locks expired.
            throwIfExternalAndCommitLocksNotValid(commitLocksToken);
            Validate.isTrue(false,
                    "Missing conflicting value for cell: " + cellToConflict.get(cell) + " for table " + table);
        }
        if (conflictingValues.get(cell).getTimestamp() != (cellEntry.getValue() - 1)) {
            // This error case could happen if our locks expired.
            throwIfExternalAndCommitLocksNotValid(commitLocksToken);
            Validate.isTrue(false, "Wrong timestamp for cell in table " + table + " Expected: "
                    + cellToConflict.get(cell) + " Actual: " + conflictingValues.get(cell));
        }
        @Nullable
        byte[] oldVal = oldValues.get(cell);
        byte[] writeVal = writes.get(cell);
        byte[] conflictingVal = conflictingValues.get(cell).getContents();
        if (!Transactions.cellValuesEqual(oldVal, writeVal) || !Arrays.equals(writeVal, conflictingVal)) {
            conflictingCells.add(cell);
        } else if (log.isInfoEnabled()) {
            log.info("Another transaction committed to the same cell before us but "
                    + "their value was the same. " + "Cell: " + cell + " Table: " + table);
        }
    }
    if (conflictingCells.isEmpty()) {
        return;
    }
    Predicate<CellConflict> conflicting = Predicates.compose(Predicates.in(conflictingCells),
            CellConflict.getCellFunction());
    throw TransactionConflictException.create(table, getStartTimestamp(),
            Sets.filter(spanningWrites, conflicting), Sets.filter(dominatingWrites, conflicting),
            System.currentTimeMillis() - timeCreated);
}

From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory.java

/**
 * Using the parsed string arguments, we convert the strings to the expected
 * return type of the methods that are found on the passed-in class.
 *
 * <p>For any return type that is expected to be an array or a collection, we further
 * split up each string on ','./*  ww w . ja v  a 2  s. c o m*/
 *
 * <p>We special case the "runner" option. It is mapped to the class of the {@link PipelineRunner}
 * based off of the {@link PipelineRunner PipelineRunners} simple class name. If the provided
 * runner name is not registered via a {@link PipelineRunnerRegistrar}, we attempt to obtain the
 * class that the name represents using {@link Class#forName(String)} and use the result class if
 * it subclasses {@link PipelineRunner}.
 *
 * <p>If strict parsing is enabled, unknown options or options that cannot be converted to
 * the expected java type using an {@link ObjectMapper} will be ignored.
 */
private static <T extends PipelineOptions> Map<String, Object> parseObjects(Class<T> klass,
        ListMultimap<String, String> options, boolean strictParsing) {
    Map<String, Method> propertyNamesToGetters = Maps.newHashMap();
    PipelineOptionsFactory.validateWellFormed(klass, REGISTERED_OPTIONS);
    @SuppressWarnings("unchecked")
    Iterable<PropertyDescriptor> propertyDescriptors = PipelineOptionsFactory
            .getPropertyDescriptors(FluentIterable.from(getRegisteredOptions()).append(klass).toSet());
    for (PropertyDescriptor descriptor : propertyDescriptors) {
        propertyNamesToGetters.put(descriptor.getName(), descriptor.getReadMethod());
    }
    Map<String, Object> convertedOptions = Maps.newHashMap();
    for (final Map.Entry<String, Collection<String>> entry : options.asMap().entrySet()) {
        try {
            // Search for close matches for missing properties.
            // Either off by one or off by two character errors.
            if (!propertyNamesToGetters.containsKey(entry.getKey())) {
                SortedSet<String> closestMatches = new TreeSet<String>(
                        Sets.filter(propertyNamesToGetters.keySet(), new Predicate<String>() {
                            @Override
                            public boolean apply(@Nullable String input) {
                                return StringUtils.getLevenshteinDistance(entry.getKey(), input) <= 2;
                            }
                        }));
                switch (closestMatches.size()) {
                case 0:
                    throw new IllegalArgumentException(
                            String.format("Class %s missing a property named '%s'.", klass, entry.getKey()));
                case 1:
                    throw new IllegalArgumentException(
                            String.format("Class %s missing a property named '%s'. Did you mean '%s'?", klass,
                                    entry.getKey(), Iterables.getOnlyElement(closestMatches)));
                default:
                    throw new IllegalArgumentException(
                            String.format("Class %s missing a property named '%s'. Did you mean one of %s?",
                                    klass, entry.getKey(), closestMatches));
                }
            }

            Method method = propertyNamesToGetters.get(entry.getKey());
            // Only allow empty argument values for String, String Array, and Collection.
            Class<?> returnType = method.getReturnType();
            JavaType type = MAPPER.getTypeFactory().constructType(method.getGenericReturnType());
            if ("runner".equals(entry.getKey())) {
                String runner = Iterables.getOnlyElement(entry.getValue());
                if (SUPPORTED_PIPELINE_RUNNERS.containsKey(runner)) {
                    convertedOptions.put("runner", SUPPORTED_PIPELINE_RUNNERS.get(runner));
                } else {
                    try {
                        Class<?> runnerClass = Class.forName(runner);
                        checkArgument(PipelineRunner.class.isAssignableFrom(runnerClass),
                                "Class '%s' does not implement PipelineRunner. Supported pipeline runners %s",
                                runner, Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet()));
                        convertedOptions.put("runner", runnerClass);
                    } catch (ClassNotFoundException e) {
                        String msg = String.format(
                                "Unknown 'runner' specified '%s', supported pipeline runners %s", runner,
                                Sets.newTreeSet(SUPPORTED_PIPELINE_RUNNERS.keySet()));
                        throw new IllegalArgumentException(msg, e);
                    }
                }
            } else if ((returnType.isArray() && (SIMPLE_TYPES.contains(returnType.getComponentType())
                    || returnType.getComponentType().isEnum()))
                    || Collection.class.isAssignableFrom(returnType)) {
                // Split any strings with ","
                List<String> values = FluentIterable.from(entry.getValue())
                        .transformAndConcat(new Function<String, Iterable<String>>() {
                            @Override
                            public Iterable<String> apply(String input) {
                                return Arrays.asList(input.split(","));
                            }
                        }).toList();

                if (returnType.isArray() && !returnType.getComponentType().equals(String.class)) {
                    for (String value : values) {
                        checkArgument(!value.isEmpty(),
                                "Empty argument value is only allowed for String, String Array, and Collection,"
                                        + " but received: " + returnType);
                    }
                }
                convertedOptions.put(entry.getKey(), MAPPER.convertValue(values, type));
            } else if (SIMPLE_TYPES.contains(returnType) || returnType.isEnum()) {
                String value = Iterables.getOnlyElement(entry.getValue());
                checkArgument(returnType.equals(String.class) || !value.isEmpty(),
                        "Empty argument value is only allowed for String, String Array, and Collection,"
                                + " but received: " + returnType);
                convertedOptions.put(entry.getKey(), MAPPER.convertValue(value, type));
            } else {
                String value = Iterables.getOnlyElement(entry.getValue());
                checkArgument(returnType.equals(String.class) || !value.isEmpty(),
                        "Empty argument value is only allowed for String, String Array, and Collection,"
                                + " but received: " + returnType);
                try {
                    convertedOptions.put(entry.getKey(), MAPPER.readValue(value, type));
                } catch (IOException e) {
                    throw new IllegalArgumentException("Unable to parse JSON value " + value, e);
                }
            }
        } catch (IllegalArgumentException e) {
            if (strictParsing) {
                throw e;
            } else {
                LOG.warn("Strict parsing is disabled, ignoring option '{}' with value '{}' because {}",
                        entry.getKey(), entry.getValue(), e.getMessage());
            }
        }
    }
    return convertedOptions;
}