Example usage for com.google.common.collect ImmutableListMultimap builder

List of usage examples for com.google.common.collect ImmutableListMultimap builder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableListMultimap builder.

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new builder.

Usage

From source file:org.ambraproject.rhino.content.xml.CustomMetadataExtractor.java

/**
 * Parse the {@code custom-meta} name-value pairs from the manuscript.
 * <p>//w  w w .ja  v  a  2  s.c om
 * It is possible for the manuscript to contain multiple custom meta nodes with the same name, though this may be
 * invalid depending on the name.
 *
 * @return the multimap of {@code custom-meta} name-value pairs
 */
private ListMultimap<String, String> parseCustomMeta() {
    List<Node> customMetaNodes = readNodeList("//custom-meta-group/custom-meta");
    ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
    for (Node node : customMetaNodes) {
        String name = readString("child::meta-name", node);
        String value = Strings.nullToEmpty(sanitize(readString("child::meta-value", node)));
        builder.put(name, value);
    }
    return builder.build();
}

From source file:com.google.devtools.build.lib.rules.java.JavaToolchain.java

private static ImmutableListMultimap<String, String> getCompatibleJavacOptions(RuleContext ruleContext) {
    ImmutableListMultimap.Builder<String, String> result = ImmutableListMultimap.builder();
    for (Map.Entry<String, List<String>> entry : ruleContext.attributes()
            .get("compatible_javacopts", Type.STRING_LIST_DICT).entrySet()) {
        result.putAll(entry.getKey(), JavaHelper.tokenizeJavaOptions(entry.getValue()));
    }/*from w w  w .j a  va  2s  .  c  om*/
    return result.build();
}

From source file:com.google.caliper.json.ImmutableMultimapTypeAdapterFactory.java

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter<T> create(Gson gson, com.google.gson.reflect.TypeToken<T> typeToken) {
    if (ImmutableListMultimap.class.isAssignableFrom(typeToken.getRawType())) {
        TypeToken<Map<?, List<?>>> mapToken = getMapOfListsToken((TypeToken) TypeToken.of(typeToken.getType()));
        final TypeAdapter<Map<?, List<?>>> adapter = (TypeAdapter<Map<?, List<?>>>) gson
                .getAdapter(com.google.gson.reflect.TypeToken.get(mapToken.getType()));
        return new TypeAdapter<T>() {
            @Override/*  ww  w. j  a  va2 s  . c o m*/
            public void write(JsonWriter out, T value) throws IOException {
                ImmutableListMultimap<?, ?> multimap = (ImmutableListMultimap<?, ?>) value;
                adapter.write(out, (Map) multimap.asMap());
            }

            @Override
            public T read(JsonReader in) throws IOException {
                Map<?, List<?>> value = adapter.read(in);
                ImmutableListMultimap.Builder builder = ImmutableListMultimap.builder();
                for (Entry<?, List<?>> entry : value.entrySet()) {
                    builder.putAll(entry.getKey(), entry.getValue());
                }
                return (T) builder.build();
            }
        };
    } else if (ImmutableSetMultimap.class.isAssignableFrom(typeToken.getRawType())) {
        TypeToken<Map<?, Set<?>>> mapToken = getMapOfSetsToken((TypeToken) TypeToken.of(typeToken.getType()));
        final TypeAdapter<Map<?, Set<?>>> adapter = (TypeAdapter<Map<?, Set<?>>>) gson
                .getAdapter(com.google.gson.reflect.TypeToken.get(mapToken.getType()));
        return new TypeAdapter<T>() {
            @Override
            public void write(JsonWriter out, T value) throws IOException {
                ImmutableSetMultimap<?, ?> multimap = (ImmutableSetMultimap<?, ?>) value;
                adapter.write(out, (Map) multimap.asMap());
            }

            @Override
            public T read(JsonReader in) throws IOException {
                Map<?, Set<?>> value = adapter.read(in);
                ImmutableSetMultimap.Builder builder = ImmutableSetMultimap.builder();
                for (Entry<?, Set<?>> entry : value.entrySet()) {
                    builder.putAll(entry.getKey(), entry.getValue());
                }
                return (T) builder.build();
            }
        };
    } else {
        return null;
    }
}

From source file:cpw.mods.fml.common.registry.GameData.java

public static void dumpRegistry(File minecraftDir) {
    if (customItemStacks == null) {
        return;//from w  ww.ja v a2s .  c  om
    }
    if (Boolean.valueOf(System.getProperty("fml.dumpRegistry", "false")).booleanValue()) {
        ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
        for (String modId : customItemStacks.rowKeySet()) {
            builder.putAll(modId, customItemStacks.row(modId).keySet());
        }

        File f = new File(minecraftDir, "itemStackRegistry.csv");
        MapJoiner mapJoiner = Joiner.on("\n").withKeyValueSeparator(",");
        try {
            Files.write(mapJoiner.join(builder.build().entries()), f, Charsets.UTF_8);
            FMLLog.log(Level.INFO, "Dumped item registry data to %s", f.getAbsolutePath());
        } catch (IOException e) {
            FMLLog.log(Level.ERROR, e, "Failed to write registry data to %s", f.getAbsolutePath());
        }
    }
}

From source file:dagger.internal.codegen.MultibindingsValidator.java

/**
 * Returns a report containing validation errors for a
 * {@link Multibindings @Multibindings}-annotated type.
 *//*from w w w .ja  v a 2 s.  co m*/
public ValidationReport<TypeElement> validate(TypeElement multibindingsType) {
    ValidationReport.Builder<TypeElement> validation = ValidationReport.about(multibindingsType);
    if (!multibindingsType.getKind().equals(INTERFACE)) {
        validation.addError(MUST_BE_INTERFACE, multibindingsType);
    }
    if (!multibindingsType.getTypeParameters().isEmpty()) {
        validation.addError(MUST_NOT_HAVE_TYPE_PARAMETERS, multibindingsType);
    }
    Optional<BindingType> bindingType = bindingType(multibindingsType);
    if (!bindingType.isPresent()) {
        validation.addError(MUST_BE_IN_MODULE, multibindingsType);
    }

    ImmutableListMultimap.Builder<Key, ExecutableElement> methodsByKey = ImmutableListMultimap.builder();
    for (ExecutableElement method : getLocalAndInheritedMethods(multibindingsType, elements)) {
        // Skip methods in Object.
        if (method.getEnclosingElement().equals(objectElement)) {
            continue;
        }
        if (!isPlainMap(method.getReturnType()) && !isPlainSet(method.getReturnType())) {
            validation.addError(METHOD_MUST_RETURN_MAP_OR_SET, method);
            continue;
        }
        ImmutableSet<? extends AnnotationMirror> qualifiers = getQualifiers(method);
        if (qualifiers.size() > 1) {
            for (AnnotationMirror qualifier : qualifiers) {
                validation.addError(TOO_MANY_QUALIFIERS, method, qualifier);
            }
            continue;
        }
        if (bindingType.isPresent()) {
            methodsByKey.put(
                    keyFactory.forMultibindingsMethod(bindingType.get(), asExecutable(method.asType()), method),
                    method);
        }
    }
    for (Map.Entry<Key, Collection<ExecutableElement>> entry : methodsByKey.build().asMap().entrySet()) {
        Collection<ExecutableElement> methods = entry.getValue();
        if (methods.size() > 1) {
            Key key = entry.getKey();
            validation.addError(tooManyMultibindingsMethodsForKey(key, methods), multibindingsType);
        }
    }
    return validation.build();
}

From source file:net.conquiris.lucene.search.Hit.java

/**
 * Constructor./*from  w  ww . ja va  2 s  .  co  m*/
 */
private Hit(int docId, float score, Document document, @Nullable Multimap<String, String> fragments) {
    this.docId = docId;
    this.score = score;
    this.document = checkNotNull(document, "The document must be provided");
    if (fragments == null) {
        this.fragments = ImmutableMultimap.of();
    } else {
        this.fragments = ImmutableMultimap.copyOf(fragments);
    }
    ImmutableListMultimap.Builder<String, Fieldable> fieldsBuilder = ImmutableListMultimap.builder();
    ImmutableListMultimap.Builder<String, Number> numericBuilder = ImmutableListMultimap.builder();
    ImmutableListMultimap.Builder<String, Fieldable> binaryBuilder = ImmutableListMultimap.builder();
    for (Fieldable f : document.getFields()) {
        final String name = f.name();
        if (f.isBinary()) {
            binaryBuilder.put(name, f);
        } else {
            fieldsBuilder.put(name, f);
            if (f instanceof NumericField) {
                numericBuilder.put(name, ((NumericField) f).getNumericValue());
            }
        }
    }
    this.fields = fieldsBuilder.build();
    this.numeric = numericBuilder.build();
    this.binary = binaryBuilder.build();
}

From source file:com.facebook.presto.tests.tpch.TpchIndexedData.java

private static IndexedTable indexTable(RecordSet recordSet, final List<String> outputColumns,
        List<String> keyColumns) {
    List<Integer> keyPositions = FluentIterable.from(keyColumns).transform(columnName -> {
        int position = outputColumns.indexOf(columnName);
        checkState(position != -1);/*from  ww w.  j a v  a  2s. c  o m*/
        return position;
    }).toList();

    ImmutableListMultimap.Builder<MaterializedTuple, MaterializedTuple> indexedValuesBuilder = ImmutableListMultimap
            .builder();

    List<Type> outputTypes = recordSet.getColumnTypes();
    List<Type> keyTypes = extractPositionValues(outputTypes, keyPositions);

    RecordCursor cursor = recordSet.cursor();
    while (cursor.advanceNextPosition()) {
        List<Object> values = extractValues(cursor, outputTypes);
        List<Object> keyValues = extractPositionValues(values, keyPositions);

        indexedValuesBuilder.put(new MaterializedTuple(keyValues), new MaterializedTuple(values));
    }

    return new IndexedTable(keyColumns, keyTypes, outputColumns, outputTypes, indexedValuesBuilder.build());
}

From source file:io.prestosql.tests.tpch.TpchIndexedData.java

private static IndexedTable indexTable(RecordSet recordSet, final List<String> outputColumns,
        List<String> keyColumns) {
    List<Integer> keyPositions = keyColumns.stream().map(columnName -> {
        int position = outputColumns.indexOf(columnName);
        checkState(position != -1);/*from w w  w  . j av  a  2 s.  c  o m*/
        return position;
    }).collect(toImmutableList());

    ImmutableListMultimap.Builder<MaterializedTuple, MaterializedTuple> indexedValuesBuilder = ImmutableListMultimap
            .builder();

    List<Type> outputTypes = recordSet.getColumnTypes();
    List<Type> keyTypes = extractPositionValues(outputTypes, keyPositions);

    RecordCursor cursor = recordSet.cursor();
    while (cursor.advanceNextPosition()) {
        List<Object> values = extractValues(cursor, outputTypes);
        List<Object> keyValues = extractPositionValues(values, keyPositions);

        indexedValuesBuilder.put(new MaterializedTuple(keyValues), new MaterializedTuple(values));
    }

    return new IndexedTable(keyColumns, keyTypes, outputColumns, outputTypes, indexedValuesBuilder.build());
}

From source file:com.kolich.curacao.mappers.request.RequestMappingTable.java

private final ImmutableListMultimap<Method, CuracaoInvokable> buildRoutingTable(final String bootPackage) {
    final ImmutableListMultimap.Builder<Method, CuracaoInvokable> builder = ImmutableListMultimap.builder();
    // Find all "controller classes" in the specified boot package that
    // are annotated with our @Controller annotation.
    final Set<Class<?>> controllers = getTypesInPackageAnnotatedWith(bootPackage, Controller.class);
    logger__.debug("Found {} controllers annotated with @{}", controllers.size(),
            Controller.class.getSimpleName());
    // For each discovered controller class, find all annotated methods
    // inside of it and add them to the routing table.
    for (final Class<?> controller : controllers) {
        logger__.debug("Found @{}: {}", Controller.class.getSimpleName(), controller.getCanonicalName());
        // Fetch a list of all request mapping annotated controller methods
        // in the controller itself, and any super classes walking up the
        // class hierarchy.
        final Set<java.lang.reflect.Method> methods = getAllRequestMappingsInHierarchy(controller);
        for (final java.lang.reflect.Method method : methods) {
            final RequestMapping mapping = method.getAnnotation(RequestMapping.class);
            // The actual "path" that the controller method will be called
            // on when a request is received.
            final String route = mapping.value();
            // Attempt to construct a new invokable for the route and add
            // it to the local routing table.
            try {
                final CuracaoInvokable invokable = getInvokableForRoute(controller, method, mapping);
                // The controller method request mapping annotation may
                // map multiple HTTP request method types to a single
                // Java method. So, for each supported/annotated method...
                for (final Method httpMethod : mapping.methods()) {
                    builder.put(httpMethod, invokable);
                    logger__.info("Successfully added route to " + "mapping table (route={}:{}, invokable={})",
                            httpMethod, route, invokable);
                }//from www.  j  a  va2s  . co m
            } catch (Exception e) {
                logger__.error("Failed to add route to routing table " + "(route={}, methods={})", route,
                        Arrays.toString(mapping.methods()), e);
            }
        }
    }
    return builder.build();
}

From source file:org.opendaylight.controller.cluster.datastore.ConfigurationImpl.java

private static ListMultimap<String, String> createModuleNameToShardName(Iterable<ModuleShard> moduleShards) {
    final com.google.common.collect.ImmutableListMultimap.Builder<String, String> b = ImmutableListMultimap
            .builder();//from   w w w  .  j  a  va  2s .  c  o m

    for (ModuleShard m : moduleShards) {
        for (Shard s : m.getShards()) {
            b.put(m.getModuleName(), s.getName());
        }
    }

    return b.build();
}