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.b2international.snowowl.snomed.datastore.index.change.RelationshipChangeProcessor.java

@Override
public void process(ICDOCommitChangeSet commitChangeSet, RevisionSearcher searcher) throws IOException {
    final Multimap<String, RefSetMemberChange> referringRefSets = memberChangeProcessor.process(commitChangeSet,
            searcher);//from w  ww .  j av a 2  s . c  om

    deleteRevisions(SnomedRelationshipIndexEntry.class,
            commitChangeSet.getDetachedComponents(SnomedPackage.Literals.RELATIONSHIP));

    final Map<String, Relationship> newRelationshipsById = StreamSupport
            .stream(commitChangeSet.getNewComponents(Relationship.class).spliterator(), false)
            .collect(Collectors.toMap(relationship -> relationship.getId(), relationship -> relationship));

    for (Relationship relationship : commitChangeSet.getNewComponents(Relationship.class)) {
        final Builder doc = SnomedRelationshipIndexEntry.builder(relationship);
        indexNewRevision(relationship.cdoID(), doc.build());
    }

    final Map<String, Relationship> changedRelationshipsById = StreamSupport
            .stream(commitChangeSet.getDirtyComponents(Relationship.class).spliterator(), false)
            .collect(Collectors.toMap(relationship -> relationship.getId(), relationship -> relationship));

    final Set<String> changedRelationshipIds = newHashSet(changedRelationshipsById.keySet());
    final Set<String> referencedRelationshipIds = newHashSet(referringRefSets.keySet());
    referencedRelationshipIds.removeAll(newRelationshipsById.keySet());
    changedRelationshipIds.addAll(referencedRelationshipIds);

    final Query<SnomedRelationshipIndexEntry> query = Query.select(SnomedRelationshipIndexEntry.class)
            .where(SnomedRelationshipIndexEntry.Expressions.ids(changedRelationshipIds))
            .limit(changedRelationshipIds.size()).build();

    final Hits<SnomedRelationshipIndexEntry> changedRelationshipHits = searcher.search(query);
    final ImmutableMap<String, SnomedRelationshipIndexEntry> changedRelationshipRevisionsById = Maps
            .uniqueIndex(changedRelationshipHits, ComponentUtils.<String>getIdFunction());

    for (final String id : changedRelationshipIds) {
        final SnomedRelationshipIndexEntry currentDoc = changedRelationshipRevisionsById.get(id);
        if (currentDoc == null) {
            throw new IllegalStateException(
                    String.format("Current relationship revision should not be null for %s", id));
        }

        final Relationship relationship = changedRelationshipsById.get(id);
        final Builder doc;
        if (relationship != null) {
            doc = SnomedRelationshipIndexEntry.builder(relationship);
        } else {
            doc = SnomedRelationshipIndexEntry.builder(currentDoc);
        }

        final Collection<String> currentMemberOf = currentDoc.getMemberOf();
        final Collection<String> currentActiveMemberOf = currentDoc.getActiveMemberOf();
        new ReferenceSetMembershipUpdater(referringRefSets.removeAll(id), currentMemberOf,
                currentActiveMemberOf).update(doc);

        indexChangedRevision(currentDoc.getStorageKey(), doc.build());
    }
}

From source file:org.locationtech.geogig.plumbing.index.MaterializedBuilderConsumer.java

private void addAll() {
    List<MaterializedBuilderConsumer.Tuple> list = new ArrayList<>(batchSize);
    nodes.drainTo(list);/*from  ww w .  j  a va2s . c om*/

    final Map<ObjectId, RevFeature> objects;
    {
        Iterable<Node> allNodes = Iterables.concat(list);
        Iterable<ObjectId> nodeIds = Iterables.transform(allNodes, (n) -> n.getObjectId());
        Iterator<RevFeature> objectsIt = featureSource.getAll(nodeIds, BulkOpListener.NOOP_LISTENER,
                RevFeature.class);
        objects = Maps.uniqueIndex(objectsIt, (o) -> o.getId());
    }

    for (MaterializedBuilderConsumer.Tuple t : list) {
        @Nullable
        Node left = materialize(t.left, objects);
        @Nullable
        Node right = materialize(t.right, objects);
        if (left == null) {
            builder.put(right);
        } else if (right == null) {
            builder.remove(left);
        } else {
            builder.update(left, right);
        }
    }
}

From source file:ca.cutterslade.match.scheduler.Scheduler.java

public Scheduler(Configuration config, Set<String> teams, Set<String> tiers, Set<String> gyms,
        Set<String> courts, Set<String> times, Set<String> days, int teamSize) throws InterruptedException {
    if (null == config)
        throw new IllegalArgumentException("config may not be null");
    if (null == teams)
        throw new IllegalArgumentException("teams may not be null");
    if (null == tiers)
        throw new IllegalArgumentException("tiers may not be null");
    if (null == gyms)
        throw new IllegalArgumentException("gyms may not be null");
    if (null == courts)
        throw new IllegalArgumentException("courts may not be null");
    if (null == times)
        throw new IllegalArgumentException("times may not be null");
    if (null == days)
        throw new IllegalArgumentException("days may not be null");
    this.config = config;
    this.gyms = Gym.forNames(gyms);
    this.courts = Court.forNames(courts, this.gyms);
    this.days = Day.forNames(days);
    this.times = Time.forNames(times);
    this.slots = Slot.forNames(this.times, this.courts, this.days);
    this.tiers = Tier.forNames(tiers);
    int slotsPerDay = gyms.size() * courts.size() * times.size();
    int possibleTeams = slotsPerDay * teamSize;
    ImmutableSet<Team> realTeams = Team.forNames(teams, this.tiers,
            (int) Math.ceil(possibleTeams / (double) this.tiers.size()));
    if (teams.size() > possibleTeams)
        throw new IllegalArgumentException(
                teams.size() + " teams cannot play in " + slotsPerDay + " slots per day");
    else if (teams.size() < possibleTeams)
        this.teams = padWithByes(this.tiers, realTeams, possibleTeams / this.tiers.size());
    else/* w  w w .  j  a  v  a 2s  . c o m*/
        this.teams = realTeams;
    this.matches = new MatchMaker(config, slots, this.teams, teamSize).getMatches();
    ImmutableMap.Builder<Day, ImmutableMap<Time, ImmutableSet<Match>>> dayTimeMatches = ImmutableMap.builder();
    for (Day day : this.days) {
        ImmutableMap.Builder<Time, ImmutableSet<Match>> timeMatches = ImmutableMap.builder();
        for (Time time : this.times) {
            ImmutableSet.Builder<Match> b = ImmutableSet.builder();
            for (Match m : matches)
                if (m.getDay().equals(day) && m.getTime().equals(time))
                    b.add(m);
            timeMatches.put(time, b.build());
        }
        dayTimeMatches.put(day, timeMatches.build());
    }
    this.dayTimeMatches = dayTimeMatches.build();
    ImmutableMap.Builder<Day, ImmutableSet<Match>> dayMatches = ImmutableMap.builder();
    for (Day day : this.days)
        dayMatches.put(day, ImmutableSet.copyOf(Iterables.concat(this.dayTimeMatches.get(day).values())));
    this.dayMatches = dayMatches.build();
    slotMatches = Maps.uniqueIndex(matches, new Function<Match, Slot>() {

        @Override
        public Slot apply(Match match) {
            return match.getSlot();
        }
    });
}

From source file:org.apache.whirr.HandlerMapFactory.java

static Map<String, ClusterActionHandler> indexHandlersByRole(Iterable<ClusterActionHandler> handlers) {
    return Maps.uniqueIndex(handlers, new Function<ClusterActionHandler, String>() {

        @Override//from   w  w w  .  java2  s.c  om
        public String apply(ClusterActionHandler arg0) {
            return arg0.getRole();
        }

    });
}

From source file:org.kie.workbench.common.screens.projecteditor.client.build.DeploymentPopupBuilder.java

private ImmutableMap<String, ServerTemplate> serverTemplateByIds(
        final Collection<ServerTemplate> serverTemplates) {
    return Maps.uniqueIndex(serverTemplates, s -> s.getId());
}

From source file:org.basepom.mojo.propertyhelper.beans.PropertyGroup.java

public String getPropertyValue(final InterpolatorFactory interpolatorFactory, final String propertyName,
        final Map<String, String> propElements) throws IOException, InterpolationException {
    final Map<String, PropertyDefinition> propertyMap = Maps.uniqueIndex(Arrays.asList(properties),
            getNameFunction());//  w  w w . ja  v a2s.c  om

    if (!propertyMap.keySet().contains(propertyName)) {
        return "";
    }

    final PropertyDefinition propertyDefinition = propertyMap.get(propertyName);

    final String result = interpolatorFactory.interpolate(propertyDefinition.getValue(), getOnMissingProperty(),
            propElements);
    return TransformerRegistry.applyTransformers(propertyDefinition.getTransformers(), result);
}

From source file:org.jclouds.abiquo.config.AbiquoHttpApiModule.java

@Provides
@Singleton//w  ww .  ja  v  a  2s. co  m
@Memoized
public Supplier<Map<Integer, Datacenter>> getAvailableRegionsIndexedById(
        final AtomicReference<AuthorizationException> authException,
        @Named(PROPERTY_SESSION_INTERVAL) final long seconds,
        @Memoized final Supplier<Enterprise> currentEnterprise) {
    Supplier<Map<Integer, Datacenter>> availableRegionsMapSupplier = Suppliers
            .compose(new Function<Iterable<Datacenter>, Map<Integer, Datacenter>>() {
                @Override
                public Map<Integer, Datacenter> apply(final Iterable<Datacenter> datacenters) {
                    // Index available regions by id
                    return Maps.uniqueIndex(datacenters, new Function<Datacenter, Integer>() {
                        @Override
                        public Integer apply(final Datacenter input) {
                            return input.getId();
                        }
                    });
                }
            }, new Supplier<Iterable<Datacenter>>() {
                @Override
                public Iterable<Datacenter> get() {
                    // Get the list of regions available for the user's tenant
                    return currentEnterprise.get().listAllowedDatacenters();
                }
            });

    return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,
            availableRegionsMapSupplier, seconds, TimeUnit.SECONDS);
}

From source file:de.metas.ui.web.process.ProcessRestController.java

public ProcessRestController(@NonNull final List<IProcessInstancesRepository> pinstancesRepositories,
        @NonNull final UserSession userSession, @NonNull final IViewsRepository viewsRepo,
        @NonNull final DocumentCollection documentsCollection) {
    this.pinstancesRepositoriesByHandlerType = Maps.uniqueIndex(pinstancesRepositories,
            IProcessInstancesRepository::getProcessHandlerType);
    logger.info("Registered process instances repositories: {}", pinstancesRepositoriesByHandlerType);

    this.userSession = userSession;
    this.viewsRepo = viewsRepo;
    this.documentsCollection = documentsCollection;
}

From source file:com.github.x3333.dagger.aop.internal.InterceptorProcessorStep.java

/**
 * Create a InterceptorProcessorStep instance.
 * /*  ww  w .  ja  va2s .  co  m*/
 * @param processingEnv ProcessingEnvironment associated to the Processor.
 * @param generateModule If we should generate a Dagger Module for intercepted methods.
 * @param modulePackage If we should generate a Dagger Module, in which package it should be created.
 */
public InterceptorProcessorStep(final ProcessingEnvironment processingEnv,
        final Optional<Boolean> disableModuleGeneration, final Optional<String> modulePackage) {
    this.processingEnv = processingEnv;
    this.disableModuleGeneration = disableModuleGeneration;
    this.modulePackage = modulePackage;
    final ServiceLoader<InterceptorHandler> handlers = ServiceLoader.load(InterceptorHandler.class,
            this.getClass().getClassLoader());
    this.services = Maps.uniqueIndex(handlers, InterceptorHandler::annotation);
    this.services.forEach((k, v) -> validateAnnotation(v, k));
    this.generator = new InterceptorGenerator(this.services);
}

From source file:com.nesscomputing.cache.PrefixedCache.java

public final Map<K, Boolean> addAll(final P prefix, final Map<K, ? extends V> entries) {
    final Function<K, String> prefixFunction = new PrefixFunction<P, K>(prefix, keySerializer);
    final Map<String, K> keyStrings = Maps.uniqueIndex(entries.keySet(), prefixFunction);

    final ImmutableMap.Builder<K, Boolean> builder = ImmutableMap.builder();

    final Map<String, Boolean> res = nessCache.add(namespace, Collections2.transform(entries.entrySet(),
            new Function<Map.Entry<K, ? extends V>, CacheStore<byte[]>>() {
                @Override/*w ww.j  a  v a  2 s. com*/
                public CacheStore<byte[]> apply(final Map.Entry<K, ? extends V> entry) {
                    final String keyString = keySerializer.apply(SerializablePair.of(prefix, entry.getKey()));
                    final byte[] valueBytes = valueSerializer.apply(entry.getValue());
                    return CacheStores.fromSharedBytes(keyString, valueBytes, getExpiry());
                }
            }));

    for (Map.Entry<String, Boolean> result : res.entrySet()) {
        builder.put(keyStrings.get(result.getKey()), result.getValue());
    }

    return builder.build();
}