Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:eu.itesla_project.modules.histo.IIDM2DB.java

public static JSONArray toTopoSet(VoltageLevel vl) throws JSONException {
    SortedMap<String, JSONArray> topoList = new TreeMap<>();

    Multimap<String, String> topoTmp = HashMultimap.create();

    vl.visitEquipments(new TerminalTopologyVisitor() {
        @Override//from  w  w  w  .  j  a  va  2  s.  c o m
        public void visitTerminal(Terminal t) {
            Connectable c = t.getConnectable();
            Bus b = t.getBusView().getBus();
            if (b == null) {
                if (c.getType() == ConnectableType.LOAD || c.getType() == ConnectableType.GENERATOR
                        || c.getType() == ConnectableType.SHUNT_COMPENSATOR) {
                    // add the injection in the topo set even if not connected but just connectable to this bus
                    // see WP4.2 data mining topology spec for more detailed information
                    b = t.getBusView().getConnectableBus();
                }
            }
            if (b != null) {
                topoTmp.put(b.getId(), c.getId());
            } else {
                // connect the equipment to its own bus
                topoTmp.put(c.getId() + "FICTIVE_BUS", c.getId());
            }
        }
    });

    for (Map.Entry<String, Collection<String>> entry : topoTmp.asMap().entrySet()) {
        SortedSet<String> topoContent = new TreeSet<>(entry.getValue());
        JSONArray topoArray = new JSONArray(topoContent.toArray(new String[] {}));
        topoList.put(topoArray.toString(), topoArray);
    }

    return new JSONArray(topoList.values().toArray(new JSONArray[] {}));
}

From source file:feign.jaxb.examples.AWSSignatureVersion4.java

private String canonicalString(RequestTemplate input, Multimap<String, String> sortedLowercaseHeaders) {
    StringBuilder canonicalRequest = new StringBuilder();
    // HTTPRequestMethod + '\n' +
    canonicalRequest.append(input.method()).append('\n');

    // CanonicalURI + '\n' +
    canonicalRequest.append(URI.create(input.url()).getPath()).append('\n');

    // CanonicalQueryString + '\n' +
    canonicalRequest.append(input.queryLine().substring(1));
    canonicalRequest.append('\n');

    // CanonicalHeaders + '\n' +
    for (Entry<String, Collection<String>> entry : sortedLowercaseHeaders.asMap().entrySet()) {
        canonicalRequest.append(entry.getKey()).append(':').append(Joiner.on(',').join(entry.getValue()))
                .append('\n');
    }/*  ww  w . j  a va 2  s.  co  m*/
    canonicalRequest.append('\n');

    // SignedHeaders + '\n' +
    canonicalRequest.append(Joiner.on(',').join(sortedLowercaseHeaders.keySet())).append('\n');

    // HexEncode(Hash(Payload))
    String bodyText = input.charset() != null && input.body() != null
            ? new String(input.body(), input.charset())
            : null;
    if (bodyText != null) {
        canonicalRequest.append(base16().lowerCase().encode(sha256().hashString(bodyText, UTF_8).asBytes()));
    } else {
        canonicalRequest.append(EMPTY_STRING_HASH);
    }
    return canonicalRequest.toString();
}

From source file:com.b2international.snowowl.snomed.importer.rf2.validation.SnomedTaxonomyValidator.java

private Collection<SnomedValidationDefect> doValidate() {

    try {//from   w  ww  . jav  a 2s  .  c  o  m

        final Multimap<String, InvalidRelationship> invalidRelationships = processTaxonomy();

        if (!invalidRelationships.isEmpty()) {

            String messageWithEffectiveTime = "'%s' relationship refers to an inactive concept '%s' (%s) in effective time '%s'";
            String messageWithOutEffectiveTime = "'%s' relationship refers to an inactive concept '%s' (%s)";

            List<String> validationMessages = invalidRelationships.asMap().entrySet().stream()
                    .flatMap(entry -> {

                        String effectiveTime = entry.getKey();
                        Collection<InvalidRelationship> relationships = entry.getValue();

                        return relationships.stream().map(relationship -> {

                            String relationshipId = String.valueOf(relationship.getRelationshipId());

                            String missingReference = MissingConcept.DESTINATION == relationship
                                    .getMissingConcept() ? String.valueOf(relationship.getDestinationId())
                                            : String.valueOf(relationship.getSourceId());

                            String missingReferenceLabel = relationship.getMissingConcept().getLabel();

                            if (!Strings.isNullOrEmpty(effectiveTime)) {
                                return String.format(messageWithEffectiveTime, relationshipId, missingReference,
                                        missingReferenceLabel, effectiveTime);
                            } else {
                                return String.format(messageWithOutEffectiveTime, relationshipId,
                                        missingReference, missingReferenceLabel);
                            }

                        });

                    }).collect(toList());

            LOGGER.info("{} SNOMED CT ontology validation successfully finished. {} taxonomy {} identified.",
                    Concepts.STATED_RELATIONSHIP.equals(characteristicType) ? "Stated" : "Inferred",
                    validationMessages.size(), validationMessages.size() > 1 ? "issues were" : "issue was");

            return singleton(new SnomedIncompleteTaxonomyValidationDefect(relationshipsFile.getName(),
                    validationMessages));

        }

    } catch (final IOException e) {
        LOGGER.error("Validation failed.", e);
        return singleton(new SnomedValidationDefect(relationshipsFile.getName(), DefectType.IO_PROBLEM,
                Collections.<String>emptySet()));
    }

    LOGGER.info("{} SNOMED CT ontology validation successfully finished. No errors were found.",
            Concepts.STATED_RELATIONSHIP.equals(characteristicType) ? "Stated" : "Inferred");

    return emptySet();
}

From source file:org.apache.cassandra.service.StorageProxy.java

/***
 * //  w  w w  .jav a  2s. c  om
 * @param rm 
 * @param hintedEndpoints 
 * @param responseHandler 
 * @param localDataCenter 
 * @param insertLocalMessages
 * @param consistency_level
 * @throws IOException
 */
//write1.0insertLocalhintedEndpointsby Hycz
private static void sendToHintedEndpoints(final RowMutation rm,
        Multimap<InetAddress, InetAddress> hintedEndpoints, IWriteResponseHandler responseHandler,
        String localDataCenter, boolean insertLocalMessages, ConsistencyLevel consistency_level)
        throws IOException {
    // Multimap that holds onto all the messages and addresses meant for a specific datacenter
    Map<String, Multimap<Message, InetAddress>> dcMessages = new HashMap<String, Multimap<Message, InetAddress>>(
            hintedEndpoints.size());
    MessageProducer producer = new CachingMessageProducer(rm);

    for (Map.Entry<InetAddress, Collection<InetAddress>> entry : hintedEndpoints.asMap().entrySet()) {
        InetAddress destination = entry.getKey();
        Collection<InetAddress> targets = entry.getValue();

        String dc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(destination);

        if (targets.size() == 1 && targets.iterator().next().equals(destination)) {
            // 
            // unhinted writes
            if (destination.equals(FBUtilities.getLocalAddress())) {
                if (insertLocalMessages)
                    insertLocal(rm, responseHandler);
            }
            // 
            else {
                // belongs on a different server
                if (logger.isDebugEnabled())
                    logger.debug(
                            "insert writing key " + ByteBufferUtil.bytesToHex(rm.key()) + " to " + destination);

                Multimap<Message, InetAddress> messages = dcMessages.get(dc);
                if (messages == null) {
                    messages = HashMultimap.create();
                    dcMessages.put(dc, messages);
                }

                messages.put(producer.getMessage(Gossiper.instance.getVersion(destination)), destination);
            }
        }
        // hint
        else {
            // hinted messages are unique, so there is no point to adding a hop by forwarding via another node.
            // thus, we use sendRR/sendOneWay directly here.
            Message hintedMessage = rm.getMessage(Gossiper.instance.getVersion(destination));
            for (InetAddress target : targets) {
                if (!target.equals(destination)) {
                    addHintHeader(hintedMessage, target);
                    if (logger.isDebugEnabled())
                        logger.debug("insert writing key " + ByteBufferUtil.bytesToHex(rm.key()) + " to "
                                + destination + " for " + target);
                }
            }
            // non-destination hints are part of the callback and count towards consistency only under CL.ANY
            if (targets.contains(destination) || consistency_level == ConsistencyLevel.ANY)
                MessagingService.instance().sendRR(hintedMessage, destination, responseHandler);
            else
                MessagingService.instance().sendOneWay(hintedMessage, destination);
        }
    }
    // 
    sendMessages(localDataCenter, dcMessages, responseHandler);
}

From source file:ninja.servlet.NinjaServletContext.java

/**
 * Utility method to convert a Guava Multimap to an unmodifiable Map that
 * uses a List<T> as a value. Optimized for the case where values are already
 * internally stored as a List<T> (e.g. ArrayListMultimap).
 * @param <T> The value type/* w  w w .ja v a  2  s. com*/
 * @param multimap The multimap to convert from
 * @return The unmodifiable converted map
 */
private <T> Map<String, List<T>> toUnmodifiableMap(Multimap<String, T> multimap) {
    Map<String, List<T>> map = new HashMap<>(multimap.size());

    for (Entry<String, Collection<T>> entry : multimap.asMap().entrySet()) {
        Collection<T> value = entry.getValue();
        if (value == null) {
            Collections.emptyList();
        } else if (value instanceof List) {
            map.put(entry.getKey(), (List<T>) value);
        } else {
            map.put(entry.getKey(), new ArrayList<>(value));
        }
    }

    return Collections.unmodifiableMap(map);
}

From source file:org.apache.calcite.rel.rules.AbstractMaterializedViewRule.java

/**
 * It will flatten a multimap containing table references to table references,
 * producing all possible combinations of mappings. Each of the mappings will
 * be bi-directional./*www.  ja  v a 2s  .c om*/
 */
private static List<BiMap<RelTableRef, RelTableRef>> generateTableMappings(
        Multimap<RelTableRef, RelTableRef> multiMapTables) {
    final List<BiMap<RelTableRef, RelTableRef>> result = new ArrayList<>();
    if (multiMapTables.isEmpty()) {
        return result;
    }
    result.add(HashBiMap.<RelTableRef, RelTableRef>create());
    for (Entry<RelTableRef, Collection<RelTableRef>> e : multiMapTables.asMap().entrySet()) {
        boolean added = false;
        for (RelTableRef target : e.getValue()) {
            if (added) {
                for (BiMap<RelTableRef, RelTableRef> m : result) {
                    final BiMap<RelTableRef, RelTableRef> newM = HashBiMap.<RelTableRef, RelTableRef>create(m);
                    newM.put(e.getKey(), target);
                    result.add(newM);
                }
            } else {
                for (BiMap<RelTableRef, RelTableRef> m : result) {
                    m.put(e.getKey(), target);
                }
                added = true;
            }
        }
        // Mapping needs to exist
        assert added;
    }
    return result;
}

From source file:buildcraft.core.proxy.CoreProxyClient.java

@Override
public void init() {
    MinecraftForge.EVENT_BUS.register(RenderTickListener.INSTANCE);

    IResourceManager resourceManager = Minecraft.getMinecraft().getResourceManager();
    IReloadableResourceManager reloadable = (IReloadableResourceManager) resourceManager;
    reloadable.registerReloadListener(DetailedConfigOption.ReloadListener.INSTANCE);

    ClientRegistry.bindTileEntitySpecialRenderer(TileEngineBase.class, new RenderEngine());
    ClientRegistry.bindTileEntitySpecialRenderer(TilePathMarker.class, new RenderPathMarker());
    ClientRegistry.bindTileEntitySpecialRenderer(TileMarker.class, new RenderMarker());

    RenderingRegistry.registerEntityRenderingHandler(EntityResizableCuboid.class,
            RenderResizableCuboid.INSTANCE);
    RenderingRegistry.registerEntityRenderingHandler(EntityLaser.class, new RenderLaser());

    for (Block block : blocksToRegisterRenderersFor) {
        if (block instanceof IModelRegister) {
            ((IModelRegister) block).registerModels();
            continue;
        }// w  w  w  .ja v a 2  s . c om

        IBlockState defaultState = block.getDefaultState();
        Multimap<Integer, IBlockState> metaStateMap = ArrayListMultimap.create();
        Map<IBlockState, String> stateTypeMap = Maps.newHashMap();

        for (IBlockState state : (List<IBlockState>) block.getBlockState().getValidStates()) {
            String type = BuildCraftStateMapper.getPropertyString(state);
            stateTypeMap.put(state, type);
            metaStateMap.put(block.damageDropped(state), state);
        }
        for (Entry<Integer, Collection<IBlockState>> entry : metaStateMap.asMap().entrySet()) {
            Collection<IBlockState> blockStates = entry.getValue();
            if (blockStates.isEmpty())
                continue;
            if (blockStates.contains(defaultState)) {
                registerBlockItemModel(defaultState, entry.getKey(), stateTypeMap.get(defaultState));
            } else {
                IBlockState state = blockStates.iterator().next();
                registerBlockItemModel(state, entry.getKey(), stateTypeMap.get(state));
            }
        }
    }
    for (Item item : itemsToRegisterRenderersFor) {
        if (item instanceof IModelRegister) {
            ((IModelRegister) item).registerModels();
        }
    }
}

From source file:org.eclipse.xtext.ide.editor.contentassist.antlr.ContentAssistContextFactory.java

protected void doCreateContexts(INode lastCompleteNode, INode currentNode, String prefix, EObject previousModel,
        Collection<FollowElement> followElements) {
    Set<AbstractElement> followElementAsAbstractElements = Sets.newLinkedHashSet();
    followElementComputer.computeFollowElements(followElements, followElementAsAbstractElements);
    Multimap<EObject, AbstractElement> contextMap = computeCurrentModel(previousModel, lastCompleteNode,
            followElementAsAbstractElements);
    currentNode = getContainingDatatypeRuleNode(currentNode);
    for (Entry<EObject, Collection<AbstractElement>> entry : contextMap.asMap().entrySet()) {
        ContentAssistContext.Builder contextBuilder = doCreateContext(lastCompleteNode, entry.getKey(),
                previousModel, currentNode, prefix);
        for (AbstractElement element : entry.getValue()) {
            contextBuilder.accept(element);
        }/*www .j  a  v  a2s .  com*/
        contextBuilders.add(contextBuilder);
    }
}

From source file:com.b2international.snowowl.snomed.datastore.index.change.DescriptionChangeProcessor.java

@Override
public void process(ICDOCommitChangeSet commitChangeSet, RevisionSearcher searcher) throws IOException {
    final Map<String, Multimap<Acceptability, RefSetMemberChange>> acceptabilityChangesByDescription = new DescriptionAcceptabilityChangeProcessor()
            .process(commitChangeSet, searcher);

    final Multimap<String, RefSetMemberChange> referringRefSets = HashMultimap
            .create(memberChangeProcessor.process(commitChangeSet, searcher));

    // delete detached descriptions
    deleteRevisions(SnomedDescriptionIndexEntry.class,
            commitChangeSet.getDetachedComponents(SnomedPackage.Literals.DESCRIPTION));

    // (re)index new and dirty descriptions
    final Map<String, Description> newDescriptionsById = StreamSupport
            .stream(commitChangeSet.getNewComponents(Description.class).spliterator(), false)
            .collect(Collectors.toMap(description -> description.getId(), description -> description));

    final Map<String, Description> changedDescriptionsById = StreamSupport
            .stream(commitChangeSet.getDirtyComponents(Description.class).spliterator(), false)
            .collect(Collectors.toMap(description -> description.getId(), description -> description));

    final Set<String> changedDescriptionIds = newHashSet(changedDescriptionsById.keySet());
    final Set<String> referencedDescriptionIds = newHashSet(referringRefSets.keySet());
    referencedDescriptionIds.removeAll(newDescriptionsById.keySet());
    changedDescriptionIds.addAll(referencedDescriptionIds);

    // load the known descriptions 
    final Query<SnomedDescriptionIndexEntry> query = Query.select(SnomedDescriptionIndexEntry.class)
            .where(SnomedDescriptionIndexEntry.Expressions.ids(changedDescriptionIds)).limit(Integer.MAX_VALUE)
            .build();/*from   w w  w . ja v a 2  s  .c  o  m*/

    final Hits<SnomedDescriptionIndexEntry> changedDescriptionHits = searcher.search(query);

    Multimap<String, SnomedDescriptionIndexEntry> changedDescriptionRevisionsById = ArrayListMultimap
            .<String, SnomedDescriptionIndexEntry>create();
    changedDescriptionHits.forEach(hit -> changedDescriptionRevisionsById.put(hit.getId(), hit));

    boolean reindexRunning = isReindexRunning(SnomedDatastoreActivator.REPOSITORY_UUID);

    for (Entry<String, Collection<SnomedDescriptionIndexEntry>> entry : changedDescriptionRevisionsById.asMap()
            .entrySet()) {
        if (entry.getValue().size() > 1) {

            String message = String.format("Description with id %s exists with multiple storage keys: [%s]",
                    entry.getKey(), Joiner.on(", ").join(entry.getValue().stream().map(e -> e.getStorageKey())
                            .collect(Collectors.toList())));

            if (reindexRunning) {
                LOG.info(message);
            } else {
                throw new IllegalStateException(message);
            }
        }
    }

    // load missing descriptions with only changed acceptability values
    final Set<String> descriptionsToBeLoaded = newHashSet();
    for (String descriptionWithAccepatibilityChange : acceptabilityChangesByDescription.keySet()) {
        if (!newDescriptionsById.containsKey(descriptionWithAccepatibilityChange)
                && !changedDescriptionIds.contains(descriptionWithAccepatibilityChange)) {
            descriptionsToBeLoaded.add(descriptionWithAccepatibilityChange);
        }
    }

    // process changes
    for (final String id : Iterables.concat(newDescriptionsById.keySet(), changedDescriptionIds)) {
        if (newDescriptionsById.containsKey(id)) {
            final Description description = newDescriptionsById.get(id);
            final long storageKey = CDOIDUtil.getLong(description.cdoID());
            final Builder doc = SnomedDescriptionIndexEntry.builder(description);
            processChanges(id, doc, null, acceptabilityChangesByDescription.get(id), referringRefSets);
            indexNewRevision(storageKey, doc.build());
        } else if (changedDescriptionIds.contains(id)) {
            final Collection<SnomedDescriptionIndexEntry> docs = changedDescriptionRevisionsById.get(id);
            for (SnomedDescriptionIndexEntry currentDoc : docs) {

                if (currentDoc == null) {
                    throw new IllegalStateException(
                            String.format("Current description revision should not be null for: %s", id));
                }

                final Description description = changedDescriptionsById.get(id);
                final Builder doc;
                if (description != null) {
                    doc = SnomedDescriptionIndexEntry.builder(description);
                } else {
                    doc = SnomedDescriptionIndexEntry.builder(currentDoc);
                }

                processChanges(id, doc, currentDoc, acceptabilityChangesByDescription.get(id),
                        referringRefSets);
                indexChangedRevision(currentDoc.getStorageKey(), doc.build());

            }

        } else {
            throw new IllegalStateException(
                    String.format("Description %s is missing from new and dirty maps", id));
        }
    }

    // process cascading acceptability changes in unchanged docs
    if (!descriptionsToBeLoaded.isEmpty()) {
        final Query<SnomedDescriptionIndexEntry> descriptionsToBeLoadedQuery = Query
                .select(SnomedDescriptionIndexEntry.class)
                .where(SnomedDocument.Expressions.ids(descriptionsToBeLoaded))
                .limit(descriptionsToBeLoaded.size()).build();

        for (SnomedDescriptionIndexEntry unchangedDescription : searcher.search(descriptionsToBeLoadedQuery)) {
            final Builder doc = SnomedDescriptionIndexEntry.builder(unchangedDescription);
            processChanges(unchangedDescription.getId(), doc, unchangedDescription,
                    acceptabilityChangesByDescription.get(unchangedDescription.getId()),
                    HashMultimap.<String, RefSetMemberChange>create());
            indexChangedRevision(unchangedDescription.getStorageKey(), doc.build());
        }
    }
}

From source file:io.prestosql.plugin.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name/*from  ww  w  .  java  2  s  . c o m*/
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}