Java Code Examples for com.google.common.collect.Multimap

The following examples show how to use com.google.common.collect.Multimap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: GregTech   Source File: ToolMetaItem.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 2
Source Project: bazel   Source File: AnalysisUtils.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
Source Project: datawave   Source File: ExtendedContentDataTypeHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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()));
    }
}
 
Example 4
Source Project: mangooio   Source File: FormControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 5
Source Project: apollo   Source File: NotificationControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 6
/**
 * 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);
  }
}
 
Example 7
Source Project: datawave   Source File: ConstraintChecker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 8
Source Project: crate   Source File: RoutingBuilder.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 9
Source Project: connector-sdk   Source File: StructuredDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConversionError() {
  setupSchema();
  Multimap<String, Object> values = ArrayListMultimap.create();
  values.put("integerProperty", "v1");
  thrown.expect(NumberFormatException.class);
  StructuredData.getStructuredData("myObject", values);
}
 
Example 10
Source Project: incubator-pinot   Source File: AlertFilterUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
/**
 * 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;
}
 
Example 12
Source Project: incubator-pinot   Source File: DataResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source Project: attic-stratos   Source File: BaseAWSEC2ApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 14
Source Project: bazel   Source File: AndroidResourceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
  }
}
 
Example 15
Source Project: datawave   Source File: EventMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 16
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;
}
 
Example 17
Source Project: tracecompass   Source File: TmfFilterHelperTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 18
Source Project: attic-apex-malhar   Source File: PojoOuterJoinTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 19
/**
 * 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;
}
 
Example 20
Source Project: bazel   Source File: ZipFilterAction.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 21
Source Project: rya   Source File: MongoDBQueryEngine.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }

}
 
Example 22
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();
		}
	}
}
 
Example 23
Source Project: xtext-extras   Source File: ResolvedFeatures.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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);
		}
	}
}
 
Example 24
@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));
}
 
Example 25
Source Project: incubator-pinot   Source File: JiraContentFormatter.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 26
Source Project: coming   Source File: Closure_103_DisambiguateProperties_t.java    License: MIT License 5 votes vote down vote up
/** 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;
}
 
Example 27
Source Project: kafka-connect-cdc-mssql   Source File: MsSqlQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 28
Source Project: bundletool   Source File: CollectorUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 29
Source Project: presto   Source File: NodeScheduler.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 30
Source Project: yarg   Source File: DefaultControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}