com.google.common.collect.ArrayListMultimap Java Examples

The following examples show how to use com.google.common.collect.ArrayListMultimap. 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 check out the related API usage on the sidebar.
Example #1
Source File: LazyLinker.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doLinkModel(final EObject model, IDiagnosticConsumer consumer) {
	final Multimap<EStructuralFeature.Setting, INode> settingsToLink = ArrayListMultimap.create();
	final LinkingDiagnosticProducer producer = new LinkingDiagnosticProducer(consumer);
	cache.execWithoutCacheClear(model.eResource(), new IUnitOfWork.Void<Resource>() {
		@Override
		public void process(Resource state) throws Exception {
			TreeIterator<EObject> iterator = getAllLinkableContents(model);
			boolean clearAllReferencesRequired = isClearAllReferencesRequired(state);
			while (iterator.hasNext()) {
				EObject eObject = iterator.next();
				if (clearAllReferencesRequired) {
					clearReferences(eObject);
				}
				installProxies(eObject, producer, settingsToLink);
			}
		}
	});
	installQueuedLinks(settingsToLink);
}
 
Example #2
Source File: AmberSiteFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
public static ListMultimap<Chromosome, AmberSite> sites(@NotNull final String vcfFile) throws IOException {
    final ListMultimap<Chromosome, AmberSite> result = ArrayListMultimap.create();

    try (final AbstractFeatureReader<VariantContext, LineIterator> reader = getFeatureReader(vcfFile, new VCFCodec(), false)) {
        for (VariantContext variant : reader.iterator()) {
            if (variant.isNotFiltered()) {
                if (HumanChromosome.contains(variant.getContig())) {
                    HumanChromosome chromosome = HumanChromosome.fromString(variant.getContig());
                    result.put(chromosome,
                            ImmutableAmberSite.builder()
                                    .chromosome(variant.getContig())
                                    .position(variant.getStart())
                                    .ref(variant.getReference().getBaseString())
                                    .alt(variant.getAlternateAllele(0).getBaseString())
                                    .snpCheck(variant.hasAttribute("SNPCHECK"))
                                    .build());
                }
            }
        }
    }

    return result;
}
 
Example #3
Source File: DefaultDataProvider.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Override
public Multimap<EventSlice, EventDTO> fetchEvents(Collection<EventSlice> slices) {
  Multimap<EventSlice, EventDTO> output = ArrayListMultimap.create();
  for (EventSlice slice : slices) {
    List<Predicate> predicates = DetectionUtils.buildPredicatesOnTime(slice.getStart(), slice.getEnd());

    if (predicates.isEmpty())
      throw new IllegalArgumentException("Must provide at least one of start, or end");
    List<EventDTO> events = this.eventDAO.findByPredicate(AND(predicates));
    Iterator<EventDTO> itEvent = events.iterator();
    while (itEvent.hasNext()) {
      if (!slice.match(itEvent.next())) {
        itEvent.remove();
      }
    }

    output.putAll(slice, events);
  }
  return output;
}
 
Example #4
Source File: AdminAuthorityServiceCache.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
/**
 * 设置首级菜单树
 *
 * @param aclDtoList
 * @return
 */
private List<AclLevelRes> aclListToTree(List<AclLevelRes> aclDtoList) {
    if (CollectionUtils.isEmpty(aclDtoList)) {
        return Lists.newArrayList();
    }
    // level -> [dept1, dept2, ...] Map<String, List<Object>>
    Multimap<String, AclLevelRes> levelDeptMap = ArrayListMultimap.create();
    List<AclLevelRes> rootList = Lists.newArrayList();

    for (AclLevelRes dto : aclDtoList) {
        levelDeptMap.put(dto.getSysAclLevel(), dto);
        if (LevelUtil.ROOT.equals(dto.getSysAclLevel())) {
            rootList.add(dto);
        }
    }
    // 按照seq从大到小排序
    rootList.sort((o1, o2) -> o2.getSysAclSeq() - o1.getSysAclSeq());
    // 递归生成树
    transformDeptTree(rootList, LevelUtil.ROOT, levelDeptMap);
    return rootList;
}
 
Example #5
Source File: RbacAuthorityService.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]}
 *
 * @return {@link ArrayListMultimap} 格式的 URL Mapping
 */
private Multimap<String, String> allUrlMapping() {
    Multimap<String, String> urlMapping = ArrayListMultimap.create();

    // 获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

    handlerMethods.forEach((k, v) -> {
        // 获取当前 key 下的获取所有URL
        Set<String> url = k.getPatternsCondition()
                .getPatterns();
        RequestMethodsRequestCondition method = k.getMethodsCondition();

        // 为每个URL添加所有的请求方法
        url.forEach(s -> urlMapping.putAll(s, method.getMethods()
                .stream()
                .map(Enum::toString)
                .collect(Collectors.toList())));
    });

    return urlMapping;
}
 
Example #6
Source File: AnalysisUtils.java    From bazel with 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 #7
Source File: TemplateProcessorTest.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Multimap<String, ReleaseNotesMessage> createNotes(
        List<ReleaseNotesMessage> breakingMessages,
        List<ReleaseNotesMessage> newFeatureMessages, List<ReleaseNotesMessage> bugMessages,
        List<ReleaseNotesMessage> miscMessages, List<ReleaseNotesMessage> newModuleMessages) {
    final Multimap<String, ReleaseNotesMessage> notes = ArrayListMultimap.create();

    if (breakingMessages != null) {
        notes.putAll(Constants.BREAKING_COMPATIBILITY_LABEL, breakingMessages);
    }
    if (newFeatureMessages != null) {
        notes.putAll(Constants.NEW_FEATURE_LABEL, newFeatureMessages);
    }
    if (bugMessages != null) {
        notes.putAll(Constants.BUG_LABEL, bugMessages);
    }
    if (miscMessages != null) {
        notes.putAll(Constants.MISCELLANEOUS_LABEL, miscMessages);
    }
    if (newModuleMessages != null) {
        notes.putAll(Constants.NEW_MODULE_LABEL, newModuleMessages);
    }

    return notes;
}
 
Example #8
Source File: PqlUtilsTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testLimit() throws Exception {
  MetricFunction metricFunction = new MetricFunction(MetricAggFunction.AVG, METRIC.getMetricName(), this.metricId, COLLECTION, null, null);

  TimeSpec timeSpec = new TimeSpec(METRIC.getMetricName(), TimeGranularity.fromString("1_SECONDS"), TimeSpec.SINCE_EPOCH_FORMAT);

  ThirdEyeRequest request = ThirdEyeRequest.newBuilder()
      .setMetricFunctions(Collections.singletonList(metricFunction))
      .setStartTimeInclusive(1000)
      .setEndTimeExclusive(2000)
      .setGroupBy("dimension")
      .setLimit(12345)
      .build("ref");

  String pql = PqlUtils.getPql(request, metricFunction, ArrayListMultimap.<String, String>create(), timeSpec);

  Assert.assertEquals(pql, "SELECT AVG(metric) FROM collection WHERE  metric >= 1 AND metric < 2 GROUP BY dimension TOP 12345");
}
 
Example #9
Source File: EntityUtilsTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeDimensionsExclusions() {
  Multimap<String, String> filters = ArrayListMultimap.create();
  filters.put("a", "A");
  filters.put("b", "!B");
  filters.put("c", "<C");
  filters.put("d", ">D");
  filters.put("e", "<=E");
  filters.put("f", ">=F");

  List<String> encoded = EntityUtils.encodeDimensions(filters);
  Assert.assertEquals(encoded.size(), 6);
  Assert.assertEquals(encoded.get(0), "a%3DA");
  Assert.assertEquals(encoded.get(1), "b!%3DB");
  Assert.assertEquals(encoded.get(2), "c%3CC");
  Assert.assertEquals(encoded.get(3), "d%3ED");
  Assert.assertEquals(encoded.get(4), "e%3C%3DE");
  Assert.assertEquals(encoded.get(5), "f%3E%3DF");
}
 
Example #10
Source File: PqlUtilsTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testLimitDefault() throws Exception {
  MetricFunction metricFunction = new MetricFunction(MetricAggFunction.AVG, METRIC.getMetricName(), this.metricId, COLLECTION, null, null);

  TimeSpec timeSpec = new TimeSpec(METRIC.getMetricName(), TimeGranularity.fromString("1_SECONDS"), TimeSpec.SINCE_EPOCH_FORMAT);

  ThirdEyeRequest request = ThirdEyeRequest.newBuilder()
      .setMetricFunctions(Collections.singletonList(metricFunction))
      .setStartTimeInclusive(1000)
      .setEndTimeExclusive(2000)
      .setGroupBy("dimension")
      .build("ref");

  String pql = PqlUtils.getPql(request, metricFunction, ArrayListMultimap.<String, String>create(), timeSpec);

  Assert.assertEquals(pql, "SELECT AVG(metric) FROM collection WHERE  metric >= 1 AND metric < 2 GROUP BY dimension TOP 100000");
}
 
Example #11
Source File: TaskDetailPrinter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ListMultimap<Class, Task> groupTasksByType(List<Task> tasks) {
    final Set<Class> taskTypes = new TreeSet<Class>(new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    taskTypes.addAll(collect(tasks, new Transformer<Class, Task>() {
        public Class transform(Task original) {
            return getDeclaredTaskType(original);
        }
    }));

    ListMultimap<Class, Task> tasksGroupedByType = ArrayListMultimap.create();
    for (final Class taskType : taskTypes) {
        tasksGroupedByType.putAll(taskType, filter(tasks, new Spec<Task>() {
            public boolean isSatisfiedBy(Task element) {
                return getDeclaredTaskType(element).equals(taskType);
            }
        }));
    }
    return tasksGroupedByType;
}
 
Example #12
Source File: CcToolchainFeaturesTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code Variables} configuration from a list of key/value pairs.
 *
 * <p>If there are multiple entries with the same key, the variable will be treated as sequence
 * type.
 */
private CcToolchainVariables createVariables(String... entries) {
  if (entries.length % 2 != 0) {
    throw new IllegalArgumentException(
        "createVariables takes an even number of arguments (key/value pairs)");
  }
  Multimap<String, String> entryMap = ArrayListMultimap.create();
  for (int i = 0; i < entries.length; i += 2) {
    entryMap.put(entries[i], entries[i + 1]);
  }
  CcToolchainVariables.Builder variables = CcToolchainVariables.builder();
  for (String name : entryMap.keySet()) {
    Collection<String> value = entryMap.get(name);
    if (value.size() == 1) {
      variables.addStringVariable(name, value.iterator().next());
    } else {
      variables.addStringSequenceVariable(name, ImmutableList.copyOf(value));
    }
  }
  return variables.build();
}
 
Example #13
Source File: LootOverlayPlugin.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
@Schedule(600)
public void pollLoot() {
    if (!isLoggedIn()) {
        return;
    }
    // Prepare the regex filter if required.
    checkFilter();

    // Group all loot by tile
    Multimap<Tile, Loot> tmpLootMap = ArrayListMultimap.create();
    Session.get().loot.find().distance(maximumDistance)
            .filter(acceptable -> {
                if (acceptable.getName().toLowerCase().matches(compiledFilter)) {
                    return !hideFiltered;
                }
                return filter.length() == 0 || hideFiltered;
            })
            .asList()
            .forEach(item -> {
                item.getComposite().getPrice();//force price to load
                if (item.getComposite().getPrice() >= minimumGePrice) {
                    tmpLootMap.put(item.getTile(), item);
                }
            });
    lootMap = tmpLootMap;
}
 
Example #14
Source File: BeforeAfterState.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
public Map<DBIdentity, UserDiff> diffState() throws SQLException, MitroServletException {
  // get the new state
  Multimap<Integer, Integer> newState = ArrayListMultimap.create();
  addUserDataToSet(userIdToSecretIds.keySet(), newState);
  
  Map<DBIdentity, UserDiff> rval = Maps.newHashMap();
  for (Integer uid : userIdToSecretIds.keySet()) {
    Set<Integer> preSecrets = Sets.newHashSet(userIdToSecretIds.get(uid));
    Set<Integer> postSecrets = Sets.newHashSet(newState.get(uid));
    UserDiff ud = new UserDiff();
    ud.removedSecrets = Sets.difference(preSecrets, postSecrets);
    ud.newSecrets = Sets.difference(postSecrets, preSecrets);
    if (ud.removedSecrets.isEmpty() && ud.newSecrets.isEmpty()) {
      continue;
    }

    // TODO: optimize this to one query instead of n queries.
    DBIdentity id = manager.identityDao.queryForId(uid);
    ud.userName = id.getName();
    rval.put(id, ud);
  }
  return rval;
}
 
Example #15
Source File: UserSyncServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
void testRemoveUsersFromGroupsNullMembersInResponse() throws Exception {
    Multimap<String, String> groupMapping = setupGroupMapping(1, 1);

    FreeIpaClient freeIpaClient = mock(FreeIpaClient.class);
    Group removeResponseGroup = mock(Group.class, RETURNS_DEEP_STUBS);
    RPCResponse<Group> mockRemoveResponse = mock(RPCResponse.class);
    when(mockRemoveResponse.getResult()).thenReturn(removeResponseGroup);
    // FreeIPA returns null when group is empty
    when(removeResponseGroup.getMemberUser()).thenReturn(null);
    when(freeIpaClient.groupRemoveMembers(any(), any())).thenReturn(mockRemoveResponse);
    Multimap<String, String> warnings = ArrayListMultimap.create();

    underTest.removeUsersFromGroups(freeIpaClient, groupMapping, warnings::put);

    assertTrue(warnings.isEmpty());
}
 
Example #16
Source File: ViewModelParser.java    From tasmo with Apache License 2.0 6 votes vote down vote up
public List<ViewBinding> parse(List<String> modelPathtrings) {
    ArrayListMultimap<String, ModelPath> viewBindings = ArrayListMultimap.create();

    for (String simpleBinding : modelPathtrings) {
        String[] class_pathId_modelPath = toStringArray(simpleBinding, "::");
        List<ModelPath> bindings = viewBindings.get(class_pathId_modelPath[0].trim());

        try {
            bindings.add(buildPath(class_pathId_modelPath[1].trim(), class_pathId_modelPath[2].trim()));
        } catch (Throwable t) {
            t.printStackTrace(System.out);
        }
    }

    List<ViewBinding> viewBindingsList = Lists.newArrayList();
    for (Map.Entry<String, Collection<ModelPath>> entry : viewBindings.asMap().entrySet()) {
        viewBindingsList.add(new ViewBinding(entry.getKey(), new ArrayList<>(entry.getValue()), false, true, null));
    }

    return viewBindingsList;
}
 
Example #17
Source File: StructuralVariantLegCopyNumberChangeFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private static ListMultimap<GenomePosition, StructuralVariant> cnaMap(@NotNull final Collection<StructuralVariant> variants) {
    final ListMultimap<GenomePosition, StructuralVariant> result = ArrayListMultimap.create();
    for (final StructuralVariant variant : variants) {
        final StructuralVariantLeg start = variant.start();
        result.put(GenomePositions.create(start.chromosome(), start.cnaPosition()), variant);

        @Nullable
        final StructuralVariantLeg end = variant.end();
        if (end != null) {
            result.put(GenomePositions.create(end.chromosome(), end.cnaPosition()), variant);
        }
    }

    return result;

}
 
Example #18
Source File: Summarizer.java    From tablesaw with Apache License 2.0 6 votes vote down vote up
/**
 * Associates the columns to be summarized with the functions that match their type. All valid
 * combinations are used
 *
 * @param group A table slice group
 * @param selectionFunction Function that provides the filter for the having clause
 * @return A table containing a row of summarized data for each group in the table slice group
 */
private Table summarizeForHaving(
    TableSliceGroup group, Function<Table, Selection> selectionFunction) {
  List<Table> results = new ArrayList<>();

  ArrayListMultimap<String, AggregateFunction<?, ?>> reductionMultimap =
      getAggregateFunctionMultimap();

  for (String name : reductionMultimap.keys()) {
    List<AggregateFunction<?, ?>> reductions = reductionMultimap.get(name);
    Table groupTable = group.aggregate(name, reductions.toArray(new AggregateFunction<?, ?>[0]));
    groupTable = groupTable.where(selectionFunction);
    if (!groupTable.isEmpty()) {
      results.add(groupTable);
    }
  }
  return combineTables(results);
}
 
Example #19
Source File: DruidAdapter2IT.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testMetadataColumns() throws Exception {
  sql("values 1")
      .withConnection(c -> {
        try {
          final DatabaseMetaData metaData = c.getMetaData();
          final ResultSet r =
              metaData.getColumns(null, null, "foodmart", null);
          Multimap<String, Boolean> map = ArrayListMultimap.create();
          while (r.next()) {
            map.put(r.getString("TYPE_NAME"), true);
          }
          if (CalciteSystemProperty.DEBUG.value()) {
            System.out.println(map);
          }
          // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
          assertThat(map.keySet().size(), is(4));
          assertThat(map.values().size(), is(92));
          assertThat(map.get("TIMESTAMP(0) NOT NULL").size(), is(1));
          assertThat(map.get("DOUBLE").size(), is(2));
          assertThat(map.get("BIGINT").size(), is(1));
          assertThat(map.get(VARCHAR_TYPE).size(), is(88));
        } catch (SQLException e) {
          throw TestUtil.rethrow(e);
        }
      });
}
 
Example #20
Source File: GlobalChangeSetApplier.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private GlobalChangeSetApplier( final TestReport testReport, final Counter counter ) {
	this.counter = counter;
	attributeDiffsLookupMap = ArrayListMultimap.create();
	insertedDiffsLookupMap = ArrayListMultimap.create();
	deletedDiffsLookupMap = ArrayListMultimap.create();
	actionChangeSetLookupMap = new HashMap<>();

	fillReplayResultLookupMaps( testReport );
}
 
Example #21
Source File: IndexedSourceAdapter.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
protected void indexQuery(List<StreamValue> out, Location location, ContextPlanner planner, List<IndexQuery> queries, List<OperatorNode<PhysicalExprOperator>> args) {
    // split IndexQuery by index and then invoke each index exactly once
    OperatorNode<PhysicalExprOperator> sourceAdapter = createSource(location, planner, args);
    Multimap<IndexKey, IndexQuery> split = ArrayListMultimap.create();
    for (IndexQuery query : queries) {
        split.put(query.index, query);
    }
    for (IndexKey idx : split.keySet()) {
        Collection<IndexQuery> todo = split.get(idx);
        selectMap.get(idx).index(out, location, sourceAdapter, planner, Lists.newArrayList(todo));
    }
}
 
Example #22
Source File: AnnotationIssueProcessor.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void processIssues(List<Issue> issues, IProgressMonitor monitor) {
	updateMarkersOnModelChange = false;
	List<Annotation> toBeRemoved = getAnnotationsToRemove(monitor);
	Multimap<Position, Annotation> positionToAnnotations = ArrayListMultimap.create();
	Map<Annotation, Position> annotationToPosition = getAnnotationsToAdd(positionToAnnotations, issues, monitor);
	updateMarkerAnnotations(monitor);
	updateAnnotations(monitor, toBeRemoved, annotationToPosition);
	updateMarkersOnModelChange = true;
}
 
Example #23
Source File: CallGraphEntity.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static CallGraphEntity fromEdge(double score, List<? extends Entity> related, DataFrame edge) {
  if (edge.size() != 1) {
    throw new IllegalArgumentException("Must provide a data frame with exactly one row");
  }

  Multimap<String, String> dimensions = ArrayListMultimap.create();
  for (String seriesName : edge.getSeriesNames()) {
    dimensions.put(seriesName, edge.getString(seriesName, 0));
  }

  return new CallGraphEntity(TYPE.formatURN(EntityUtils.encodeDimensions(dimensions)), score, related, edge);
}
 
Example #24
Source File: AbstractJavaNameBindingsExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ResolvedSourceCode getResolvedSourceCode(final String sourceCode,
		final Set<Set<ASTNode>> nodeBindings, final String filename,
		final Predicate<ASTNode> includeNode) {
	final SortedMap<Integer, String> tokenPositions = tokenizer
			.tokenListWithPos(sourceCode.toCharArray());
	final SortedMap<Integer, Integer> positionToIndex = getTokenIndexForPostion(tokenPositions);
	final List<String> tokens = Lists.newArrayList(tokenPositions.values());

	final ArrayListMultimap<String, TokenNameBinding> bindings = ArrayListMultimap
			.create();

	for (final Set<ASTNode> boundName : nodeBindings) {
		if (boundName.isEmpty()
				|| boundName.stream().noneMatch(includeNode)) {
			continue;
		}
		final List<Integer> boundPositions = Lists.newArrayList();
		for (final ASTNode name : boundName) {
			// Convert position to token index and add
			final int tokenIdx = positionToIndex.get(name
					.getStartPosition());
			boundPositions.add(tokenIdx);
		}
		bindings.put(tokens.get(boundPositions.get(0)),
				new TokenNameBinding(Sets.newTreeSet(boundPositions),
						tokens, getFeatures(boundName)));
	}

	return new ResolvedSourceCode(filename, tokens, bindings);
}
 
Example #25
Source File: Summarizer.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
/**
 * Associates the columns to be summarized with the functions that match their type. All valid
 * combinations are used
 *
 * @param group A table slice group
 * @return A table containing a row of summarized data for each group in the table slice group
 */
private Table summarize(TableSliceGroup group) {
  List<Table> results = new ArrayList<>();

  ArrayListMultimap<String, AggregateFunction<?, ?>> reductionMultimap =
      getAggregateFunctionMultimap();

  for (String name : reductionMultimap.keys()) {
    List<AggregateFunction<?, ?>> reductions = reductionMultimap.get(name);
    results.add(group.aggregate(name, reductions.toArray(new AggregateFunction<?, ?>[0])));
  }
  return combineTables(results);
}
 
Example #26
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEmptyValues() {
  setupSchema();
  assertTrue(StructuredData.isInitialized());
  assertEquals(
      new StructuredDataObject().setProperties(Collections.emptyList()),
      StructuredData.getStructuredData("myObject", ArrayListMultimap.create()));
  assertFalse(StructuredData.hasObjectDefinition("undefinedObject"));
}
 
Example #27
Source File: StructuredDataTest.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEmptyObjectDefinition() {
  Schema schema = new Schema();
  schema.setObjectDefinitions(
      Collections.singletonList(getObjectDefinition("myObject", Collections.emptyList())));
  StructuredData.init(schema);
  assertTrue(StructuredData.isInitialized());
  Multimap<String, Object> values = ArrayListMultimap.create();
  values.put("textProperty", "v1");
  values.put("textProperty", "v2");
  assertEquals(
      new StructuredDataObject().setProperties(Collections.emptyList()),
      StructuredData.getStructuredData("myObject", values));
  assertTrue(StructuredData.hasObjectDefinition("myObject"));
}
 
Example #28
Source File: DocServiceBuilder.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified example paths for the method with the specified service and method name.
 */
public DocServiceBuilder examplePaths(String serviceName, String methodName, Iterable<String> paths) {
    requireNonNull(serviceName, "serviceName");
    checkArgument(!serviceName.isEmpty(), "serviceName is empty.");
    requireNonNull(methodName, "methodName");
    checkArgument(!methodName.isEmpty(), "methodName is empty.");
    requireNonNull(paths, "paths");
    for (String examplePath : paths) {
        requireNonNull(examplePath, "paths contains null");
        examplePaths.computeIfAbsent(serviceName, unused -> ArrayListMultimap.create())
                    .put(methodName, examplePath);
    }
    return this;
}
 
Example #29
Source File: JoinCompiler.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PTableWrapper mergeProjectedTables(PTableWrapper lWrapper, PTableWrapper rWrapper, boolean innerJoin) throws SQLException {
	PTable left = lWrapper.getTable();
	PTable right = rWrapper.getTable();
	List<PColumn> merged = new ArrayList<PColumn>();
	merged.addAll(left.getColumns());
	int position = merged.size();
	for (PColumn c : right.getColumns()) {
		if (!SchemaUtil.isPKColumn(c)) {
			PColumnImpl column = new PColumnImpl(c.getName(), 
					PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), c.getDataType(), 
					c.getMaxLength(), c.getScale(), innerJoin ? c.isNullable() : true, position++, 
					c.getColumnModifier());
			merged.add(column);
		}
	}
    if (left.getBucketNum() != null) {
        merged.remove(0);
    }
    PTable t = PTableImpl.makePTable(left.getSchemaName(), PNameFactory.newName(SchemaUtil.getTableName(left.getName().getString(), right.getName().getString())),
            left.getType(), left.getIndexState(), left.getTimeStamp(), left.getSequenceNumber(), left.getPKName(), left.getBucketNum(), merged, left.getParentTableName(),
            left.getIndexes(), left.isImmutableRows(), null, null, null, null, PTable.DEFAULT_DISABLE_WAL, left.isMultiTenant(), left.getViewType());

    ListMultimap<String, String> mergedMap = ArrayListMultimap.<String, String>create();
    mergedMap.putAll(lWrapper.getColumnNameMap());
    mergedMap.putAll(rWrapper.getColumnNameMap());
    
    return new PTableWrapper(t, mergedMap);
}
 
Example #30
Source File: FilterByGroups.java    From xian with Apache License 2.0 5 votes vote down vote up
private static Multimap<String, UnitProxy> filterByUnitFullNames(Multimap<String, UnitProxy> units, List<String> groups) {
    Multimap<String, UnitProxy> results = ArrayListMultimap.create();
    for (String groupName : units.keySet()) {
        for (String group : groups) {
            if (Objects.equals(group, groupName))
                results.putAll(group, units.get(group));
        }
    }
    return results;
}