Java Code Examples for com.google.common.collect.ImmutableMultimap#get()

The following examples show how to use com.google.common.collect.ImmutableMultimap#get() . 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: Actions.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public String blame(XmlDocument xmlDocument)
        throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping =
            getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(
            new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;
    int count = 1;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count).append("-->")
                        .append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}
 
Example 2
Source File: Actions.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
public String blame(XmlDocument xmlDocument)
        throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping =
            getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(
            new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;
    int count = 0;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count + 1).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count + 1).append("-->")
                        .append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}
 
Example 3
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 6 votes vote down vote up
private void writeReverse(JsonWriter out, ImmutableMultimap<String, Thing> map)
    throws IOException {
  Set<String> keySet = map.keySet();
  if (keySet.size() == 0) {
    return;
  }
  out.name(JsonLdConstants.REVERSE);
  out.beginObject();
  for (String key : keySet) {
    out.name(shortNameOf(key));
    Collection<Thing> values = map.get(key);
    if (values.size() == 0) {
      throw new JsonLdSyntaxException(
          String.format("JSON-LD reverse property %s has no value", key));
    } else if (values.size() == 1) {
      writeObject(out, (Thing) values.toArray()[0], false /* isTopLevelObject */);
    } else {
      out.beginArray();
      for (Thing value : values) {
        writeObject(out, value, false /* isTopLevelObject */);
      }
      out.endArray();
    }
  }
  out.endObject();
}
 
Example 4
Source File: DropwizardInvalidationTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) {
    String name = checkNotNull(Iterables.getFirst(parameters.get("cache"), null), "cache");
    String scopeString = Iterables.getFirst(parameters.get("scope"), "LOCAL");
    InvalidationScope scope = InvalidationScope.valueOf(scopeString.toUpperCase());
    Collection<String> keys = parameters.get("key");
    boolean invalidateAll = keys.isEmpty();

    CacheHandle handle = _registry.lookup(name, false);
    if (handle == null) {
        out.println("Cache not found: " + name);
        return;
    }

    if (invalidateAll) {
        handle.invalidateAll(scope);
    } else {
        handle.invalidateAll(scope, keys);
    }

    out.println("Done!");
}
 
Example 5
Source File: Actions.java    From buck with Apache License 2.0 6 votes vote down vote up
@NonNull
public String blame(@NonNull XmlDocument xmlDocument)
        throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping =
            getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(
            new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;
    int count = 0;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count + 1).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count + 1).append("-->")
                        .append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}
 
Example 6
Source File: DedupMigrationTask.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    boolean oldEnabled = _dedupEnabled.get();
    boolean newEnabled = oldEnabled;

    for (String value : parameters.get("dedup")) {
        newEnabled = Boolean.parseBoolean(value);
        _dedupEnabled.set(newEnabled);
    }

    out.printf("dedup-enabled: %s%n", newEnabled);

    Collection<String> migrations = parameters.get("migrate");
    if (!migrations.isEmpty()) {
        if (newEnabled) {
            out.println("Ignoring migrations since Databus dedup is still enabled.");
        } else {
            if (oldEnabled) {
                out.println("Sleeping 15 seconds to allow in-flight requests to complete.");
                out.flush();
                Thread.sleep(Duration.seconds(15).toMilliseconds());
            }
            migrate(migrations, out);
        }
    }
}
 
Example 7
Source File: AndroidBinaryGraphEnhancer.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Group DexProducedFromJavaLibrary rules by module, into partitions of at most
 * dex_group_lib_limit. Create a single partition per APK module if dex_group_lib_limit is 0
 */
private ImmutableMultimap<APKModule, List<DexProducedFromJavaLibrary>> groupDexes(
    ImmutableMultimap<APKModule, DexProducedFromJavaLibrary> dexFilesToMerge) {
  ImmutableMultimap.Builder<APKModule, List<DexProducedFromJavaLibrary>> resultBuilder =
      ImmutableMultimap.builder();

  int limit = dexSplitMode.getDexGroupLibLimit();
  for (APKModule module : dexFilesToMerge.keySet()) {
    List<DexProducedFromJavaLibrary> currentDexContents = null;
    for (DexProducedFromJavaLibrary dexWithClasses : dexFilesToMerge.get(module)) {
      if (currentDexContents == null || (limit != 0 && currentDexContents.size() + 1 > limit)) {
        currentDexContents = new ArrayList<>();
        resultBuilder.put(module, currentDexContents);
      }
      currentDexContents.add(dexWithClasses);
    }
  }
  return resultBuilder.build();
}
 
Example 8
Source File: APKModuleGraph.java    From buck with Apache License 2.0 6 votes vote down vote up
private void verifyNoSharedSeeds() {
  ImmutableMultimap<BuildTarget, String> sharedSeeds = sharedSeedsSupplier.get();
  if (!sharedSeeds.isEmpty()) {
    StringBuilder errorMessage = new StringBuilder();
    for (BuildTarget seed : sharedSeeds.keySet()) {
      errorMessage
          .append("BuildTarget: ")
          .append(seed)
          .append(" is used as seed in multiple modules: ");
      for (String module : sharedSeeds.get(seed)) {
        errorMessage.append(module).append(' ');
      }
      errorMessage.append('\n');
    }
    throw new IllegalArgumentException(errorMessage.toString());
  }
}
 
Example 9
Source File: JSqlSchema.java    From kafka-eagle with Apache License 2.0 5 votes vote down vote up
@Override
protected Multimap<String, Function> getFunctionMultimap() {
	ImmutableMultimap<String, ScalarFunction> funcs = ScalarFunctionImpl.createAll(JSONFunction.class);
	Multimap<String, Function> functions = HashMultimap.create();
	for (String key : funcs.keySet()) {
		for (ScalarFunction func : funcs.get(key)) {
			functions.put(key, func);
		}
	}
	return functions;
}
 
Example 10
Source File: APKModuleGraph.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Group the classes in the input jars into a multimap based on the APKModule they belong to
 *
 * @param apkModuleToJarPathMap the mapping of APKModules to the path for the jar files
 * @param translatorFunction function used to translate the class names to obfuscated names
 * @param filesystem filesystem representation for resolving paths
 * @return The mapping of APKModules to the class names they contain
 * @throws IOException
 */
public static ImmutableMultimap<APKModule, String> getAPKModuleToClassesMap(
    ImmutableMultimap<APKModule, Path> apkModuleToJarPathMap,
    Function<String, String> translatorFunction,
    ProjectFilesystem filesystem)
    throws IOException {
  ImmutableMultimap.Builder<APKModule, String> builder = ImmutableSetMultimap.builder();
  if (!apkModuleToJarPathMap.isEmpty()) {
    for (APKModule dexStore : apkModuleToJarPathMap.keySet()) {
      for (Path jarFilePath : apkModuleToJarPathMap.get(dexStore)) {
        ClasspathTraverser classpathTraverser = new DefaultClasspathTraverser();
        classpathTraverser.traverse(
            new ClasspathTraversal(ImmutableSet.of(jarFilePath), filesystem) {
              @Override
              public void visit(FileLike entry) {
                if (!entry.getRelativePath().endsWith(".class")) {
                  // ignore everything but class files in the jar.
                  return;
                }

                String classpath = entry.getRelativePath().replaceAll("\\.class$", "");

                if (translatorFunction.apply(classpath) != null) {
                  builder.put(dexStore, translatorFunction.apply(classpath));
                }
              }
            });
      }
    }
  }
  return builder.build();
}
 
Example 11
Source File: BlazeGoPackageFactory.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static ConcurrentMap<File, String> buildFileToImportPathMap(
    Project project, BlazeProjectData projectData) {
  TargetMap targetMap = projectData.getTargetMap();
  ConcurrentMap<File, String> map = new ConcurrentHashMap<>();
  ImmutableMultimap<Label, File> targetToFile =
      BlazeGoPackage.getTargetToFileMap(project, projectData);
  for (TargetIdeInfo target : targetMap.targets()) {
    if (target.getGoIdeInfo() == null) {
      continue;
    }
    String importPath =
        target.getGoIdeInfo().getLibraryLabels().stream()
            .map(TargetKey::forPlainTarget)
            .map(targetMap::get)
            .filter(Objects::nonNull)
            .map(TargetIdeInfo::getGoIdeInfo)
            .filter(Objects::nonNull)
            .map(GoIdeInfo::getImportPath)
            .filter(Objects::nonNull)
            .findFirst()
            .orElse(target.getGoIdeInfo().getImportPath());
    if (importPath == null) {
      continue;
    }
    for (File file : targetToFile.get(target.getKey().getLabel())) {
      map.putIfAbsent(file, importPath);
    }
  }
  return map;
}
 
Example 12
Source File: SourceToTargetMapImpl.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableCollection<TargetKey> getRulesForSourceFile(File sourceFile) {
  ImmutableMultimap<File, TargetKey> sourceToTargetMap = getSourceToTargetMap();
  if (sourceToTargetMap == null) {
    return ImmutableList.of();
  }
  return sourceToTargetMap.get(sourceFile);
}
 
Example 13
Source File: SearchCluster.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static Optional<Node> findLocalCorpusDispatchTarget(String selfHostname,
                                                            int searchClusterSize,
                                                            int containerClusterSize,
                                                            ImmutableMultimap<String, Node> nodesByHost,
                                                            ImmutableMap<Integer, Group> groups) {
    // A search node in the search cluster in question is configured on the same host as the currently running container.
    // It has all the data <==> No other nodes in the search cluster have the same group id as this node.
    //         That local search node responds.
    // The search cluster to be searched has at least as many nodes as the container cluster we're running in.
    ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname);
    // Only use direct dispatch if we have exactly 1 search node on the same machine:
    if (localSearchNodes.size() != 1) return Optional.empty();

    Node localSearchNode = localSearchNodes.iterator().next();
    Group localSearchGroup = groups.get(localSearchNode.group());

    // Only use direct dispatch if the local search node has the entire corpus
    if (localSearchGroup.nodes().size() != 1) return Optional.empty();

    // Only use direct dispatch if this container cluster has at least as many nodes as the search cluster
    // to avoid load skew/preserve fanout in the case where a subset of the search nodes are also containers.
    // This disregards the case where the search and container clusters are partially overlapping.
    // Such configurations produce skewed load in any case.
    if (containerClusterSize < searchClusterSize) return Optional.empty();

    return Optional.of(localSearchNode);
}
 
Example 14
Source File: TableChangesEnabledTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    for (String enabled : parameters.get("enabled")) {
        _enabled.set(new BooleanParam(enabled).get());

        Thread.sleep(500);  // Wait for values to round trip through ZooKeeper.
    }

    out.printf("Table create/drop/update operations and table maintenance are: %s%n",
            _enabled.get() ? "ENABLED" : "DISABLED");
}
 
Example 15
Source File: DrainFanoutPartitionTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
private String getOnlyParameter(String name, ImmutableMultimap<String, String> parameters) {
    Collection<String> values = parameters.get(name);
    if (values.size() != 1) {
        return null;
    }
    return values.iterator().next();
}
 
Example 16
Source File: ReplicationEnabledTask.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
    for (String enabled : parameters.get("enabled")) {
        _enabled.set(new BooleanParam(enabled).get());

        Thread.sleep(500);  // Wait for values to round trip through ZooKeeper.
    }

    out.printf("Databus inbound event replication from other data centers is: %s%n",
            _enabled.get() ? "ENABLED" : "DISABLED");
}
 
Example 17
Source File: StandardScoringAligner.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
@Override
public EventArgScoringAlignment<EquivClassType> align(final AnswerKey answerKey,
    final ArgumentOutput argumentOutput) {
  checkArgument(answerKey.docId() == argumentOutput.docId());
  final ImmutableMultimap<EquivClassType, Response> equivClassToSystemResponses = Multimaps.index(
      argumentOutput.responses(), equivClassFunction);
  final ImmutableMultimap<EquivClassType, AssessedResponse> equivClassToAnswerKeyResponses =
      Multimaps.index(
          answerKey.annotatedResponses(),
          Functions.compose(equivClassFunction, AssessedResponseFunctions.response()));

  final ImmutableSet<EquivClassType> allEquivClasses =
      Sets.union(equivClassToSystemResponses.keySet(),
          equivClassToAnswerKeyResponses.keySet()).immutableCopy();

  final ImmutableSet.Builder<EquivClassType> truePositives = ImmutableSet.builder();
  final ImmutableSet.Builder<EquivClassType> falsePositives = ImmutableSet.builder();
  final ImmutableSet.Builder<EquivClassType> falseNegatives = ImmutableSet.builder();
  final ImmutableSet.Builder<EquivClassType> unassessed = ImmutableSet.builder();

  for (final EquivClassType eqivClass : allEquivClasses) {
    // a key equivalence class is correct if anyone found a correct response in that class
    final ImmutableCollection<AssessedResponse> answerKeyResponsesForEC =
        equivClassToAnswerKeyResponses.get(eqivClass);
    final boolean isCorrectEquivClass = !FluentIterable.
        from(answerKeyResponsesForEC)
        .filter(AssessedResponse.IsCorrectUpToInexactJustifications)
        .isEmpty();

    final ImmutableCollection<Response> systemResponsesForEC = equivClassToSystemResponses.get(
        eqivClass);

    if (isCorrectEquivClass) {
      // only the top-scoring system response for an equivalence class counts
      final Optional<Response> selectedSystemResponse =
          argumentOutput.selectFromMultipleSystemResponses(
              equivClassToSystemResponses.get(eqivClass));

      if (selectedSystemResponse.isPresent()) {
        final Optional<AssessedResponse> assessmentOfSelectedResponse =
            AssessedResponse.findAnnotationForArgument(
                selectedSystemResponse.get(), answerKeyResponsesForEC);
        if (assessmentOfSelectedResponse.isPresent()) {
          if (assessmentOfSelectedResponse.get().isCorrectUpToInexactJustifications()) {
            truePositives.add(eqivClass);
          } else {
            // it was a correct equivalence class, but we the system response for that
            // equivalence class was incorrect (e.g. due to bad justifications).
            // This counts as both a false positive and a false negative. Note that there
            // could be a correct system response for the equivalence class which has a lower
            // confidence, but it won't count.
            falseNegatives.add(eqivClass);
            falsePositives.add(eqivClass);
          }
        } else {
          // the best system response for this equivalence class is unassessed
          unassessed.add(eqivClass);
        }
      } else {
        // it was a correct equivalence class, but we didn't find any responses
        falseNegatives.add(eqivClass);
      }
    } else {
      // if the equivalence class is incorrect, the system is wrong if it returned *any* response
      if (!systemResponsesForEC.isEmpty()) {
        falsePositives.add(eqivClass);
      } else {
        // do nothing - it was a true negative
      }
    }
  }

  return EventArgScoringAlignment
      .create(argumentOutput.docId(), argumentOutput, answerKey, truePositives.build(),
          falsePositives.build(),
          falseNegatives.build(), unassessed.build(), equivClassToAnswerKeyResponses,
          equivClassToSystemResponses);
}
 
Example 18
Source File: PreDexedFilesSorterTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private ImmutableMap<String, PreDexedFilesSorter.Result> generatePreDexSorterResults(
    int numberOfPrimaryDexes, int numberOfSecondaryDexes, int numberOfExtraDexes)
    throws IOException {
  FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
  ImmutableMultimap.Builder<APKModule, DexWithClasses> inputDexes = ImmutableMultimap.builder();
  for (int i = 0; i < numberOfPrimaryDexes; i++) {
    inputDexes.put(
        moduleGraph.getRootAPKModule(),
        createFakeDexWithClasses(
            filesystem,
            Paths.get("primary").resolve(String.format("primary%d.dex", i)),
            ImmutableSet.of(String.format("primary.primary%d.class", i)),
            STANDARD_DEX_FILE_ESTIMATE));
  }
  for (int i = 0; i < numberOfSecondaryDexes; i++) {
    inputDexes.put(
        moduleGraph.getRootAPKModule(),
        createFakeDexWithClasses(
            filesystem,
            Paths.get("secondary").resolve(String.format("secondary%d.dex", i)),
            ImmutableSet.of(String.format("secondary.secondary%d.class", i)),
            STANDARD_DEX_FILE_ESTIMATE));
  }
  for (int i = 0; i < numberOfExtraDexes; i++) {
    inputDexes.put(
        extraModule,
        createFakeDexWithClasses(
            filesystem,
            Paths.get("extra").resolve(String.format("extra%d.dex", i)),
            ImmutableSet.of(String.format("extra.extra%d.class", i)),
            STANDARD_DEX_FILE_ESTIMATE));
  }

  ImmutableMultimap<APKModule, DexWithClasses> dexes = inputDexes.build();
  ImmutableMap.Builder<String, PreDexedFilesSorter.Result> results = ImmutableMap.builder();
  ImmutableList.Builder<Step> steps = ImmutableList.builder();

  for (APKModule module : dexes.keySet()) {
    PreDexedFilesSorter sorter =
        new PreDexedFilesSorter(
            dexes.get(module),
            ImmutableSet.of(PRIMARY_DEX_PATTERN),
            moduleGraph,
            module,
            tempDir.newFolder(module.getName(), "scratch").toPath(),
            DEX_WEIGHT_LIMIT,
            DexStore.JAR,
            tempDir.newFolder(module.getName(), "secondary").toPath(),
            Optional.empty());
    results.put(module.getName(), sorter.sortIntoPrimaryAndSecondaryDexes(filesystem, steps));
  }
  return results.build();
}