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:org.apache.twill.internal.state.SystemMessages.java

/**
 * Helper method to get System {@link Message} for resetting log levels for one or all runnables.
 *
 * @param runnableName The name of the runnable to set the log level, null if apply to all runnables.
 * @return An instance of System {@link Message} to reset the log levels.
 *//*w  w  w.  ja  va2s. c  om*/
public static Message resetLogLevels(@Nullable String runnableName, Set<String> loggerNames) {
    return new SimpleMessage(Message.Type.SYSTEM,
            runnableName == null ? Message.Scope.ALL_RUNNABLE : Message.Scope.RUNNABLE, runnableName,
            Command.Builder.of(RESET_LOG_LEVEL)
                    .addOptions(Maps.uniqueIndex(loggerNames, Functions.toStringFunction())).build());
}

From source file:org.opendaylight.netconf.cli.reader.impl.ChoiceReader.java

private static Map<String, ChoiceCaseNode> collectAllCases(final ChoiceSchemaNode schemaNode) {
    return Maps.uniqueIndex(schemaNode.getCases(), new Function<ChoiceCaseNode, String>() {
        @Override//ww  w .  j a va2  s .  c  o m
        public String apply(final ChoiceCaseNode input) {
            return input.getQName().getLocalName();
        }
    });
}

From source file:com.facebook.presto.util.GraphvizPrinter.java

public static String printDistributed(SubPlan plan) {
    List<PlanFragment> fragments = plan.getAllFragments();
    Map<PlanFragmentId, PlanFragment> fragmentsById = Maps.uniqueIndex(fragments, PlanFragment::getId);
    PlanNodeIdGenerator idGenerator = new PlanNodeIdGenerator();

    StringBuilder output = new StringBuilder();
    output.append("digraph distributed_plan {\n");

    printSubPlan(plan, fragmentsById, idGenerator, output);

    output.append("}\n");

    return output.toString();
}

From source file:com.google.security.zynamics.binnavi.Database.cache.EdgeCache.java

public void addEdges(final List<INaviEdge> edges) {
    final ImmutableMap<Integer, INaviEdge> edgesMap = Maps.uniqueIndex(edges,
            new Function<INaviEdge, Integer>() {
                @Override//www  .  j av a 2 s  .c o m
                public Integer apply(final INaviEdge edge) {
                    return edge.getId();
                }
            });

    edgesByIdCache.putAll(edgesMap);

    for (final INaviEdge edge : edges) {
        if (edge.getSource() instanceof IAddressNode && edge.getTarget() instanceof IAddressNode) {
            final IAddress sourceAddress = ((IAddressNode) edge.getSource()).getAddress();
            final IAddress targetAddress = ((IAddressNode) edge.getTarget()).getAddress();
            Integer sourceModuleId = null;
            Integer targetModuleId = null;
            if (edge.getSource() instanceof INaviCodeNode) {
                sourceModuleId = getModuleId((INaviCodeNode) edge.getSource());
            } else if (edge.getSource() instanceof INaviFunctionNode) {
                sourceModuleId = getModuleId((INaviFunctionNode) edge.getSource());
            }
            if (edge.getTarget() instanceof INaviCodeNode) {
                targetModuleId = getModuleId((INaviCodeNode) edge.getTarget());
            } else if (edge.getTarget() instanceof INaviFunctionNode) {
                targetModuleId = getModuleId((INaviFunctionNode) edge.getTarget());
            }
            if (targetModuleId != null && sourceModuleId != null) {
                UpdateAddressModuleIdCache(sourceAddress, sourceModuleId, targetAddress, targetModuleId, edge);
            }
        }
    }
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedRelationshipConverter.java

@Override
protected void expand(List<SnomedRelationship> results) {
    if (expand().isEmpty()) {
        return;/*ww w  . j a  va2s.  c o  m*/
    }

    final Set<String> relationshipIds = FluentIterable.from(results).transform(ID_FUNCTION).toSet();
    new MembersExpander(context(), expand(), locales()).expand(results, relationshipIds);
    if (expand().containsKey("source")) {
        final Options sourceOptions = expand().get("source", Options.class);
        final Set<String> sourceConceptIds = FluentIterable.from(results)
                .transform(new Function<SnomedRelationship, String>() {
                    @Override
                    public String apply(SnomedRelationship input) {
                        return input.getSourceId();
                    }
                }).toSet();
        final SnomedConcepts sourceConcepts = SnomedRequests.prepareSearchConcept()
                .filterByIds(sourceConceptIds).setLimit(sourceConceptIds.size())
                .setExpand(sourceOptions.get("expand", Options.class)).setLocales(locales()).build()
                .execute(context());
        final Map<String, SnomedConcept> sourceConceptsById = Maps.uniqueIndex(sourceConcepts, ID_FUNCTION);
        for (SnomedRelationship relationship : results) {
            final String sourceId = relationship.getSourceId();
            if (sourceConceptsById.containsKey(sourceId)) {
                final SnomedConcept sourceConcept = sourceConceptsById.get(sourceId);
                ((SnomedRelationship) relationship).setSource(sourceConcept);
            }
        }
    }
    if (expand().containsKey("destination")) {
        final Options destinationOptions = expand().get("destination", Options.class);
        final Set<String> destinationConceptIds = FluentIterable.from(results)
                .transform(new Function<SnomedRelationship, String>() {
                    @Override
                    public String apply(SnomedRelationship input) {
                        return input.getDestinationId();
                    }
                }).toSet();
        final SnomedConcepts destinationConcepts = SnomedRequests.prepareSearchConcept()
                .filterByIds(destinationConceptIds).setLimit(destinationConceptIds.size())
                .setExpand(destinationOptions.get("expand", Options.class)).setLocales(locales()).build()
                .execute(context());
        final Map<String, SnomedConcept> destinationConceptsById = Maps.uniqueIndex(destinationConcepts,
                ID_FUNCTION);
        for (SnomedRelationship relationship : results) {
            final String destinationId = relationship.getDestinationId();
            if (destinationConceptsById.containsKey(destinationId)) {
                final SnomedConcept destinationConcept = destinationConceptsById.get(destinationId);
                ((SnomedRelationship) relationship).setDestination(destinationConcept);
            }
        }
    }
    if (expand().containsKey("type")) {
        final Options typeOptions = expand().get("type", Options.class);
        final Set<String> typeConceptIds = FluentIterable.from(results)
                .transform(new Function<SnomedRelationship, String>() {
                    @Override
                    public String apply(SnomedRelationship input) {
                        return input.getTypeId();
                    }
                }).toSet();
        final SnomedConcepts typeConcepts = SnomedRequests.prepareSearchConcept().filterByIds(typeConceptIds)
                .setLimit(typeConceptIds.size()).setExpand(typeOptions.get("expand", Options.class))
                .setLocales(locales()).build().execute(context());
        final Map<String, SnomedConcept> typeConceptsById = Maps.uniqueIndex(typeConcepts, ID_FUNCTION);
        for (SnomedRelationship relationship : results) {
            final String typeId = relationship.getTypeId();
            if (typeConceptsById.containsKey(typeId)) {
                final SnomedConcept typeConcept = typeConceptsById.get(typeId);
                ((SnomedRelationship) relationship).setType(typeConcept);
            }
        }
    }
}

From source file:org.sonar.server.measure.ws.ComponentTreeSort.java

private static Ordering<ComponentDto> metricValueOrdering(ComponentTreeWsRequest wsRequest,
        List<MetricDto> metrics,
        Table<String, MetricDto, ComponentTreeData.Measure> measuresByComponentUuidAndMetric) {
    if (wsRequest.getMetricSort() == null) {
        return componentNameOrdering(wsRequest.getAsc());
    }// w  w  w .ja  v a  2s . co  m
    Map<String, MetricDto> metricsByKey = Maps.uniqueIndex(metrics, MetricDto::getKey);
    MetricDto metric = metricsByKey.get(wsRequest.getMetricSort());

    boolean isAscending = wsRequest.getAsc();
    ValueType metricValueType = ValueType.valueOf(metric.getValueType());
    if (NUMERIC_VALUE_TYPES.contains(metricValueType)) {
        return numericalMetricOrdering(isAscending, metric, measuresByComponentUuidAndMetric);
    } else if (TEXTUAL_VALUE_TYPES.contains(metricValueType)) {
        return stringOrdering(isAscending,
                new ComponentDtoToTextualMeasureValue(metric, measuresByComponentUuidAndMetric));
    } else if (ValueType.LEVEL.equals(ValueType.valueOf(metric.getValueType()))) {
        return levelMetricOrdering(isAscending, metric, measuresByComponentUuidAndMetric);
    }

    throw new IllegalStateException("Unrecognized metric value type: " + metric.getValueType());
}

From source file:com.opengamma.financial.marketdatasnapshot.StructuredSnapper.java

private Map<TKey, TCalculatedValue> getValues(final ViewCycle viewCycle,
        final Map<String, DependencyGraph> dependencyGraphs) {
    final Map<String, Collection<ValueSpecification>> values = getMatchingSpecifications(dependencyGraphs,
            _requirementName);// w ww. j  a v  a2 s  . c o m
    final Map<TKey, TCalculatedValue> ts = new HashMap<TKey, TCalculatedValue>();

    for (final Entry<String, Collection<ValueSpecification>> entry : values.entrySet()) {
        final Iterable<ValueSpecification> requiredSpecsIt = Iterables.filter(entry.getValue(),
                new Predicate<ValueSpecification>() {

                    @Override
                    public boolean apply(final ValueSpecification input) {
                        return !ts.containsKey(getKey(input));
                    }

                });
        final Collection<ValueSpecification> requiredSpecs = Lists.newArrayList(requiredSpecsIt);
        if (requiredSpecs.isEmpty()) {
            continue;
        }

        final ComputationCycleQuery cacheQuery = new ComputationCycleQuery();
        cacheQuery.setCalculationConfigurationName(entry.getKey());
        cacheQuery.setValueSpecifications(requiredSpecs);
        final ComputationCacheResponse computationCacheResponse = viewCycle.queryComputationCaches(cacheQuery);

        if (computationCacheResponse.getResults().size() != requiredSpecs.size()) {
            s_logger.debug("Failed to get all results from computation cache");
        }

        final Map<TKey, Pair<ValueSpecification, Object>> infos = Maps.uniqueIndex(
                computationCacheResponse.getResults(), new Function<Pair<ValueSpecification, Object>, TKey>() {

                    @Override
                    public TKey apply(final Pair<ValueSpecification, Object> from) {
                        return getKey(from.getFirst());
                    }
                });

        for (final Entry<TKey, Pair<ValueSpecification, Object>> result : infos.entrySet()) {
            @SuppressWarnings("unchecked")
            final TCalculatedValue calcValue = (TCalculatedValue) result.getValue().getSecond();
            ts.put(result.getKey(), calcValue);
        }
    }
    return ts;
}

From source file:org.sonar.server.qualityprofile.ws.QProfileSearchAction.java

private void writeProfiles(JsonWriter json, List<QProfile> profiles, List<String> fields) {
    Map<String, QProfile> profilesByKey = Maps.uniqueIndex(profiles,
            new NonNullInputFunction<QProfile, String>() {
                @Override//from  w  w  w . ja  v a 2  s. com
                protected String doApply(QProfile input) {
                    return input.key();
                }
            });
    Map<String, Long> activeRuleCountByKey = profileLoader.countAllActiveRules();

    json.name("profiles").beginArray();
    for (QProfile profile : profiles) {
        if (languages.get(profile.language()) == null) {
            // Hide profiles on an unsupported language
            continue;
        }

        String key = profile.key();
        Long activeRuleCount = activeRuleCountByKey.containsKey(key) ? activeRuleCountByKey.get(key) : 0L;
        json.beginObject().prop(FIELD_KEY, nullUnlessNeeded(FIELD_KEY, key, fields))
                .prop(FIELD_NAME, nullUnlessNeeded(FIELD_NAME, profile.name(), fields))
                .prop(FIELD_ACTIVE_RULE_COUNT,
                        nullUnlessNeeded(FIELD_ACTIVE_RULE_COUNT, activeRuleCount, fields));
        writeLanguageFields(json, profile, fields);
        writeParentFields(json, profile, fields, profilesByKey);
        // Special case for booleans
        if (fieldIsNeeded(FIELD_IS_INHERITED, fields)) {
            json.prop(FIELD_IS_INHERITED, profile.isInherited());
        }
        if (fieldIsNeeded(FIELD_IS_DEFAULT, fields) && profile.isDefault()) {
            json.prop(FIELD_IS_DEFAULT, true);
        }
        json.endObject();
    }
    json.endArray();
}

From source file:com.facebook.presto.connector.jmx.JmxMetadata.java

@Override
public Map<String, ColumnHandle> getColumnHandles(ConnectorSession session, ConnectorTableHandle tableHandle) {
    JmxTableHandle jmxTableHandle = checkType(tableHandle, JmxTableHandle.class, "tableHandle");
    return ImmutableMap.copyOf(Maps.uniqueIndex(jmxTableHandle.getColumns(),
            column -> column.getColumnName().toLowerCase(ENGLISH)));
}

From source file:org.jclouds.elasticstack.compute.config.ElasticStackComputeServiceContextModule.java

@Singleton
@Provides/*from  www. j a v a  2  s . c  o m*/
protected Map<String, WellKnownImage> provideImages(Json json, @Provider String providerName)
        throws IOException {
    List<WellKnownImage> wellKnowns = json.fromJson(
            Strings2.toStringAndClose(
                    getClass().getResourceAsStream("/" + providerName + "/preinstalled_images.json")),
            new TypeLiteral<List<WellKnownImage>>() {
            }.getType());
    return Maps.uniqueIndex(wellKnowns, new Function<WellKnownImage, String>() {

        @Override
        public String apply(WellKnownImage input) {
            return input.getUuid();
        }

    });
}