Java Code Examples for com.google.common.collect.ImmutableListMultimap#keySet()

The following examples show how to use com.google.common.collect.ImmutableListMultimap#keySet() . 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: ArtifactProblem.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns formatted string describing {@code problems} by removing similar problems per artifact.
 */
public static String formatProblems(Iterable<ArtifactProblem> problems) {
  ImmutableListMultimap<Artifact, ArtifactProblem> artifactToProblems =
      Multimaps.index(problems, ArtifactProblem::getArtifact);

  StringBuilder output = new StringBuilder();
  for (Artifact artifact : artifactToProblems.keySet()) {
    ImmutableList<ArtifactProblem> artifactProblems = artifactToProblems.get(artifact);
    int otherCount = artifactProblems.size() - 1;
    verify(otherCount >= 0, "artifactToProblems should have at least one value for one key");
    ArtifactProblem firstProblem = Iterables.getFirst(artifactProblems, null);
    output.append(firstProblem);
    if (otherCount == 1) {
      output.append(" and a problem on the same artifact.");
    } else if (otherCount > 1) {
      output.append(" and " + otherCount + " problems on the same artifact.");
    }
    output.append("\n");
  }
  return output.toString();
}
 
Example 2
Source File: DumpManager.java    From bundletool with Apache License 2.0 6 votes vote down vote up
void printResources(Predicate<ResourceTableEntry> resourcePredicate, boolean printValues) {
  ImmutableList<ResourceTable> resourceTables;
  try (ZipFile zipFile = new ZipFile(bundlePath.toFile())) {
    resourceTables =
        ZipUtils.allFileEntriesPaths(zipFile)
            .filter(path -> path.endsWith(SpecialModuleEntry.RESOURCE_TABLE.getPath()))
            .map(path -> extractAndParse(zipFile, path, ResourceTable::parseFrom))
            .collect(toImmutableList());
  } catch (IOException e) {
    throw new UncheckedIOException("Error occurred when reading the bundle.", e);
  }

  ImmutableListMultimap<String, ResourceTableEntry> entriesByPackageName =
      resourceTables.stream()
          .flatMap(ResourcesUtils::entries)
          .filter(resourcePredicate)
          .collect(groupingBySortedKeys(entry -> entry.getPackage().getPackageName()));

  for (String packageName : entriesByPackageName.keySet()) {
    printStream.printf("Package '%s':%n", packageName);
    entriesByPackageName.get(packageName).forEach(entry -> printEntry(entry, printValues));
    printStream.println();
  }
}
 
Example 3
Source File: SwaggerGenerator.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private Swagger writeSwagger(Iterable<ApiConfig> configs, SwaggerContext context,
    GenerationContext genCtx)
    throws ApiConfigException {
  ImmutableListMultimap<ApiKey, ? extends ApiConfig> configsByKey = FluentIterable.from(configs)
      .index(CONFIG_TO_ROOTLESS_KEY);
  Swagger swagger = new Swagger()
      .produces("application/json")
      .consumes("application/json")
      .scheme(context.scheme)
      .host(context.hostname)
      .basePath(context.basePath)
      .info(new Info()
          .title(context.hostname)
          .version(context.docVersion));
  for (ApiKey apiKey : configsByKey.keySet()) {
    writeApi(apiKey, configsByKey.get(apiKey), swagger, genCtx);
  }
  writeQuotaDefinitions(swagger, genCtx);
  return swagger;
}
 
Example 4
Source File: MultiArchBinarySupport.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all child configurations for this multi-arch target, mapped to the toolchains that they
 * should use.
 */
static ImmutableMap<BuildConfiguration, CcToolchainProvider> getChildConfigurationsAndToolchains(
    RuleContext ruleContext) {
  ImmutableListMultimap<BuildConfiguration, ToolchainInfo> configToProvider =
      ruleContext.getPrerequisitesByConfiguration(
          ObjcRuleClasses.CHILD_CONFIG_ATTR, TransitionMode.SPLIT, ToolchainInfo.PROVIDER);

  ImmutableMap.Builder<BuildConfiguration, CcToolchainProvider> result = ImmutableMap.builder();
  for (BuildConfiguration config : configToProvider.keySet()) {
    CcToolchainProvider toolchain =
        (CcToolchainProvider) Iterables.getOnlyElement(configToProvider.get(config));
    result.put(config, toolchain);
  }

  return result.build();
}
 
Example 5
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private String dependencyPathToArtifacts(
    ResolvedComponentResult componentResult, Set<ClassPathEntry> classPathEntries) {

  ImmutableSet<String> targetCoordinates =
      classPathEntries.stream()
          .map(ClassPathEntry::getArtifact)
          .map(Artifacts::toCoordinates)
          .collect(toImmutableSet());

  StringBuilder output = new StringBuilder();

  ArrayDeque<ResolvedComponentResult> stack = new ArrayDeque<>();
  stack.add(componentResult);

  ImmutableListMultimap.Builder<String, String> coordinatesToDependencyPaths =
      ImmutableListMultimap.builder();

  recordDependencyPaths(coordinatesToDependencyPaths, stack, targetCoordinates);

  ImmutableListMultimap<String, String> dependencyPaths = coordinatesToDependencyPaths.build();
  for (String coordinates : dependencyPaths.keySet()) {
    output.append(coordinates + " is at:\n");
    for (String dependencyPath : dependencyPaths.get(coordinates)) {
      output.append("  " + dependencyPath + "\n");
    }
  }

  return output.toString();
}
 
Example 6
Source File: SameTargetingMerger.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableList<ModuleSplit> merge(ImmutableCollection<ModuleSplit> moduleSplits) {
  checkArgument(
      moduleSplits.stream().map(ModuleSplit::getVariantTargeting).distinct().count() == 1,
      "SameTargetingMerger doesn't support merging splits from different variants.");
  ImmutableList.Builder<ModuleSplit> result = ImmutableList.builder();
  ImmutableListMultimap<ApkTargeting, ModuleSplit> splitsByTargeting =
      Multimaps.index(moduleSplits, ModuleSplit::getApkTargeting);
  for (ApkTargeting targeting : splitsByTargeting.keySet()) {
    result.add(mergeSplits(splitsByTargeting.get(targeting)));
  }
  return result.build();
}
 
Example 7
Source File: DiscoveryGenerator.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
public Result writeDiscovery(
    Iterable<ApiConfig> configs, DiscoveryContext context, SchemaRepository schemaRepository) {
  ImmutableListMultimap<ApiKey, ApiConfig> configsByKey = Multimaps.index(configs,
      new Function<ApiConfig, ApiKey>() {
        @Override public ApiKey apply(ApiConfig config) {
          return config.getApiKey();
        }
      });
  ImmutableMap.Builder<ApiKey, RestDescription> builder = ImmutableMap.builder();
  // "Default" API versions were determined automagically in legacy endpoints.
  // This version only allows to remove an API from default ones by adding
  // defaultVersion = AnnotationBoolean.FALSE to @Api
  ImmutableSet.Builder<ApiKey> preferred = ImmutableSet.builder();
  for (ApiKey apiKey : configsByKey.keySet()) {
    ImmutableList<ApiConfig> apiConfigs = configsByKey.get(apiKey);
    if (context.generateAll || apiConfigs.get(0).getIsDiscoverable()) {
      builder.put(apiKey, writeApi(apiKey, apiConfigs, context, schemaRepository));
      // last config takes precedence (same as writeApi)
      if (Iterables.getLast(apiConfigs).getIsDefaultVersion()) {
        preferred.add(apiKey);
      }
    }
  }
  ImmutableMap<ApiKey, RestDescription> discoveryDocs = builder.build();
  return Result.builder()
      .setDiscoveryDocs(discoveryDocs)
      .setDirectory(generateDirectory(discoveryDocs, preferred.build(), context))
      .build();
}
 
Example 8
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkMultipleAnnotations(final XtendAnnotationTarget annotationTarget) {
	if (annotationTarget.getAnnotations().size() <= 1 || !isRelevantAnnotationTarget(annotationTarget)) {
		return;
	}
	
	ImmutableListMultimap<String, XAnnotation> groupByIdentifier = Multimaps.index(annotationTarget.getAnnotations(),
			new Function<XAnnotation, String>() {
				@Override
				public String apply(XAnnotation input) {
					return input.getAnnotationType().getIdentifier();
				}
			});

	for (String qName : groupByIdentifier.keySet()) {
		ImmutableList<XAnnotation> sameType = groupByIdentifier.get(qName);
		if (sameType.size() > 1) {
			JvmType type = sameType.get(0).getAnnotationType();
			if (type instanceof JvmAnnotationType && !type.eIsProxy()
					&& !annotationLookup.isRepeatable((JvmAnnotationType) type)) {
				for (XAnnotation xAnnotation : sameType) {
					error("Multiple annotations of non-repeatable type @"
							+ xAnnotation.getAnnotationType().getSimpleName()
							+ ". Only annotation types marked @Repeatable can be used multiple times at one target.",
							xAnnotation, XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, INSIGNIFICANT_INDEX, ANNOTATION_MULTIPLE);
				}
			}
		}
	}
}
 
Example 9
Source File: BinaryOperationSuffixExpressionParser.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Override
@Label("BinaryOperationSuffix Expression")
public Rule ExpressionRule() {
    Rule initialExpression = EMPTY;
    ImmutableListMultimap<Integer, BinaryOperator> index = Multimaps.index(operators, precedence());

    List<Integer> integers = new ArrayList<>(index.keySet());
    Collections.sort(integers);
    for (Integer integer : integers) {
        initialExpression = BinaryOperation(initialExpression, index.get(integer));
    }
    return initialExpression;
}
 
Example 10
Source File: SortACollection.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Display top wrestlers in each weight class
 */
@Test
public void sort_collection_with_multiple_comparables_guava_getfirstElement() {

	// first order elements
	Collections.sort(wrestlers, byWeightClass.compound(byWins.reverse()));

	// next get the first wrestler in each weight class which should have
	// the most wins
	ImmutableListMultimap<Double, Wrestler> wrestlersMappedByWeightClass = Multimaps
			.index(wrestlers, new Function<Wrestler, Double>() {
				public Double apply(Wrestler from) {
					return new Double(from.getWeightClass());
				}
			});

	logger.info(wrestlersMappedByWeightClass);

	// for each weight class get the first element which should be wrestler
	// with most wins
	for (Double weightClass : wrestlersMappedByWeightClass.keySet()) {

		List<Wrestler> weightClassWrestlers = wrestlersMappedByWeightClass
				.get(weightClass);
		logger.info(weightClass + " - "
				+ Iterables.getFirst(weightClassWrestlers, null));
	}
}
 
Example 11
Source File: ApkSerializerManager.java    From bundletool with Apache License 2.0 4 votes vote down vote up
private ImmutableList<Variant> serializeApks(
    GeneratedApks generatedApks, ApkBuildMode apkBuildMode, Optional<DeviceSpec> deviceSpec) {
  validateInput(generatedApks, apkBuildMode);

  // Running with system APK mode generates a fused APK and additional unmatched language splits.
  // To avoid filtering of unmatched language splits we skip device filtering for system mode.
  Predicate<ModuleSplit> deviceFilter =
      deviceSpec.isPresent() && !apkBuildMode.isAnySystemMode()
          ? new ApkMatcher(deviceSpec.get())::matchesModuleSplitByTargeting
          : alwaysTrue();

  ImmutableListMultimap<VariantKey, ModuleSplit> splitsByVariant =
      generatedApks.getAllApksGroupedByOrderedVariants();

  // Assign the variant numbers to each variant present.
  AtomicInteger variantNumberCounter = new AtomicInteger(firstVariantNumber);
  ImmutableMap<VariantKey, Integer> variantNumberByVariantKey =
      splitsByVariant.keySet().stream()
          .collect(toImmutableMap(identity(), unused -> variantNumberCounter.getAndIncrement()));

  // 1. Remove APKs not matching the device spec.
  // 2. Modify the APKs based on the ApkModifier.
  // 3. Serialize all APKs in parallel.
  ApkSerializer apkSerializer = new ApkSerializer(apkListener, apkBuildMode);

  // Modifies the APK using APK modifier, then returns a map by extracting the variant
  // of APK first and later clearing out its variant targeting.

  ImmutableListMultimap<VariantKey, ModuleSplit> finalSplitsByVariant =
      splitsByVariant.entries().stream()
          .filter(keyModuleSplitEntry -> deviceFilter.test(keyModuleSplitEntry.getValue()))
          .collect(
              groupingBySortedKeys(
                  Entry::getKey,
                  entry ->
                      clearVariantTargeting(
                          modifyApk(
                              entry.getValue(), variantNumberByVariantKey.get(entry.getKey())))));

  checkState(!finalSplitsByVariant.isEmpty(), "Internal error: No variants were generated.");

  // After variant targeting of APKs are cleared, there might be duplicate APKs
  // which are removed and the distinct APKs are then serialized in parallel.
  // Note: Only serializing compressed system APK produces multiple ApkDescriptions,
  // i.e compressed and stub APK descriptions.
  ImmutableMap<ModuleSplit, ImmutableList<ApkDescription>> apkDescriptionBySplit =
      finalSplitsByVariant.values().stream()
          .distinct()
          .collect(
              collectingAndThen(
                  toImmutableMap(
                      identity(),
                      (ModuleSplit split) -> {
                        ZipPath apkPath = apkPathManager.getApkPath(split);
                        return executorService.submit(
                            () -> apkSerializer.serialize(split, apkPath));
                      }),
                  ConcurrencyUtils::waitForAll));

  // Build the result proto.
  ImmutableList.Builder<Variant> variants = ImmutableList.builder();
  for (VariantKey variantKey : finalSplitsByVariant.keySet()) {
    Variant.Builder variant =
        Variant.newBuilder()
            .setVariantNumber(variantNumberByVariantKey.get(variantKey))
            .setTargeting(variantKey.getVariantTargeting());

    Multimap<BundleModuleName, ModuleSplit> splitsByModuleName =
        finalSplitsByVariant.get(variantKey).stream()
            .collect(groupingBySortedKeys(ModuleSplit::getModuleName));

    for (BundleModuleName moduleName : splitsByModuleName.keySet()) {
      variant.addApkSet(
          ApkSet.newBuilder()
              .setModuleMetadata(appBundle.getModule(moduleName).getModuleMetadata())
              .addAllApkDescription(
                  splitsByModuleName.get(moduleName).stream()
                      .flatMap(split -> apkDescriptionBySplit.get(split).stream())
                      .collect(toImmutableList())));
    }
    variants.add(variant.build());
  }

  return variants.build();
}
 
Example 12
Source File: JsonLdSerializer.java    From schemaorg-java with Apache License 2.0 4 votes vote down vote up
private void writeObject(JsonWriter out, Thing value, boolean isTopLevelObject)
    throws IOException {
  if (value instanceof Enumeration) {
    throw new JsonLdSyntaxException(
        String.format(
            "Enumeration value '%s' cannot be a JSON-LD entity",
            ((Enumeration) value).getFullEnumValue()));
  }
  out.beginObject();
  // @context should be at the top of generated JSON-LD entity if exists.
  writeContext(out, value, isTopLevelObject);
  out.name(JsonLdConstants.TYPE).value(shortNameOf(value.getFullTypeName()));
  ImmutableListMultimap<String, ValueType> properties =
      ((SchemaOrgTypeImpl) value).getAllProperties();
  for (String key : properties.keySet()) {
    if (key.equals(JsonLdConstants.CONTEXT)) {
      continue;
    } else if (key.equals(JsonLdConstants.ID)) {
      out.name(key);
      try {
        String id = value.getJsonLdId();
        if (id == null) {
          out.nullValue();
        } else {
          out.value(id);
        }
      } catch (SchemaOrgException e) {
        throw new JsonLdSyntaxException(
            String.format("Multiple value found for @id in type %s", value.getFullTypeName()));
      }
    } else {
      out.name(shortNameOf(key));
      List<SchemaOrgType> values = ((SchemaOrgTypeImpl) value).getProperty(key);
      if (values.size() == 0) {
        throw new JsonLdSyntaxException(
            String.format(
                "Schema.org type %s's property %s has no value", value.getFullTypeName(), key));
      } else if (values.size() == 1) {
        writeInternal(out, values.get(0));
      } else {
        writeArray(out, values);
      }
    }
  }
  writeReverse(out, value.getJsonLdReverseMap());
  out.endObject();
}
 
Example 13
Source File: Publisher.java    From buck with Apache License 2.0 4 votes vote down vote up
public ImmutableSet<DeployResult> publish(
    SourcePathResolverAdapter pathResolver, ImmutableSet<MavenPublishable> publishables)
    throws DeploymentException {
  ImmutableListMultimap<UnflavoredBuildTarget, UnflavoredBuildTarget> duplicateBuiltinBuileRules =
      checkForDuplicatePackagedDeps(publishables);
  if (duplicateBuiltinBuileRules.size() > 0) {
    StringBuilder sb = new StringBuilder();
    sb.append("Duplicate transitive dependencies for publishable libraries found!  This means");
    sb.append(StandardSystemProperty.LINE_SEPARATOR);
    sb.append("that the following libraries would have multiple copies if these libraries were");
    sb.append(StandardSystemProperty.LINE_SEPARATOR);
    sb.append("used together.  The can be resolved by adding a maven URL to each target listed");
    sb.append(StandardSystemProperty.LINE_SEPARATOR);
    sb.append("below:");
    for (UnflavoredBuildTarget unflavoredBuildTargetView : duplicateBuiltinBuileRules.keySet()) {
      sb.append(StandardSystemProperty.LINE_SEPARATOR);
      sb.append(unflavoredBuildTargetView.getFullyQualifiedName());
      sb.append(" (referenced by these build targets: ");
      Joiner.on(", ").appendTo(sb, duplicateBuiltinBuileRules.get(unflavoredBuildTargetView));
      sb.append(")");
    }
    throw new DeploymentException(sb.toString());
  }

  ImmutableSet.Builder<DeployResult> deployResultBuilder = ImmutableSet.builder();
  for (MavenPublishable publishable : publishables) {
    DefaultArtifact coords =
        new DefaultArtifact(
            Preconditions.checkNotNull(
                publishable.getMavenCoords().get(),
                "No maven coordinates specified for published rule ",
                publishable));
    Path relativePathToOutput =
        pathResolver.getRelativePath(
            Preconditions.checkNotNull(
                publishable.getSourcePathToOutput(),
                "No path to output present in ",
                publishable));
    File mainItem = publishable.getProjectFilesystem().resolve(relativePathToOutput).toFile();

    if (!coords.getClassifier().isEmpty()) {
      deployResultBuilder.add(publish(coords, ImmutableList.of(mainItem)));
    }

    try {
      // If this is the "main" artifact (denoted by lack of classifier) generate and publish
      // pom alongside
      File pom = Pom.generatePomFile(pathResolver, publishable).toFile();
      deployResultBuilder.add(publish(coords, ImmutableList.of(mainItem, pom)));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  return deployResultBuilder.build();
}