Example usage for com.google.common.collect ListMultimap get

List of usage examples for com.google.common.collect ListMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect ListMultimap get.

Prototype

@Override
List<V> get(@Nullable K key);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.rackspacecloud.blueflood.io.astyanax.AstyanaxReader.java

/**
 * Get data points for multiple {@link Locator}, for the specified {@link Range} and
 * {@link Granularity}.//from w  w  w.  j  a v  a 2s  . c o  m
 *
 * This method is eventually called from all the output handlers for query requests.
 *
 * @param locators
 * @param range
 * @param gran
 * @return
 */
public Map<Locator, MetricData> getDatapointsForRange(List<Locator> locators, Range range, Granularity gran) {
    ListMultimap<ColumnFamily, Locator> locatorsByCF = ArrayListMultimap.create();
    Map<Locator, MetricData> results = new HashMap<Locator, MetricData>();
    for (Locator locator : locators) {
        try {
            RollupType rollupType = RollupType
                    .fromString(metaCache.get(locator, MetricMetadata.ROLLUP_TYPE.name().toLowerCase()));

            ColumnFamily cf = CassandraModel.getColumnFamily(rollupType, gran);
            List<Locator> locs = locatorsByCF.get(cf);
            locs.add(locator);
        } catch (Exception e) {
            // pass for now. need metric to figure this stuff out.
            log.error(String.format("error getting datapoints for locator %s, range %s, granularity %s",
                    locator, range.toString(), gran.toString()), e);
        }
    }

    for (ColumnFamily CF : locatorsByCF.keySet()) {
        List<Locator> locs = locatorsByCF.get(CF);
        results.putAll(getNumericDataForRangeLocatorList(range, gran, CF, locs));
    }

    return results;
}

From source file:org.sonar.server.qualityprofile.QProfileExporters.java

private RulesProfile wrap(QualityProfileDto profile) {
    try (DbSession dbSession = dbClient.openSession(false)) {
        RulesProfile target = new RulesProfile(profile.getName(), profile.getLanguage());
        List<ActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfileKey(dbSession,
                profile.getKey());//ww  w  .j av  a  2 s  .c om
        List<ActiveRuleParamDto> activeRuleParamDtos = dbClient.activeRuleDao()
                .selectParamsByActiveRuleIds(dbSession, Lists.transform(activeRuleDtos, ActiveRuleDto::getId));
        ListMultimap<Integer, ActiveRuleParamDto> activeRuleParamsByActiveRuleId = FluentIterable
                .from(activeRuleParamDtos).index(ActiveRuleParamDto::getActiveRuleId);

        for (ActiveRuleDto activeRule : activeRuleDtos) {
            // TODO all rules should be loaded by using one query with all active rule keys as parameter
            Rule rule = ruleFinder.findByKey(activeRule.getKey().ruleKey());
            org.sonar.api.rules.ActiveRule wrappedActiveRule = target.activateRule(rule,
                    RulePriority.valueOf(activeRule.getSeverityString()));
            List<ActiveRuleParamDto> paramDtos = activeRuleParamsByActiveRuleId.get(activeRule.getId());
            for (ActiveRuleParamDto activeRuleParamDto : paramDtos) {
                wrappedActiveRule.setParameter(activeRuleParamDto.getKey(), activeRuleParamDto.getValue());
            }
        }
        return target;
    }
}

From source file:fr.inria.eventcloud.webservices.EventCloudsManagementServiceImpl.java

private boolean destroyWebServices(String streamUrl, ListMultimap<String, String> wsEndpointUrls) {
    boolean result = true;

    for (String wsEndpointUrl : ImmutableList.copyOf(wsEndpointUrls.get(streamUrl))) {
        result &= this.destroyWebService(wsEndpointUrl, wsEndpointUrls);
    }//from ww w .java 2 s  . co m

    return result;
}

From source file:org.apache.beam.sdk.options.PipelineOptionsFactory.java

/**
 * Determines whether the generic {@code --help} was requested or help was
 * requested for a specific class and invokes the appropriate
 * {@link PipelineOptionsFactory#printHelp(PrintStream)} and
 * {@link PipelineOptionsFactory#printHelp(PrintStream, Class)} variant.
 * Prints to the specified {@link PrintStream}, and exits if requested.
 *
 * <p>Visible for testing.//  w w w  .j  a  v a 2 s  .c o m
 * {@code printStream} and {@code exit} used for testing.
 */
@SuppressWarnings("unchecked")
static boolean printHelpUsageAndExitIfNeeded(ListMultimap<String, String> options, PrintStream printStream,
        boolean exit) {
    if (options.containsKey("help")) {
        final String helpOption = Iterables.getOnlyElement(options.get("help"));

        // Print the generic help if only --help was specified.
        if (Boolean.TRUE.toString().equals(helpOption)) {
            printHelp(printStream);
            if (exit) {
                System.exit(0);
            } else {
                return true;
            }
        }

        // Otherwise attempt to print the specific help option.
        try {
            Class<?> klass = Class.forName(helpOption);
            if (!PipelineOptions.class.isAssignableFrom(klass)) {
                throw new ClassNotFoundException("PipelineOptions of type " + klass + " not found.");
            }
            printHelp(printStream, (Class<? extends PipelineOptions>) klass);
        } catch (ClassNotFoundException e) {
            // If we didn't find an exact match, look for any that match the class name.
            Iterable<Class<? extends PipelineOptions>> matches = Iterables.filter(getRegisteredOptions(),
                    new Predicate<Class<? extends PipelineOptions>>() {
                        @Override
                        public boolean apply(@Nonnull Class<? extends PipelineOptions> input) {
                            if (helpOption.contains(".")) {
                                return input.getName().endsWith(helpOption);
                            } else {
                                return input.getSimpleName().equals(helpOption);
                            }
                        }
                    });
            try {
                printHelp(printStream, Iterables.getOnlyElement(matches));
            } catch (NoSuchElementException exception) {
                printStream.format("Unable to find option %s.%n", helpOption);
                printHelp(printStream);
            } catch (IllegalArgumentException exception) {
                printStream.format("Multiple matches found for %s: %s.%n", helpOption,
                        Iterables.transform(matches, ReflectHelpers.CLASS_NAME));
                printHelp(printStream);
            }
        }
        if (exit) {
            System.exit(0);
        } else {
            return true;
        }
    }
    return false;
}

From source file:fr.ens.biologie.genomique.eoulsan.core.workflow.StepOutputPort.java

/**
 * Get Existing Data.//from  ww  w.  ja  va2s  .c  o m
 * @return a set with Data elements
 */
public Set<Data> getExistingData() {

    // List the existing files generated by the port and sort it
    final List<DataFile> files = Lists.newArrayList(getExistingOutputFiles());

    // Do nothing if there is no file
    if (files.isEmpty()) {
        return Collections.emptySet();
    }

    // Create the result object
    final Set<Data> result = new HashSet<>();

    // Sort the file
    Collections.sort(files);

    final ListMultimap<String, DataFile> map = ArrayListMultimap.create();

    for (DataFile file : files) {

        // Parse the fields of the filename
        FileNaming fields = FileNaming.parse(file);

        map.put(fields.getDataName() + "\t" + fields.getPart(), file);
    }

    // Get the design for metadata of the data
    final Design design = this.step.getAbstractWorkflow().getDesign();

    // Fill the result
    for (String key : map.keySet()) {

        // Set the data name
        final DataElement data = new DataElement(getFormat(), map.get(key), design);
        data.setName(key.substring(0, key.indexOf('\t')));

        result.add(data);
    }

    return result;
}

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

private void expandInboundRelationships(List<SnomedConcept> results, final Set<String> conceptIds) {
    if (!expand().containsKey(SnomedConcept.Expand.INBOUND_RELATIONSHIPS)) {
        return;/*from www.java  2s.c  o m*/
    }

    final Options expandOptions = expand().get(SnomedConcept.Expand.INBOUND_RELATIONSHIPS, Options.class);

    final int relationshipSearchLimit = getLimit(expandOptions);

    final SnomedRelationships inboundRelationships = SnomedRequests.prepareSearchRelationship()
            .setLimit(relationshipSearchLimit)
            .filterByType(
                    expandOptions.containsKey("typeId") ? expandOptions.getCollection("typeId", String.class)
                            : null)
            .filterBySource(expandOptions.containsKey("sourceId")
                    ? expandOptions.getCollection("sourceId", String.class)
                    : null)
            .filterByActive(expandOptions.containsKey("active") ? expandOptions.getBoolean("active") : null)
            .filterByCharacteristicType(expandOptions.containsKey("characteristicType")
                    ? expandOptions.getString("characteristicType")
                    : null)
            .filterByDestination(conceptIds).setExpand(expandOptions.get("expand", Options.class))
            .setLocales(locales()).build().execute(context());

    final ListMultimap<String, SnomedRelationship> inboundRelationshipsByConceptId = Multimaps
            .index(inboundRelationships, inboundRelationship -> inboundRelationship.getDestinationId());

    for (SnomedConcept concept : results) {
        final List<SnomedRelationship> conceptInboundRelationships = inboundRelationshipsByConceptId
                .get(concept.getId());
        concept.setInboundRelationships(new SnomedRelationships(conceptInboundRelationships, null, null,
                conceptInboundRelationships.size(), conceptInboundRelationships.size()));
    }
}

From source file:msi.gama.lang.gaml.resource.GamlResource.java

private ModelDescription buildModelDescription(final LinkedHashMultimap<String, GamlResource> resources) {

    // Initializations
    GAML.getExpressionFactory().resetParser();
    final ModelFactory f = GAML.getModelFactory();
    final String modelPath = GamlResourceServices.getModelPathOf(this);
    final String projectPath = GamlResourceServices.getProjectPathOf(this);
    final boolean isEdited = GamlResourceServices.isEdited(this);
    final ValidationContext context = GamlResourceServices.getValidationContext(this);
    // If the resources imported are null, no need to go through their
    // validation
    if (resources == null) {
        final List<ISyntacticElement> self = Collections.singletonList(getSyntacticContents());
        return f.createModelDescription(projectPath, modelPath, self, context, isEdited, null);
    }/*from   w w w .  j  av  a2s .  c o m*/
    // If there are no micro-models
    final Set<String> keySet = resources.keySet();
    if (keySet.size() == 1 && keySet.contains(null)) {
        final Iterable<ISyntacticElement> selfAndImports = Iterables.concat(
                Collections.singleton(getSyntacticContents()),
                Multimaps.transformValues(resources, TO_SYNTACTIC_CONTENTS).get(null));
        return f.createModelDescription(projectPath, modelPath, selfAndImports, context, isEdited, null);
    }
    final ListMultimap<String, ISyntacticElement> models = ArrayListMultimap.create();
    models.put(null, getSyntacticContents());
    models.putAll(Multimaps.transformValues(resources, TO_SYNTACTIC_CONTENTS));
    final List<ISyntacticElement> ownImports = models.removeAll(null);
    final Map<String, ModelDescription> compiledMicroModels = new THashMap<String, ModelDescription>();
    for (final String aliasName : models.keySet()) {
        final ModelDescription mic = GAML.getModelFactory().createModelDescription(projectPath, modelPath,
                models.get(aliasName), context, isEdited, null);
        mic.setAlias(aliasName);
        compiledMicroModels.put(aliasName, mic);
    }
    return f.createModelDescription(projectPath, modelPath, ownImports, context, isEdited, compiledMicroModels);
}

From source file:de.metas.ui.web.handlingunits.HUEditorRowsPagedLoadingIterator.java

private Iterator<HUEditorRow> getNextPageIterator() {
    // the result; part of it will be taken from cache, the, rest will be loaded
    final HUEditorRow[] rows = new HUEditorRow[bufferSize];

    // HUEditorRowIds that we don't have in the cache and that therefore need to be loaded
    final Map<HUEditorRowId, Integer> rowIdToLoad2index = new HashMap<>();

    // Get from cache as much as possible
    {/*  ww  w.  j  ava  2  s  . c  o  m*/
        int idx = 0;
        while (rowIds.hasNext() && idx < bufferSize) {
            final HUEditorRowId rowId = rowIds.next();

            final HUEditorRowId topLevelRowId = rowId.toTopLevelRowId();
            final HUEditorRow topLevelRow = cache.get(topLevelRowId.toDocumentId());

            if (topLevelRow == null) {
                // to be loaded
                rowIdToLoad2index.put(rowId, idx);
            } else {
                if (rowId.equals(topLevelRowId)) {
                    rows[idx] = topLevelRow;
                } else {
                    rows[idx] = topLevelRow.getIncludedRowById(rowId.toDocumentId()).orElse(null);
                }
            }

            idx++;
        }
    }

    //
    // Load missing rows (which were not found in cache)
    if (!rowIdToLoad2index.isEmpty()) {
        final ListMultimap<HUEditorRowId, HUEditorRowId> topLevelRowId2rowIds = rowIdToLoad2index.keySet()
                .stream().map(rowId -> GuavaCollectors.entry(rowId.toTopLevelRowId(), rowId))
                .collect(GuavaCollectors.toImmutableListMultimap());

        final Set<HuId> topLevelHUIds = topLevelRowId2rowIds.keys().stream().map(HUEditorRowId::getTopLevelHUId)
                .collect(ImmutableSet.toImmutableSet());

        huEditorRepo.retrieveHUEditorRows(topLevelHUIds, filter).forEach(topLevelRow -> {
            final HUEditorRowId topLevelRowId = topLevelRow.getHURowId();
            for (final HUEditorRowId includedRowId : topLevelRowId2rowIds.get(topLevelRowId)) {
                final Integer idx = rowIdToLoad2index.remove(includedRowId);
                if (idx == null) {
                    // wtf?! shall not happen
                    continue;
                }

                if (topLevelRowId.equals(includedRowId)) {
                    rows[idx] = topLevelRow;
                    cache.put(topLevelRow.getId(), topLevelRow);
                } else {
                    rows[idx] = topLevelRow.getIncludedRowById(includedRowId.toDocumentId()).orElse(null);
                }
            }
        });
    }

    return Stream.of(rows).filter(Predicates.notNull()) // IMPORTANT: just to make sure we won't stream some empty gaps (e.g. missing rows because HU was not a top level one)
            .filter(filterPredicate).iterator();
}

From source file:com.android.ide.common.res2.DataMerger.java

/**
 * Post merge clean up./*from ww w  . jav a  2  s.c  o m*/
 *
 * - Remove the removed items.
 * - Clear the state of all the items (this allow newly overridden items to lose their
 *   WRITTEN state)
 * - Set the items that are part of the new merge to be WRITTEN to allow the next merge to
 *   be incremental.
 */
private void postMergeCleanUp() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // remove all removed items, and copy the rest in the full map while resetting their state.
    for (S dataSet : mDataSets) {
        ListMultimap<String, I> map = dataSet.getDataMap();

        List<String> keys = Lists.newArrayList(map.keySet());
        for (String key : keys) {
            List<I> list = map.get(key);
            for (int i = 0; i < list.size();) {
                I item = list.get(i);
                if (item.isRemoved()) {
                    list.remove(i);
                } else {
                    //noinspection unchecked
                    itemMap.put(key, (I) item.resetStatus());
                    i++;
                }
            }
        }
    }

    // for the last items (the one that have been written into the consumer), set their
    // state to WRITTEN
    for (String key : itemMap.keySet()) {
        List<I> itemList = itemMap.get(key);
        itemList.get(itemList.size() - 1).resetStatusToWritten();
    }
}

From source file:org.geogit.api.plumbing.diff.DiffTreeVisitor.java

/**
 * Compares a bucket tree (i.e. its size is greater than {@link RevTree#NORMALIZED_SIZE_LIMIT}
 * and hence has been split into buckets) at the left side of the comparison, and a the
 * {@link RevTree#children() children} nodes of a leaf tree at the right side of the comparison.
 * <p>// w  w w .  j  av a2s .  com
 * This happens when the left tree is much larger than the right tree
 * <p>
 * This traversal is symmetric to {@link #traverseLeafBucket} so be careful that any change made
 * to this method shall have a matching change at {@link #traverseLeafBucket}
 * 
 * @precondition {@code left.buckets().isPresent()}
 */
private void traverseBucketLeaf(final Consumer consumer, final RevTree left, final Iterator<Node> right,
        final int bucketDepth) {

    checkState(left.buckets().isPresent());
    final SortedMap<Integer, Bucket> leftBuckets = left.buckets().get();
    final ListMultimap<Integer, Node> nodesByBucket = splitNodesToBucketsAtDepth(right, bucketDepth);

    final SortedSet<Integer> bucketIndexes = Sets
            .newTreeSet(Sets.union(leftBuckets.keySet(), nodesByBucket.keySet()));

    for (Integer bucketIndex : bucketIndexes) {
        Bucket leftBucket = leftBuckets.get(bucketIndex);
        List<Node> rightNodes = nodesByBucket.get(bucketIndex);// never returns null, but empty
        if (null == leftBucket) {
            traverseLeafLeaf(consumer, Iterators.<Node>emptyIterator(), rightNodes.iterator());
        } else if (rightNodes.isEmpty()) {
            if (consumer.bucket(bucketIndex, bucketDepth, leftBucket, null)) {
                traverseBucketBucket(consumer, leftBucket, null, bucketDepth);
            }
        } else {
            RevTree leftTree = leftSource.getTree(leftBucket.id());
            if (leftTree.buckets().isPresent()) {
                traverseBucketLeaf(consumer, leftTree, rightNodes.iterator(), bucketDepth + 1);
            } else {
                traverseLeafLeaf(consumer, leftTree.children(), rightNodes.iterator());
            }
        }
    }
}