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

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

源代码1 项目: GregTech   文件: ToolMetaItem.java
@Override
public Multimap<String, AttributeModifier> getAttributeModifiers(EntityEquipmentSlot slot, ItemStack stack) {
    T metaValueItem = getItem(stack);
    HashMultimap<String, AttributeModifier> modifiers = HashMultimap.create();
    modifiers.putAll(super.getAttributeModifiers(slot, stack));
    if (metaValueItem != null && slot == EntityEquipmentSlot.MAINHAND) {
        IToolStats toolStats = metaValueItem.getToolStats();
        if (toolStats == null) {
            return HashMultimap.create();
        }
        float attackDamage = getToolAttackDamage(stack);
        float attackSpeed = toolStats.getAttackSpeed(stack);

        modifiers.put(SharedMonsterAttributes.ATTACK_DAMAGE.getName(), new AttributeModifier(ATTACK_DAMAGE_MODIFIER, "Weapon modifier", attackDamage, 0));
        modifiers.put(SharedMonsterAttributes.ATTACK_SPEED.getName(), new AttributeModifier(ATTACK_SPEED_MODIFIER, "Weapon modifier", attackSpeed, 0));
    }
    return modifiers;
}
 
源代码2 项目: bazel   文件: AnalysisUtils.java
@VisibleForTesting
public static Multimap<BuildConfiguration, DependencyKey> targetsToDeps(
    Collection<TargetAndConfiguration> nodes, ConfiguredRuleClassProvider ruleClassProvider) {
  Multimap<BuildConfiguration, DependencyKey> asDeps = ArrayListMultimap.create();
  for (TargetAndConfiguration targetAndConfig : nodes) {
    ConfigurationTransition transition =
        TransitionResolver.evaluateTransition(
            targetAndConfig.getConfiguration(),
            NoTransition.INSTANCE,
            targetAndConfig.getTarget(),
            ruleClassProvider.getTrimmingTransitionFactory());
    if (targetAndConfig.getConfiguration() != null) {
      // TODO(bazel-team): support top-level aspects
      asDeps.put(
          targetAndConfig.getConfiguration(),
          DependencyKey.builder()
              .setLabel(targetAndConfig.getLabel())
              .setTransition(transition)
              .build());
    }
  }
  return asDeps;
}
 
源代码3 项目: datawave   文件: ExtendedContentDataTypeHelper.java
/**
 * Populates the provided metadata parser map from the configuration. This allows different metadata parser maps to be populated based on different
 * configuration keys.
 * 
 * @param conf
 *            Configuration
 * @param keySuffix
 *            The configuration key suffix
 * @param metadataParserMap
 *            The metadata parser map to populate.
 */
protected void putMetadataParsers(Configuration conf, String keySuffix, Multimap<String,MetadataIdParser> metadataParserMap) {
    String prefix;
    Map<String,String> keyParsers;
    prefix = this.getType().typeName() + keySuffix;
    keyParsers = getValues(conf, prefix);
    for (Map.Entry<String,String> entry : keyParsers.entrySet()) {
        String field = entry.getKey();
        if (field.length() <= (prefix.length() + 1)) {
            throw new IllegalArgumentException("Field metadata parser key is invalid: missing fieldname: " + field);
        }
        field = field.substring(prefix.length() + 1);
        int index = field.indexOf('.');
        if (index >= 0) {
            field = field.substring(0, index);
        }
        if (field.isEmpty()) {
            throw new IllegalArgumentException("Field metadata parser key is invalid: missing fieldname: " + field);
        }
        metadataParserMap.put(field, MetadataIdParser.createParser(entry.getValue()));
    }
}
 
源代码4 项目: mangooio   文件: FormControllerTest.java
@Test
public void testFlashify() {
    // given
    String data = "this is my [email protected]";
    Multimap<String, String> parameter = ArrayListMultimap.create();
    parameter.put("name", "this is my name");
    parameter.put("email", "[email protected]");
    
    // when
    TestResponse response = TestRequest.post("/submit")
            .withContentType(MediaType.FORM_DATA.withoutParameters().toString())
            .withForm(parameter)
            .execute();

    // then
    assertThat(response, not(nullValue()));
    assertThat(response.getStatusCode(), equalTo(StatusCodes.OK));
    assertThat(response.getContent(), equalTo(data));
}
 
源代码5 项目: apollo   文件: NotificationControllerTest.java
@Before
public void setUp() throws Exception {
  controller = new NotificationController(watchKeysUtil, releaseMessageService, entityManagerUtil, namespaceUtil);

  someAppId = "someAppId";
  someCluster = "someCluster";
  defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
  someDataCenter = "someDC";
  someNotificationId = 1;
  someClientIp = "someClientIp";

  when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);

  deferredResults =
      (Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
          .getField(controller, "deferredResults");
}
 
源代码6 项目: codebuff   文件: SubscriberRegistry.java
/**
 * Registers all subscriber methods on the given listener object.
 */
void register(Object listener) {
  Multimap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener);

  for (Map.Entry<Class<?>, Collection<Subscriber>> entry : listenerMethods.asMap().entrySet()) {
    Class<?> eventType = entry.getKey();
    Collection<Subscriber> eventMethodsInListener = entry.getValue();

    CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType);

    if (eventSubscribers == null) {
      CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<Subscriber>();
      eventSubscribers =
          MoreObjects.firstNonNull(subscribers.putIfAbsent(eventType, newSet), newSet);
    }

    eventSubscribers.addAll(eventMethodsInListener);
  }
}
 
源代码7 项目: datawave   文件: ConstraintChecker.java
/**
 * Factory method to create a new ConstraintChecker from a Configuration.
 *
 * @param conf
 * @return constraint checker
 */
public static ConstraintChecker create(Configuration conf) {
    
    Multimap<Text,VisibilityConstraint> constraints = null;
    
    String[] initializerClasses = conf.getStrings(INITIALIZERS);
    
    if (initializerClasses != null) {
        for (String initializerClass : initializerClasses) {
            if (constraints == null) {
                constraints = HashMultimap.create();
            }
            
            try {
                ConstraintInitializer initializer = Class.forName(initializerClass).asSubclass(ConstraintInitializer.class).newInstance();
                initializer.addConstraints(conf, constraints);
                
            } catch (Exception e) {
                log.error("Could invoke ConstraintInitializer: " + initializerClass, e);
                throw new RuntimeException("Could invoke ConstraintInitializer: " + initializerClass, e);
            }
        }
    }
    
    return new ConstraintChecker(constraints);
}
 
源代码8 项目: crate   文件: RoutingBuilder.java
ReaderAllocations buildReaderAllocations() {
    Multimap<RelationName, String> indicesByTable = HashMultimap.create();
    IndexBaseBuilder indexBaseBuilder = new IndexBaseBuilder();
    Map<String, Map<Integer, String>> shardNodes = new HashMap<>();

    for (final Map.Entry<RelationName, List<Routing>> tableRoutingEntry : routingListByTable.entrySet()) {
        RelationName table = tableRoutingEntry.getKey();
        List<Routing> routingList = tableRoutingEntry.getValue();
        for (Routing routing : routingList) {
            allocateRoutingNodes(shardNodes, routing.locations());

            for (Map.Entry<String, Map<String, IntIndexedContainer>> entry : routing.locations().entrySet()) {
                Map<String, IntIndexedContainer> shardsByIndex = entry.getValue();
                indicesByTable.putAll(table, shardsByIndex.keySet());

                for (Map.Entry<String, IntIndexedContainer> shardsByIndexEntry : shardsByIndex.entrySet()) {
                    indexBaseBuilder.allocate(shardsByIndexEntry.getKey(), shardsByIndexEntry.getValue());
                }
            }
        }
    }
    routingListByTable.clear();
    return new ReaderAllocations(indexBaseBuilder.build(), shardNodes, indicesByTable);
}
 
源代码9 项目: connector-sdk   文件: StructuredDataTest.java
@Test
public void testConversionError() {
  setupSchema();
  Multimap<String, Object> values = ArrayListMultimap.create();
  values.put("integerProperty", "v1");
  thrown.expect(NumberFormatException.class);
  StructuredData.getStructuredData("myObject", values);
}
 
源代码10 项目: incubator-pinot   文件: AlertFilterUtils.java
static MergedAnomalyResultDTO makeAnomaly(Long configId, long baseTime, long start, long end,
    Map<String, String> dimensions, AnomalyFeedbackDTO feedback) {
  MergedAnomalyResultDTO anomaly = DetectionTestUtils.makeAnomaly(configId, baseTime + start, baseTime + end);
  anomaly.setType(AnomalyType.DEVIATION);
  anomaly.setChildIds(Collections.emptySet());

  Multimap<String, String> filters = HashMultimap.create();
  for (Map.Entry<String, String> dimension : dimensions.entrySet()) {
    filters.put(dimension.getKey(), dimension.getValue());
  }
  anomaly.setMetricUrn(MetricEntity.fromMetric(1.0, 1l, filters).getUrn());

  DimensionMap dimMap = new DimensionMap();
  dimMap.putAll(dimensions);
  anomaly.setDimensions(dimMap);

  anomaly.setCreatedBy("no-auth-user");
  anomaly.setUpdatedBy("no-auth-user");
  anomaly.setId(DAORegistry.getInstance().getMergedAnomalyResultDAO().save(anomaly));

  if (feedback != null) {
    anomaly.setFeedback(feedback);
    anomaly.setDimensions(null);
    DAORegistry.getInstance().getMergedAnomalyResultDAO().updateAnomalyFeedback(anomaly);
  }

  return anomaly;
}
 
源代码11 项目: netcdf-java   文件: HTTPMethod.java
/**
 * Get all Request headers as a map of name to list of values.
 * A value may be null.
 *
 * @return Map, may be empty but not null.
 */
public Multimap<String, String> getRequestHeaders() {
  if (this.lastrequest == null)
    return ImmutableMultimap.of();

  ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
  for (Header header : this.lastrequest.getAllHeaders()) {
    for (HeaderElement element : header.getElements()) {
      multimap.put(element.getName(), element.getValue());
    }
  }
  return multimap;
}
 
源代码12 项目: incubator-pinot   文件: DataResource.java
/**
 * Returns {@code true} if a given anomaly passes the dimension filters {@code filters}, or
 * {@code false} otherwise. If {@code filters} contains multiple values for the same dimension
 * key, ANY match will pass the filter.
 *
 * @param anomaly anomaly to filter
 * @param filters dimension filter multimap
 * @return {@code true} if anomaly passed the filters, {@code false} otherwise
 */
static boolean applyAnomalyFilters(MergedAnomalyResultDTO anomaly, Multimap<String, String> filters) {
  Multimap<String, String> anomalyFilter = AnomaliesResource.generateFilterSetForTimeSeriesQuery(anomaly);
  for (String filterKey : filters.keySet()) {
    if (!anomalyFilter.containsKey(filterKey))
      return false;

    Collection<String> filterValues = filters.get(filterKey);
    if (!filterValues.containsAll(anomalyFilter.get(filterKey)))
      return false;
  }
  return true;
}
 
源代码13 项目: attic-stratos   文件: BaseAWSEC2ApiTest.java
@Override protected void assertNonPayloadHeadersEqual(HttpRequest request, String toMatch) {
   Multimap<String, String> headersToCheck = LinkedHashMultimap.create();
   for (String key : request.getHeaders().keySet()) {
      if (key.equals("X-Amz-Date")) {
         assertEquals(request.getFirstHeaderOrNull(key), "20120416T155408Z");
      } else if (key.equals("Authorization")) {
         assertThat(request.getFirstHeaderOrNull(AUTHORIZATION)).startsWith(
               "AWS4-HMAC-SHA256 Credential=identity/20120416/"
                     + "us-east-1/ec2/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=");
      } else {
         headersToCheck.putAll(key, request.getHeaders().get(key));
      }
   }
   assertEquals(sortAndConcatHeadersIntoString(headersToCheck), toMatch);
}
 
源代码14 项目: bazel   文件: AndroidResourceProcessor.java
void writeDependencyPackageRJavaFiles(
    List<DependencyAndroidData> dependencyData,
    String customPackageForR,
    Path androidManifest,
    Path sourceOut)
    throws IOException {
  List<SymbolFileProvider> libraries = new ArrayList<>();
  for (DependencyAndroidData dataDep : dependencyData) {
    SymbolFileProvider library = dataDep.asSymbolFileProvider();
    libraries.add(library);
  }
  String appPackageName = customPackageForR;
  if (appPackageName == null) {
    appPackageName = VariantConfiguration.getManifestPackage(androidManifest.toFile());
  }
  Multimap<String, ResourceSymbols> libSymbolMap = ArrayListMultimap.create();
  Path primaryRTxt = sourceOut != null ? sourceOut.resolve("R.txt") : null;
  if (primaryRTxt != null && !libraries.isEmpty()) {
    ResourceSymbols fullSymbolValues =
        loadResourceSymbolTable(libraries, appPackageName, primaryRTxt, libSymbolMap);
    // Loop on all the package name, merge all the symbols to write, and write.
    for (String packageName : libSymbolMap.keySet()) {
      Collection<ResourceSymbols> symbols = libSymbolMap.get(packageName);
      fullSymbolValues.writeSourcesTo(sourceOut, packageName, symbols, /* finalFields= */ true);
    }
  }
}
 
源代码15 项目: datawave   文件: EventMapperTest.java
@Test
public void shouldHandleNullRawData() throws IOException, InterruptedException {
    // some RecordReaders may null out raw data entirely because they pass data to their
    // handlers in other ways. Verify that the EventMapper can handle this case.
    record.setRawData(null);
    
    eventMapper.setup(mapContext);
    eventMapper.map(new LongWritable(1), record, mapContext);
    eventMapper.cleanup(mapContext);
    
    Multimap<BulkIngestKey,Value> written = TestContextWriter.getWritten();
    
    // two fields mutations + LOAD_DATE + ORIG_FILE + RAW_FILE
    assertEquals(5, written.size());
}
 
private Collection<Value> getCorrespondingValue(Multimap<BulkIngestKey,Value> entries, BulkIngestKey expectedBulkIngestKey) {
    for (BulkIngestKey actualBulkIngestKey : entries.keySet()) {
        if (actualBulkIngestKey.getTableName().equals(expectedBulkIngestKey.getTableName())
                        && actualBulkIngestKey.getKey().equals(expectedBulkIngestKey.getKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
            return entries.get(actualBulkIngestKey);
        }
    }
    return null;
}
 
源代码17 项目: tracecompass   文件: TmfFilterHelperTest.java
private static Predicate<Multimap<String, Object>> getRegex(ITmfFilter filter, String expected) {
    String regex = TmfFilterHelper.getRegexFromFilter(filter);
    assertEquals(expected, regex);
    FilterCu compile = FilterCu.compile(regex);
    assertNotNull(compile);
    Predicate<Multimap<String, Object>> predicate = compile.generate();
    return predicate;
}
 
源代码18 项目: attic-apex-malhar   文件: PojoOuterJoinTest.java
@Test
public void PojoFullOuterJoinTestWithMap()
{
  String[] leftKeys = {"uId", "uName"};
  String[] rightKeys = {"uId", "uNickName"};
  Map<String,KeyValPair<AbstractPojoJoin.STREAM, String>> outputInputMap = new HashMap<>();
  outputInputMap.put("uId",new KeyValPair<>(AbstractPojoJoin.STREAM.LEFT,"uId"));
  outputInputMap.put("age",new KeyValPair<>(AbstractPojoJoin.STREAM.RIGHT,"age"));
  PojoFullOuterJoin<TestPojo1, TestPojo3> pij = new PojoFullOuterJoin<>(TestOutClass.class, leftKeys, rightKeys, outputInputMap);

  List<Multimap<List<Object>, Object>> accu = pij.defaultAccumulatedValue();

  Assert.assertEquals(2, accu.size());

  accu = pij.accumulate(accu, new TestPojo1(1, "Josh"));
  accu = pij.accumulate(accu, new TestPojo1(2, "Bob"));

  accu = pij.accumulate2(accu, new TestPojo3(1, "Josh", 12));
  accu = pij.accumulate2(accu, new TestPojo3(3, "Bob", 13));

  Assert.assertEquals(3, pij.getOutput(accu).size());
  Set<Integer> checkMap = new HashSet<>();
  for ( int i = 0; i < 3; i++ ) {
    Object o = pij.getOutput(accu).get(i);
    Assert.assertTrue(o instanceof TestOutClass);
    TestOutClass testOutClass = (TestOutClass)o;
    int uId = testOutClass.getUId();
    checkMap.add(uId);
  }
  Assert.assertEquals(3,checkMap.size());
}
 
源代码19 项目: grammaticus   文件: ComplexGrammaticalForm.java
/**
 * For possessive languages, it makes sense to keep an enum map around for that
 */
public static <A extends NounForm> EnumMap<LanguagePossessive,NounFormMap<A>> getPossessiveSpecificMap(Collection<? extends A> forms) {
    Multimap<LanguagePossessive,A> mm = ArrayListMultimap.create();
    for (A form : forms) {
        mm.put(form.getPossessive(), form);
    }
    EnumMap<LanguagePossessive,NounFormMap<A>> result = new EnumMap<LanguagePossessive,NounFormMap<A>>(LanguagePossessive.class);
    for (LanguagePossessive poss : LanguagePossessive.values()) {
        result.put(poss, new NounFormMap<A>(mm.get(poss)));
    }
    return result;
}
 
源代码20 项目: bazel   文件: ZipFilterAction.java
static int run(String[] args) throws IOException {
  Options options = new Options();
  new JCommander(options).parse(args);
  logger.fine(
      String.format(
          "Creating filter from entries of type %s, in zip files %s.",
          options.filterTypes, options.filterZips));

  final Stopwatch timer = Stopwatch.createStarted();
  Multimap<String, Long> entriesToOmit =
      getEntriesToOmit(options.filterZips, options.filterTypes);
  final String explicitFilter =
      options.explicitFilters.isEmpty()
          ? ""
          : String.format(".*(%s).*", Joiner.on("|").join(options.explicitFilters));
  logger.fine(String.format("Filter created in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));

  ImmutableMap.Builder<String, Long> inputEntries = ImmutableMap.builder();
  try (ZipReader input = new ZipReader(options.inputZip.toFile())) {
    for (ZipFileEntry entry : input.entries()) {
      inputEntries.put(entry.getName(), entry.getCrc());
    }
  }

  // TODO(jingwen): Remove --errorOnHashMismatch when Blaze release with --checkHashMismatch
  // is checked in.
  if (options.errorOnHashMismatch) {
    options.hashMismatchCheckMode = HashMismatchCheckMode.ERROR;
  }
  ZipFilterEntryFilter entryFilter =
      new ZipFilterEntryFilter(
          explicitFilter, entriesToOmit, inputEntries.build(), options.hashMismatchCheckMode);

  try (OutputStream out = Files.newOutputStream(options.outputZip);
      ZipCombiner combiner = new ZipCombiner(options.outputMode, entryFilter, out)) {
    combiner.addZip(options.inputZip.toFile());
  }
  logger.fine(String.format("Filtering completed in %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
  return entryFilter.sawErrors() ? 1 : 0;
}
 
源代码21 项目: rya   文件: MongoDBQueryEngine.java
@Override
public CloseableIteration<? extends Entry<RyaStatement, BindingSet>, RyaDAOException> queryWithBindingSet(
        final Collection<Entry<RyaStatement, BindingSet>> stmts,
        final StatefulMongoDBRdfConfiguration conf) throws RyaDAOException {
    checkNotNull(stmts);
    checkNotNull(conf);

    final Multimap<RyaStatement, BindingSet> rangeMap = HashMultimap.create();

    //TODO: cannot span multiple tables here
    try {
        for (final Map.Entry<RyaStatement, BindingSet> stmtbs : stmts) {
            final RyaStatement stmt = stmtbs.getKey();
            final BindingSet bs = stmtbs.getValue();
            rangeMap.put(stmt, bs);
        }

        // TODO not sure what to do about regex ranges?
        final RyaStatementBindingSetCursorIterator iterator = new RyaStatementBindingSetCursorIterator(
                getCollection(conf), rangeMap, strategy, conf.getAuthorizations());

        return iterator;
    } catch (final Exception e) {
        throw new RyaDAOException(e);
    }

}
 
private void collectRelevantFiles(IPackageFragment element, Multimap<IProject, IFile> result)
		throws JavaModelException {
	if (!element.isDefaultPackage()) {
		collectIFiles(result, element.getNonJavaResources());
	} else if (element.getResource() instanceof IFolder) {
		IFolder folder = (IFolder) element.getResource();
		try {
			collectIFiles(result, folder.members());
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
 
源代码23 项目: xtext-extras   文件: ResolvedFeatures.java
protected void computeAllOperationsFromSuperTypes(JvmDeclaredType type, Multimap<String, AbstractResolvedOperation> processedOperations,
		Set<JvmType> processedTypes) {
	for (JvmTypeReference superType: type.getSuperTypes()) {
		JvmType rawSuperType = superType.getType();
		if (rawSuperType instanceof JvmDeclaredType && !rawSuperType.eIsProxy() && processedTypes.add(rawSuperType)) {
			computeAllOperations((JvmDeclaredType) rawSuperType, processedOperations);
			computeAllOperationsFromSuperTypes((JvmDeclaredType) rawSuperType, processedOperations, processedTypes);
		}
	}
}
 
源代码24 项目: molgenis   文件: OntologyTagServiceTest.java
@Test
void testGetTagsForAttribute() {
  EntityType emd = entityTypeFactory.create("org.molgenis.SNP");
  Attribute attribute = attrFactory.create().setName("Chr");
  attribute.setTags(asList(chromosomeNameTagEntity, geneAnnotationTagEntity));

  Relation instanceOf = Relation.valueOf("instanceOf");

  Ontology edamOntology =
      Ontology.create("EDAM", "http://edamontology.org", "The EDAM ontology.");
  OntologyTerm chromosomeName =
      OntologyTerm.create(
          "http://edamontology.org/data_0987", "Chromosome name", "Name of a chromosome.");
  OntologyTerm geneAnnotation =
      OntologyTerm.create(
          "http://edamontology.org/data_0919",
          "Gene annotation (chromosome)",
          "This includes basic information. e.g. chromosome number...");

  when(ontologyService.getOntology("http://edamontology.org")).thenReturn(edamOntology);
  when(ontologyService.getOntologyTerm("http://edamontology.org/data_0987"))
      .thenReturn(chromosomeName);
  when(ontologyService.getOntologyTerm("http://edamontology.org/data_0919"))
      .thenReturn(geneAnnotation);

  Multimap<Relation, OntologyTerm> expected = LinkedHashMultimap.create();
  expected.put(instanceOf, chromosomeName);
  expected.put(instanceOf, geneAnnotation);

  assertEquals(expected, ontologyTagService.getTagsForAttribute(emd, attribute));
}
 
源代码25 项目: incubator-pinot   文件: JiraContentFormatter.java
private String buildSummary(Map<String, Object> templateValues, Multimap<String, String> dimensionFilters) {
  String issueSummary =
      BaseNotificationContent.makeSubject(super.getSubjectType(alertClientConfig), this.subsConfig, templateValues);

  // Append dimensional info to summary
  StringBuilder dimensions = new StringBuilder();
  for (Map.Entry<String, Collection<String>> dimFilter : dimensionFilters.asMap().entrySet()) {
    dimensions.append(", ").append(dimFilter.getKey()).append("=").append(String.join(",", dimFilter.getValue()));
  }
  issueSummary = issueSummary + dimensions.toString();

  // Truncate summary due to jira character limit
  return StringUtils.abbreviate(issueSummary, MAX_JIRA_SUMMARY_LENGTH);
}
 
/** Returns a map from field name to types for which it will be renamed. */
Multimap<String, Collection<T>> getRenamedTypesForTesting() {
  Multimap<String, Collection<T>> ret = HashMultimap.create();
  for (Map.Entry<String, Property> entry: properties.entrySet()) {
    Property prop = entry.getValue();
    if (!prop.skipRenaming) {
      for (Collection<T> c : prop.getTypes().allEquivalenceClasses()) {
        if (!c.isEmpty() && !prop.typesToSkip.contains(c.iterator().next())) {
          ret.put(entry.getKey(), c);
        }
      }
    }
  }
  return ret;
}
 
String joinSelect(Multimap<String, String> columns) {
  List<String> selectColumns = new ArrayList<>();

  for (String table : columns.keySet()) {
    final Collection<String> keyColumns = columns.get(table);
    for (String keyColumn : keyColumns) {
      selectColumns.add(
          String.format("[%s].[%s]", table, keyColumn)
      );
    }
  }

  return Joiner.on(", ").join(selectColumns);
}
 
源代码28 项目: bundletool   文件: CollectorUtilsTest.java
@Test
public void groupingBySortedKeys() {
  Multimap<Integer, String> map =
      Stream.of("this", "is", "a", "test", "for", "that", "method")
          .collect(CollectorUtils.groupingBySortedKeys(String::length));

  assertThat(map)
      .containsExactly(1, "a", 2, "is", 3, "for", 4, "this", 4, "test", 4, "that", 6, "method")
      .inOrder();
}
 
源代码29 项目: presto   文件: NodeScheduler.java
public static SplitPlacementResult selectDistributionNodes(
        NodeMap nodeMap,
        NodeTaskMap nodeTaskMap,
        int maxSplitsPerNode,
        int maxPendingSplitsPerTask,
        Set<Split> splits,
        List<RemoteTask> existingTasks,
        BucketNodeMap bucketNodeMap)
{
    Multimap<InternalNode, Split> assignments = HashMultimap.create();
    NodeAssignmentStats assignmentStats = new NodeAssignmentStats(nodeTaskMap, nodeMap, existingTasks);

    Set<InternalNode> blockedNodes = new HashSet<>();
    for (Split split : splits) {
        // node placement is forced by the bucket to node map
        InternalNode node = bucketNodeMap.getAssignedNode(split).get();

        // if node is full, don't schedule now, which will push back on the scheduling of splits
        if (assignmentStats.getTotalSplitCount(node) < maxSplitsPerNode ||
                assignmentStats.getQueuedSplitCountForStage(node) < maxPendingSplitsPerTask) {
            assignments.put(node, split);
            assignmentStats.addAssignedSplit(node);
        }
        else {
            blockedNodes.add(node);
        }
    }

    ListenableFuture<?> blocked = toWhenHasSplitQueueSpaceFuture(blockedNodes, existingTasks, calculateLowWatermark(maxPendingSplitsPerTask));
    return new SplitPlacementResult(blocked, ImmutableMultimap.copyOf(assignments));
}
 
源代码30 项目: yarg   文件: DefaultControllerTest.java
@Test
public void testJsonExtractionForBand() throws IOException, URISyntaxException {
    ReportBand band = YmlDataUtil.bandFrom(FileLoader.load("extraction/fixture/default_json_report_band.yml"));

    BandData rootBand = new BandData(BandData.ROOT_BAND_NAME);
    rootBand.setData(new HashMap<>());
    rootBand.setFirstLevelBandDefinitionNames(new HashSet<>());

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

    for (ReportBand definition : band.getChildren()) {
        List<BandData> data = controllerFactory.controllerBy(definition.getBandOrientation())
                .extract(contextFactory.context(definition, rootBand, ExtractionUtils.getParams(definition)));

        Assert.assertNotNull(data);

        data.forEach(b-> {
            Assert.assertNotNull(b);
            Assert.assertTrue(StringUtils.isNotEmpty(b.getName()));

            reportBandMap.put(b.getName(), b);
        });

        rootBand.addChildren(data);
        rootBand.getFirstLevelBandDefinitionNames().add(definition.getName());
    }

    checkHeader(reportBandMap.get("header"), 2, "name", "id");
    checkMasterData(reportBandMap.get("master_data"), 2, 2,
            "id", "name", "value", "user_id");
}
 
 同包方法