类com.google.common.collect.Multimaps源码实例Demo

下面列出了怎么用com.google.common.collect.Multimaps的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: buck   文件: CxxPreprocessables.java
/** Builds a {@link CxxPreprocessorInput} for a rule. */
public static CxxPreprocessorInput getCxxPreprocessorInput(
    BuildTarget buildTarget,
    ActionGraphBuilder graphBuilder,
    boolean hasHeaderSymlinkTree,
    CxxPlatform platform,
    HeaderVisibility headerVisibility,
    IncludeType includeType,
    Multimap<CxxSource.Type, String> exportedPreprocessorFlags,
    Iterable<FrameworkPath> frameworks) {
  CxxPreprocessorInput.Builder builder = CxxPreprocessorInput.builder();
  if (hasHeaderSymlinkTree) {
    addHeaderSymlinkTree(
        builder, buildTarget, graphBuilder, platform, headerVisibility, includeType);
  }
  return builder
      .putAllPreprocessorFlags(
          ImmutableListMultimap.copyOf(
              Multimaps.transformValues(exportedPreprocessorFlags, StringArg::of)))
      .addAllFrameworks(frameworks)
      .build();
}
 
源代码2 项目: incubator-pinot   文件: AlertUtils.java
public static Map<Long, Long> makeVectorClock(Collection<MergedAnomalyResultDTO> anomalies) {
  Multimap<Long, MergedAnomalyResultDTO> grouped = Multimaps.index(anomalies, new Function<MergedAnomalyResultDTO, Long>() {
    @Nullable
    @Override
    public Long apply(@Nullable MergedAnomalyResultDTO mergedAnomalyResultDTO) {
      // Return functionId to support alerting of legacy anomalies
      if (mergedAnomalyResultDTO.getDetectionConfigId() == null) {
        return mergedAnomalyResultDTO.getFunctionId();
      }

      return mergedAnomalyResultDTO.getDetectionConfigId();
    }
  });
  Map<Long, Long> detection2max = new HashMap<>();
  for (Map.Entry<Long, Collection<MergedAnomalyResultDTO>> entry : grouped.asMap().entrySet()) {
    detection2max.put(entry.getKey(), getLastTimeStamp(entry.getValue(), -1));
  }
  return detection2max;
}
 
源代码3 项目: presto   文件: ShardCompactionManager.java
private void discoverShards()
{
    log.info("Discovering shards that need compaction...");
    Set<ShardMetadata> allShards = shardManager.getNodeShards(currentNodeIdentifier);
    ListMultimap<Long, ShardMetadata> tableShards = Multimaps.index(allShards, ShardMetadata::getTableId);

    for (Entry<Long, List<ShardMetadata>> entry : Multimaps.asMap(tableShards).entrySet()) {
        long tableId = entry.getKey();
        if (!metadataDao.isCompactionEligible(tableId)) {
            continue;
        }
        List<ShardMetadata> shards = entry.getValue();
        Collection<OrganizationSet> organizationSets = filterAndCreateCompactionSets(tableId, shards);
        log.info("Created %s organization set(s) for table ID %s", organizationSets.size(), tableId);

        for (OrganizationSet set : organizationSets) {
            organizer.enqueue(set);
        }
    }
}
 
源代码4 项目: codebuff   文件: MediaType.java
private String computeToString() {
  StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
  if (!parameters.isEmpty()) {
    builder.append("; ");
    Multimap<String, String> quotedParameters =
        Multimaps.transformValues(
            parameters,
            new Function<String, String>() {
              @Override
              public String apply(String value) {
                return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
              }
            });
    PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
  }
  return builder.toString();
}
 
源代码5 项目: onboard   文件: WebsocketHandler.java
public void sendMessage(String userEmail, String message) {

        Multimap<String, WebSocketSession> syncMap = Multimaps.synchronizedMultimap(userPagesMap);
        Collection<WebSocketSession> mis = syncMap.get(userEmail);
        synchronized (syncMap) {
            if (mis != null) {
                Iterator<WebSocketSession> it = mis.iterator();
                while (it.hasNext()) {
                    WebSocketSession session = it.next();
                    try {
                        session.sendMessage(new TextMessage(message));
                    } catch (Exception e) {
                        logger.info("The WebSocket connection has been closed: " + session.toString());
                    }

                }
            }
        }

    }
 
源代码6 项目: datawave   文件: DefaultQueryPlanner.java
protected Multimap<String,Type<?>> configureIndexedAndNormalizedFields(Multimap<String,Type<?>> fieldToDatatypeMap, Set<String> indexedFields,
                Set<String> reverseIndexedFields, Set<String> normalizedFields, ShardQueryConfiguration config, ASTJexlScript queryTree)
                throws DatawaveQueryException, TableNotFoundException, InstantiationException, IllegalAccessException {
    log.debug("config.getDatatypeFilter() = " + config.getDatatypeFilter());
    log.debug("fieldToDatatypeMap.keySet() is " + fieldToDatatypeMap.keySet());
    
    config.setIndexedFields(indexedFields);
    config.setReverseIndexedFields(reverseIndexedFields);
    
    log.debug("normalizedFields = " + normalizedFields);
    
    config.setQueryFieldsDatatypes(HashMultimap.create(Multimaps.filterKeys(fieldToDatatypeMap, input -> !normalizedFields.contains(input))));
    log.debug("IndexedFields Datatypes: " + config.getQueryFieldsDatatypes());
    
    config.setNormalizedFieldsDatatypes(HashMultimap.create(Multimaps.filterKeys(fieldToDatatypeMap, normalizedFields::contains)));
    log.debug("NormalizedFields Datatypes: " + config.getNormalizedFieldsDatatypes());
    if (log.isTraceEnabled()) {
        log.trace("Normalizers:");
        for (String field : fieldToDatatypeMap.keySet()) {
            log.trace(field + ": " + fieldToDatatypeMap.get(field));
        }
    }
    
    return fieldToDatatypeMap;
    
}
 
源代码7 项目: cloud-opensource-java   文件: DashboardMain.java
/**
 * Partitions {@code symbolProblems} by the JAR file that contains the {@link ClassFile}.
 *
 * <p>For example, {@code classes = result.get(JarX).get(SymbolProblemY)} where {@code classes}
 * are not null means that {@code JarX} has {@code SymbolProblemY} and that {@code JarX} contains
 * {@code classes} which reference {@code SymbolProblemY.getSymbol()}.
 */
private static ImmutableMap<ClassPathEntry, ImmutableSetMultimap<SymbolProblem, String>>
    indexByJar(ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems) {

  ImmutableMap<ClassPathEntry, Collection<Entry<SymbolProblem, ClassFile>>> jarMap =
      Multimaps.index(symbolProblems.entries(), entry -> entry.getValue().getClassPathEntry())
          .asMap();

  return ImmutableMap.copyOf(
      Maps.transformValues(
          jarMap,
          entries ->
              ImmutableSetMultimap.copyOf(
                  Multimaps.transformValues(
                      ImmutableSetMultimap.copyOf(entries), ClassFile::getBinaryName))));
}
 
源代码8 项目: grpc-java   文件: ClientAuthInterceptorTest.java
@Test
public void testCopyCredentialToHeaders() throws IOException {
  ListMultimap<String, String> values = LinkedListMultimap.create();
  values.put("Authorization", "token1");
  values.put("Authorization", "token2");
  values.put("Extra-Authorization", "token3");
  values.put("Extra-Authorization", "token4");
  when(credentials.getRequestMetadata(any(URI.class))).thenReturn(Multimaps.asMap(values));
  ClientCall<String, Integer> interceptedCall =
      interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
  Metadata headers = new Metadata();
  interceptedCall.start(listener, headers);
  assertEquals(listener, call.responseListener);
  assertEquals(headers, call.headers);

  Iterable<String> authorization = headers.getAll(AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token1", "token2"},
      Iterables.toArray(authorization, String.class));
  Iterable<String> extraAuthorization = headers.getAll(EXTRA_AUTHORIZATION);
  Assert.assertArrayEquals(new String[]{"token3", "token4"},
      Iterables.toArray(extraAuthorization, String.class));
}
 
源代码9 项目: dsl-devkit   文件: CheckCfgJavaValidator.java
/**
 * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
 * to a string which is used for checking for duplicates.
 *
 * @param <T>
 *          the generic type
 * @param predicate
 *          the predicate acting as a guard
 * @param function
 *          returns a string for an instance of type T
 * @param elements
 *          the elements to be checked
 * @return the duplicates
 */
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
  List<T> result = Lists.newArrayList();
  Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
    @Override
    public Collection<T> get() {
      return Lists.<T> newArrayList();
    }
  });
  for (final T candidate : elements) {
    if (predicate.apply(candidate)) {
      multiMap.put(function.apply(candidate), candidate);
    }
  }
  for (String elem : multiMap.keySet()) {
    final Collection<T> duplicates = multiMap.get(elem);
    if (duplicates.size() > 1) {
      result.addAll(duplicates);
    }
  }

  return result;
}
 
源代码10 项目: powsybl-core   文件: ImpactAnalysisTool.java
private static Multimap<String, SecurityIndex> runImpactAnalysis(Network network, Set<String> contingencyIds,
                                                                 ComputationManager computationManager, SimulatorFactory simulatorFactory,
                                                                 ContingenciesProvider contingenciesProvider,
                                                                 PrintStream out) throws Exception {
    Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0);
    ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingenciesProvider);
    Map<String, Object> initContext = new HashMap<>();
    SimulationParameters simulationParameters = SimulationParameters.load();
    stabilization.init(simulationParameters, initContext);
    impactAnalysis.init(simulationParameters, initContext);
    out.println("running stabilization simulation...");
    StabilizationResult sr = stabilization.run();
    out.println("stabilization status: " + sr.getStatus());
    out.println("stabilization metrics: " + sr.getMetrics());
    if (sr.getStatus() == StabilizationStatus.COMPLETED) {
        out.println("running impact analysis...");
        ImpactAnalysisResult iar = impactAnalysis.run(sr.getState(), contingencyIds);
        out.println("impact analysis metrics: " + iar.getMetrics());

        return Multimaps.index(iar.getSecurityIndexes(), securityIndex -> securityIndex.getId().getContingencyId());

    }
    return null;
}
 
源代码11 项目: attic-aurora   文件: SchedulerThriftInterface.java
private static Set<InstanceTaskConfig> buildInitialState(Map<Integer, ITaskConfig> tasks) {
  // Translate tasks into instance IDs.
  Multimap<ITaskConfig, Integer> instancesByConfig = HashMultimap.create();
  Multimaps.invertFrom(Multimaps.forMap(tasks), instancesByConfig);

  // Reduce instance IDs into contiguous ranges.
  Map<ITaskConfig, Set<Range<Integer>>> rangesByConfig =
      Maps.transformValues(instancesByConfig.asMap(), Numbers::toRanges);

  ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder();
  for (Map.Entry<ITaskConfig, Set<Range<Integer>>> entry : rangesByConfig.entrySet()) {
    builder.add(new InstanceTaskConfig()
        .setTask(entry.getKey().newBuilder())
        .setInstances(IRange.toBuildersSet(convertRanges(entry.getValue()))));
  }

  return builder.build();
}
 
源代码12 项目: tac-kbp-eal   文件: _CorpusQueryAssessments.java
public final CorpusQueryAssessments filterForAssessment(final Set<QueryAssessment2016> assessment2016) {
  final ImmutableSet.Builder<QueryResponse2016> matchingQueriesB = ImmutableSet.builder();
  for (final QueryResponse2016 queryResponse2016 : assessments().keySet()) {
    if (assessment2016.contains(assessments().get(queryResponse2016))) {
      matchingQueriesB.add(queryResponse2016);
    }
  }
  final ImmutableSet<QueryResponse2016> matchingQueries = matchingQueriesB.build();
  final CorpusQueryAssessments.Builder ret = CorpusQueryAssessments.builder();
  ret.queryReponses(matchingQueries);
  ret.putAllQueryResponsesToSystemIDs(
      Multimaps.filterKeys(queryResponsesToSystemIDs(), in(matchingQueries)));
  ret.putAllMetadata(Maps.filterKeys(metadata(), in(matchingQueries)));
  ret.putAllAssessments(Maps.filterKeys(assessments(), in(matchingQueries)));
  return ret.build();
}
 
源代码13 项目: james-project   文件: EventDeadLettersContract.java
@Test
default void storeShouldKeepConsistencyWhenConcurrentStore() throws Exception {
    EventDeadLetters eventDeadLetters = eventDeadLetters();

    ImmutableMap<Integer, Group> groups = concurrentGroups();
    Multimap<Integer, EventDeadLetters.InsertionId> storedInsertionIds = Multimaps.synchronizedSetMultimap(HashMultimap.create());

    ConcurrentTestRunner.builder()
        .operation((threadNumber, step) -> {
            Event.EventId eventId = Event.EventId.random();
            EventDeadLetters.InsertionId insertionId = eventDeadLetters.store(groups.get(threadNumber), event(eventId)).block();
            storedInsertionIds.put(threadNumber, insertionId);
        })
        .threadCount(THREAD_COUNT)
        .operationCount(OPERATION_COUNT)
        .runSuccessfullyWithin(RUN_SUCCESSFULLY_IN);

    groups.forEach((groupId, group) -> {
        Group storedGroup = groups.get(groupId);
        assertThat(eventDeadLetters.failedIds(storedGroup).collectList().block())
            .hasSameElementsAs(storedInsertionIds.get(groupId));
    });
}
 
源代码14 项目: FreeBuilder   文件: ListMultimapProperty.java
private void addGetter(SourceBuilder code) {
  code.addLine("")
      .addLine("/**")
      .addLine(" * Returns an unmodifiable view of the multimap that will be returned by")
      .addLine(" * %s.", datatype.getType().javadocNoArgMethodLink(property.getGetterName()))
      .addLine(" * Changes to this builder will be reflected in the view.")
      .addLine(" */")
      .addLine("public %s<%s, %s> %s() {",
          ListMultimap.class,
          keyType,
          valueType,
          getter(property))
      .addLine("  return %s.unmodifiableListMultimap(%s);",
          Multimaps.class, property.getField())
      .addLine("}");
}
 
源代码15 项目: bazel-buildfarm   文件: RedisShardBackplane.java
private void startSubscriptionThread() {
  ListMultimap<String, TimedWatchFuture> watchers =
      Multimaps.synchronizedListMultimap(
          MultimapBuilder.linkedHashKeys().arrayListValues().build());
  subscriberService = Executors.newFixedThreadPool(32);
  subscriber =
      new RedisShardSubscriber(watchers, workerSet, config.getWorkerChannel(), subscriberService);

  operationSubscription =
      new RedisShardSubscription(
          subscriber,
          /* onUnsubscribe=*/ () -> {
            subscriptionThread = null;
            if (onUnsubscribe != null) {
              onUnsubscribe.runInterruptibly();
            }
          },
          /* onReset=*/ this::updateWatchedIfDone,
          /* subscriptions=*/ subscriber::subscribedChannels,
          client);

  // use Executors...
  subscriptionThread = new Thread(operationSubscription);

  subscriptionThread.start();
}
 
源代码16 项目: apollo   文件: RemoteConfigLongPollService.java
/**
 * Constructor.
 */
public RemoteConfigLongPollService() {
  m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
  m_longPollingStopped = new AtomicBoolean(false);
  m_longPollingService = Executors.newSingleThreadExecutor(
      ApolloThreadFactory.create("RemoteConfigLongPollService", true));
  m_longPollStarted = new AtomicBoolean(false);
  m_longPollNamespaces =
      Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
  m_notifications = Maps.newConcurrentMap();
  m_remoteNotificationMessages = Maps.newConcurrentMap();
  m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
  }.getType();
  gson = new Gson();
  m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
  m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
  m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
 
源代码17 项目: tutorials   文件: AssertJGuavaUnitTest.java
@Test
public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
    final Multimap<Integer, String> mmap1 = ArrayListMultimap.create();
    mmap1.put(1, "one");
    mmap1.put(1, "1");
    mmap1.put(2, "two");
    mmap1.put(2, "2");

    final Multimap<Integer, String> mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
    mmap1_clone.put(1, "one");
    mmap1_clone.put(1, "1");
    mmap1_clone.put(2, "two");
    mmap1_clone.put(2, "2");

    final Multimap<Integer, String> mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
    mmap2.put(1, "one");
    mmap2.put(1, "1");

    assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
}
 
源代码18 项目: dsl-devkit   文件: CheckJavaValidator.java
/**
 * Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
 * to a string which is used for checking for duplicates.
 *
 * @param <T>
 *          the generic type
 * @param predicate
 *          the predicate acting as a guard
 * @param function
 *          returns a string for an instance of type T
 * @param elements
 *          the elements to be checked
 * @return the duplicates
 */
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
  List<T> result = Lists.newArrayList();
  Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
    @Override
    public Collection<T> get() {
      return Lists.<T> newArrayList();
    }
  });
  for (final T candidate : elements) {
    if (predicate.apply(candidate)) {
      multiMap.put(function.apply(candidate), candidate);
    }
  }
  for (String elem : multiMap.keySet()) {
    final Collection<T> duplicates = multiMap.get(elem);
    if (duplicates.size() > 1) {
      result.addAll(duplicates);
    }
  }

  return result;
}
 
源代码19 项目: buck   文件: CxxDescriptionEnhancer.java
private static ImmutableListMultimap<CxxSource.Type, Arg> createCompilerFlagsForCxxBinary(
    BuildTarget target,
    CellPathResolver cellRoots,
    ActionGraphBuilder graphBuilder,
    CxxLinkOptions linkOptions,
    CxxPlatform cxxPlatform,
    ImmutableList<StringWithMacros> compilerFlags,
    ImmutableMap<Type, ImmutableList<StringWithMacros>> langCompilerFlags,
    PatternMatchedCollection<ImmutableList<StringWithMacros>> platformCompilerFlags,
    ImmutableMap<Type, PatternMatchedCollection<ImmutableList<StringWithMacros>>>
        langPlatformCompilerFlags) {
  StringWithMacrosConverter macrosConverter =
      getStringWithMacrosArgsConverter(target, cellRoots, graphBuilder, cxxPlatform);
  ImmutableListMultimap.Builder<CxxSource.Type, Arg> allCompilerFlagsBuilder =
      ImmutableListMultimap.builder();
  allCompilerFlagsBuilder.putAll(
      Multimaps.transformValues(
          CxxFlags.getLanguageFlagsWithMacros(
              compilerFlags,
              platformCompilerFlags,
              langCompilerFlags,
              langPlatformCompilerFlags,
              cxxPlatform),
          macrosConverter::convert));
  if (linkOptions.getThinLto()) {
    allCompilerFlagsBuilder.putAll(CxxFlags.toLanguageFlags(StringArg.from("-flto=thin")));
  } else if (linkOptions.getFatLto()) {
    allCompilerFlagsBuilder.putAll(CxxFlags.toLanguageFlags(StringArg.from("-flto")));
  }

  return allCompilerFlagsBuilder.build();
}
 
源代码20 项目: james-project   文件: MessageViewFactory.java
static ImmutableMap<String, String> toHeaderMap(List<Field> fields) {
    Function<Map.Entry<String, Collection<Field>>, String> bodyConcatenator = fieldListEntry -> fieldListEntry.getValue()
        .stream()
        .map(Field::getBody)
        .map(MimeUtil::unscrambleHeaderValue)
        .collect(Collectors.toList())
        .stream()
        .collect(Collectors.joining(JMAP_MULTIVALUED_FIELD_DELIMITER));

    return Multimaps.index(fields, Field::getName)
        .asMap()
        .entrySet()
        .stream()
        .collect(Guavate.toImmutableMap(Map.Entry::getKey, bodyConcatenator));
}
 
源代码21 项目: presto   文件: SetOperationNode.java
/**
 * Returns the input to output symbol mapping for the given source channel.
 * A single input symbol can map to multiple output symbols, thus requiring a Multimap.
 */
public Multimap<Symbol, SymbolReference> outputSymbolMap(int sourceIndex)
{
    return Multimaps.transformValues(FluentIterable.from(getOutputSymbols())
            .toMap(outputToSourceSymbolFunction(sourceIndex))
            .asMultimap()
            .inverse(), Symbol::toSymbolReference);
}
 
/**
 * Converts a {@link ResponseLinking} to an {@link EventArgumentLinking} using a {@link
 * CorefAnnotation} from an {@link com.bbn.kbp.events2014.AnswerKey} to canonicalize the
 * responses.  If the canonicalization is inconsistent with the response linking, an {@link
 * java.lang.IllegalArgumentException} will be thrown.
 */
@Override
public EventArgumentLinking align(ResponseLinking responseLinking,
    AnswerKey answerKey)  {
  checkArgument(answerKey.docId() == responseLinking.docID());

  // assertLinkingSubsetOfAnswerKey(responseLinking, answerKey);
  // the above assertion was too strong - the system response linking could
  // validly include responses which were not included in the answerKey because
  // there was a higher scoring system response in the same equivalence class

  final ImmutableMultimap<TypeRoleFillerRealis, Response> canonicalToResponses =
      Multimaps.index(responseLinking.allResponses(),
          TypeRoleFillerRealis.extractFromSystemResponse(
              answerKey.corefAnnotation().strictCASNormalizerFunction()));

  final Multimap<Response, TypeRoleFillerRealis> responsesToCanonical =
      canonicalToResponses.inverse();

  final ImmutableSet.Builder<TypeRoleFillerRealisSet> coreffedArgs = ImmutableSet.builder();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    coreffedArgs.add(TypeRoleFillerRealisSet.from(
        canonicalizeResponseSet(responseSet.asSet(),
            canonicalToResponses, responsesToCanonical)));
  }
  final ImmutableSet<TypeRoleFillerRealis> incompleteResponses = canonicalizeResponseSet(
      responseLinking.incompleteResponses(), canonicalToResponses, responsesToCanonical);

  return EventArgumentLinking.builder().docID(responseLinking.docID())
      .eventFrames(coreffedArgs.build()).incomplete(incompleteResponses).build();
}
 
源代码23 项目: presto   文件: PartitionUpdate.java
public static List<PartitionUpdate> mergePartitionUpdates(Iterable<PartitionUpdate> unMergedUpdates)
{
    ImmutableList.Builder<PartitionUpdate> partitionUpdates = ImmutableList.builder();
    for (Collection<PartitionUpdate> partitionGroup : Multimaps.index(unMergedUpdates, PartitionUpdate::getName).asMap().values()) {
        PartitionUpdate firstPartition = partitionGroup.iterator().next();

        ImmutableList.Builder<String> allFileNames = ImmutableList.builder();
        long totalRowCount = 0;
        long totalInMemoryDataSizeInBytes = 0;
        long totalOnDiskDataSizeInBytes = 0;
        for (PartitionUpdate partition : partitionGroup) {
            // verify partitions have the same new flag, write path and target path
            // this shouldn't happen but could if another user added a partition during the write
            if (partition.getUpdateMode() != firstPartition.getUpdateMode() ||
                    !partition.getWritePath().equals(firstPartition.getWritePath()) ||
                    !partition.getTargetPath().equals(firstPartition.getTargetPath())) {
                throw new PrestoException(HIVE_CONCURRENT_MODIFICATION_DETECTED, format("Partition %s was added or modified during INSERT", firstPartition.getName()));
            }
            allFileNames.addAll(partition.getFileNames());
            totalRowCount += partition.getRowCount();
            totalInMemoryDataSizeInBytes += partition.getInMemoryDataSizeInBytes();
            totalOnDiskDataSizeInBytes += partition.getOnDiskDataSizeInBytes();
        }

        partitionUpdates.add(new PartitionUpdate(firstPartition.getName(),
                firstPartition.getUpdateMode(),
                firstPartition.getWritePath(),
                firstPartition.getTargetPath(),
                allFileNames.build(),
                totalRowCount,
                totalInMemoryDataSizeInBytes,
                totalOnDiskDataSizeInBytes));
    }
    return partitionUpdates.build();
}
 
源代码24 项目: datawave   文件: TermOffsetPopulator.java
/**
 * Finds all the content functions and returns a map indexed by function name to the function.
 */
public static Multimap<String,Function> getContentFunctions(JexlNode query) {
    FunctionReferenceVisitor visitor = new FunctionReferenceVisitor();
    query.jjtAccept(visitor, null);
    
    Multimap<String,Function> functionsInNamespace = Multimaps.index(visitor.functions().get(ContentFunctions.CONTENT_FUNCTION_NAMESPACE), Function::name);
    
    return Multimaps.filterKeys(functionsInNamespace, TermOffsetPopulator::isContentFunctionTerm);
}
 
@SuppressWarnings("unchecked")
@Override
public <R extends HttpRequest> R bindToRequest(R request, Object input) {
   checkArgument(input instanceof LaunchSpecification, "this binder is only valid for LaunchSpecifications!");
   LaunchSpecification launchSpec = LaunchSpecification.class.cast(input);
   return (R) request.toBuilder().replaceFormParams(Multimaps.forMap(apply(launchSpec))).build();
}
 
源代码26 项目: codebuff   文件: ServiceManager.java
@GuardedBy("monitor")
void checkHealthy() {
  if (states.count(RUNNING) != numberOfServices) {
    IllegalStateException exception = new IllegalStateException("Expected to be healthy after starting. The following services are not running: " + Multimaps.filterKeys(servicesByState, not(equalTo(RUNNING))));
    throw exception;
  }
}
 
源代码27 项目: attic-aurora   文件: JobUpdaterIT.java
private void assertStateUpdate(
    IJobUpdateKey key,
    JobUpdateStatus expected,
    Multimap<Integer, JobUpdateAction> expectedActions) {

  IJobUpdateDetails details = getDetails(key);
  Iterable<IJobInstanceUpdateEvent> orderedEvents =
      EVENT_ORDER.sortedCopy(details.getInstanceEvents());
  Multimap<Integer, IJobInstanceUpdateEvent> eventsByInstance =
      Multimaps.index(orderedEvents, EVENT_TO_INSTANCE);
  Multimap<Integer, JobUpdateAction> actionsByInstance =
      Multimaps.transformValues(eventsByInstance, JobUpdateControllerImpl.EVENT_TO_ACTION);
  assertEquals(expectedActions, actionsByInstance);
  assertEquals(expected, details.getUpdate().getSummary().getState().getStatus());
}
 
源代码28 项目: sailfish-core   文件: SimpleMessageFilter.java
private boolean checkMapIntersect(Multimap<String, String> fieldsMultimap, Multimap<String, String> filterValues, boolean containsEntries) {
    if (!fieldsMultimap.keySet().containsAll(filterValues.keySet())){
        return true;
    }
    Multimap<String, String> intersectMultimap = Multimaps.filterEntries(fieldsMultimap, e -> filterValues.containsEntry(e.getKey(), e.getValue()));
    if (containsEntries) {
        return intersectMultimap.keySet().size() == filterValues.keySet().size();
    } else {
        return intersectMultimap.isEmpty();
    }

}
 
源代码29 项目: Pushjet-Android   文件: RuleVisitor.java
public static void visitGeneratedClosure(ClassNode node) {
    MethodNode method = AstUtils.getGeneratedClosureImplMethod(node);
    Statement closureCode = method.getCode();
    SourceLocation sourceLocation = closureCode.getNodeMetaData(AST_NODE_METADATA_LOCATION_KEY);
    if (sourceLocation != null) {
        AnnotationNode metadataAnnotation = new AnnotationNode(ANNOTATION_CLASS_NODE);

        metadataAnnotation.addMember("scriptSourceDescription", new ConstantExpression(sourceLocation.getScriptSourceDescription()));
        metadataAnnotation.addMember("lineNumber", new ConstantExpression(sourceLocation.getLineNumber()));
        metadataAnnotation.addMember("columnNumber", new ConstantExpression(sourceLocation.getColumnNumber()));

        ListMultimap<String, Integer> inputs = closureCode.getNodeMetaData(AST_NODE_METADATA_INPUTS_KEY);
        if (!inputs.isEmpty()) {
            List<Expression> pathValues = Lists.newArrayListWithCapacity(inputs.size());
            List<Expression> lineNumberValues = Lists.newArrayListWithCapacity(inputs.size());
            for (Map.Entry<String, List<Integer>> input : Multimaps.asMap(inputs).entrySet()) {
                pathValues.add(new ConstantExpression(input.getKey()));
                lineNumberValues.add(new ConstantExpression(input.getValue().get(0)));
            }

            metadataAnnotation.addMember("inputPaths", new ListExpression(pathValues));
            metadataAnnotation.addMember("inputLineNumbers", new ListExpression(lineNumberValues));
        }

        node.addAnnotation(metadataAnnotation);
    }
}
 
源代码30 项目: bundletool   文件: CollectorUtils.java
/**
 * Returns a {@code Collector} accumulating entries into an {@code ImmutableListMultimap}.
 *
 * <p>The keys of the entries are the result of applying the provided key mapping function while
 * the values are generated by applying the value mapping function and accumulated in the
 * encounter order of the stream.
 */
public static <T, K extends Comparable<K>, V>
    Collector<T, ?, ImmutableListMultimap<K, V>> groupingBySortedKeys(
        Function<? super T, ? extends K> keyFunction,
        Function<? super T, ? extends V> valueFunction) {
  return Collectors.collectingAndThen(
      Multimaps.toMultimap(
          keyFunction, valueFunction, MultimapBuilder.treeKeys().arrayListValues()::<K, V>build),
      ImmutableListMultimap::copyOf);
}
 
 同包方法