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

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

Introduction

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

Prototype

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

Source Link

Document

Returns a new Builder .

Usage

From source file:com.facebook.presto.kinesis.decoder.KinesisDecoderRegistry.java

@Inject
KinesisDecoderRegistry(Set<KinesisRowDecoder> rowDecoders, Set<KinesisFieldDecoder<?>> fieldDecoders) {
    checkNotNull(rowDecoders, "rowDecoders is null");

    ImmutableMap.Builder<String, KinesisRowDecoder> rowBuilder = ImmutableMap.builder();
    for (KinesisRowDecoder rowDecoder : rowDecoders) {
        rowBuilder.put(rowDecoder.getName(), rowDecoder);
    }/*from   w w w. j ava2 s.  com*/

    this.rowDecoders = rowBuilder.build();

    Map<String, ImmutableSetMultimap.Builder<Class<?>, KinesisFieldDecoder<?>>> fieldDecoderBuilders = new HashMap<>();

    for (KinesisFieldDecoder<?> fieldDecoder : fieldDecoders) {
        ImmutableSetMultimap.Builder<Class<?>, KinesisFieldDecoder<?>> fieldDecoderBuilder = fieldDecoderBuilders
                .get(fieldDecoder.getRowDecoderName());
        if (fieldDecoderBuilder == null) {
            fieldDecoderBuilder = ImmutableSetMultimap.builder();
            fieldDecoderBuilders.put(fieldDecoder.getRowDecoderName(), fieldDecoderBuilder);
        }

        for (Class<?> clazz : fieldDecoder.getJavaTypes()) {
            fieldDecoderBuilder.put(clazz, fieldDecoder);
        }
    }

    ImmutableMap.Builder<String, SetMultimap<Class<?>, KinesisFieldDecoder<?>>> fieldDecoderBuilder = ImmutableMap
            .builder();
    for (Map.Entry<String, ImmutableSetMultimap.Builder<Class<?>, KinesisFieldDecoder<?>>> entry : fieldDecoderBuilders
            .entrySet()) {
        fieldDecoderBuilder.put(entry.getKey(), entry.getValue().build());
    }

    this.fieldDecoders = fieldDecoderBuilder.build();
    log.debug("Field decoders found: %s", this.fieldDecoders);
}

From source file:com.facebook.buck.java.JavaLibraryClasspathProvider.java

public static ImmutableSetMultimap<JavaLibrary, Path> getDeclaredClasspathEntries(
        DefaultJavaLibrary javaLibraryRule) {
    final ImmutableSetMultimap.Builder<JavaLibrary, Path> classpathEntries = ImmutableSetMultimap.builder();

    Iterable<JavaLibrary> javaLibraryDeps = getJavaLibraryDeps(javaLibraryRule.getDeps());

    for (JavaLibrary rule : javaLibraryDeps) {
        classpathEntries.putAll(rule, rule.getOutputClasspathEntries().values());
    }//from  w w w .j ava 2  s .  c om
    return classpathEntries.build();
}

From source file:org.spongepowered.mod.registry.SpongeForgeGameDictionary.java

@Override
public SetMultimap<String, Entry> getAll() {
    ImmutableSetMultimap.Builder<String, Entry> allItems = ImmutableSetMultimap.builder();
    for (String key : OreDictionary.getOreNames()) {
        allItems.putAll(key, this.get(key));
    }/*  ww  w .  j a va 2s . c  om*/
    return allItems.build();
}

From source file:com.facebook.presto.orc.checkpoint.Checkpoints.java

public static Map<StreamId, StreamCheckpoint> getStreamCheckpoints(Set<Integer> columns,
        List<OrcType> columnTypes, CompressionKind compressionKind, int rowGroupId,
        List<ColumnEncoding> columnEncodings, Map<StreamId, Stream> streams,
        Map<Integer, List<RowGroupIndex>> columnIndexes) throws InvalidCheckpointException {
    ImmutableSetMultimap.Builder<Integer, StreamKind> streamKindsBuilder = ImmutableSetMultimap.builder();
    for (Stream stream : streams.values()) {
        streamKindsBuilder.put(stream.getColumn(), stream.getStreamKind());
    }//w  w w  .  j a  v a2 s  .  c  o  m
    SetMultimap<Integer, StreamKind> streamKinds = streamKindsBuilder.build();

    ImmutableMap.Builder<StreamId, StreamCheckpoint> checkpoints = ImmutableMap.builder();
    for (int column : columns) {
        List<Integer> positionsList = columnIndexes.get(column).get(rowGroupId).getPositions();

        ColumnEncodingKind columnEncoding = columnEncodings.get(column).getColumnEncodingKind();
        OrcTypeKind columnType = columnTypes.get(column).getOrcTypeKind();
        Set<StreamKind> availableStreams = streamKinds.get(column);

        ColumnPositionsList columnPositionsList = new ColumnPositionsList(column, columnType, positionsList);
        switch (columnType) {
        case BOOLEAN:
            checkpoints.putAll(getBooleanColumnCheckpoints(column, compressionKind, availableStreams,
                    columnPositionsList));
            break;
        case BYTE:
            checkpoints.putAll(
                    getByteColumnCheckpoints(column, compressionKind, availableStreams, columnPositionsList));
            break;
        case SHORT:
        case INT:
        case LONG:
        case DATE:
            checkpoints.putAll(getLongColumnCheckpoints(column, columnEncoding, compressionKind,
                    availableStreams, columnPositionsList));
            break;
        case FLOAT:
            checkpoints.putAll(
                    getFloatColumnCheckpoints(column, compressionKind, availableStreams, columnPositionsList));
            break;
        case DOUBLE:
            checkpoints.putAll(
                    getDoubleColumnCheckpoints(column, compressionKind, availableStreams, columnPositionsList));
            break;
        case TIMESTAMP:
            checkpoints.putAll(getTimestampColumnCheckpoints(column, columnEncoding, compressionKind,
                    availableStreams, columnPositionsList));
            break;
        case BINARY:
        case STRING:
            checkpoints.putAll(getSliceColumnCheckpoints(column, columnEncoding, compressionKind,
                    availableStreams, columnPositionsList));
            break;
        case LIST:
        case MAP:
            checkpoints.putAll(getListOrMapColumnCheckpoints(column, columnEncoding, compressionKind,
                    availableStreams, columnPositionsList));
            break;
        case STRUCT:
            checkpoints.putAll(
                    getStructColumnCheckpoints(column, compressionKind, availableStreams, columnPositionsList));
            break;
        case DECIMAL:
        case CHAR:
        case VARCHAR:
        case UNION:
            throw new IllegalArgumentException("Unsupported column type " + columnType);
        }

        // The DWRF code is not meticulous in the handling of checkpoints.  It appears that for the first row group
        // it will write checkpoints for all streams, but in other cases it will write only the streams that exist.
        // We detect this case by checking that all offsets in the initial position list are zero, and if so, we
        // clear the extra offsets
        if (columnPositionsList.hasNextPosition() && !Iterables.all(positionsList, equalTo(0))) {
            throw new InvalidCheckpointException(format(
                    "Column %s, of type %s, contains %s offset positions, but only %s positions were consumed",
                    column, columnType, positionsList.size(), columnPositionsList.getIndex()));
        }
    }
    return checkpoints.build();
}

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

/**
 * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSetMultimap}
 * whose keys and values are the result of applying the provided mapping functions to the input
 * elements. Entries appear in the result {@code ImmutableSetMultimap} in encounter order.
 *///w  w  w .j  a v  a 2  s . co  m
// TODO(b/68008628): Use ImmutableSetMultimap.toImmutableSetMultimap().
public static <T, K, V> Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(
        Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
    return Collectors.mapping(value -> Maps.immutableEntry(keyMapper.apply(value), valueMapper.apply(value)),
            Collector.of(ImmutableSetMultimap::builder,
                    (ImmutableSetMultimap.Builder<K, V> builder, Map.Entry<K, V> entry) -> builder.put(entry),
                    (left, right) -> left.putAll(right.build()), ImmutableSetMultimap.Builder::build));
}

From source file:io.prestosql.orc.checkpoint.Checkpoints.java

public static Map<StreamId, StreamCheckpoint> getStreamCheckpoints(Set<Integer> columns,
        List<OrcType> columnTypes, boolean compressed, int rowGroupId, List<ColumnEncoding> columnEncodings,
        Map<StreamId, Stream> streams, Map<StreamId, List<RowGroupIndex>> columnIndexes)
        throws InvalidCheckpointException {
    // map from (column, sequence) to available StreamKind
    ImmutableSetMultimap.Builder<ColumnAndSequence, StreamKind> streamKindsBuilder = ImmutableSetMultimap
            .builder();/*from w w w.  j  av a  2s . co  m*/
    for (Stream stream : streams.values()) {
        streamKindsBuilder.put(new ColumnAndSequence(stream.getColumn(), stream.getSequence()),
                stream.getStreamKind());
    }
    SetMultimap<ColumnAndSequence, StreamKind> streamKinds = streamKindsBuilder.build();

    ImmutableMap.Builder<StreamId, StreamCheckpoint> checkpoints = ImmutableMap.builder();
    for (Map.Entry<StreamId, List<RowGroupIndex>> entry : columnIndexes.entrySet()) {
        int column = entry.getKey().getColumn();

        if (!columns.contains(column)) {
            continue;
        }

        int sequence = entry.getKey().getSequence();
        List<Integer> positionsList = entry.getValue().get(rowGroupId).getPositions();

        ColumnEncodingKind columnEncoding = columnEncodings.get(column).getColumnEncoding(sequence)
                .getColumnEncodingKind();
        OrcTypeKind columnType = columnTypes.get(column).getOrcTypeKind();
        Set<StreamKind> availableStreams = streamKinds.get(new ColumnAndSequence(column, sequence));

        ColumnPositionsList columnPositionsList = new ColumnPositionsList(column, sequence, columnType,
                positionsList);
        switch (columnType) {
        case BOOLEAN:
            checkpoints.putAll(getBooleanColumnCheckpoints(column, sequence, compressed, availableStreams,
                    columnPositionsList));
            break;
        case BYTE:
            checkpoints.putAll(getByteColumnCheckpoints(column, sequence, compressed, availableStreams,
                    columnPositionsList));
            break;
        case SHORT:
        case INT:
        case LONG:
        case DATE:
            checkpoints.putAll(getLongColumnCheckpoints(column, sequence, columnEncoding, compressed,
                    availableStreams, columnPositionsList));
            break;
        case FLOAT:
            checkpoints.putAll(getFloatColumnCheckpoints(column, sequence, compressed, availableStreams,
                    columnPositionsList));
            break;
        case DOUBLE:
            checkpoints.putAll(getDoubleColumnCheckpoints(column, sequence, compressed, availableStreams,
                    columnPositionsList));
            break;
        case TIMESTAMP:
            checkpoints.putAll(getTimestampColumnCheckpoints(column, sequence, columnEncoding, compressed,
                    availableStreams, columnPositionsList));
            break;
        case BINARY:
        case STRING:
        case VARCHAR:
        case CHAR:
            checkpoints.putAll(getSliceColumnCheckpoints(column, sequence, columnEncoding, compressed,
                    availableStreams, columnPositionsList));
            break;
        case LIST:
        case MAP:
            checkpoints.putAll(getListOrMapColumnCheckpoints(column, sequence, columnEncoding, compressed,
                    availableStreams, columnPositionsList));
            break;
        case STRUCT:
            checkpoints.putAll(getStructColumnCheckpoints(column, sequence, compressed, availableStreams,
                    columnPositionsList));
            break;
        case DECIMAL:
            checkpoints.putAll(getDecimalColumnCheckpoints(column, sequence, columnEncoding, compressed,
                    availableStreams, columnPositionsList));
            break;
        default:
            throw new IllegalArgumentException("Unsupported column type " + columnType);
        }

        // The DWRF code is not meticulous in the handling of checkpoints.  It appears that for the first row group
        // it will write checkpoints for all streams, but in other cases it will write only the streams that exist.
        // We detect this case by checking that all offsets in the initial position list are zero, and if so, we
        // clear the extra offsets
        if (columnPositionsList.hasNextPosition() && !Iterables.all(positionsList, equalTo(0))) {
            throw new InvalidCheckpointException(format(
                    "Column %s, of type %s, contains %s offset positions, but only %s positions were consumed",
                    column, columnType, positionsList.size(), columnPositionsList.getIndex()));
        }
    }
    return checkpoints.build();
}

From source file:com.google.devtools.build.lib.analysis.featurecontrol.FeaturePolicyLoader.java

@Override
@Nullable//from www .j  a  v a  2s  .  c  om
public BuildConfiguration.Fragment create(ConfigurationEnvironment env, BuildOptions buildOptions)
        throws InvalidConfigurationException, InterruptedException {
    ImmutableSetMultimap.Builder<String, PackageSpecification> features = new ImmutableSetMultimap.Builder<>();
    ImmutableMap.Builder<String, String> policies = new ImmutableMap.Builder<>();
    LinkedHashSet<String> unseenFeatures = new LinkedHashSet<>(permittedFeatures);

    for (PolicyEntry entry : buildOptions.get(FeaturePolicyOptions.class).policies) {
        if (!permittedFeatures.contains(entry.getFeature())) {
            // It would be so nice to be able to do this during parsing... but because options are
            // parsed statically through reflection, we have no way of doing this until we get to the
            // configuration loader.
            throw new InvalidConfigurationException("No such feature: " + entry.getFeature());
        }
        if (!unseenFeatures.remove(entry.getFeature())) {
            // TODO(mstaib): Perhaps we should allow for overriding or concatenation here?
            throw new InvalidConfigurationException(
                    "Multiple definitions of the rollout policy for feature " + entry.getFeature()
                            + ". To use multiple package_groups, use a package_group with the includes "
                            + "attribute instead.");
        }

        Iterable<PackageSpecification> packageSpecifications = getAllPackageSpecificationsForPackageGroup(env,
                entry.getPackageGroupLabel(), entry.getFeature());

        if (packageSpecifications == null) {
            return null;
        }

        features.putAll(entry.getFeature(), packageSpecifications);
        policies.put(entry.getFeature(), entry.getPackageGroupLabel().toString());
    }

    // Default to universal access for all features not declared.
    for (String unseenFeature : unseenFeatures) {
        features.put(unseenFeature, PackageSpecification.everything());
        policies.put(unseenFeature, "//...");
    }

    return new FeaturePolicyConfiguration(features.build(), policies.build());
}

From source file:com.github.nmorel.gwtjackson.guava.client.deser.ImmutableSetMultimapJsonDeserializer.java

@Override
protected ImmutableSetMultimap<K, V> doDeserialize(JsonReader reader, JsonDeserializationContext ctx,
        JsonDeserializerParameters params) {
    ImmutableSetMultimap.Builder<K, V> builder = ImmutableSetMultimap.builder();
    buildMultimap(reader, ctx, params, builder);
    return builder.build();
}

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

/** Creates a new {@link ComponentCreatorDescriptor} for the given creator {@code type}. */
static ComponentCreatorDescriptor create(DeclaredType type, DaggerElements elements, DaggerTypes types,
        DependencyRequestFactory dependencyRequestFactory) {
    TypeElement typeElement = asTypeElement(type);
    TypeMirror componentType = typeElement.getEnclosingElement().asType();

    ImmutableSetMultimap.Builder<ComponentRequirement, ExecutableElement> requirementElements = ImmutableSetMultimap
            .builder();//from   w  w  w  . j a va 2s  .  c o m

    ExecutableElement factoryMethod = null;
    for (ExecutableElement method : elements.getUnimplementedMethods(typeElement)) {
        ExecutableType resolvedMethodType = MoreTypes.asExecutable(types.asMemberOf(type, method));

        if (types.isSubtype(componentType, resolvedMethodType.getReturnType())) {
            factoryMethod = method;
        } else {
            VariableElement parameter = getOnlyElement(method.getParameters());
            TypeMirror parameterType = getOnlyElement(resolvedMethodType.getParameterTypes());
            requirementElements.put(requirement(method, parameter, parameterType, dependencyRequestFactory),
                    method);
        }
    }
    verify(factoryMethod != null); // validation should have ensured this.

    return new AutoValue_ComponentCreatorDescriptor(typeElement, factoryMethod, requirementElements.build());
}

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

/**
 * A variant of {@link #indexDependenciesByKey} that maps from unresolved keys
 * to requests.  This is used when generating component's initialize()
 * methods (and in members injectors) in order to instantiate dependent
 * providers.  Consider a generic type of {@code Foo<T>} with a constructor
 * of {@code Foo(T t, T t1, A a, A a1)}.  That will be collapsed to a factory
 * taking a {@code Provider<T> tProvider, Provider<A> aProvider}. However,
 * if it was referenced as {@code Foo<A>}, we need to make sure we still
 * pass two providers.  Naively (if we just referenced by resolved BindingKey),
 * we would have passed a single {@code aProvider}.
 *//*w  w w. j a  va2 s  .c  o  m*/
// TODO(user): Refactor these indexing methods so that the binding itself knows what sort of
// binding keys and framework classes that it needs.
static ImmutableSetMultimap<BindingKey, DependencyRequest> indexDependenciesByUnresolvedKey(Types types,
        Iterable<? extends DependencyRequest> dependencies) {
    ImmutableSetMultimap.Builder<BindingKey, DependencyRequest> dependenciesByKeyBuilder = new ImmutableSetMultimap.Builder<BindingKey, DependencyRequest>()
            .orderValuesBy(DEPENDENCY_ORDERING);
    for (DependencyRequest dependency : dependencies) {
        BindingKey resolved = dependency.bindingKey();
        // To get the proper unresolved type, we have to extract the proper type from the
        // request type again (because we're looking at the actual element's type).
        TypeMirror unresolvedType = DependencyRequest.Factory
                .extractKindAndType(dependency.requestElement().asType()).type();
        BindingKey unresolved = BindingKey.create(resolved.kind(),
                resolved.key().withType(types, unresolvedType));
        dependenciesByKeyBuilder.put(unresolved, dependency);
    }
    return dependenciesByKeyBuilder.build();
}