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.sonar.server.measure.ws.ComponentTreeDataLoader.java

private Table<String, MetricDto, Measure> searchMeasuresByComponentUuidAndMetric(DbSession dbSession,
        ComponentDto baseComponent, ComponentTreeQuery componentTreeQuery, List<ComponentDto> components,
        List<MetricDto> metrics, @Nullable Long developerId) {

    Map<Integer, MetricDto> metricsById = Maps.uniqueIndex(metrics, MetricDto::getId);
    MeasureTreeQuery measureQuery = MeasureTreeQuery.builder()
            .setStrategy(MeasureTreeQuery.Strategy.valueOf(componentTreeQuery.getStrategy().name()))
            .setNameOrKeyQuery(componentTreeQuery.getNameOrKeyQuery())
            .setQualifiers(componentTreeQuery.getQualifiers()).setPersonId(developerId)
            .setMetricIds(new ArrayList<>(metricsById.keySet())).build();

    Table<String, MetricDto, Measure> measuresByComponentUuidAndMetric = HashBasedTable
            .create(components.size(), metrics.size());
    dbClient.measureDao().selectTreeByQuery(dbSession, baseComponent, measureQuery, result -> {
        MeasureDto measureDto = (MeasureDto) result.getResultObject();
        measuresByComponentUuidAndMetric.put(measureDto.getComponentUuid(),
                metricsById.get(measureDto.getMetricId()), Measure.createFromMeasureDto(measureDto));
    });/*from w  w w  . ja v a  2 s.co  m*/

    addBestValuesToMeasures(measuresByComponentUuidAndMetric, components, metrics);

    return measuresByComponentUuidAndMetric;
}

From source file:org.jclouds.openstack.nova.v1_1.compute.config.NovaComputeServiceContextModule.java

@Provides
@Singleton//w w w.  j a  v a2 s.  com
protected Supplier<Map<String, Location>> createLocationIndexedById(
        @Memoized Supplier<Set<? extends Location>> locations) {
    return Suppliers.compose(new Function<Set<? extends Location>, Map<String, Location>>() {

        @SuppressWarnings("unchecked")
        @Override
        public Map<String, Location> apply(Set<? extends Location> arg0) {
            // TODO: find a nice way to get rid of this cast.
            Iterable<Location> locations = (Iterable<Location>) arg0;
            return Maps.uniqueIndex(locations, new Function<Location, String>() {

                @Override
                public String apply(Location arg0) {
                    return arg0.getId();
                }

            });
        }
    }, locations);

}

From source file:org.jclouds.ec2.compute.strategy.EC2CreateNodesInGroupThenAddToSet.java

private void blockUntilRunningAndAssignElasticIpsToInstancesOrPutIntoBadMap(Set<RunningInstance> input,
        Map<NodeMetadata, Exception> badNodes) {
    Map<RegionAndName, RunningInstance> instancesById = Maps.uniqueIndex(input, instanceToRegionAndName);
    for (Map.Entry<RegionAndName, RunningInstance> entry : instancesById.entrySet()) {
        RegionAndName id = entry.getKey();
        RunningInstance instance = entry.getValue();
        try {//www  .  ja  v a2 s.co m
            logger.debug("<< allocating elastic IP instance(%s)", id);
            String ip = client.getElasticIPAddressApi().get().allocateAddressInRegion(id.getRegion());
            // block until instance is running
            logger.debug(">> awaiting status running instance(%s)", id);
            AtomicReference<NodeMetadata> node = newReference(runningInstanceToNodeMetadata.apply(instance));
            nodeRunning.apply(node);
            logger.trace("<< running instance(%s)", id);
            logger.debug(">> associating elastic IP %s to instance %s", ip, id);
            client.getElasticIPAddressApi().get().associateAddressInRegion(id.getRegion(), ip, id.getName());
            logger.trace("<< associated elastic IP %s to instance %s", ip, id);
            // add mapping of instance to ip into the cache
            elasticIpCache.put(id, ip);
        } catch (RuntimeException e) {
            badNodes.put(runningInstanceToNodeMetadata.apply(instancesById.get(id)), e);
        }
    }
}

From source file:org.eclipse.sw360.moderation.db.ModerationRequestGenerator.java

protected void dealWithAttachments(U attachmentField) {
    Set<Attachment> actualAttachments = (Set<Attachment>) actualDocument.getFieldValue(attachmentField);
    Set<Attachment> updateAttachments = (Set<Attachment>) updateDocument.getFieldValue(attachmentField);
    Map<String, Attachment> actualAttachmentMap = Maps.uniqueIndex(actualAttachments,
            Attachment::getAttachmentContentId);
    Set<String> actualAttachmentIds = actualAttachmentMap.keySet();
    Map<String, Attachment> updateAttachmentMap = Maps.uniqueIndex(updateAttachments,
            Attachment::getAttachmentContentId);
    Set<String> updateAttachmentIds = updateAttachmentMap.keySet();

    Set<Attachment> attachmentAdditions = updateAttachmentMap.values().stream()
            .filter(attachment -> !actualAttachmentIds.contains(attachment.getAttachmentContentId()))
            .collect(Collectors.toSet());

    Set<Attachment> attachmentDeletions = actualAttachmentMap.values().stream()
            .filter(attachment -> !updateAttachmentIds.contains(attachment.getAttachmentContentId()))
            .collect(Collectors.toSet());

    //determine changes in common attachments
    Set<String> commonAttachmentIds = Sets.intersection(actualAttachmentIds, updateAttachmentIds);
    for (String id : commonAttachmentIds) {
        Attachment actual = actualAttachmentMap.get(id);
        Attachment update = updateAttachmentMap.get(id);
        if (actual != null && !actual.equals(update)) {
            attachmentAdditions.add(getAdditionsFromCommonAttachment(actual, update));
            attachmentDeletions.add(getDeletionsFromCommonAttachment(actual, update));
        }/* w  ww  .  j a v  a  2 s  .c  o  m*/
    }
    documentAdditions.setFieldValue(attachmentField, attachmentAdditions);
    documentDeletions.setFieldValue(attachmentField, attachmentDeletions);
}

From source file:springfox.documentation.builders.OperationBuilder.java

private Set<ResponseMessage> mergeResponseMessages(Set<ResponseMessage> responseMessages) {
    //Add logic to consolidate the response messages
    ImmutableMap<Integer, ResponseMessage> responsesByCode = Maps.uniqueIndex(this.responseMessages,
            byStatusCode());/*from  w w  w.j a v a  2s .co m*/
    Set<ResponseMessage> merged = newHashSet(this.responseMessages);
    for (ResponseMessage each : responseMessages) {
        if (responsesByCode.containsKey(each.getCode())) {
            ResponseMessage responseMessage = responsesByCode.get(each.getCode());
            String message = defaultIfAbsent(emptyToNull(each.getMessage()), responseMessage.getMessage());
            ModelReference responseWithModel = defaultIfAbsent(each.getResponseModel(),
                    responseMessage.getResponseModel());
            merged.remove(responseMessage);
            merged.add(new ResponseMessageBuilder().code(each.getCode()).message(message)
                    .responseModel(responseWithModel).headersWithDescription(each.getHeaders()).build());
        } else {
            merged.add(each);
        }
    }
    return merged;
}

From source file:de.metas.ui.web.picking.pickingslot.PickingSlotRow.java

/**
 * Constructor for a row that represents an HU which is already assigned to a picking slot (aka a picked HU).
 *
 * @param pickingSlotId/*  ww w. j a va2 s  . c o m*/
 * @param huId
 * @param huStorageProductId
 * @param type
 * @param processed
 * @param code
 * @param product
 * @param packingInfo
 * @param qtyCU
 * @param includedHURows
 */
@Builder(builderMethodName = "fromPickedHUBuilder", builderClassName = "FromPickedHUBuilder")
private PickingSlotRow(@NonNull final PickingSlotId pickingSlotId, @NonNull final HuId huId,
        final int huStorageProductId,
        //
        final HUEditorRowType huEditorRowType, final boolean processed,
        //
        final String huCode, final JSONLookupValue product, final String packingInfo, final BigDecimal qtyCU,
        final boolean topLevelHU,
        //
        final List<PickingSlotRow> includedHURows) {
    pickingSlotRowId = PickingSlotRowId.ofPickedHU(pickingSlotId, huId, huStorageProductId);

    this.type = PickingSlotRowType.forPickingHuRow(huEditorRowType);
    this.processed = processed;

    documentPath = DocumentPath.rootDocumentPath(WEBUI_HU_Constants.WEBUI_HU_Window_ID, huId);

    // HU
    this.huCode = huCode;
    huProduct = product;
    huPackingInfo = packingInfo;
    huQtyCU = qtyCU;
    huTopLevel = topLevelHU;

    // Picking slot info
    pickingSlotWarehouse = null;
    pickingSlotLocatorId = null;
    pickingSlotBPartner = null;
    pickingSlotBPLocation = null;
    pickingSlotCaption = null;

    // Included rows
    this.includedHURows = includedHURows == null ? ImmutableMap.of()
            : Maps.uniqueIndex(includedHURows, PickingSlotRow::getPickingSlotRowId);

    this.includedViewId = null;
}

From source file:org.locationtech.geogig.porcelain.RemoveOp.java

private Map<String, NodeRef> getDeleteTrees(RevTree workTree) {

    Iterator<NodeRef> childTrees = command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_TREES)
            .setReference(workTree.getId().toString()).call();

    ImmutableMap<String, NodeRef> treesByPath = Maps.uniqueIndex(childTrees, (ref) -> ref.path());

    Set<String> requestedTrees = Sets.intersection(treesByPath.keySet(), new HashSet<>(pathsToRemove));
    Predicate<String> keyPredicate = Predicates.in(requestedTrees);
    Map<String, NodeRef> requestedTreesMap = Maps.filterKeys(treesByPath, keyPredicate);
    return requestedTreesMap;
}

From source file:org.trancecode.xproc.step.Step.java

public Step declarePorts(final Iterable<Port> ports) {
    LOG.trace("{@method} step = {} ; ports = {}", name, ports);

    final Map<String, Port> newPorts = Maps.newHashMap(this.ports);
    newPorts.putAll(Maps.uniqueIndex(ports, PortFunctions.getPortName()));

    return new Step(node, type, name, internalName, location, stepProcessor, compoundStep, variables,
            parameters, newPorts, steps, logs);
}

From source file:org.locationtech.geogig.remotes.pack.FetchOp.java

/**
 * Based on the remote's {@link Remote#getFetchSpecs() fetch specs}, resolves which remote
 * references need to be fetched and returns the mapping of each ref in the remote's namespate
 * to the local remotes namespace (e.g. {@code refs/heads/master -> refs/remotes/origin/master}
 *//*from ww w  .j  a  v a2s  .  c  o  m*/
private List<LocalRemoteRef> resolveRemoteRefs(IRemoteRepo remoteRepo) {

    final Map<String, Ref> remoteRemoteRefs;
    final Map<String, Ref> localRemoteRefs;

    {
        LsRemoteOp lsRemote = command(LsRemoteOp.class).setRemote(remoteRepo);
        remoteRemoteRefs = new HashMap<>(Maps.uniqueIndex(lsRemote.call(), r -> r.getName()));
        localRemoteRefs = new HashMap<>(
                Maps.uniqueIndex(lsRemote.retrieveLocalRefs(true).call(), r -> r.getName()));
    }

    List<LocalRemoteRef> refsToFectch = new ArrayList<>();
    final Remote remote = remoteRepo.getInfo();

    for (Ref remoteRef : remoteRemoteRefs.values()) {
        for (LocalRemoteRefSpec spec : remote.getFetchSpecs()) {
            java.util.Optional<String> localName = remote.mapToLocal(remoteRef.getName());
            boolean isNew = false, remoteDeleted = false;
            if (localName.isPresent()) {
                Ref localRemoteRef = localRemoteRefs.remove(localName.get());
                if (localRemoteRef == null) {
                    localRemoteRef = new Ref(localName.get(), ObjectId.NULL);
                    isNew = true;
                }
                if (!remoteRef.getObjectId().equals(localRemoteRef.getObjectId())) {
                    LocalRemoteRef localRemoteMapping;
                    localRemoteMapping = new LocalRemoteRef(remoteRef, localRemoteRef, spec.isForce(), isNew,
                            remoteDeleted);
                    refsToFectch.add(localRemoteMapping);
                }
                break;
            }
        }
    }
    // remaining refs found in the local repository
    for (Ref localRemote : localRemoteRefs.values()) {
        for (LocalRemoteRefSpec spec : remote.getFetchSpecs()) {
            java.util.Optional<String> remoteName;
            remoteName = remote.mapToRemote(localRemote.getName());
            boolean isNew = false, remoteDeleted = false;
            if (remoteName.isPresent()) {
                Ref remoteRef = remoteRemoteRefs.remove(remoteName.get());
                if (remoteRef == null) {
                    remoteRef = new Ref(remoteName.get(), ObjectId.NULL);
                    remoteDeleted = true;
                }
                if (remoteDeleted || !localRemote.getObjectId().equals(remoteRef.getObjectId())) {
                    LocalRemoteRef localRemoteMapping;
                    localRemoteMapping = new LocalRemoteRef(remoteRef, localRemote, spec.isForce(), isNew,
                            remoteDeleted);
                    refsToFectch.add(localRemoteMapping);
                }
                break;
            }
        }
    }

    return refsToFectch;
}

From source file:org.jclouds.ec2.compute.EC2ComputeService.java

private Set<NodeMetadata> addTagsAndNamesToInstancesInRegion(Map<String, String> common, Set<String> nodeNames,
        Set<? extends NodeMetadata> input, String region, String group) {
    Map<String, ? extends NodeMetadata> instancesById = Maps.uniqueIndex(input, instanceId);
    ImmutableSet.Builder<NodeMetadata> builder = ImmutableSet.<NodeMetadata>builder();

    if (generateInstanceNames && !common.containsKey("Name")) {
        for (Map.Entry<String, ? extends NodeMetadata> entry : instancesById.entrySet()) {
            String id = entry.getKey();
            String name;//from   w ww  . j av a 2  s  .  com
            if (!nodeNames.isEmpty()) {
                name = Iterables.get(nodeNames, 0);
            } else {
                name = id.replaceAll(".*-", group + "-");
            }
            Map<String, String> tags = ImmutableMap.<String, String>builder().putAll(common).put("Name", name)
                    .build();
            logger.debug(">> applying tags %s to instance %s in region %s", tags, id, region);
            client.getTagApiForRegion(region).get().applyToResources(tags, ImmutableSet.of(id));
            builder.add(addTagsForInstance(tags, instancesById.get(id)));
        }
    } else {
        Iterable<String> ids = instancesById.keySet();
        logger.debug(">> applying tags %s to instances %s in region %s", common, ids, region);
        client.getTagApiForRegion(region).get().applyToResources(common, ids);
        for (NodeMetadata in : input)
            builder.add(addTagsForInstance(common, in));
    }
    if (logger.isDebugEnabled()) {
        Multimap<String, String> filter = new TagFilterBuilder().resourceIds(instancesById.keySet()).build();
        FluentIterable<Tag> tags = client.getTagApiForRegion(region).get().filter(filter);
        logger.debug("<< applied tags in region %s: %s", region, resourceToTagsAsMap(tags));
    }
    return builder.build();
}