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.api.impl.SnomedBrowserService.java

@Override
public SnomedBrowserDescriptionResults getDescriptions(String branchPath, String query,
        List<ExtendedLocale> locales, SnomedBrowserDescriptionType preferredDescriptionType, String searchAfter,
        int limit) {

    checkNotNull(branchPath, "BranchPath may not be null.");
    checkNotNull(query, "Query may not be null.");
    checkArgument(query.length() >= 3, "Query must be at least 3 characters long.");

    final DescriptionService descriptionService = new DescriptionService(getBus(), branchPath);

    SnomedDescriptions snomedDescriptions = SnomedRequests.prepareSearchDescription()
            .setSearchAfter(searchAfter).setLimit(limit).filterByTerm(query)
            .filterByType(ImmutableSet.of(Concepts.FULLY_SPECIFIED_NAME, Concepts.SYNONYM))
            .sortBy(SearchIndexResourceRequest.SCORE)
            .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath).execute(getBus()).getSync();

    final Collection<SnomedDescription> descriptions = snomedDescriptions.getItems();

    final List<SnomedDescription> sortedDescriptions = FluentIterable.from(descriptions)
            .toSortedList((d1, d2) -> {
                int result = d2.getScore().compareTo(d1.getScore());
                return result == 0 ? Ints.compare(d1.getTerm().length(), d2.getTerm().length()) : result;
            });//from   ww w.ja v a  2s. co  m

    final Set<String> conceptIds = FluentIterable.from(sortedDescriptions)
            .transform(description -> description.getConceptId()).toSet();

    final Iterable<SnomedConcept> concepts = getConcepts(branchPath, conceptIds);
    final Map<String, SnomedConcept> conceptMap = Maps.uniqueIndex(concepts, IComponent.ID_FUNCTION);

    final Map<String, SnomedDescription> descriptionByConceptIdMap;
    switch (preferredDescriptionType) {
    case FSN:
        descriptionByConceptIdMap = descriptionService.getFullySpecifiedNames(conceptIds, locales);
        break;
    default:
        descriptionByConceptIdMap = descriptionService.getPreferredTerms(conceptIds, locales);
        break;
    }

    final Cache<String, SnomedBrowserDescriptionResultDetails> detailCache = CacheBuilder.newBuilder().build();
    final ImmutableList.Builder<ISnomedBrowserDescriptionResult> resultBuilder = ImmutableList.builder();

    for (final SnomedDescription description : sortedDescriptions) {

        final SnomedBrowserDescriptionResult descriptionResult = new SnomedBrowserDescriptionResult();
        descriptionResult.setActive(description.isActive());
        descriptionResult.setTerm(description.getTerm());

        try {
            final SnomedBrowserDescriptionResultDetails details = detailCache.get(description.getConceptId(),
                    new Callable<SnomedBrowserDescriptionResultDetails>() {

                        @Override
                        public SnomedBrowserDescriptionResultDetails call() throws Exception {
                            final String conceptId = description.getConceptId();
                            final SnomedConcept concept = conceptMap.get(conceptId);
                            final SnomedBrowserDescriptionResultDetails details = new SnomedBrowserDescriptionResultDetails();

                            if (concept != null) {
                                details.setActive(concept.isActive());
                                details.setConceptId(concept.getId());
                                details.setDefinitionStatus(concept.getDefinitionStatus());
                                details.setModuleId(concept.getModuleId());

                                if (preferredDescriptionType == SnomedBrowserDescriptionType.FSN) {
                                    if (descriptionByConceptIdMap.containsKey(conceptId)) {
                                        details.setFsn(descriptionByConceptIdMap.get(conceptId).getTerm());
                                    } else {
                                        details.setFsn(conceptId);
                                    }
                                } else {
                                    if (descriptionByConceptIdMap.containsKey(conceptId)) {
                                        details.setPreferredSynonym(
                                                descriptionByConceptIdMap.get(conceptId).getTerm());
                                    } else {
                                        details.setPreferredSynonym(conceptId);
                                    }
                                }

                            } else {
                                LOGGER.warn("Concept {} not found in map, properties will not be set.",
                                        conceptId);
                            }

                            return details;
                        }
                    });

            descriptionResult.setConcept(details);
        } catch (ExecutionException e) {
            LOGGER.error(
                    "Exception thrown during computing details for concept {}, properties will not be set.",
                    description.getConceptId(), e);
        }

        resultBuilder.add(descriptionResult);
    }

    return SnomedBrowserDescriptionResults.of(resultBuilder.build(), snomedDescriptions);
}

From source file:org.gradle.model.internal.manage.binding.DefaultStructBindingsStore.java

private static ImmutableMap<Wrapper<Method>, WeaklyTypeReferencingMethod<?, ?>> indexBySignature(
        Iterable<WeaklyTypeReferencingMethod<?, ?>> methods) {
    return Maps.uniqueIndex(methods, new Function<WeaklyTypeReferencingMethod<?, ?>, Wrapper<Method>>() {
        @Override//from  w  ww  .j  a v  a  2 s .co  m
        public Wrapper<Method> apply(WeaklyTypeReferencingMethod<?, ?> weakMethod) {
            return SIGNATURE_EQUIVALENCE.wrap(weakMethod.getMethod());
        }
    });
}

From source file:com.boundlessgeo.geoserver.api.controllers.MapController.java

@RequestMapping(value = "/{wsName}/{name}/layers", method = RequestMethod.POST)
public @ResponseBody JSONArr mapLayerListPost(@PathVariable String wsName, @PathVariable String name,
        @RequestBody JSONArr layers, HttpServletRequest req) {
    Catalog cat = geoServer.getCatalog();
    LayerGroupInfo m = findMap(wsName, name, cat);
    WorkspaceInfo ws = m.getWorkspace();

    List<PublishedInfo> appendLayers = new ArrayList<PublishedInfo>();
    Map<String, PublishedInfo> check = Maps.uniqueIndex(appendLayers, new Function<PublishedInfo, String>() {
        @Nullable//from  ww  w  . j  a  v a 2s .c  o m
        public String apply(@Nullable PublishedInfo input) {
            return input.getName();
        }
    });
    List<StyleInfo> appendStyles = new ArrayList<StyleInfo>();
    for (JSONObj l : Lists.reverse(Lists.newArrayList(layers.objects()))) {
        String layerName = l.str("name");
        String layerWorkspace = l.str("workspace");
        if (check.containsKey(layerName)) {
            throw new BadRequestException("Duplicate layer: " + l.toString());
        }
        LayerInfo layer = findLayer(layerWorkspace, layerName, cat);
        if (layer == null) {
            throw new NotFoundException("No such layer: " + l.toString());
        }
        appendLayers.add(layer);
        appendStyles.add(layer.getDefaultStyle());
    }
    m.getLayers().addAll(appendLayers);
    m.getStyles().addAll(appendStyles);

    Date modified = new Date();
    Metadata.modified(m, modified);
    Metadata.modified(ws, modified);

    cat.save(m);
    cat.save(ws);

    recent.add(LayerGroupInfo.class, m);
    recent.add(WorkspaceInfo.class, ws);
    return mapLayerList(m, req);
}

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

private void expandDescendants(List<SnomedConcept> results, final Set<String> conceptIds, String descendantKey,
        boolean stated) {
    if (!expand().containsKey(descendantKey)) {
        return;/*from   w  w  w .ja va  2 s.co  m*/
    }

    final Options expandOptions = expand().get(descendantKey, Options.class);
    final boolean direct = checkDirect(expandOptions);

    try {

        final ExpressionBuilder expression = Expressions.builder();
        expression.filter(active());
        final ExpressionBuilder descendantFilter = Expressions.builder();
        if (stated) {
            descendantFilter.should(statedParents(conceptIds));
            if (!direct) {
                descendantFilter.should(statedAncestors(conceptIds));
            }
        } else {
            descendantFilter.should(parents(conceptIds));
            if (!direct) {
                descendantFilter.should(ancestors(conceptIds));
            }
        }
        expression.filter(descendantFilter.build());

        final Query<SnomedConceptDocument> query = Query.select(SnomedConceptDocument.class)
                .where(expression.build()).limit(Integer.MAX_VALUE).build();

        final RevisionSearcher searcher = context().service(RevisionSearcher.class);
        final Hits<SnomedConceptDocument> hits = searcher.search(query);

        if (hits.getTotal() < 1) {
            final SnomedConcepts descendants = new SnomedConcepts(0, 0);
            for (SnomedConcept concept : results) {
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
            return;
        }

        // in case of only one match and limit zero, use shortcut instead of loading all IDs and components
        // XXX won't work if number of results is greater than one, either use custom ConceptSearch or figure out how to expand descendants effectively
        final int limit = getLimit(expandOptions);
        if (conceptIds.size() == 1 && limit == 0) {
            for (SnomedConcept concept : results) {
                final SnomedConcepts descendants = new SnomedConcepts(0, hits.getTotal());
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
            return;
        }

        final Multimap<String, String> descendantsByAncestor = TreeMultimap.create();
        for (SnomedConceptDocument hit : hits) {
            final Set<String> parentsAndAncestors = newHashSet();
            if (stated) {
                parentsAndAncestors.addAll(LongSets.toStringSet(hit.getStatedParents()));
                if (!direct) {
                    parentsAndAncestors.addAll(LongSets.toStringSet(hit.getStatedAncestors()));
                }
            } else {
                parentsAndAncestors.addAll(LongSets.toStringSet(hit.getParents()));
                if (!direct) {
                    parentsAndAncestors.addAll(LongSets.toStringSet(hit.getAncestors()));
                }
            }

            parentsAndAncestors.retainAll(conceptIds);
            for (String ancestor : parentsAndAncestors) {
                descendantsByAncestor.put(ancestor, hit.getId());
            }
        }

        final Collection<String> componentIds = newHashSet(descendantsByAncestor.values());

        if (limit > 0 && !componentIds.isEmpty()) {
            // query descendants again
            final SnomedConcepts descendants = SnomedRequests.prepareSearchConcept().all().filterByActive(true)
                    .filterByIds(componentIds).setLocales(locales())
                    .setExpand(expandOptions.get("expand", Options.class)).build().execute(context());

            final Map<String, SnomedConcept> descendantsById = newHashMap();
            descendantsById.putAll(Maps.uniqueIndex(descendants, ID_FUNCTION));
            for (SnomedConcept concept : results) {
                final Collection<String> descendantIds = descendantsByAncestor.get(concept.getId());
                final List<SnomedConcept> currentDescendants = FluentIterable.from(descendantIds).limit(limit)
                        .transform(Functions.forMap(descendantsById)).toList();
                final SnomedConcepts descendantConcepts = new SnomedConcepts(currentDescendants, null, null,
                        limit, descendantIds.size());
                if (stated) {
                    concept.setStatedDescendants(descendantConcepts);
                } else {
                    concept.setDescendants(descendantConcepts);
                }
            }
        } else {
            for (SnomedConcept concept : results) {
                final Collection<String> descendantIds = descendantsByAncestor.get(concept.getId());
                final SnomedConcepts descendants = new SnomedConcepts(limit, descendantIds.size());
                if (stated) {
                    concept.setStatedDescendants(descendants);
                } else {
                    concept.setDescendants(descendants);
                }
            }
        }

    } catch (IOException e) {
        throw SnowowlRuntimeException.wrap(e);
    }
}

From source file:controllers.SearchController.java

public Result showMessage(String index, String id) {
    final Set<InputDescription> inputs = Sets.newHashSet();
    final Set<StreamDescription> streams = Sets.newHashSet();
    final Set<NodeDescription> nodes = Sets.newHashSet();

    try {//w w  w . ja  v  a  2 s  . co m
        final MessageResult message = messagesService.getMessage(index, id);
        final Node sourceNode = getSourceNode(message);
        final Radio sourceRadio = getSourceRadio(message);
        final Input sourceInput = getSourceInput(sourceNode, message);
        final Input sourceRadioInput = getSourceInput(sourceRadio, message);

        if (sourceNode != null) {
            nodes.add(new NodeDescription(sourceNode));
        }
        if (sourceRadio != null) {
            nodes.add(new NodeDescription(sourceRadio));
        }
        if (sourceInput != null) {
            inputs.add(new InputDescription(sourceInput));
        }
        if (sourceRadioInput != null) {
            inputs.add(new InputDescription(sourceRadioInput));
        }

        for (String streamId : message.getStreamIds()) {
            if (isPermitted(RestPermissions.STREAMS_READ, streamId)) {
                try {
                    final Stream stream = streamService.get(streamId);
                    streams.add(StreamDescription.of(stream));
                } catch (APIException e) {
                    //  We get a 404 if the stream no longer exists.
                    Logger.debug("Skipping stream of message", e);
                }
            }
        }

        return ok(views.html.search.show_message.render(currentUser(), message,
                Maps.uniqueIndex(nodes, new Function<NodeDescription, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable NodeDescription node) {
                        return node == null ? null : node.getNodeId();
                    }
                }), Maps.uniqueIndex(streams, new Function<StreamDescription, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable StreamDescription stream) {
                        return stream == null ? null : stream.getId();
                    }
                }), Maps.uniqueIndex(inputs, new Function<InputDescription, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable InputDescription input) {
                        return input == null ? null : input.getId();
                    }
                })));
    } catch (IOException e) {
        return status(500, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request()));
    } catch (APIException e) {
        String message = "Could not get message. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + ".";
        return status(500, views.html.errors.error.render(message, e, request()));
    }
}

From source file:org.opentestsystem.authoring.testauth.service.impl.ScoringRuleHelper.java

protected List<BlueprintElement> findBlueprintElementsMissingScoringRule(final String assessmentId) {
    final Assessment assessment = this.assessmentRepository.findOne(assessmentId);
    final List<Segment> segmentList = this.sharedPublisherHelper.retrieveSegmentList(assessmentId);
    final List<BlueprintElement> blueprintElementList = this.sharedPublisherHelper
            .getActiveBlueprintElements(assessmentId);
    final List<AffinityGroup> affinityGroupList = this.sharedPublisherHelper
            .getActiveAffinityGroups(assessmentId);
    final Map<BlueprintReferenceType, Map<String, String>> blueprintReferenceMap = this.sharedPublisherHelper
            .buildBlueprintReferenceMap(assessment, segmentList, blueprintElementList, affinityGroupList);
    final List<ScoringRule> scoringRuleList = this.sharedPublisherHelper.retrieveScoringRules(assessmentId);
    final ScoringRuleData scoringRuleData = this.sharedPublisherHelper.setupScoringRuleData(assessmentId,
            blueprintReferenceMap, scoringRuleList, blueprintElementList, false);
    final List<String> blueprintElementStandardKeysCoveredByScoringRule = Lists
            .transform(scoringRuleData.getComputationRuleList(), COMPRULE_BPE_ID_TRANSFORMER);

    final Map<String, BlueprintElement> bpElementMap = Maps.uniqueIndex(blueprintElementList,
            BPELEMENT_STANDARD_KEY_TRANSFORMER);

    final List<BlueprintElement> blueprintElementsNotCoveredByScoringRule = Lists.newArrayList(Maps
            .filterEntries(bpElementMap,
                    BPE_WITHOUT_SCORULE_FILTER.getInstance(blueprintElementStandardKeysCoveredByScoringRule))
            .values());/*from  w  w  w. jav a 2  s.c o  m*/
    return blueprintElementsNotCoveredByScoringRule;
}

From source file:com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService.java

private Map<String, SctId> readSctIds(final Set<String> componentIds) {
    HttpPost bulkRequest = null;//  w w  w  . j a  va2  s . c  om
    HttpGet singleRequest = null;

    try {

        if (componentIds.size() > 1) {
            LOGGER.debug("Sending bulk component ID get request.");
            final ImmutableMap.Builder<String, SctId> resultBuilder = ImmutableMap.builder();

            for (final Collection<String> ids : Iterables.partition(componentIds, BULK_LIMIT)) {
                final String idsAsString = Joiner.on(',').join(ids);
                final ObjectNode idsAsJson = mapper.createObjectNode().put("sctids", idsAsString);
                bulkRequest = client.httpPost(String.format("sct/bulk/ids/?token=%s", getToken()), idsAsJson);
                final String response = execute(bulkRequest);

                final SctId[] sctIds = mapper.readValue(response, SctId[].class);
                final Map<String, SctId> sctIdMap = Maps.uniqueIndex(Arrays.asList(sctIds), SctId::getSctid);
                resultBuilder.putAll(sctIdMap);
            }

            return resultBuilder.build();

        } else {

            final String componentId = Iterables.getOnlyElement(componentIds);
            LOGGER.debug(String.format("Sending component ID %s get request.", componentId));
            singleRequest = httpGet(String.format("sct/ids/%s?token=%s", componentId, getToken()));
            final String response = execute(singleRequest);

            final SctId sctId = mapper.readValue(response, SctId.class);
            return ImmutableMap.of(sctId.getSctid(), sctId);
        }

    } catch (IOException e) {
        throw new SnowowlRuntimeException("Exception while getting all IDs", e);
    } finally {
        release(bulkRequest);
        release(singleRequest);
    }
}

From source file:org.locationtech.geogig.test.integration.remoting.RemoteRepositoryTestCase.java

protected void assertSummary(TransferSummary result, String remoteURL, Optional<Ref> before,
        Optional<Ref> after) {
    assertNotNull(result);/*from   ww  w.ja  v a 2 s  .c o m*/
    Collection<RefDiff> diffs = result.getRefDiffs().get(remoteURL);
    assertNotNull(diffs);
    String name = before.or(after).get().getName();
    RefDiff diff = Maps.uniqueIndex(diffs, (d) -> d.oldRef().or(d.newRef()).get().getName()).get(name);
    assertNotNull(diff);
    assertEquals(before, diff.oldRef());
    assertEquals(after, diff.newRef());
}

From source file:org.restlet.test.ext.apispark.conversion.swagger.v2_0.Swagger2TestCase.java

private void compareRwadefEndpoints(Definition savedDefinition, Definition translatedDefinition) {
    if (assertBothNull(savedDefinition.getEndpoints(), translatedDefinition.getEndpoints())) {
        return;//from www. j  a va 2s  .com
    }

    ImmutableMap<String, Endpoint> savedEndpoints = Maps.uniqueIndex(savedDefinition.getEndpoints(),
            new Function<Endpoint, String>() {
                public String apply(Endpoint endpoint) {
                    return endpoint.computeUrl();
                }
            });
    ImmutableMap<String, Endpoint> translatedEndpoints = Maps.uniqueIndex(translatedDefinition.getEndpoints(),
            new Function<Endpoint, String>() {
                public String apply(Endpoint endpoint) {
                    return endpoint.computeUrl();
                }
            });
    assertEquals(savedEndpoints.size(), translatedEndpoints.size());
    for (String key : savedEndpoints.keySet()) {
        Endpoint savedEndpoint = savedEndpoints.get(key);
        Endpoint translatedEndpoint = translatedEndpoints.get(key);
        assertNotNull(savedEndpoint);
        assertNotNull(translatedEndpoint);
        assertEquals(savedEndpoint.getAuthenticationProtocol(), translatedEndpoint.getAuthenticationProtocol());
        assertEquals(savedEndpoint.getBasePath(), translatedEndpoint.getBasePath());
        assertEquals(savedEndpoint.getDomain(), translatedEndpoint.getDomain());
        assertEquals(savedEndpoint.getProtocol(), translatedEndpoint.getProtocol());
        assertEquals(savedEndpoint.getPort(), translatedEndpoint.getPort());
    }
}

From source file:org.caleydo.view.domino.internal.Block.java

@Override
public boolean doLayout(List<? extends IGLLayoutElement> children, float w, float h, IGLLayoutElement parent,
        int deltaTimeMs) {
    final Map<GLElement, ? extends IGLLayoutElement> lookup = Maps.uniqueIndex(children,
            AGLLayoutElement.TO_GL_ELEMENT);
    for (LinearBlock block : linearBlocks)
        block.doLayout(lookup);//from w  w  w  .  j a  v a  2s  .  c  o  m
    children.get(0).setBounds(0, 0, w, h);
    return false;
}