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:com.cinchapi.concourse.util.Convert.java

/**
 * Serialize the {@code map} of a data as a JSON string that can inserted
 * into Concourse.//from  www.  j  a v  a2 s. c  om
 * 
 * @param map the data to include in the JSON object. This is meant to map
 *            to the return value of {@link #jsonToJava(String)}
 * @return the JSON string representation of the {@code map}
 */
public static String mapToJson(Multimap<String, Object> map) {
    return mapToJson(map.asMap());
}

From source file:msi.gama.util.GAML.java

public static String getDocumentationOn(final String query) {
    final String keyword = StringUtils.removeEnd(StringUtils.removeStart(query.trim(), "#"), ":");
    final Multimap<GamlIdiomsProvider<?>, IGamlDescription> results = GamlIdiomsProvider.forName(keyword);
    if (results.isEmpty()) {
        return "No result found";
    }/*from   ww w  .j  a v  a2 s .  c  om*/
    final StringBuilder sb = new StringBuilder();
    final int max = results.keySet().stream().mapToInt(each -> each.name.length()).max().getAsInt();
    final String separator = StringUtils.repeat("", max + 6).concat(Strings.LN);
    results.asMap().forEach((provider, list) -> {
        sb.append("").append(separator).append("|| ");
        sb.append(StringUtils.rightPad(provider.name, max));
        sb.append(" ||").append(Strings.LN).append(separator);
        for (final IGamlDescription d : list) {
            sb.append("== ").append(toText(d.getTitle())).append(Strings.LN)
                    .append(toText(provider.document(d))).append(Strings.LN);
        }
    });

    return sb.toString();

    //
}

From source file:br.com.tecsinapse.exporter.importer.ImporterUtils.java

public static final Map<Method, TableCellMapping> getMappedMethods(Class<?> clazz, final Class<?> group) {

    Set<Method> cellMappingMethods = ReflectionUtils.getAllMethods(clazz,
            ReflectionUtils.withAnnotation(TableCellMapping.class));
    cellMappingMethods.addAll(//from  www  . j ava 2  s  . c  o  m
            ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withAnnotation(TableCellMappings.class)));

    Multimap<Method, Optional<TableCellMapping>> tableCellMappingByMethod = FluentIterable
            .from(cellMappingMethods).index(new Function<Method, Optional<TableCellMapping>>() {
                @Override
                public Optional<TableCellMapping> apply(@Nonnull Method method) {
                    checkNotNull(method);
                    return Optional.fromNullable(method.getAnnotation(TableCellMapping.class))
                            .or(getFirstTableCellMapping(method.getAnnotation(TableCellMappings.class), group));
                }
            }).inverse();

    tableCellMappingByMethod = filterEntries(tableCellMappingByMethod,
            new Predicate<Entry<Method, Optional<TableCellMapping>>>() {
                @Override
                public boolean apply(@Nonnull Entry<Method, Optional<TableCellMapping>> entry) {
                    checkNotNull(entry);
                    return entry.getValue().isPresent()
                            && any(Lists.newArrayList(entry.getValue().get().groups()), assignableTo(group));
                }
            });

    Multimap<Method, TableCellMapping> methodByTableCellMapping = transformValues(tableCellMappingByMethod,
            new Function<Optional<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Optional<TableCellMapping> tcmOptional) {
                    checkNotNull(tcmOptional);
                    return tcmOptional.get();
                }
            });

    return Maps.transformValues(methodByTableCellMapping.asMap(),
            new Function<Collection<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Collection<TableCellMapping> tcms) {
                    checkNotNull(tcms);
                    return Iterables.getFirst(tcms, null);
                }
            });
}

From source file:com.eucalyptus.blockstorage.VolumeUpdateEventListener.java

static void update() {
    final Multimap<String, Volume> partitionVolumeMap = HashMultimap.create();
    try (final TransactionResource tx = Entities.readOnlyDistinctTransactionFor(Volume.class)) {
        for (final Volume v : Entities.query(Volume.named(null, null))) {
            partitionVolumeMap.put(v.getPartition().intern(), v);
        }/*from  w w w.j  a v  a 2s.  c om*/
    } catch (final Exception ex) {
        Logs.extreme().error(ex, ex);
    }
    final Map<String, Collection<Volume>> volumesByPartition = ImmutableMap.copyOf(partitionVolumeMap.asMap());
    final Map<String, Supplier<Map<String, StorageVolume>>> scVolumesByPartition = Maps.newHashMap();
    for (final String partition : volumesByPartition.keySet()) {
        scVolumesByPartition.put(partition, updateVolumesInPartition(partition));//TODO:GRZE: restoring volume state
    }
    for (final String partition : volumesByPartition.keySet()) {
        try {
            final Map<String, StorageVolume> idStorageVolumeMap = scVolumesByPartition.get(partition).get();
            for (final Volume v : volumesByPartition.get(partition)) {
                try {
                    final StorageVolume storageVolume = idStorageVolumeMap.get(v.getDisplayName());
                    if (pendingUpdates.putIfAbsent(v.getDisplayName(), System.currentTimeMillis()) == null)
                        try {
                            Threads.enqueue(Storage.class, VolumeUpdateEventListener.class,
                                    (Runtime.getRuntime().availableProcessors() * 2) + 1, new Callable<Void>() {
                                        @Override
                                        public Void call() throws Exception {
                                            try {
                                                volumeStateUpdate(v, storageVolume);
                                            } finally {
                                                pendingUpdates.remove(v.getDisplayName());
                                            }
                                            return null;
                                        }
                                    });
                        } catch (Throwable t) {
                            pendingUpdates.remove(v.getDisplayName());
                            throw Throwables.propagate(t);
                        }
                } catch (final Exception ex) {
                    LOG.error(ex);
                    Logs.extreme().error(ex, ex);
                }
            }
        } catch (final Exception ex) {
            LOG.error(ex);
            Logs.extreme().error(ex, ex);
        }
    }
}

From source file:com.yammer.collections.azure.AzureTestUtil.java

@SafeVarargs
private static void setupRowQueries(String tableName, AzureTableRequestFactory azureTableRequestFactoryMock,
        AzureTableCloudClient azureTableCloudClientMock, Table.Cell<Bytes, Bytes, Bytes>... cells) {

    TableQuery<AzureEntity> emptyQueryMock = mock(TableQuery.class);
    when(azureTableRequestFactoryMock.selectAllForRow(anyString(), anyString())).thenReturn(emptyQueryMock);
    when(azureTableRequestFactoryMock.containsValueForRowQuery(anyString(), anyString(), anyString()))
            .thenReturn(emptyQueryMock);
    when(azureTableCloudClientMock.execute(emptyQueryMock)).thenReturn(Collections.<AzureEntity>emptyList());

    Multimap<Bytes, Table.Cell<Bytes, Bytes, Bytes>> rowCellMap = HashMultimap.create();
    for (Table.Cell<Bytes, Bytes, Bytes> cell : cells) {
        rowCellMap.put(cell.getRowKey(), cell);

        TableQuery<AzureEntity> rowValueQueryMock = mock(TableQuery.class);
        when(azureTableRequestFactoryMock.containsValueForRowQuery(tableName, encode(cell.getRowKey()),
                encode(cell.getValue()))).thenReturn(rowValueQueryMock);
        when(azureTableCloudClientMock.execute(rowValueQueryMock))
                .thenReturn(Collections.singletonList(ENCODE_CELL.apply(cell)));
    }/*from w w  w.  ja  v a2 s .  co  m*/

    for (Map.Entry<Bytes, Collection<Table.Cell<Bytes, Bytes, Bytes>>> entry : rowCellMap.asMap().entrySet()) {
        // row query
        TableQuery<AzureEntity> rowQueryMock = mock(TableQuery.class);
        when(azureTableRequestFactoryMock.selectAllForRow(tableName, encode(entry.getKey())))
                .thenReturn(rowQueryMock);
        when(azureTableCloudClientMock.execute(rowQueryMock))
                .thenReturn(Collections2.transform(entry.getValue(), ENCODE_CELL));
    }
}

From source file:eu.itesla_project.modules.simulation.ImpactAnalysisTool.java

private static void writeCsv(Multimap<String, SecurityIndex> securityIndexesPerContingency, Path outputCsvFile)
        throws IOException {
    Objects.requireNonNull(outputCsvFile);
    try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
        writer.write("Contingency");
        for (SecurityIndexType securityIndexType : SecurityIndexType.values()) {
            writer.write(CSV_SEPARATOR);
            writer.write(securityIndexType.toString());
        }/*from  w w  w.ja v  a2  s . c  o  m*/
        writer.newLine();

        for (Map.Entry<String, Collection<SecurityIndex>> entry : securityIndexesPerContingency.asMap()
                .entrySet()) {
            String contingencyId = entry.getKey();
            writer.write(contingencyId);
            for (String str : toRow(entry.getValue())) {
                writer.write(CSV_SEPARATOR);
                writer.write(str);
            }
            writer.newLine();
        }
    }
}

From source file:com.yammer.collections.azure.AzureTestUtil.java

@SafeVarargs
private static void setupColumnQueries(String tableName, AzureTableRequestFactory azureTableRequestFactoryMock,
        AzureTableCloudClient azureTableCloudClientMock, Table.Cell<Bytes, Bytes, Bytes>... cells) {

    TableQuery<AzureEntity> emptyQueryMock = mock(TableQuery.class);
    when(azureTableRequestFactoryMock.selectAllForColumn(anyString(), anyString())).thenReturn(emptyQueryMock);
    when(azureTableRequestFactoryMock.containsValueForColumnQuery(anyString(), anyString(), anyString()))
            .thenReturn(emptyQueryMock);
    when(azureTableCloudClientMock.execute(emptyQueryMock)).thenReturn(Collections.<AzureEntity>emptyList());

    Multimap<Bytes, Table.Cell<Bytes, Bytes, Bytes>> columnCellMap = HashMultimap.create();
    for (Table.Cell<Bytes, Bytes, Bytes> cell : cells) {
        columnCellMap.put(cell.getColumnKey(), cell);

        TableQuery<AzureEntity> columnValueQueryMock = mock(TableQuery.class);
        when(azureTableRequestFactoryMock.containsValueForColumnQuery(tableName, encode(cell.getColumnKey()),
                encode(cell.getValue()))).thenReturn(columnValueQueryMock);
        when(azureTableCloudClientMock.execute(columnValueQueryMock))
                .thenReturn(Collections.singletonList(ENCODE_CELL.apply(cell)));
    }/*from  w ww. j  av a  2  s.com*/

    for (Map.Entry<Bytes, Collection<Table.Cell<Bytes, Bytes, Bytes>>> entry : columnCellMap.asMap()
            .entrySet()) {
        // row query
        TableQuery<AzureEntity> columnQueryMock = mock(TableQuery.class);
        when(azureTableRequestFactoryMock.selectAllForColumn(tableName, encode(entry.getKey())))
                .thenReturn(columnQueryMock);
        when(azureTableCloudClientMock.execute(columnQueryMock))
                .thenReturn(Collections2.transform(entry.getValue(), ENCODE_CELL));
    }
}

From source file:dollar.api.DollarStatic.java

/**
 * Map to json./*from  ww  w  . j  a  v  a  2  s  .  com*/
 *
 * @param map the map
 * @return the json object
 */
@NotNull
public static JsonObject mapToJson(@NotNull Multimap<String, String> map) {
    JsonObject jsonObject = new JsonObject();
    for (Map.Entry<String, Collection<String>> entry : map.asMap().entrySet()) {
        jsonObject.putString(entry.getKey(), entry.getValue().iterator().next());
    }
    return jsonObject;
}

From source file:org.apache.beam.sdk.io.FileSystems.java

@VisibleForTesting
static Map<String, FileSystem> verifySchemesAreUnique(PipelineOptions options,
        Set<FileSystemRegistrar> registrars) {
    Multimap<String, FileSystem> fileSystemsBySchemes = TreeMultimap.create(Ordering.<String>natural(),
            Ordering.arbitrary());/*  w  w  w.j a v  a 2  s . com*/

    for (FileSystemRegistrar registrar : registrars) {
        for (FileSystem fileSystem : registrar.fromOptions(options)) {
            fileSystemsBySchemes.put(fileSystem.getScheme(), fileSystem);
        }
    }
    for (Entry<String, Collection<FileSystem>> entry : fileSystemsBySchemes.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            String conflictingFileSystems = Joiner.on(", ")
                    .join(FluentIterable.from(entry.getValue()).transform(new Function<FileSystem, String>() {
                        @Override
                        public String apply(@Nonnull FileSystem input) {
                            return input.getClass().getName();
                        }
                    }).toSortedList(Ordering.<String>natural()));
            throw new IllegalStateException(String.format("Scheme: [%s] has conflicting filesystems: [%s]",
                    entry.getKey(), conflictingFileSystems));
        }
    }

    ImmutableMap.Builder<String, FileSystem> schemeToFileSystem = ImmutableMap.builder();
    for (Entry<String, FileSystem> entry : fileSystemsBySchemes.entries()) {
        schemeToFileSystem.put(entry.getKey(), entry.getValue());
    }
    return schemeToFileSystem.build();
}

From source file:org.apache.beam.runners.core.construction.graph.OutputDeduplicator.java

/**
 * Ensure that no {@link PCollection} output by any of the {@code stages} or {@code
 * unfusedTransforms} is produced by more than one of those stages or transforms.
 *
 * <p>For each {@link PCollection} output by multiple stages and/or transforms, each producer is
 * rewritten to produce a partial {@link PCollection}, which are then flattened together via an
 * introduced Flatten node which produces the original output.
 *///  w  w  w.  j  a v  a2  s .  c o m
static DeduplicationResult ensureSingleProducer(QueryablePipeline pipeline, Collection<ExecutableStage> stages,
        Collection<PTransformNode> unfusedTransforms) {
    RunnerApi.Components.Builder unzippedComponents = pipeline.getComponents().toBuilder();

    Multimap<PCollectionNode, StageOrTransform> pcollectionProducers = getProducers(pipeline, stages,
            unfusedTransforms);
    Multimap<StageOrTransform, PCollectionNode> requiresNewOutput = HashMultimap.create();
    // Create a synthetic PCollection for each of these nodes. The transforms in the runner
    // portion of the graph that creates them should be replaced in the result components. The
    // ExecutableStage must also be rewritten to have updated outputs and transforms.
    for (Map.Entry<PCollectionNode, Collection<StageOrTransform>> collectionProducer : pcollectionProducers
            .asMap().entrySet()) {
        if (collectionProducer.getValue().size() > 1) {
            for (StageOrTransform producer : collectionProducer.getValue()) {
                requiresNewOutput.put(producer, collectionProducer.getKey());
            }
        }
    }

    Map<ExecutableStage, ExecutableStage> updatedStages = new LinkedHashMap<>();
    Map<String, PTransformNode> updatedTransforms = new LinkedHashMap<>();
    Multimap<String, PCollectionNode> originalToPartial = HashMultimap.create();
    for (Map.Entry<StageOrTransform, Collection<PCollectionNode>> deduplicationTargets : requiresNewOutput
            .asMap().entrySet()) {
        if (deduplicationTargets.getKey().getStage() != null) {
            StageDeduplication deduplication = deduplicatePCollections(deduplicationTargets.getKey().getStage(),
                    deduplicationTargets.getValue(), unzippedComponents::containsPcollections);
            for (Entry<String, PCollectionNode> originalToPartialReplacement : deduplication
                    .getOriginalToPartialPCollections().entrySet()) {
                originalToPartial.put(originalToPartialReplacement.getKey(),
                        originalToPartialReplacement.getValue());
                unzippedComponents.putPcollections(originalToPartialReplacement.getValue().getId(),
                        originalToPartialReplacement.getValue().getPCollection());
            }
            updatedStages.put(deduplicationTargets.getKey().getStage(), deduplication.getUpdatedStage());
        } else if (deduplicationTargets.getKey().getTransform() != null) {
            PTransformDeduplication deduplication = deduplicatePCollections(
                    deduplicationTargets.getKey().getTransform(), deduplicationTargets.getValue(),
                    unzippedComponents::containsPcollections);
            for (Entry<String, PCollectionNode> originalToPartialReplacement : deduplication
                    .getOriginalToPartialPCollections().entrySet()) {
                originalToPartial.put(originalToPartialReplacement.getKey(),
                        originalToPartialReplacement.getValue());
                unzippedComponents.putPcollections(originalToPartialReplacement.getValue().getId(),
                        originalToPartialReplacement.getValue().getPCollection());
            }
            updatedTransforms.put(deduplicationTargets.getKey().getTransform().getId(),
                    deduplication.getUpdatedTransform());
        } else {
            throw new IllegalStateException(
                    String.format("%s with no %s or %s", StageOrTransform.class.getSimpleName(),
                            ExecutableStage.class.getSimpleName(), PTransformNode.class.getSimpleName()));
        }
    }

    Set<PTransformNode> introducedFlattens = new LinkedHashSet<>();
    for (Map.Entry<String, Collection<PCollectionNode>> partialFlattenTargets : originalToPartial.asMap()
            .entrySet()) {
        String flattenId = SyntheticComponents.uniqueId("unzipped_flatten",
                unzippedComponents::containsTransforms);
        PTransform flattenPartialPCollections = createFlattenOfPartials(flattenId,
                partialFlattenTargets.getKey(), partialFlattenTargets.getValue());
        unzippedComponents.putTransforms(flattenId, flattenPartialPCollections);
        introducedFlattens.add(PipelineNode.pTransform(flattenId, flattenPartialPCollections));
    }

    Components components = unzippedComponents.build();
    return DeduplicationResult.of(components, introducedFlattens, updatedStages, updatedTransforms);
}