Java 类com.google.common.collect.ImmutableSetMultimap 实例源码

项目:Reer    文件:ModelMapNodeInitializerExtractionStrategy.java   
@Override
public Multimap<ModelActionRole, ModelAction> getActions(ModelReference<?> subject, ModelRuleDescriptor descriptor) {
    return ImmutableSetMultimap.<ModelActionRole, ModelAction>builder()
        .put(ModelActionRole.Discover, AddProjectionsAction.of(subject, descriptor,
            ModelMapModelProjection.managed(schema.getType(), schema.getElementType(), ChildNodeInitializerStrategyAccessors.fromPrivateData())
        ))
        .put(ModelActionRole.Create, DirectNodeInputUsingModelAction.of(subject, descriptor,
            ModelReference.of(NodeInitializerRegistry.class),
            new BiAction<MutableModelNode, NodeInitializerRegistry>() {
                @Override
                public void execute(MutableModelNode modelNode, NodeInitializerRegistry nodeInitializerRegistry) {
                    ChildNodeInitializerStrategy<E> childStrategy = NodeBackedModelMap.createUsingRegistry(nodeInitializerRegistry);
                    modelNode.setPrivateData(ChildNodeInitializerStrategy.class, childStrategy);
                }
            }
        ))
        .build();
}
项目:Reer    文件:ModelSetNodeInitializerExtractionStrategy.java   
@Override
public Multimap<ModelActionRole, ModelAction> getActions(ModelReference<?> subject, ModelRuleDescriptor descriptor) {
    return ImmutableSetMultimap.<ModelActionRole, ModelAction>builder()
        .put(ModelActionRole.Discover, AddProjectionsAction.of(subject, descriptor,
            TypedModelProjection.of(
                ModelTypes.modelSet(schema.getElementType()),
                new ModelSetModelViewFactory<E>(schema.getElementType())
            )
        ))
        .put(ModelActionRole.Create, DirectNodeInputUsingModelAction.of(subject, descriptor,
            ModelReference.of(NodeInitializerRegistry.class),
            new BiAction<MutableModelNode, NodeInitializerRegistry>() {
                @Override
                public void execute(MutableModelNode modelNode, NodeInitializerRegistry nodeInitializerRegistry) {
                    ChildNodeInitializerStrategy<T> childStrategy = new ManagedChildNodeCreatorStrategy<T>(nodeInitializerRegistry);
                    modelNode.setPrivateData(ChildNodeInitializerStrategy.class, childStrategy);
                }
            }
        ))
        .build();
}
项目:Reer    文件:NodeBackedModelMap.java   
public static <T> ChildNodeInitializerStrategy<T> createUsingParentNode(final Transformer<? extends NamedEntityInstantiator<T>, ? super MutableModelNode> instantiatorTransform) {
    return new ChildNodeInitializerStrategy<T>() {
        @Override
        public <S extends T> NodeInitializer initializer(final ModelType<S> type, Spec<ModelType<?>> constraints) {
            return new NodeInitializer() {
                @Override
                public Multimap<ModelActionRole, ModelAction> getActions(ModelReference<?> subject, ModelRuleDescriptor descriptor) {
                    return ImmutableSetMultimap.<ModelActionRole, ModelAction>builder()
                        .put(ModelActionRole.Discover, AddProjectionsAction.of(subject, descriptor,
                            UnmanagedModelProjection.of(type),
                            new ModelElementProjection(type)
                        ))
                        .put(ModelActionRole.Create, DirectNodeNoInputsModelAction.of(subject, descriptor, new Action<MutableModelNode>() {
                            @Override
                            public void execute(MutableModelNode modelNode) {
                                NamedEntityInstantiator<T> instantiator = instantiatorTransform.transform(modelNode.getParent());
                                S item = instantiator.create(modelNode.getPath().getName(), type.getConcreteClass());
                                modelNode.setPrivateData(type, item);
                            }
                        }))
                        .build();
                }
            };
        }
    };
}
项目:GitHub    文件:CaseStructure.java   
private static SetMultimap<String, ValueType> buildSubtyping(List<ValueType> implementationTypes) {
  ImmutableSetMultimap.Builder<String, ValueType> builder = ImmutableSetMultimap.builder();

  for (ValueType type : implementationTypes) {
    String abstractValueTypeName = type.typeAbstract().toString();
    builder.put(abstractValueTypeName, type);

    for (String className : type.getExtendedClassesNames()) {
      if (!className.equals(abstractValueTypeName)) {
        builder.put(className, type);
      }
    }
    for (String interfaceName : type.getImplementedInterfacesNames()) {
      if (!interfaceName.equals(abstractValueTypeName)) {
        builder.put(interfaceName, type);
      }
    }
  }

  return builder.build();
}
项目:tac-kbp-eal    文件:EventArgScoringAlignment.java   
private EventArgScoringAlignment(final Symbol docID,
    final ArgumentOutput argumentOutput,
    final AnswerKey answerKey,
    final Iterable<EquivClassType> truePositiveECs,
    final Iterable<EquivClassType> falsePositiveECs,
    final Iterable<EquivClassType> falseNegativeECs,
    final Iterable<EquivClassType> unassessed,
    final Multimap<EquivClassType, AssessedResponse> ecsToAnswerKey,
    final Multimap<EquivClassType, Response> ecsToSystem) {
  this.docID = checkNotNull(docID);
  this.argumentOutput = checkNotNull(argumentOutput);
  this.answerKey = checkNotNull(answerKey);
  this.truePositiveECs = ImmutableSet.copyOf(truePositiveECs);
  this.falsePositiveECs = ImmutableSet.copyOf(falsePositiveECs);
  this.falseNegativeECs = ImmutableSet.copyOf(falseNegativeECs);
  this.unassessed = ImmutableSet.copyOf(unassessed);
  this.ecsToAnswerKey = ImmutableSetMultimap.copyOf(ecsToAnswerKey);
  this.ecsToSystem = ImmutableSetMultimap.copyOf(ecsToSystem);
}
项目:tac-kbp-eal    文件:QueryResponseFromERE.java   
/**
 * Collapses DocEventFrameReferences into their PJs for the particular document at hand.
 */
public static ImmutableSetMultimap<Symbol, QueryResponse2016> response2016CollapsedJustifications(
    final Iterable<Map.Entry<Symbol, Collection<DocEventFrameReference>>> matchesByDocument,
    final SystemOutputStore2016 store, final CorpusQuery2016 query)
    throws IOException {
  final ImmutableSetMultimap.Builder<Symbol, QueryResponse2016> retB =
      ImmutableSetMultimap.builder();
  for (final Map.Entry<Symbol, Collection<DocEventFrameReference>> matchEntry : matchesByDocument) {
    final Symbol docID = matchEntry.getKey();
    final Collection<DocEventFrameReference> eventFramesMatchedInDoc =
        matchEntry.getValue();
    final DocumentSystemOutput2015 docSystemOutput = store.read(docID);
    final ImmutableSet<CharOffsetSpan> matchJustifications =
        matchJustificationsForDoc(eventFramesMatchedInDoc, docSystemOutput);

    final QueryResponse2016 queryResponse2016 =
        QueryResponse2016.builder().docID(docID).queryID(query.id())
            .addAllPredicateJustifications(matchJustifications).build();
    retB.put(docID, queryResponse2016);
  }
  return retB.build();
}
项目:tac-kbp-eal    文件:ScoreKBPAgainstERE.java   
public void finish() throws IOException {
  outputDir.mkdirs();

  final ImmutableSetMultimap<String, String> mentionAlignmentFailures =
      mentionAlignmentFailuresB.build();
  log.info("Of {} system responses, got {} mention alignment failures",
      numResponses.size(), mentionAlignmentFailures.size());

  final File serializedFailuresFile = new File(outputDir, "alignmentFailures.json");
  final JacksonSerializer serializer =
      JacksonSerializer.builder().forJson().prettyOutput().build();
  serializer.serializeTo(mentionAlignmentFailures, Files.asByteSink(serializedFailuresFile));

  final File failuresCount = new File(outputDir, "alignmentFailures.count.txt");
  serializer.serializeTo(mentionAlignmentFailures.size(), Files.asByteSink(failuresCount));
}
项目:CustomWorldGen    文件:ForgeChunkManager.java   
public static Iterator<Chunk> getPersistentChunksIterableFor(final World world, Iterator<Chunk> chunkIterator)
{
    final ImmutableSetMultimap<ChunkPos, Ticket> persistentChunksFor = getPersistentChunksFor(world);
    final ImmutableSet.Builder<Chunk> builder = ImmutableSet.builder();
    world.theProfiler.startSection("forcedChunkLoading");
    builder.addAll(Iterators.transform(persistentChunksFor.keys().iterator(), new Function<ChunkPos, Chunk>() {
        @Nullable
        @Override
        public Chunk apply(@Nullable ChunkPos input)
        {
            return world.getChunkFromChunkCoords(input.chunkXPos, input.chunkZPos);
        }
    }));
    world.theProfiler.endStartSection("regularChunkLoading");
    builder.addAll(chunkIterator);
    world.theProfiler.endSection();
    return builder.build().iterator();
}
项目:metasfresh-webui-api    文件:DocumentFieldDependencyMap.java   
private ImmutableMap<DependencyType, Multimap<String, String>> getType2Name2DependenciesMap()
{
    final ImmutableMap.Builder<DependencyType, Multimap<String, String>> builder = ImmutableMap.builder();
    for (final Entry<DependencyType, ImmutableSetMultimap.Builder<String, String>> e : type2name2dependencies.entrySet())
    {
        final DependencyType dependencyType = e.getKey();
        final Multimap<String, String> name2dependencies = e.getValue().build();
        if (name2dependencies.isEmpty())
        {
            continue;
        }

        builder.put(dependencyType, name2dependencies);
    }

    return builder.build();
}
项目:metasfresh-webui-api    文件:DocumentFieldDependencyMap.java   
public Builder add(final String fieldName, final Collection<String> dependsOnFieldNames, final DependencyType dependencyType)
{
    if (dependsOnFieldNames == null || dependsOnFieldNames.isEmpty())
    {
        return this;
    }

    ImmutableSetMultimap.Builder<String, String> fieldName2dependsOnFieldNames = type2name2dependencies.get(dependencyType);
    if (fieldName2dependsOnFieldNames == null)
    {
        fieldName2dependsOnFieldNames = ImmutableSetMultimap.builder();
        type2name2dependencies.put(dependencyType, fieldName2dependsOnFieldNames);
    }

    for (final String dependsOnFieldName : dependsOnFieldNames)
    {
        fieldName2dependsOnFieldNames.put(dependsOnFieldName, fieldName);
    }

    return this;
}
项目:metasfresh-webui-api    文件:DocumentFieldDependencyMap.java   
public Builder add(final DocumentFieldDependencyMap dependencies)
{
    if (dependencies == null || dependencies == EMPTY)
    {
        return this;
    }

    for (final Map.Entry<DependencyType, Multimap<String, String>> l1 : dependencies.type2name2dependencies.entrySet())
    {
        final DependencyType dependencyType = l1.getKey();

        ImmutableSetMultimap.Builder<String, String> name2dependencies = type2name2dependencies.get(dependencyType);
        if (name2dependencies == null)
        {
            name2dependencies = ImmutableSetMultimap.builder();
            type2name2dependencies.put(dependencyType, name2dependencies);
        }

        name2dependencies.putAll(l1.getValue());
    }

    return this;
}
项目:zipkin    文件:IndexerTest.java   
/**
 * Most partition keys will not clash, as they are delimited differently. For example, spans index
 * partition keys are delimited with dots, and annotations with colons.
 *
 * <p>This tests an edge case, where a delimiter exists in a service name.
 */
@Test
public void entriesThatIncreaseGap_treatsIndexesSeparately() throws Exception {
  ConcurrentMap<PartitionKeyToTraceId, Pair<Long>> sharedState = Maps.newConcurrentMap();

  // If indexes were not implemented properly, the span index app.foo would be mistaken as the
  // first service index
  ImmutableSetMultimap<PartitionKeyToTraceId, Long> parsed =
      ImmutableSetMultimap.<PartitionKeyToTraceId, Long>builder()
          .put(new PartitionKeyToTraceId(SERVICE_NAME_INDEX, "app.foo", 20), 1467676800050L)
          .put(new PartitionKeyToTraceId(SERVICE_NAME_INDEX, "app.foo", 20), 1467676800110L)
          .put(new PartitionKeyToTraceId(SERVICE_NAME_INDEX, "app.foo", 20), 1467676800125L)
          .put(new PartitionKeyToTraceId(SERVICE_SPAN_NAME_INDEX, "app.foo", 20), 1467676800000L)
          .build();

  assertThat(Indexer.entriesThatIncreaseGap(sharedState, parsed)).hasSameEntriesAs(
      ImmutableSetMultimap.<PartitionKeyToTraceId, Long>builder()
          .put(new PartitionKeyToTraceId(SERVICE_NAME_INDEX, "app.foo", 20), 1467676800050L)
          .put(new PartitionKeyToTraceId(SERVICE_NAME_INDEX, "app.foo", 20), 1467676800125L)
          .put(new PartitionKeyToTraceId(SERVICE_SPAN_NAME_INDEX, "app.foo", 20), 1467676800000L)
          .build()
  );
}
项目:grakn    文件:AtomicTest.java   
@Test //missing role is ambiguous without cardinality constraints
public void testRoleInference_RoleHierarchyInvolved() {
    GraknTx graph = unificationTestSet.tx();
    String relationString = "{($p, subRole2: $gc) isa binary;}";
    String relationString2 = "{(subRole1: $gp, $p) isa binary;}";
    RelationshipAtom relation = (RelationshipAtom) ReasonerQueries.atomic(conjunction(relationString, graph), graph).getAtom();
    RelationshipAtom relation2 = (RelationshipAtom) ReasonerQueries.atomic(conjunction(relationString2, graph), graph).getAtom();
    Multimap<Role, Var> roleMap = roleSetMap(relation.getRoleVarMap());
    Multimap<Role, Var> roleMap2 = roleSetMap(relation2.getRoleVarMap());

    ImmutableSetMultimap<Role, Var> correctRoleMap = ImmutableSetMultimap.of(
            graph.getRole("role"), var("p"),
            graph.getRole("subRole2"), var("gc"));
    ImmutableSetMultimap<Role, Var> correctRoleMap2 = ImmutableSetMultimap.of(
            graph.getRole("role"), var("p"),
            graph.getRole("subRole1"), var("gp"));
    assertEquals(correctRoleMap, roleMap);
    assertEquals(correctRoleMap2, roleMap2);
}
项目:graylog-plugin-pipeline-processor    文件:PipelineInterpreter.java   
private ImmutableSet<Pipeline> selectPipelines(InterpreterListener interpreterListener,
                                               Set<Tuple2<String, String>> processingBlacklist,
                                               Message message,
                                               Set<String> initialStreamIds,
                                               ImmutableSetMultimap<String, Pipeline> streamConnection) {
    final String msgId = message.getId();

    // if a message-stream combination has already been processed (is in the set), skip that execution
    final Set<String> streamsIds = initialStreamIds.stream()
            .filter(streamId -> !processingBlacklist.contains(tuple(msgId, streamId)))
            .filter(streamConnection::containsKey)
            .collect(Collectors.toSet());
    final ImmutableSet<Pipeline> pipelinesToRun = streamsIds.stream()
            .flatMap(streamId -> streamConnection.get(streamId).stream())
            .collect(ImmutableSet.toImmutableSet());
    interpreterListener.processStreams(message, pipelinesToRun, streamsIds);
    log.debug("[{}] running pipelines {} for streams {}", msgId, pipelinesToRun, streamsIds);
    return pipelinesToRun;
}
项目:graylog-plugin-pipeline-processor    文件:PipelineInterpreter.java   
@AssistedInject
public State(@Assisted ImmutableMap<String, Pipeline> currentPipelines,
             @Assisted ImmutableSetMultimap<String, Pipeline> streamPipelineConnections,
             MetricRegistry metricRegistry,
             @Named("processbuffer_processors") int processorCount,
             @Named("cached_stageiterators") boolean cachedIterators) {
    this.currentPipelines = currentPipelines;
    this.streamPipelineConnections = streamPipelineConnections;
    this.cachedIterators = cachedIterators;

    cache = CacheBuilder.newBuilder()
            .concurrencyLevel(processorCount)
            .recordStats()
            .build(new CacheLoader<Set<Pipeline>, StageIterator.Configuration>() {
                @Override
                public StageIterator.Configuration load(@Nonnull Set<Pipeline> pipelines) throws Exception {
                    return new StageIterator.Configuration(pipelines);
                }
            });

    // we have to remove the metrics, because otherwise we leak references to the cache (and the register call with throw)
    metricRegistry.removeMatching((name, metric) -> name.startsWith(name(PipelineInterpreter.class, "stage-cache")));
    MetricUtils.safelyRegisterAll(metricRegistry, new CacheStatsSet(name(PipelineInterpreter.class, "stage-cache"), cache));
}
项目:AChunkLoader    文件:CommandStats.java   
public int getChunkCount(ImmutableSetMultimap<ChunkPos, ForgeChunkManager.Ticket> tickets)
{
    int count = 0;
    for(ChunkPos key : tickets.asMap().keySet())
    {
        Collection<ForgeChunkManager.Ticket> ticketList = tickets.asMap().get(key);
        for(ForgeChunkManager.Ticket ticket : ticketList)
        {
            if(Reference.MOD_ID.equals(ticket.getModId()))
            {
                count++;
            }
        }
    }
    return count;
}
项目:nomulus    文件:PendingDepositChecker.java   
/** Returns multimap of TLDs to all RDE and BRDA deposits that need to happen. */
public ImmutableSetMultimap<String, PendingDeposit>
    getTldsAndWatermarksPendingDepositForRdeAndBrda() {
  return new ImmutableSetMultimap.Builder<String, PendingDeposit>()
      .putAll(
          getTldsAndWatermarksPendingDeposit(
              RdeMode.FULL,
              CursorType.RDE_STAGING,
              rdeInterval,
              clock.nowUtc().withTimeAtStartOfDay()))
      .putAll(
          getTldsAndWatermarksPendingDeposit(
              RdeMode.THIN,
              CursorType.BRDA,
              brdaInterval,
              advanceToDayOfWeek(clock.nowUtc().withTimeAtStartOfDay(), brdaDayOfWeek)))
      .build();
}
项目:nomulus    文件:PendingDepositChecker.java   
private ImmutableSetMultimap<String, PendingDeposit> getTldsAndWatermarksPendingDeposit(
    RdeMode mode, CursorType cursorType, Duration interval, DateTime startingPoint) {
  checkArgument(interval.isLongerThan(Duration.ZERO));
  ImmutableSetMultimap.Builder<String, PendingDeposit> builder =
      new ImmutableSetMultimap.Builder<>();
  DateTime now = clock.nowUtc();
  for (String tld : Registries.getTldsOfType(TldType.REAL)) {
    Registry registry = Registry.get(tld);
    if (!registry.getEscrowEnabled()) {
      continue;
    }
    // Avoid creating a transaction unless absolutely necessary.
    Cursor cursor = ofy().load().key(Cursor.createKey(cursorType, registry)).now();
    DateTime cursorValue = (cursor != null ? cursor.getCursorTime() : startingPoint);
    if (isBeforeOrAt(cursorValue, now)) {
      DateTime watermark = (cursor != null
          ? cursor.getCursorTime()
          : transactionallyInitializeCursor(registry, cursorType, startingPoint));
      if (isBeforeOrAt(watermark, now)) {
        builder.put(tld, PendingDeposit.create(tld, watermark, mode, cursorType, interval));
      }
    }
  }
  return builder.build();
}
项目:intellij    文件:AbstractPyImportResolverStrategy.java   
@SuppressWarnings("unused")
private PySourcesIndex buildSourcesIndex(Project project, BlazeProjectData projectData) {
  ImmutableSetMultimap.Builder<String, QualifiedName> shortNames = ImmutableSetMultimap.builder();
  Map<QualifiedName, PsiElementProvider> map = new HashMap<>();
  ArtifactLocationDecoder decoder = projectData.artifactLocationDecoder;
  for (TargetIdeInfo target : projectData.targetMap.targets()) {
    for (ArtifactLocation source : getPySources(target)) {
      QualifiedName name = toImportString(source);
      if (name == null || name.getLastComponent() == null) {
        continue;
      }
      shortNames.put(name.getLastComponent(), name);
      PsiElementProvider psiProvider = psiProviderFromArtifact(decoder, source);
      map.put(name, psiProvider);
      if (includeParentDirectory(source)) {
        map.put(name.removeTail(1), PsiElementProvider.getParent(psiProvider));
      }
    }
  }
  return new PySourcesIndex(shortNames.build(), ImmutableMap.copyOf(map));
}
项目:FreeBuilder    文件:SetMultimapProperty.java   
@Override
public Optional<SetMultimapProperty> create(Config config) {
  DeclaredType type = maybeDeclared(config.getProperty().getType()).orNull();
  if (type == null || !erasesToAnyOf(type, SetMultimap.class, ImmutableSetMultimap.class)) {
    return Optional.absent();
  }

  TypeMirror keyType = upperBound(config.getElements(), type.getTypeArguments().get(0));
  TypeMirror valueType = upperBound(config.getElements(), type.getTypeArguments().get(1));
  Optional<TypeMirror> unboxedKeyType = maybeUnbox(keyType, config.getTypes());
  Optional<TypeMirror> unboxedValueType = maybeUnbox(valueType, config.getTypes());
  boolean overridesPutMethod =
      hasPutMethodOverride(config, unboxedKeyType.or(keyType), unboxedValueType.or(valueType));
  return Optional.of(new SetMultimapProperty(
      config.getMetadata(),
      config.getProperty(),
      overridesPutMethod,
      keyType,
      unboxedKeyType,
      valueType,
      unboxedValueType));
}
项目:ChunkyPeripherals    文件:CRModListForgePersistentChunks.java   
@Override
public void processCommand(ICommandSender icommandsender, String[] astring)
{
    ChunkyPeripherals.logger.info("World: " + icommandsender.getEntityWorld().getWorldInfo().getWorldName());
    ImmutableSetMultimap<ChunkCoordIntPair, Ticket> l = ForgeChunkManager.getPersistentChunksFor(icommandsender.getEntityWorld());
    Collection<Ticket> c =l.values();
    Iterator<Ticket> i = c.iterator();
    int count=0;
    while (i.hasNext())
    {
        Ticket t = i.next();
        ChunkyPeripherals.logger.info("ticket #"+(count++)+" ="+t);
        ImmutableSet<ChunkCoordIntPair> sc = t.getChunkList();
        ImmutableList<ChunkCoordIntPair> lc = sc.asList();
        Iterator<ChunkCoordIntPair> ic = lc.iterator();
        while(ic.hasNext())
        {
            ChunkCoordIntPair ccoord = ic.next();
            ChunkyPeripherals.logger.info("chunk " + ccoord.toString() + "("+ ccoord.chunkXPos*16+" ; "+ ccoord.chunkZPos*16 + ")");
        }
    }
}
项目:presto    文件:EqualityInference.java   
private EqualityInference(Iterable<Set<Expression>> equalityGroups)
{
    ImmutableSetMultimap.Builder<Expression, Expression> setBuilder = ImmutableSetMultimap.builder();
    for (Set<Expression> equalityGroup : equalityGroups) {
        if (!equalityGroup.isEmpty()) {
            setBuilder.putAll(CANONICAL_ORDERING.min(equalityGroup), equalityGroup);
        }
    }
    equalitySets = setBuilder.build();

    ImmutableMap.Builder<Expression, Expression> mapBuilder = ImmutableMap.builder();
    for (Map.Entry<Expression, Expression> entry : equalitySets.entries()) {
        Expression canonical = entry.getKey();
        Expression expression = entry.getValue();
        mapBuilder.put(expression, canonical);
    }
    canonicalMap = mapBuilder.build();
}
项目:presto    文件:LocalExecutionPlanner.java   
/**
 * This method creates a mapping from each index source lookup symbol (directly applied to the index)
 * to the corresponding probe key Input
 */
private SetMultimap<Symbol, Integer> mapIndexSourceLookupSymbolToProbeKeyInput(IndexJoinNode node, Map<Symbol, Integer> probeKeyLayout)
{
    Set<Symbol> indexJoinSymbols = node.getCriteria().stream()
            .map(IndexJoinNode.EquiJoinClause::getIndex)
            .collect(toImmutableSet());

    // Trace the index join symbols to the index source lookup symbols
    // Map: Index join symbol => Index source lookup symbol
    Map<Symbol, Symbol> indexKeyTrace = IndexJoinOptimizer.IndexKeyTracer.trace(node.getIndexSource(), indexJoinSymbols);

    // Map the index join symbols to the probe key Input
    Multimap<Symbol, Integer> indexToProbeKeyInput = HashMultimap.create();
    for (IndexJoinNode.EquiJoinClause clause : node.getCriteria()) {
        indexToProbeKeyInput.put(clause.getIndex(), probeKeyLayout.get(clause.getProbe()));
    }

    // Create the mapping from index source look up symbol to probe key Input
    ImmutableSetMultimap.Builder<Symbol, Integer> builder = ImmutableSetMultimap.builder();
    for (Map.Entry<Symbol, Symbol> entry : indexKeyTrace.entrySet()) {
        Symbol indexJoinSymbol = entry.getKey();
        Symbol indexLookupSymbol = entry.getValue();
        builder.putAll(indexLookupSymbol, indexToProbeKeyInput.get(indexJoinSymbol));
    }
    return builder.build();
}
项目:gerrit    文件:GitOverHttpServlet.java   
@Override
public ReceivePack create(HttpServletRequest req, Repository db)
    throws ServiceNotAuthorizedException {
  final ProjectState state = (ProjectState) req.getAttribute(ATT_STATE);

  if (!(userProvider.get().isIdentifiedUser())) {
    // Anonymous users are not permitted to push.
    throw new ServiceNotAuthorizedException();
  }

  AsyncReceiveCommits arc =
      factory.create(
          state, userProvider.get().asIdentifiedUser(), db, null, ImmutableSetMultimap.of());
  ReceivePack rp = arc.getReceivePack();
  req.setAttribute(ATT_ARC, arc);
  return rp;
}
项目:gerrit    文件:Emails.java   
/**
 * Returns the accounts for the given emails.
 *
 * @see #getAccountFor(String)
 */
public ImmutableSetMultimap<String, Account.Id> getAccountsFor(String... emails)
    throws IOException, OrmException {
  ImmutableSetMultimap.Builder<String, Account.Id> builder = ImmutableSetMultimap.builder();
  externalIds
      .byEmails(emails)
      .entries()
      .stream()
      .forEach(e -> builder.put(e.getKey(), e.getValue().accountId()));
  queryProvider
      .get()
      .byPreferredEmail(emails)
      .entries()
      .stream()
      .forEach(e -> builder.put(e.getKey(), e.getValue().getAccount().getId()));
  return builder.build();
}
项目:gerrit    文件:StalenessCheckerTest.java   
@Test
public void parseStates() {
  assertInvalidState(null);
  assertInvalidState("");
  assertInvalidState("project1:refs/heads/foo");
  assertInvalidState("project1:refs/heads/foo:notasha");
  assertInvalidState("project1:refs/heads/foo:");

  assertThat(
          StalenessChecker.parseStates(
              byteArrays(
                  P1 + ":refs/heads/foo:" + SHA1,
                  P1 + ":refs/heads/bar:" + SHA2,
                  P2 + ":refs/heads/baz:" + SHA1)))
      .isEqualTo(
          ImmutableSetMultimap.of(
              P1, RefState.create("refs/heads/foo", SHA1),
              P1, RefState.create("refs/heads/bar", SHA2),
              P2, RefState.create("refs/heads/baz", SHA1)));
}
项目:killbill-simple-tax-plugin    文件:TaxCodeService.java   
/**
 * Find tax codes that apply to the items of a given invoice, looking for
 * custom fields named {@value #TAX_CODES_FIELD_NAME} that can be attached
 * to these items.
 *
 * @param invoice
 *            An invoice in which existing tax codes are to be found.
 * @return The existing tax codes, grouped by the identifiers of their
 *         related invoice items. Never {@code null}, and guaranteed not
 *         having any {@code null} values.
 * @throws NullPointerException
 *             when {@code invoice} is {@code null}.
 */
@Nonnull
public SetMultimap<UUID, TaxCode> findExistingTaxCodes(Invoice invoice) {
    Set<CustomField> taxFields = taxFieldsOfInvoices.get(invoice.getId());
    // Note: taxFields is not null, by Multimap contract

    ImmutableSetMultimap.Builder<UUID, TaxCode> taxCodesOfInvoiceItems = ImmutableSetMultimap.builder();
    for (CustomField taxField : taxFields) {
        if (!TAX_CODES_FIELD_NAME.equals(taxField.getFieldName())) {
            continue;
        }
        String taxCodesCSV = taxField.getFieldValue();
        if (taxCodesCSV == null) {
            continue;
        }
        UUID invoiceItemId = taxField.getObjectId();
        Set<TaxCode> taxCodes = cfg.findTaxCodes(taxCodesCSV, "from custom field '" + TAX_CODES_FIELD_NAME
                + "' of invoice item [" + invoiceItemId + "]");
        taxCodesOfInvoiceItems.putAll(invoiceItemId, taxCodes);
    }
    return taxCodesOfInvoiceItems.build();
}
项目:killbill-simple-tax-plugin    文件:TestTaxCodeService.java   
@Test(groups = "fast")
public void shouldResolveProperlyAndIgnoreCornerCases() {
    // Given
    withTaxes(taxCfg()//
            .putAll("plan1-product", asList(taxA))//
            .putAll("plan3-product", asList(taxA, taxB, taxC)));

    // When
    SetMultimap<UUID, TaxCode> taxCodesOfInvoiceItems = taxCodeService.resolveTaxCodesFromConfig(invoice);

    // Then
    assertEquals(taxCodesOfInvoiceItems, ImmutableSetMultimap.<UUID, TaxCode> builder()//
            .putAll(item1.get().getId(), asList(taxA))//
            .putAll(item3.get().getId(), asList(taxA, taxB, taxC))//
            .build());
}
项目:killbill-simple-tax-plugin    文件:TestTaxCodeService.java   
@Test(groups = "fast")
public void shouldTrustTheGivenTaxFieldsOfInvoices() {
    // Given
    UUID otherItemId = uuidOtherThan(item0.get().getId(), item1.get().getId(), item3.get().getId());
    SetMultimap<UUID, CustomField> taxFieldsOfInvoices = ImmutableSetMultimap.<UUID, CustomField> builder()//
            // Tax codes on other item that does not exists in invoice
            .put(invoice.getId(), new CustomFieldBuilder()//
                    .withObjectType(INVOICE_ITEM).withObjectId(otherItemId)//
                    .withFieldName("taxCodes").withFieldValue("taxC")//
                    .build())//
            .build();
    TaxCodeService taxCodeService = new TaxCodeService(catalog, cfg, taxFieldsOfInvoices);

    // When
    SetMultimap<UUID, TaxCode> taxCodesOfInvoiceItems = taxCodeService.findExistingTaxCodes(invoice);

    // Then
    assertEquals(taxCodesOfInvoiceItems, ImmutableSetMultimap.<UUID, TaxCode> builder()//
            .put(otherItemId, taxC)//
            .build());
}
项目:MOE    文件:MetadataScrubber.java   
/**
 * A utility method that is useful for stripping a list of words from all the fields of the
 * RevisionMetadata.
 *
 * @param rm the RevisionMetadata to scrub
 * @param words the list of words to replace
 * @param replacement the String to replace the target words with
 * @param wordAlone true if the words to match must surrounded by word boundaries
 * @return a copy representing the RevisionMetadata resulting from the scrub
 */
public static RevisionMetadata stripFromAllFields(
    RevisionMetadata rm, List<String> words, String replacement, boolean wordAlone) {

  String newId = rm.id();
  String newAuthor = rm.author();
  String newDescription = rm.description();
  ListMultimap<String, String> newFields = LinkedListMultimap.create(rm.fields());
  for (String word : words) {
    String regex = (wordAlone) ? ("(?i)(\\b)" + word + "(\\b)") : ("(?i)" + word);
    newId = newId.replaceAll(regex, replacement);
    newAuthor = newAuthor.replaceAll(regex, replacement);
    newDescription = newDescription.replaceAll(regex, replacement);
    for (Entry<String, String> entry : newFields.entries()) {
      entry.setValue(entry.getValue().replaceAll(regex, replacement));
    }
  }
  return rm.toBuilder()
      .id(newId)
      .author(newAuthor)
      .description(newDescription)
      .replacingFieldsWith(ImmutableSetMultimap.copyOf(newFields))
      .build();
}
项目:bue-common-open    文件:BrokenDownLinearScoreAggregator.java   
@Override
public void observeSample(
    final Collection<Map<String, FMeasureCounts>> observationSummaries) {
  final ImmutableSetMultimap.Builder<String, FMeasureCounts> allCountsB =
      ImmutableSetMultimap.builder();

  for (final Map<String, FMeasureCounts> observationSummary : observationSummaries) {
    allCountsB.putAll(Multimaps.forMap(observationSummary));
  }

  for (final Map.Entry<String, Collection<FMeasureCounts>> breakdownKeySamples : allCountsB.build().asMap().entrySet()) {
    double scoreAggregator = 0.0;
    double normalizer = 0.0;

    for (final FMeasureCounts fMeasureCounts : breakdownKeySamples.getValue()) {
      // per-doc scores clipped at 0
      scoreAggregator += Math.max(fMeasureCounts.truePositives()
          - alpha()*fMeasureCounts.falsePositives(), 0);
      normalizer += fMeasureCounts.truePositives() + fMeasureCounts.falseNegatives();
    }
    double normalizedScore = 100.0*scoreAggregator/normalizer;
    linearScoresB.put(breakdownKeySamples.getKey(), normalizedScore);
  }
}
项目:bue-common-open    文件:BrokenDownFMeasureAggregator.java   
@Override
public void observeSample(
    final Collection<Map<String, FMeasureCounts>> observationSummaries) {
  final ImmutableSetMultimap.Builder<String, FMeasureCounts> allCountsB =
      ImmutableSetMultimap.builder();

  for (final Map<String, FMeasureCounts> observationSummary : observationSummaries) {
    allCountsB.putAll(Multimaps.forMap(observationSummary));
  }

  for (final Map.Entry<String, Collection<FMeasureCounts>> aggregate : allCountsB.build().asMap().entrySet()) {
    final FMeasureCounts fMeasureInfo = FMeasureCounts.combineToMicroFMeasure(aggregate.getValue());
    f1sB.put(aggregate.getKey(), fMeasureInfo.F1());
    precisionsB.put(aggregate.getKey(), fMeasureInfo.precision());
    recallsB.put(aggregate.getKey(), fMeasureInfo.recall());
  }
}
项目:bue-common-open    文件:AnnotationWrapperModule.java   
@Value.Check
protected void check() {
  checkArgument(!wrappedModuleParam().isEmpty());

  // check for wrapped module bindings which will collide when we strip their own annotations
  // and replace them with the wrapping annotation
  final ImmutableSetMultimap.Builder<TypeLiteral<?>, Key<?>> externalTypesToInternalTypesB =
      ImmutableSetMultimap.builder();
  for (final Key<?> key : simpleTypesToWrap()) {
    externalTypesToInternalTypesB.put(key.getTypeLiteral(), key);
  }
  final ImmutableSetMultimap<TypeLiteral<?>, Key<?>> externalTypesToInternalTypes =
      externalTypesToInternalTypesB.build();

  for (final Map.Entry<TypeLiteral<?>, Collection<Key<?>>> e : externalTypesToInternalTypes
      .asMap().entrySet()) {
    if (e.getValue().size() > 1) {
      throw new IllegalArgumentException("You are exposing multiple inner module bindings which"
          + " will have the same external binding key: " + e.getValue());
    }
  }
}
项目:yangtools    文件:Bug8307Test.java   
@Test
public void testDeviationsSupportedInSomeModules() throws Exception {
    final SetMultimap<QNameModule, QNameModule> modulesWithSupportedDeviations =
            ImmutableSetMultimap.<QNameModule, QNameModule>builder()
            .put(foo, bar)
            .put(foo, baz)
            .put(bar, baz)
            .build();

    final SchemaContext schemaContext = RFC7950Reactors.defaultReactor().newBuild()
            .addSources(FOO_MODULE, BAR_MODULE, BAZ_MODULE, FOOBAR_MODULE)
            .setModulesWithSupportedDeviations(modulesWithSupportedDeviations)
            .buildEffective();
    assertNotNull(schemaContext);

    assertNull(SchemaContextUtil.findDataSchemaNode(schemaContext, SchemaPath.create(true, myFooContA)));
    assertNull(SchemaContextUtil.findDataSchemaNode(schemaContext, SchemaPath.create(true, myFooContB)));
    assertNotNull(SchemaContextUtil.findDataSchemaNode(schemaContext, SchemaPath.create(true, myFooContC)));
    assertNull(SchemaContextUtil.findDataSchemaNode(schemaContext, SchemaPath.create(true, myBarContA)));
    assertNotNull(SchemaContextUtil.findDataSchemaNode(schemaContext, SchemaPath.create(true, myBarContB)));
}
项目:bazel    文件:ImmutableMultimapSerializer.java   
@Override
public ImmutableMultimap<Object, Object> read(
    Kryo kryo, Input input, Class<ImmutableMultimap<Object, Object>> type) {
  ImmutableMultimap.Builder<Object, Object> builder;
  if (type.equals(ImmutableListMultimap.class)) {
    builder = ImmutableListMultimap.builder();
  } else if (type.equals(ImmutableSetMultimap.class)) {
    builder = ImmutableSetMultimap.builder();
  } else {
    builder = ImmutableMultimap.builder();
  }

  @SuppressWarnings("unchecked")
  Map<Object, Collection<Object>> map = kryo.readObject(input, ImmutableMap.class);
  for (Map.Entry<Object, Collection<Object>> entry : map.entrySet()) {
    builder.putAll(entry.getKey(), entry.getValue());
  }
  return builder.build();
}
项目:bazel    文件:ZipFilterAction.java   
@VisibleForTesting
static Multimap<String, Long> getEntriesToOmit(
    Collection<Path> filterZips, Collection<String> filterTypes) throws IOException {
  // Escape filter types to prevent regex abuse
  Set<String> escapedFilterTypes = new HashSet<>();
  for (String filterType : filterTypes) {
    escapedFilterTypes.add(Pattern.quote(filterType));
  }
  // Match any string that ends with any of the filter file types
  String filterRegex = String.format(".*(%s)$", Joiner.on("|").join(escapedFilterTypes));

  ImmutableSetMultimap.Builder<String, Long> entriesToOmit = ImmutableSetMultimap.builder();
  for (Path filterZip : filterZips) {
    try (ZipReader zip = new ZipReader(filterZip.toFile())) {
      for (ZipFileEntry entry : zip.entries()) {
        if (filterTypes.isEmpty() || entry.getName().matches(filterRegex)) {
          entriesToOmit.put(entry.getName(), entry.getCrc());
        }
      }
    }
  }
  return entriesToOmit.build();
}
项目:buck-cutom    文件:DefaultJavaLibraryTest.java   
@Test
public void testEmptySuggestBuildFunction() {
  BuildRuleResolver ruleResolver = new BuildRuleResolver();

  BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone");
  JavaLibrary libraryOne = (JavaLibrary) JavaLibraryBuilder
      .createBuilder(libraryOneTarget)
      .addSrc(Paths.get("java/src/com/libone/bar.java"))
      .build();

  BuildContext context = createSuggestContext(ruleResolver,
      BuildDependencies.FIRST_ORDER_ONLY);

  ImmutableSetMultimap<JavaLibrary, Path> classpathEntries =
      libraryOne.getTransitiveClasspathEntries();

  assertEquals(
      Optional.<JavacInMemoryStep.SuggestBuildRules>absent(),
      ((DefaultJavaLibrary) libraryOne).createSuggestBuildFunction(
          context,
          classpathEntries,
          classpathEntries,
          createJarResolver(/* classToSymbols */ImmutableMap.<Path, String>of())));

  EasyMock.verify(context);
}
项目:buck-cutom    文件:Classpaths.java   
/**
 * Include the classpath entries from all JavaLibraryRules that have a direct line of lineage
 * to this rule through other JavaLibraryRules. For example, in the following dependency graph:
 *
 *        A
 *      /   \
 *     B     C
 *    / \   / \
 *    D E   F G
 *
 * If all of the nodes correspond to BuildRules that implement JavaLibraryRule except for
 * B (suppose B is a Genrule), then A's classpath will include C, F, and G, but not D and E.
 * This is because D and E are used to generate B, but do not contribute .class files to things
 * that depend on B. However, if C depended on E as well as F and G, then E would be included in
 * A's classpath.
 */
public static ImmutableSetMultimap<JavaLibrary, Path> getClasspathEntries(
    Set<BuildRule> deps) {
  final ImmutableSetMultimap.Builder<JavaLibrary, Path> classpathEntries =
      ImmutableSetMultimap.builder();
  for (BuildRule dep : deps) {
    JavaLibrary library = null;
    if (dep instanceof JavaLibrary) {
      library = (JavaLibrary) dep;
    }

    if (library != null) {
      classpathEntries.putAll(library.getTransitiveClasspathEntries());
    }
  }
  return classpathEntries.build();
}
项目:cm_ext    文件:ReferenceValidatorImpl.java   
@Override
public void beforeNode(Object obj, DescriptorPath path) {
  Preconditions.checkState(!refsStack.containsKey(path));

  SetMultimap<ReferenceType, String> refs = getRelatedPaths(obj, path);
  SetMultimap<ReferenceType, String> newRefs = LinkedHashMultimap.create();

  for (Map.Entry<ReferenceType, Collection<String>> entry : refs.asMap().entrySet()) {
    ReferenceType type = entry.getKey();
    for (String reference : entry.getValue()) {
      if (!allowedRefs.containsEntry(type, reference)) {
        newRefs.put(type, reference);
        allowedRefs.put(type, reference);
      }
    }
  }

  // consolidate into the singleton if it's empty
  newRefs = newRefs.size() == 0 ? ImmutableSetMultimap
      .<ReferenceType, String> of() : newRefs;
  refsStack.put(path, newRefs);

  callReferenceConstraints(obj, path);
}
项目:Reer    文件:IvyDependencyMetadata.java   
public IvyDependencyMetadata(ModuleVersionSelector requested, String dynamicConstraintVersion, boolean force, boolean changing, boolean transitive, Multimap<String, String> confMappings, List<Artifact> artifacts, List<Exclude> excludes) {
    super(requested, artifacts);
    this.dynamicConstraintVersion = dynamicConstraintVersion;
    this.force = force;
    this.changing = changing;
    this.transitive = transitive;
    this.confs = ImmutableSetMultimap.copyOf(confMappings);
    this.excludes = ImmutableList.copyOf(excludes);
}