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.nesscomputing.cache.guava.GuavaCacheAdapter.java

@Override
public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
    @SuppressWarnings("unchecked")
    Iterable<? extends K> extendedKeys = ImmutableSet.copyOf((Iterable<? extends K>) keys);
    Map<String, ? extends K> keyStrings = Maps.uniqueIndex(extendedKeys, keySerializer);
    Map<String, byte[]> response = cache.get(keyStrings.keySet());

    Builder<K, V> result = ImmutableMap.builder();

    for (Entry<String, byte[]> e : response.entrySet()) {
        K key = keyStrings.get(e.getKey());
        try {//w  w  w.  jav a  2s.  c o m
            result.put(key, valueDeserializer.apply(e.getValue()));
        } catch (Exception exc) {
            invalidate(key);
            throw Throwables.propagate(exc);
        }
    }

    return result.build();
}

From source file:com.viadeo.kasper.core.id.DefaultIDTransformer.java

private Map<ID, ID> doConvert(String vendor, Format sourceFormat, Format targetFormat, Collection<ID> values) {
    if (values.isEmpty() || targetFormat.equals(sourceFormat)) {
        return Maps.uniqueIndex(values, Functions.<ID>identity());
    }/* w  w  w .  ja v a2  s. c om*/

    for (final Converter converter : converterRegistry.getConverters(vendor, targetFormat)) {
        if (sourceFormat.equals(converter.getSource()) && targetFormat.equals(converter.getTarget())
                && vendor.equals(converter.getVendor())) {
            try {
                return converter.convert(values);
            } catch (FailedToTransformIDException e) {
                throw e;
            } catch (RuntimeException e) {
                throw new FailedToTransformIDException(
                        String.format("Failed to convert id from '%s' to '%s', <ids=%s>", sourceFormat,
                                targetFormat, values),
                        e);
            }
        }
    }

    throw new FailedToTransformIDException(
            String.format("No available converter allowing to convert id from '%s' to '%s', <ids=%s>",
                    sourceFormat, targetFormat, values));
}

From source file:com.proofpoint.cloudmanagement.service.JCloudsInstanceConnector.java

public JCloudsInstanceConnector(final JCloudsConfig config) {
    Preconditions.checkNotNull(config);/*w  w w . j av a  2  s  .  c o m*/

    this.name = config.getName();

    Properties overrides = new Properties();
    if (config.getLocation() != null) {
        overrides.setProperty(Constants.PROPERTY_ENDPOINT, config.getLocation());
    }
    overrides.setProperty(KeystoneProperties.CREDENTIAL_TYPE, CredentialType.PASSWORD_CREDENTIALS.toString());
    overrides.setProperty(KeystoneProperties.VERSION, "2.0");

    Set<Module> moduleOverrides = ImmutableSet.<Module>of(new JCloudsLoggingAdapterModule());

    ComputeServiceContext context = new ComputeServiceContextFactory().createContext(config.getApi(),
            config.getUser(), config.getSecret(), moduleOverrides, overrides);

    computeService = context.getComputeService();

    //There are too many images in ec2 to list them all, so we can't verify.
    if (!config.getApi().equals("aws-ec2")) {
        Preconditions
                .checkState(any(computeService.listImages(), new Predicate<org.jclouds.compute.domain.Image>() {
                    @Override
                    public boolean apply(@Nullable org.jclouds.compute.domain.Image image) {
                        return image.getId().endsWith(config.getDefaultImageId());
                    }
                }), "No image found for default image id [" + config.getDefaultImageId()
                        + "] please verify that this image exists");
    }

    defaultImageId = config.getDefaultImageId();

    hardwareMap = Maps.uniqueIndex(computeService.listHardwareProfiles(), new Function<Hardware, String>() {
        @Override
        public String apply(@Nullable Hardware hardware) {
            return firstNonNull(hardware.getName(), hardware.getId());
        }
    });

    locationMap = Maps.uniqueIndex(computeService.listAssignableLocations(), new Function<Location, String>() {
        @Override
        public String apply(@Nullable Location location) {
            return location.getId();
        }
    });

    templateOptions = getProviderSpecificOptions(config);

    getAllInstances();
}

From source file:org.dslforge.xtext.common.actions.BasicGenerateAction.java

protected Map<String, OutputConfiguration> getOutputConfigurations() {
    Set<OutputConfiguration> configurations = getDefaultOutputConfigurations();
    return Maps.uniqueIndex(configurations, new Function<OutputConfiguration, String>() {
        public String apply(OutputConfiguration from) {
            return from.getName();
        }/*from  ww  w.  j a v a2s. c  o  m*/
    });
}

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

/**
 * Groups {@code binding}'s implicit dependencies by their binding key, using the dependency keys
 * from the {@link Binding#unresolved()} binding if it exists.
 *//*from  ww  w .j  av a  2 s.  c  o m*/
private static ImmutableList<Collection<DependencyRequest>> groupByUnresolvedKey(Binding binding) {
    // If the binding has no unresolved version, just group the dependencies by binding key.
    if (!binding.unresolved().isPresent()) {
        return groupByKey(binding, Functions.<DependencyRequest>identity());
    }

    // Group the unresolved dependencies, replacing each one with its resolved version by looking it
    // up by request element.
    final ImmutableMap<Element, DependencyRequest> resolvedDependencies = Maps
            .uniqueIndex(binding.implicitDependencies(), new Function<DependencyRequest, Element>() {
                @Override
                public Element apply(DependencyRequest dependencyRequest) {
                    return dependencyRequest.requestElement();
                }
            });
    return groupByKey(binding.unresolved().get(), new Function<DependencyRequest, DependencyRequest>() {
        @Override
        public DependencyRequest apply(DependencyRequest unresolvedRequest) {
            return resolvedDependencies.get(unresolvedRequest.requestElement());
        }
    });
}

From source file:com.twitter.aurora.scheduler.storage.mem.MemTaskStore.java

@Timed("mem_storage_save_tasks")
@Override/*from ww  w .j a  v  a 2 s . c om*/
public void saveTasks(Set<IScheduledTask> newTasks) {
    checkNotNull(newTasks);
    Preconditions.checkState(Tasks.ids(newTasks).size() == newTasks.size(),
            "Proposed new tasks would create task ID collision.");

    Iterable<Task> canonicalized = Iterables.transform(newTasks, toTask);
    tasks.putAll(Maps.uniqueIndex(canonicalized, TO_ID));
    tasksByJobKey.putAll(taskIdsByJobKey(canonicalized));
}

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

private void expandTargetComponent(List<SnomedReferenceSetMember> results) {
    if (expand().containsKey(SnomedRf2Headers.FIELD_TARGET_COMPONENT)) {
        final Options expandOptions = expand().get(SnomedRf2Headers.FIELD_TARGET_COMPONENT, Options.class);

        final Multimap<String, SnomedReferenceSetMember> membersByTargetComponent = HashMultimap.create();
        for (SnomedReferenceSetMember member : results) {
            final Map<String, Object> props = member.getProperties();
            if (props.containsKey(SnomedRf2Headers.FIELD_TARGET_COMPONENT)) {
                membersByTargetComponent.put(
                        ((SnomedCoreComponent) props.get(SnomedRf2Headers.FIELD_TARGET_COMPONENT)).getId(),
                        member);//from ww  w.  j a  va 2s. c  o  m
            }
        }

        final Multimap<ComponentCategory, String> targetComponentIdsByCategory = Multimaps
                .index(membersByTargetComponent.keySet(), new Function<String, ComponentCategory>() {
                    @Override
                    public ComponentCategory apply(String id) {
                        return SnomedIdentifiers.getComponentCategory(id);
                    }
                });

        for (ComponentCategory category : targetComponentIdsByCategory.keySet()) {
            final Collection<String> targetComponentIds = targetComponentIdsByCategory.get(category);
            final Map<String, ? extends SnomedCoreComponent> componentsById = Maps.uniqueIndex(
                    getComponents(category, targetComponentIds, expandOptions.get("expand", Options.class)),
                    IComponent.ID_FUNCTION);
            for (String targetComponentId : targetComponentIds) {
                final SnomedCoreComponent targetComponent = componentsById.get(targetComponentId);
                if (targetComponent != null) {
                    for (SnomedReferenceSetMember member : membersByTargetComponent.get(targetComponentId)) {
                        final Map<String, Object> newProps = newHashMap(member.getProperties());
                        newProps.put(SnomedRf2Headers.FIELD_TARGET_COMPONENT, targetComponent);
                        ((SnomedReferenceSetMember) member).setProperties(newProps);
                    }
                }
            }
        }
    }
}

From source file:org.apache.whirr.actions.ConfigureClusterAction.java

private Map<String, ? extends NodeMetadata> getNodesForInstanceIdsInCluster(Cluster cluster,
        ComputeService computeService) {
    Iterable<String> ids = Iterables.transform(cluster.getInstances(), new Function<Instance, String>() {

        @Override//from  w w  w . j av  a  2 s. c om
        public String apply(Instance arg0) {
            return arg0.getId();
        }

    });

    Set<? extends NodeMetadata> nodes = computeService
            .listNodesDetailsMatching(NodePredicates.withIds(Iterables.toArray(ids, String.class)));

    return Maps.uniqueIndex(nodes, getNodeId);
}

From source file:com.twitter.aurora.scheduler.base.Tasks.java

public static Map<String, IScheduledTask> mapById(Iterable<IScheduledTask> tasks) {
    return Maps.uniqueIndex(tasks, SCHEDULED_TO_ID);
}

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

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