Java Code Examples for com.google.common.collect.Multimap.putAll()

The following are Jave code examples for showing how to use putAll() of the com.google.common.collect.Multimap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: spring2ts   File: AnnotationUtils.java   Source Code and License Vote up 6 votes
public static Multimap<String, String> getAnnotationAsMap(org.jboss.forge.roaster.model.Annotation<?> annotation,
                                                    Class<? extends Annotation> type) {

    if(annotation == null) return null;
    List<Method> methods = getAnnotationAttributes(type);
    Multimap<String, String> result = HashMultimap.create();
    for (Method method : methods) {
        String name = method.getName();
        boolean array = method.getReturnType().isArray();
        String value = annotation.getLiteralValue(name);
        if(StringUtils.isBlank(value)) continue;
        String [] values = array
                ? annotation.getStringArrayValue(name) : new String[]{annotation.getStringValue(name)};
        if(allElementsNull(values)) continue;
        result.putAll(name, Arrays.asList(values));
    }
    return result;
}
 
Example 2
Project: dremio-oss   File: ScanResult.java   Source Code and License Vote up 6 votes
/**
 * merges this and other together into a new result object
 * @param other
 * @return the resulting merge
 */
public ScanResult merge(ScanResult other) {
  final Multimap<String, ChildClassDescriptor> newImpls = HashMultimap.create();
  for (Collection<ParentClassDescriptor> impls : asList(implementations, other.implementations)) {
    for (ParentClassDescriptor c : impls) {
      newImpls.putAll(c.getName(), c.getChildren());
    }
  }
  List<ParentClassDescriptor> newImplementations = new ArrayList<>();
  for (Entry<String, Collection<ChildClassDescriptor>> entry : newImpls.asMap().entrySet()) {
    newImplementations.add(new ParentClassDescriptor(entry.getKey(), new ArrayList<>(entry.getValue())));
  }

  return new ScanResult(
      merge(scannedPackages, other.scannedPackages),
      merge(scannedClasses, other.scannedClasses),
      merge(scannedAnnotations, other.scannedAnnotations),
      merge(annotatedClasses, other.annotatedClasses),
      newImplementations);
}
 
Example 3
Project: apollo-custom   File: WatchKeysUtil.java   Source Code and License Vote up 6 votes
/**
 * Assemble watch keys for the given appId, cluster, namespaces, dataCenter combination
 *
 * @return a multimap with namespace as the key and watch keys as the value
 */
public Multimap<String, String> assembleAllWatchKeys(String appId, String clusterName,
                                                     Set<String> namespaces,
                                                     String dataCenter) {
  Multimap<String, String> watchedKeysMap =
      assembleWatchKeys(appId, clusterName, namespaces, dataCenter);

  //Every app has an 'application' namespace
  if (!(namespaces.size() == 1 && namespaces.contains(ConfigConsts.NAMESPACE_APPLICATION))) {
    Set<String> namespacesBelongToAppId = namespacesBelongToAppId(appId, namespaces);
    Set<String> publicNamespaces = Sets.difference(namespaces, namespacesBelongToAppId);

    //Listen on more namespaces if it's a public namespace
    if (!publicNamespaces.isEmpty()) {
      watchedKeysMap
          .putAll(findPublicConfigWatchKeys(appId, clusterName, publicNamespaces, dataCenter));
    }
  }

  return watchedKeysMap;
}
 
Example 4
Project: apollo-custom   File: WatchKeysUtil.java   Source Code and License Vote up 6 votes
private Multimap<String, String> findPublicConfigWatchKeys(String applicationId,
                                                           String clusterName,
                                                           Set<String> namespaces,
                                                           String dataCenter) {
  Multimap<String, String> watchedKeysMap = HashMultimap.create();
  List<AppNamespace> appNamespaces = appNamespaceService.findPublicNamespacesByNames(namespaces);

  for (AppNamespace appNamespace : appNamespaces) {
    //check whether the namespace's appId equals to current one
    if (Objects.equals(applicationId, appNamespace.getAppId())) {
      continue;
    }

    String publicConfigAppId = appNamespace.getAppId();

    watchedKeysMap.putAll(appNamespace.getName(),
        assembleWatchKeys(publicConfigAppId, clusterName, appNamespace.getName(), dataCenter));
  }

  return watchedKeysMap;
}
 
Example 5
Project: n4js   File: SelectAllProjectExplorer_PluginUITest.java   Source Code and License Vote up 5 votes
@Override
@Before
public void setUp() throws Exception {
	super.setUp();
	waitForIdleState();
	projectExplorer = (ProjectExplorer) showView(ProjectExplorer.VIEW_ID);
	waitForUiThread();
	assertNotNull("Cannot show Project Explorer.", projectExplorer);
	commonViewer = projectExplorer.getCommonViewer();
	assertFalse("Expected projects as top level elements in navigator.", broker.isWorkingSetTopLevel());
	assertNull(
			"Select working set drop down contribution was visible when projects are configured as top level elements.",
			getWorkingSetDropDownContribution());

	final Multimap<ProjectType, String> typeNamesMapping = HashMultimap.create();

	typeNamesMapping.putAll(LIBRARY, LIBRARY_PROJECTS);
	typeNamesMapping.putAll(TEST, TEST_PROJECTS);
	for (final Entry<ProjectType, Collection<String>> entry : typeNamesMapping.asMap().entrySet()) {
		for (final String projectName : entry.getValue()) {
			createN4JSProject(projectName, entry.getKey());
		}
	}

	// Actually close "Closed*" projects
	closeProject("ClosedL2");
	closeProject("ClosedT2");

	// Wait for workbench to reflect project changes
	waitForIdleState();
	commonViewer.refresh();

	// Disable auto-building, as there is no real code to build involved
	ResourcesPlugin.getWorkspace().getDescription().setAutoBuilding(false);
}
 
Example 6
Project: graphouse   File: MetricTreeTest.java   Source Code and License Vote up 5 votes
private Multimap<String, String> generate() {
    Multimap<String, String> pattern2Candidates = ArrayListMultimap.create();
    pattern2Candidates.putAll("msh0[1-6]d_market_yandex_net", Arrays.asList("msh01d_market_yandex_net", "msh03d_market_yandex_net"));
    pattern2Candidates.putAll("min.market-front*.e", Arrays.asList("min.market-front.e", "min.market-front-ugr.e"));
    pattern2Candidates.putAll("min.market-front{-ugr,-fol}.e", Arrays.asList("min.market-front-fol.e", "min.market-front-ugr.e"));
    pattern2Candidates.putAll("min.market-front{,-ugr,-fol}.e", Arrays.asList("min.market-front.e", "min.market-front-ugr.e"));
    return pattern2Candidates;
}
 
Example 7
Project: sentry   File: ChartUtil.java   Source Code and License Vote up 5 votes
public static <T> List<Series> getSeriesFromData(List<T> counts,
                                                 Function<T, String> seriesMapper,
                                                 Function<T, ZonedDateTime> timeMapper,
                                                 Function<T, Long> valueMapper) {
    // create a map of categories to x-y pairs
    Multimap<String, Point> byRegion = counts.stream()
        .collect(toMultimap(
            seriesMapper,
            count -> new Point(timeMapper.apply(count).toEpochSecond() * 1000, valueMapper.apply(count)),
            MultimapBuilder.treeKeys().hashSetValues()::build));
    // build a list of default values x-0 for each category
    Set<Long> timestamps = counts.stream()
        .map(count -> timeMapper.apply(count).toEpochSecond())
        .collect(Collectors.toSet());
    Multimap<String, Point> defaults = byRegion.keySet().stream()
        .collect(flatteningToMultimap(
            region -> region,
            region -> timestamps.stream().map(timestamp -> new Point(timestamp * 1000, 0)),
            MultimapBuilder.treeKeys().hashSetValues()::build));
    byRegion.putAll(defaults);
    log.debug("{} across {} found",
        inflect(byRegion.size(), "data point"), inflect(timestamps.size(), "timestamp"));
    // convert to expected structure
    return byRegion.asMap().entrySet().stream()
        .map(entry -> new Series(entry.getKey()).values(
            entry.getValue().stream()
                .map(pair -> Arrays.asList(pair.getX(), pair.getY()))
                .sorted(Comparator.comparingInt(o -> o.get(0).intValue()))
                .collect(Collectors.toList())))
        .collect(Collectors.toList());
}
 
Example 8
Project: ProjectAres   File: MapDevelopmentCommands.java   Source Code and License Vote up 5 votes
@Command(
    aliases = {"errors", "xmlerrors"},
    usage = "[-p page] [map name]",
    desc = "Reads back XML errors",
    min = 0,
    max = -1,
    flags = "p:"
)
@CommandPermissions(Permissions.MAPERRORS)
public List<String> errorsCommand(CommandContext args, final CommandSender sender) throws CommandException {
    final String mapName = args.argsLength() > 0 ? args.getJoinedStrings(0) : "";
    if(args.getSuggestionContext() != null) {
        return tc.oc.pgm.commands.CommandUtils.completeMapName(mapName);
    }

    Multimap<MapDefinition, MapLogRecord> errors = mapErrorTracker.getErrors();
    PGMMap filterMap = null;
    if(!mapName.isEmpty()) {
        filterMap = tc.oc.pgm.commands.CommandUtils.getMap(mapName, sender);
        Multimap<MapDefinition, MapLogRecord> filtered = ArrayListMultimap.create();
        filtered.putAll(filterMap, errors.get(filterMap));
        errors = filtered;
    }

    new PrettyPaginatedResult<Map.Entry<MapDefinition, MapLogRecord>>(filterMap == null ? "Map Errors (" + errors.keySet().size() + " maps)"
                                                                                        : filterMap.getName() + " Errors") {
        @Override
        public String format(Map.Entry<MapDefinition, MapLogRecord> entry, int index) {
            return entry.getValue().getLegacyFormattedMessage();
        }

        @Override
        public String formatEmpty() {
            return ChatColor.GREEN + PGMTranslations.get().t("command.development.listErrors.noErrors", sender);
        }
    }.display(new BukkitWrappedCommandSender(sender), errors.entries(), args.getFlagInteger('p', 1));
    return null;
}
 
Example 9
Project: kafka-connect-cdc-mssql   File: MsSqlQueryBuilder.java   Source Code and License Vote up 5 votes
String changeTrackingStatementQuery(TableMetadataProvider.TableMetadata tableMetadata) {
  Preconditions.checkState(
      tableMetadata.keyColumns().size() > 0,
      "Table([%s].[%s]) must have at least one primary key column.",
      tableMetadata.schemaName(),
      tableMetadata.tableName()
  );
  Collection<String> valueColumns = Collections2.filter(tableMetadata.columnSchemas().keySet(), Predicates.not(Predicates.in(tableMetadata.keyColumns())));

  String joinCriteria = joinCriteria(tableMetadata.keyColumns());
  Multimap<String, String> adfs = LinkedListMultimap.create();
  adfs.putAll("ct", tableMetadata.keyColumns());
  adfs.putAll("u", valueColumns);


  final String sql = String.format("SELECT " +
          "[ct].[sys_change_version] AS [__metadata_sys_change_version], " +
          "[ct].[sys_change_creation_version] AS [__metadata_sys_change_creation_version], " +
          "[ct].[sys_change_operation] AS [__metadata_sys_change_operation], " +
          joinSelect(adfs) + " " +
          "FROM [%s].[%s] AS [u] " +
          "RIGHT OUTER JOIN " +
          "CHANGETABLE(CHANGES [%s].[%s], ?) AS [ct] " +
          "ON %s",
      tableMetadata.schemaName(),
      tableMetadata.tableName(),
      tableMetadata.schemaName(),
      tableMetadata.tableName(),
      joinCriteria
  );
  log.trace("changeTrackingStatementQuery() - sql:\n{}", sql);
  return sql;
}
 
Example 10
Project: Fir   File: Fir.java   Source Code and License Vote up 5 votes
public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Usage: java -jar Fir.jar <input>");
        System.err.println("Input can be a single file, multiple files, or a directory, which will be scanned recursively.");
        System.exit(1);
    }

    // Add inputs
    List<File> inputs = new ArrayList<>();
    Multimap<String, Map<String, Object>> output = HashMultimap.create();
    for (String inputString : args) {
        File file = new File(inputString);
        if (!file.exists()) {
            continue;
        }

        addInputFilesRecursively(inputs, file);
    }

    // Produce outputs
    for (File input : inputs) {
        List<Map<String, Object>> processed = processInput(input);
        if (processed != null) {
            output.putAll(input.getPath(), processed);
        }
    }

    // Print JSON output
    System.out.println(gson.toJson(output.asMap()));
}
 
Example 11
Project: apollo-custom   File: WatchKeysUtil.java   Source Code and License Vote up 5 votes
private Multimap<String, String> assembleWatchKeys(String appId, String clusterName,
                                                   Set<String> namespaces,
                                                   String dataCenter) {
  Multimap<String, String> watchedKeysMap = HashMultimap.create();

  for (String namespace : namespaces) {
    watchedKeysMap
        .putAll(namespace, assembleWatchKeys(appId, clusterName, namespace, dataCenter));
  }

  return watchedKeysMap;
}
 
Example 12
Project: pandionj   File: ObjectModel.java   Source Code and License Vote up 5 votes
public Multimap<String, String> getAttributeTags() {
	Multimap<String, String> map = ArrayListMultimap.create();

	for(VariableModel<IJavaObject, IEntityModel> r : references.values()) {
		if(r.hasTags())
			map.putAll(r.getName(), r.getTags());
	}
	return map;
}
 
Example 13
Project: apollo-custom   File: NotificationControllerV2Test.java   Source Code and License Vote up 4 votes
@Test
public void testPollNotificationWithMultipleNamespaces() throws Exception {
  String defaultNamespaceAsFile = defaultNamespace + ".properties";
  String somePublicNamespaceAsFile = somePublicNamespace + ".xml";

  when(namespaceUtil.filterNamespaceName(defaultNamespaceAsFile)).thenReturn(defaultNamespace);
  when(namespaceUtil.filterNamespaceName(somePublicNamespaceAsFile)).thenReturn(somePublicNamespaceAsFile);
  when(namespaceUtil.normalizeNamespace(someAppId, somePublicNamespaceAsFile)).thenReturn(somePublicNamespaceAsFile);

  String someWatchKey = "someKey";
  String anotherWatchKey = "anotherKey";
  String somePublicWatchKey = "somePublicWatchKey";
  String somePublicFileWatchKey = "somePublicFileWatchKey";

  Multimap<String, String> watchKeysMap =
      assembleMultiMap(defaultNamespace, Lists.newArrayList(someWatchKey, anotherWatchKey));
  watchKeysMap
      .putAll(assembleMultiMap(somePublicNamespace, Lists.newArrayList(somePublicWatchKey)));
  watchKeysMap
      .putAll(assembleMultiMap(somePublicNamespaceAsFile,
          Lists.newArrayList(somePublicFileWatchKey)));

  String notificationAsString =
      transformApolloConfigNotificationsToString(defaultNamespaceAsFile, someNotificationId,
          somePublicNamespace, someNotificationId, somePublicNamespaceAsFile,
          someNotificationId);

  when(watchKeysUtil
      .assembleAllWatchKeys(someAppId, someCluster,
          Sets.newHashSet(defaultNamespace, somePublicNamespace, somePublicNamespaceAsFile),
          someDataCenter)).thenReturn(
      watchKeysMap);

  DeferredResult<ResponseEntity<List<ApolloConfigNotification>>>
      deferredResult = controller
      .pollNotification(someAppId, someCluster, notificationAsString, someDataCenter,
          someClientIp);

  assertEquals(watchKeysMap.size(), deferredResults.size());

  assertWatchKeys(watchKeysMap, deferredResult);

  verify(watchKeysUtil, times(1)).assembleAllWatchKeys(someAppId, someCluster,
      Sets.newHashSet(defaultNamespace, somePublicNamespace, somePublicNamespaceAsFile),
      someDataCenter);
}
 
Example 14
Project: apollo-custom   File: NotificationControllerV2Test.java   Source Code and License Vote up 4 votes
@Test
public void testPollNotificationWithMultipleNamespaceWithNotificationIdOutDated()
    throws Exception {
  String someWatchKey = "someKey";
  String anotherWatchKey = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
      .join(someAppId, someCluster, somePublicNamespace);
  String yetAnotherWatchKey = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
      .join(someAppId, defaultCluster, somePublicNamespace);
  long notificationId = someNotificationId + 1;
  long yetAnotherNotificationId = someNotificationId;

  Multimap<String, String> watchKeysMap =
      assembleMultiMap(defaultNamespace, Lists.newArrayList(someWatchKey));
  watchKeysMap
      .putAll(assembleMultiMap(somePublicNamespace, Lists.newArrayList(anotherWatchKey, yetAnotherWatchKey)));

  when(watchKeysUtil
      .assembleAllWatchKeys(someAppId, someCluster,
          Sets.newHashSet(defaultNamespace, somePublicNamespace), someDataCenter)).thenReturn(
      watchKeysMap);

  ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
  when(someReleaseMessage.getId()).thenReturn(notificationId);
  when(someReleaseMessage.getMessage()).thenReturn(anotherWatchKey);
  ReleaseMessage yetAnotherReleaseMessage = mock(ReleaseMessage.class);
  when(yetAnotherReleaseMessage.getId()).thenReturn(yetAnotherNotificationId);
  when(yetAnotherReleaseMessage.getMessage()).thenReturn(yetAnotherWatchKey);
  when(releaseMessageService
      .findLatestReleaseMessagesGroupByMessages(Sets.newHashSet(watchKeysMap.values())))
      .thenReturn(Lists.newArrayList(someReleaseMessage, yetAnotherReleaseMessage));

  String notificationAsString =
      transformApolloConfigNotificationsToString(defaultNamespace, someNotificationId,
          somePublicNamespace, someNotificationId);

  DeferredResult<ResponseEntity<List<ApolloConfigNotification>>>
      deferredResult = controller
      .pollNotification(someAppId, someCluster, notificationAsString, someDataCenter,
          someClientIp);

  ResponseEntity<List<ApolloConfigNotification>> result =
      (ResponseEntity<List<ApolloConfigNotification>>) deferredResult.getResult();

  assertEquals(HttpStatus.OK, result.getStatusCode());
  assertEquals(1, result.getBody().size());
  assertEquals(somePublicNamespace, result.getBody().get(0).getNamespaceName());
  assertEquals(notificationId, result.getBody().get(0).getNotificationId());

  ApolloNotificationMessages notificationMessages = result.getBody().get(0).getMessages();
  assertEquals(2, notificationMessages.getDetails().size());
  assertEquals(notificationId, notificationMessages.get(anotherWatchKey).longValue());
  assertEquals(yetAnotherNotificationId, notificationMessages.get(yetAnotherWatchKey).longValue());
}
 
Example 15
Project: apollo-custom   File: NotificationControllerV2Test.java   Source Code and License Vote up 4 votes
@Test
public void testPollNotificationWithMultipleNamespacesAndHandleMessage() throws Exception {
  String someWatchKey = "someKey";
  String anotherWatchKey = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
      .join(someAppId, someCluster, somePublicNamespace);

  Multimap<String, String> watchKeysMap =
      assembleMultiMap(defaultNamespace, Lists.newArrayList(someWatchKey));
  watchKeysMap
      .putAll(assembleMultiMap(somePublicNamespace, Lists.newArrayList(anotherWatchKey)));

  when(watchKeysUtil
      .assembleAllWatchKeys(someAppId, someCluster,
          Sets.newHashSet(defaultNamespace, somePublicNamespace), someDataCenter)).thenReturn(
      watchKeysMap);

  String notificationAsString =
      transformApolloConfigNotificationsToString(defaultNamespace, someNotificationId,
          somePublicNamespace, someNotificationId);

  DeferredResult<ResponseEntity<List<ApolloConfigNotification>>>
      deferredResult = controller
      .pollNotification(someAppId, someCluster, notificationAsString, someDataCenter,
          someClientIp);

  assertEquals(watchKeysMap.size(), deferredResults.size());

  long someId = 1;
  ReleaseMessage someReleaseMessage = new ReleaseMessage(anotherWatchKey);
  someReleaseMessage.setId(someId);

  controller.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);

  ResponseEntity<List<ApolloConfigNotification>> response =
      (ResponseEntity<List<ApolloConfigNotification>>) deferredResult.getResult();

  assertEquals(1, response.getBody().size());
  ApolloConfigNotification notification = response.getBody().get(0);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  assertEquals(somePublicNamespace, notification.getNamespaceName());
  assertEquals(someId, notification.getNotificationId());

  ApolloNotificationMessages notificationMessages = response.getBody().get(0).getMessages();
  assertEquals(1, notificationMessages.getDetails().size());
  assertEquals(someId, notificationMessages.get(anotherWatchKey).longValue());
}
 
Example 16
Project: apollo-custom   File: NotificationControllerV2Test.java   Source Code and License Vote up 4 votes
private Multimap<String, String> assembleMultiMap(String key, Iterable<String> values) {
  Multimap<String, String> multimap = HashMultimap.create();
  multimap.putAll(key, values);
  return multimap;
}