Example usage for com.google.common.collect TreeMultimap create

List of usage examples for com.google.common.collect TreeMultimap create

Introduction

In this page you can find the example usage for com.google.common.collect TreeMultimap create.

Prototype

public static <K, V> TreeMultimap<K, V> create(Comparator<? super K> keyComparator,
        Comparator<? super V> valueComparator) 

Source Link

Document

Creates an empty TreeMultimap instance using explicit comparators.

Usage

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

/**
 * Validates that a given class conforms to the following properties:
 * <ul>/*from  w  ww  .  ja va2  s.c om*/
 *   <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:org.apache.beam.sdk.options.PipelineOptionsFactory.java

/**
 * Validates that a given class conforms to the following properties:
 * <ul>/*w  w  w  . jav  a2 s  . c om*/
 *   <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 allInterfaceMethods All interface methods that derive from {@link PipelineOptions}.
 * @param descriptors The list of {@link PropertyDescriptor}s representing all valid bean
 * properties of {@code iface}.
 */
private static void validateMethodAnnotations(SortedSet<Method> allInterfaceMethods,
        List<PropertyDescriptor> descriptors) {
    SortedSetMultimap<Method, Method> methodNameToAllMethodMap = TreeMultimap
            .create(MethodNameComparator.INSTANCE, MethodComparator.INSTANCE);
    for (Method method : allInterfaceMethods) {
        methodNameToAllMethodMap.put(method, method);
    }

    // Verify that there is no getter with a mixed @JsonIgnore annotation.
    validateGettersHaveConsistentAnnotation(methodNameToAllMethodMap, descriptors,
            AnnotationPredicates.JSON_IGNORE);

    // Verify that there is no getter with a mixed @Default annotation.
    validateGettersHaveConsistentAnnotation(methodNameToAllMethodMap, descriptors,
            AnnotationPredicates.DEFAULT_VALUE);

    // Verify that no setter has @JsonIgnore.
    validateSettersDoNotHaveAnnotation(methodNameToAllMethodMap, descriptors, AnnotationPredicates.JSON_IGNORE);

    // Verify that no setter has @Default.
    validateSettersDoNotHaveAnnotation(methodNameToAllMethodMap, descriptors,
            AnnotationPredicates.DEFAULT_VALUE);
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonUsingModules.java

public Map<String, Map<String, Double>> pathwayComparisonCoalesce(PathwayUsingModules newSource,
        PathwayUsingModules newTarget, BiMap<String, Integer> newSourceGeneIdToPositionMap,
        BiMap<String, Integer> newTargetGeneIdToPositionMap) {

    Multimap<Integer, Multimap<Double, String>> forward = pcompare(newSource, newTarget); // key: qgeneId, value: {score=tgenecombination;...}
    Multimap<Integer, Multimap<Double, String>> reverse = pcompare(newTarget, newSource);

    // Re-construct the bimaps
    newSourceGeneIdToPositionMap = HashBiMap.create();
    int temp = 0;
    for (Module e : newSource.getModules()) {
        newSourceGeneIdToPositionMap.put(e.getModuleId(), temp++);
    }//w w w .  ja  va 2  s  . c om
    newTargetGeneIdToPositionMap = HashBiMap.create();
    temp = 0;
    for (Module e : newTarget.getModules()) {
        newTargetGeneIdToPositionMap.put(e.getModuleId(), temp++);
    }

    /* Create global list of matchings ordered by score by joining forward and reverse lists
     * key: querygene -> targetgenes
     * value: score
     */
    TreeMultimap<Double, String> globalMap = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural());
    for (Map.Entry<Integer, Multimap<Double, String>> e : forward.entries()) {
        int fgene = e.getKey();
        Multimap<Double, String> geneAndScore = e.getValue();
        for (Map.Entry<Double, String> scoreEntry : geneAndScore.entries()) {
            double score = scoreEntry.getKey();
            String matchingGeneString = scoreEntry.getValue();
            String[] multipleMatchingGenes = matchingGeneString.split(",");
            for (String matchingGene : multipleMatchingGenes) {
                String newKey = fgene + "->" + matchingGene;
                globalMap.put(score, newKey);
            }
        }
    }
    for (Map.Entry<Integer, Multimap<Double, String>> e : reverse.entries()) {
        int rgene = e.getKey();
        Multimap<Double, String> geneAndScore = e.getValue();
        for (Map.Entry<Double, String> scoreEntry : geneAndScore.entries()) {
            double score = scoreEntry.getKey();
            String matchingGeneString = scoreEntry.getValue();
            String[] multipleMatchingGenes = matchingGeneString.split(",");
            for (String matchingGene : multipleMatchingGenes) {
                String newKey = matchingGene + "->" + rgene;
                globalMap.put(score, newKey);
            }
        }
    }
    //////System.out.println("----------------------------------------------------------------------------------------------------------------------------------");
    // create alignment
    // ////System.out.println(globalMap);
    Map<String, Double> matchingInTarget;
    Set<String> queryGenesCovered = new HashSet<String>();
    Set<String> targetGenesCovered = new HashSet<String>();
    Map<String, Map<String, Double>> currentBestResultMapping = new TreeMap<String, Map<String, Double>>();
    for (Map.Entry<Double, String> entry : globalMap.entries()) {
        double score = entry.getKey();
        //score=[alignment1, aligment2, ..]
        String alignment = entry.getValue();
        int i = 100;
        for (String collection : globalMap.asMap().get(score)) {
            int count = collection.length() - collection.replace("+", "").length();
            if (i > count) {
                i = count;
                alignment = collection;
            }
        }
        String bestScoreAlignment = alignment.split(",")[0];
        // start->end
        String start = bestScoreAlignment.split("->")[0];
        String end = bestScoreAlignment.split("->")[1];

        // start and end can be combination of genes
        Set<String> s = new HashSet<String>(Arrays.asList((start + "+").split("\\+")));
        Set<String> t = new HashSet<String>(Arrays.asList((end + "+").split("\\+")));

        // add to result mapping
        Set<String> sIntersection = new HashSet<String>();
        sIntersection.addAll(queryGenesCovered);
        sIntersection.retainAll(s);

        Set<String> tIntersection = new HashSet<String>();
        tIntersection.addAll(targetGenesCovered);
        tIntersection.retainAll(t);

        if (sIntersection.isEmpty() && tIntersection.isEmpty()) {
            matchingInTarget = new HashMap<String, Double>();
            matchingInTarget.put(reconstructWithGeneId(end, newTargetGeneIdToPositionMap), score);
            currentBestResultMapping.put(reconstructWithGeneId(start, newSourceGeneIdToPositionMap),
                    matchingInTarget);
            queryGenesCovered.addAll(s);
            targetGenesCovered.addAll(t);
            break;
        }
    }
    return currentBestResultMapping;
}