Example usage for com.google.common.collect Maps uniqueIndex

List of usage examples for com.google.common.collect Maps uniqueIndex

Introduction

In this page you can find the example usage for com.google.common.collect Maps uniqueIndex.

Prototype

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Returns a map with the given values , indexed by keys derived from those values.

Usage

From source file:com.facebook.swift.codec.internal.reflection.ReflectionThriftUnionCodec.java

public ReflectionThriftUnionCodec(ThriftCodecManager manager, ThriftStructMetadata metadata) {
    super(manager, metadata);

    ThriftFieldMetadata idField = getOnlyElement(metadata.getFields(FieldKind.THRIFT_UNION_ID));

    this.idField = Maps.<ThriftFieldMetadata, ThriftCodec<?>>immutableEntry(idField,
            manager.getCodec(idField.getThriftType()));
    checkNotNull(this.idField.getValue(), "No codec for id field %s found", idField);

    this.metadataMap = Maps.uniqueIndex(metadata.getFields(), ThriftFieldMetadata.getIdGetter());
}

From source file:net.freifunk.autodeploy.AutoDeployOptions.java

private AutoDeployOptions(final List<Command> commands, final Set<PhaseOptions> phases) {
    Preconditions.checkArgument(commands.contains(RUN_PHASES) == (phases != null),
            "Phases must be set if the RUN_PHASES command is set.");
    _commands = commands;/*from   w w w .  j  a  va2s . c om*/

    if (phases == null) {
        _phases = ImmutableMap.of();
    } else {
        _phases = Maps.uniqueIndex(phases, PhaseOptions.GET_PHASE);
    }
}

From source file:com.facebook.presto.metadata.AbstractPropertyManager.java

public final void addProperties(ConnectorId connectorId, List<PropertyMetadata<?>> properties) {
    requireNonNull(connectorId, "connectorId is null");
    requireNonNull(properties, "properties is null");

    Map<String, PropertyMetadata<?>> propertiesByName = Maps.uniqueIndex(properties, PropertyMetadata::getName);

    checkState(connectorProperties.putIfAbsent(connectorId, propertiesByName) == null,
            "Properties for connector '%s' are already registered", connectorId);
}

From source file:de.softwareforge.kafka.LoadCommand.java

@Override
public void execute() throws Exception {
    Logging logging = Logging.initialize();
    logging.configure(new LoggingConfiguration());
    new LoggingMBean().setLevel("kafka", "ERROR");

    String tableNames = loaderOptions.tables;
    final Map<String, TpchTable<?>> allTables = ImmutableMap
            .copyOf(Maps.uniqueIndex(TpchTable.getTables(), new Function<TpchTable<?>, String>() {
                @Override/*  ww  w.  j  a v a2s  .c  o m*/
                public String apply(@Nonnull TpchTable<?> input) {
                    return input.getTableName();
                }
            }));

    List<String> tables;
    if (tableNames == null) {
        tables = ImmutableList.copyOf(allTables.keySet());
    } else {
        ImmutableList.Builder<String> builder = ImmutableList.builder();
        for (String tableName : Splitter.on(",").omitEmptyStrings().trimResults().split(tableNames)) {
            checkState(allTables.keySet().contains(tableName), "Table %s is unknown", tableName);
            builder.add(tableName);
        }
        tables = builder.build();
    }

    LOG.info("Processing tables: %s", tables);

    Properties props = new Properties();
    props.put("metadata.broker.list", loaderOptions.brokers);
    props.put("serializer.class", StringEncoder.class.getName());
    props.put("key.serializer.class", LongEncoder.class.getName());
    props.put("partitioner.class", LongPartitioner.class.getName());
    props.put("serializer.encoding", "UTF8");
    props.put("request.required.acks", "1");
    ProducerConfig producerConfig = new ProducerConfig(props);

    final ObjectMapper mapper = objectMapperProvider.get();
    mapper.enable(MapperFeature.AUTO_DETECT_GETTERS);

    final Producer<Long, String> producer = new Producer<>(producerConfig);

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

    ImmutableList.Builder<ListenableFuture<Long>> futureBuilder = ImmutableList.builder();

    for (final String table : tables) {
        ListenableFuture<Long> future = executor.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                TpchTable<?> tpchTable = allTables.get(table);
                LOG.info("Loading table '%s' into topic '%s%s'...", table, loaderOptions.prefix, table);
                long count = 0;

                for (List<? extends TpchEntity> partition : Iterables.partition(
                        tpchTable.createGenerator(loaderOptions.tpchType.getScaleFactor(), 1, 1), 100)) {
                    ImmutableList.Builder<KeyedMessage<Long, String>> builder = ImmutableList.builder();
                    for (TpchEntity o : partition) {
                        builder.add(new KeyedMessage<>(loaderOptions.prefix + table, count++,
                                mapper.writeValueAsString(o)));
                    }
                    producer.send(builder.build());
                }
                LOG.info("Generated %d rows for table '%s'.", count, table);
                return count;
            }
        });
        futureBuilder.add(future);
    }

    Futures.allAsList(futureBuilder.build()).get();
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.DAYS);
    producer.close();
}

From source file:com.twitter.common.stats.NumericStatExporter.java

/**
 * Creates a new numeric stat exporter that will export to the specified sink.
 *
 * @param exportSink Consumes stats.//  w ww .ja  v  a  2 s  . c  o  m
 * @param executor Executor to handle export thread.
 * @param exportInterval Export period.
 */
public NumericStatExporter(final Closure<Map<String, ? extends Number>> exportSink,
        ScheduledExecutorService executor, Amount<Long, Time> exportInterval) {
    checkNotNull(exportSink);
    this.executor = checkNotNull(executor);
    this.exportInterval = checkNotNull(exportInterval);
    this.exportSink = exportSink;

    exporter = new Runnable() {
        @Override
        public void run() {
            exportSink.execute(
                    Maps.transformValues(Maps.uniqueIndex(Stats.getNumericVariables(), GET_NAME), READ_STAT));
        }
    };
}

From source file:org.apache.aurora.common.args.Parsers.java

static Parsers fromConfiguration(Configuration configuration) {
    Map<Class<?>, Parser<?>> parsers = Maps
            .transformValues(Maps.uniqueIndex(configuration.parserInfo(), INFO_TO_PARSED_TYPE), INFO_TO_PARSER);
    return new Parsers(parsers);
}

From source file:org.jclouds.byon.functions.NodesFromYaml.java

@Override
public Map<String, Node> apply(InputStream source) {
    Constructor constructor = new Constructor(Config.class);

    TypeDescription nodeDesc = new TypeDescription(Node.class);
    nodeDesc.putListPropertyType("tags", String.class);
    constructor.addTypeDescription(nodeDesc);

    TypeDescription configDesc = new TypeDescription(Config.class);
    configDesc.putListPropertyType("nodes", Node.class);
    constructor.addTypeDescription(configDesc);

    Yaml yaml = new Yaml(new Loader(constructor));
    Config config = (Config) yaml.load(source);
    checkState(config != null, "missing config: class");
    checkState(config.nodes != null, "missing nodes: collection");

    return Maps.uniqueIndex(config.nodes, new Function<Node, String>() {
        public String apply(Node node) {
            return node.getId();
        }/*from w ww  .  j a  v  a2  s  .  co  m*/
    });
}

From source file:org.sonar.server.computation.qualityprofile.QPMeasureData.java

public Map<String, QualityProfile> getProfilesByKey() {
    return Maps.uniqueIndex(this.profiles, QualityProfileToKey.INSTANCE);
}

From source file:com.b2international.commons.collections.Collections3.java

/**
 * Adds each element of the iterable to the map argument after applying the given unique key index function. Duplicates are prohibited.
 *//*from  w w w .  j  a  v a  2  s. c  o  m*/
public static <K, V> void putAllWithNoDuplicates(final Map<K, V> to, final Iterable<? extends V> toAdd,
        final Function<? super V, K> f) {
    Preconditions.checkNotNull(to)
            .putAll(Maps.uniqueIndex(Preconditions.checkNotNull(toAdd), Preconditions.checkNotNull(f)));
}

From source file:org.xacml4j.v30.pdp.Policy.java

private Policy(Builder b) {
    super(b);//from   ww w  .ja v a 2s. com
    Preconditions.checkNotNull(b.combiningAlgorithm, "Rule decision combining algorithm must be specified");
    this.combiningAlgorithm = b.combiningAlgorithm;
    this.policyDefaults = b.policyDefaults;
    this.reference = PolicyIDReference.builder(b.id).version(b.version).build();
    this.rules = b.rules.build();
    this.variableDefinitions = Maps.uniqueIndex(b.variables, new Function<VariableDefinition, String>() {
        @Override
        public String apply(VariableDefinition from) {
            return from.getVariableId();
        }
    });
    this.ruleCombiningParameters = Maps.newHashMap();
    for (Entry<String, Multimap<String, CombinerParameter>> p : b.ruleCombinerParameters.entrySet()) {
        ruleCombiningParameters.put(p.getKey(), ImmutableListMultimap.copyOf(p.getValue()));
    }
}