Java Code Examples for com.google.common.collect.ImmutableSortedSet#orderedBy()

The following examples show how to use com.google.common.collect.ImmutableSortedSet#orderedBy() . 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: ResourceTable.java    From buck with Apache License 2.0 6 votes vote down vote up
public static ResourceTable slice(ResourceTable table, Map<Integer, Integer> countsToExtract) {
  ResTablePackage newPackage = ResTablePackage.slice(table.resPackage, countsToExtract);

  StringPool strings = table.strings;
  // Figure out what strings are used by the retained references.
  ImmutableSortedSet.Builder<Integer> stringRefs =
      ImmutableSortedSet.orderedBy(
          Comparator.comparing(strings::getString).thenComparingInt(i -> i));
  newPackage.visitStringReferences(stringRefs::add);
  ImmutableList<Integer> stringsToExtract = stringRefs.build().asList();
  ImmutableMap<Integer, Integer> stringMapping =
      Maps.uniqueIndex(
          IntStream.range(0, stringsToExtract.size())::iterator, stringsToExtract::get);

  // Extract a StringPool that contains just the strings used by the new package.
  // This drops styles.
  StringPool newStrings =
      StringPool.create(stringsToExtract.stream().map(strings::getString)::iterator);

  // Adjust the string references.
  newPackage.transformStringReferences(stringMapping::get);

  return new ResourceTable(newStrings, newPackage);
}
 
Example 2
Source File: ConfigCommand.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ConfigurationDiffForOutput getConfigurationDiffForOutput(
    String configHash1,
    String configHash2,
    Table<Class<? extends FragmentOptions>, String, Pair<Object, Object>> diffs) {
  ImmutableSortedSet.Builder<FragmentDiffForOutput> fragmentDiffs =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  diffs.rowKeySet().stream()
      .forEach(
          fragmentClass -> {
            String fragmentName =
                fragmentClass.equals(UserDefinedFragment.class)
                    ? UserDefinedFragment.DESCRIPTIVE_NAME
                    : fragmentClass.getName();
            ImmutableSortedMap<String, Pair<String, String>> sortedOptionDiffs =
                diffs.row(fragmentClass).entrySet().stream()
                    .collect(
                        toImmutableSortedMap(
                            Ordering.natural(),
                            Map.Entry::getKey,
                            e -> toNullableStringPair(e.getValue())));
            fragmentDiffs.add(new FragmentDiffForOutput(fragmentName, sortedOptionDiffs));
          });
  return new ConfigurationDiffForOutput(
      configHash1, configHash2, ImmutableList.copyOf(fragmentDiffs.build()));
}
 
Example 3
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 4
Source File: TestCommand.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
Iterable<TestRule> filterTestRules(
    BuckConfig buckConfig,
    ImmutableSet<BuildTarget> explicitBuildTargets,
    Iterable<TestRule> testRules) {

  ImmutableSortedSet.Builder<TestRule> builder =
      ImmutableSortedSet.orderedBy(Comparator.comparing(TestRule::getFullyQualifiedName));

  for (TestRule rule : testRules) {
    boolean explicitArgument = explicitBuildTargets.contains(rule.getBuildTarget());
    boolean matchesLabel = isMatchedByLabelOptions(buckConfig, rule.getLabels());

    // We always want to run the rules that are given on the command line. Always. Unless we don't
    // want to.
    if (shouldExcludeWin() && !matchesLabel) {
      continue;
    }

    // The testRules Iterable contains transitive deps of the arguments given on the command line,
    // filter those out if such is the user's will.
    if (shouldExcludeTransitiveTests() && !explicitArgument) {
      continue;
    }

    // Normal behavior is to include all rules that match the given label as well as any that
    // were explicitly specified by the user.
    if (explicitArgument || matchesLabel) {
      builder.add(rule);
    }
  }

  return builder.build();
}
 
Example 5
Source File: IjProjectWriter.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Update the modules.xml file with any new modules from the given set */
private void updateModulesIndex(ImmutableSet<IjModule> modulesEdited) throws IOException {
  final Set<ModuleIndexEntry> existingModules =
      modulesParser.getAllModules(
          projectFilesystem.newFileInputStream(getIdeaConfigDir().resolve("modules.xml")));
  final Set<Path> existingModuleFilepaths =
      existingModules.stream()
          .map(ModuleIndexEntry::getFilePath)
          .map(PathFormatter::pathWithUnixSeparators)
          .map(Paths::get)
          .collect(ImmutableSet.toImmutableSet());
  ImmutableSet<Path> remainingModuleFilepaths =
      modulesEdited.stream()
          .map(projectPaths::getModuleImlFilePath)
          .map(PathFormatter::pathWithUnixSeparators)
          .map(Paths::get)
          .filter(modulePath -> !existingModuleFilepaths.contains(modulePath))
          .collect(ImmutableSet.toImmutableSet());

  // Merge the existing and new modules into a single sorted set
  ImmutableSortedSet.Builder<ModuleIndexEntry> finalModulesBuilder =
      ImmutableSortedSet.orderedBy(Comparator.<ModuleIndexEntry>naturalOrder());
  // Add the existing definitions
  finalModulesBuilder.addAll(existingModules);
  // Add any new module definitions that we haven't seen yet
  remainingModuleFilepaths.forEach(
      modulePath ->
          finalModulesBuilder.add(
              ModuleIndexEntry.of(
                  getUrl(projectPaths.getProjectQualifiedPath(modulePath)),
                  projectPaths.getProjectRelativePath(modulePath),
                  projectConfig.getModuleGroupName())));

  // Write out the merged set to disk
  writeModulesIndex(finalModulesBuilder.build());
}
 
Example 6
Source File: ConfiguredRuleClassProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Returns all registered {@link Fragment} classes. */
public ImmutableSortedSet<Class<? extends Fragment>> getAllFragments() {
  ImmutableSortedSet.Builder<Class<? extends Fragment>> fragmentsBuilder =
      ImmutableSortedSet.orderedBy(BuildConfiguration.lexicalFragmentSorter);
  for (ConfigurationFragmentFactory factory : getConfigurationFragments()) {
    fragmentsBuilder.add(factory.creates());
  }
  fragmentsBuilder.addAll(getUniversalFragments());
  return fragmentsBuilder.build();
}
 
Example 7
Source File: PublishCommandIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private static ImmutableSortedSet<ZipEntry> getZipContents(File zipFile) throws IOException {
  assertTrue(zipFile + " should exits", zipFile.isFile());
  ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFile));
  Builder<ZipEntry> zipEntries =
      ImmutableSortedSet.orderedBy(Comparator.comparing(ZipEntry::getName));
  ZipEntry entry = inputStream.getNextEntry();
  while (entry != null) {
    zipEntries.add(entry);
    entry = inputStream.getNextEntry();
  }
  return zipEntries.build();
}
 
Example 8
Source File: JimfsFileSystem.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // safe cast of immutable set
@Override
public ImmutableSortedSet<Path> getRootDirectories() {
  ImmutableSortedSet.Builder<JimfsPath> builder = ImmutableSortedSet.orderedBy(pathService);
  for (Name name : fileStore.getRootDirectoryNames()) {
    builder.add(pathService.createRoot(name));
  }
  return (ImmutableSortedSet<Path>) (ImmutableSortedSet<?>) builder.build();
}
 
Example 9
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 10
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 11
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 12
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 13
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 14
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 15
Source File: DataJanitorStateTest.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedSet<byte[]> toISet(byte[]... args) {
  ImmutableSortedSet.Builder<byte[]> builder = ImmutableSortedSet.orderedBy(Bytes.BYTES_COMPARATOR);
  for (byte[] arg : args) {
    builder.add(arg);
  }
  return builder.build();
}
 
Example 16
Source File: FilterLineReachabilityAnswerer.java    From batfish with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static BlockingProperties findBlockingPropsForLine(
    int blockedLineNum, List<PermitAndDenyBdds> bdds) {
  PermitAndDenyBdds blockedLine = bdds.get(blockedLineNum);

  ImmutableSortedSet.Builder<LineAndWeight> linesByWeight =
      ImmutableSortedSet.orderedBy(LineAndWeight.COMPARATOR);

  // First, we find all lines before blockedLine that actually terminate any packets
  // blockedLine intends to. These, collectively, are the (partially-)blocking lines.
  //
  // In this same loop, we also compute the overlap of each such line with the blocked line
  // and weight each blocking line by that overlap.
  //
  // Finally, we record whether any of these lines has a different action than the blocked line.
  PermitAndDenyBdds restOfLine = blockedLine;
  boolean diffAction = false; // true if some partially-blocking line has a different action.
  for (int prevLineNum = 0; prevLineNum < blockedLineNum && !restOfLine.isZero(); prevLineNum++) {
    PermitAndDenyBdds prevLine = bdds.get(prevLineNum);

    if (!prevLine.getMatchBdd().andSat(restOfLine.getMatchBdd())) {
      continue;
    }

    BDD blockedLineOverlap = prevLine.getMatchBdd().and(blockedLine.getMatchBdd());
    linesByWeight.add(new LineAndWeight(prevLineNum, blockedLineOverlap.satCount()));
    diffAction = diffAction || takeDifferentActions(prevLine, restOfLine);
    restOfLine = restOfLine.diff(prevLine.getMatchBdd());
  }

  // In this second loop, we compute the answer:
  // * include partially-blocking lines in weight order until the blocked line is fully blocked by
  //   this subset.
  // * also include the largest blocking line with a different action than the blocked line, if
  //   not already in the above subset.
  ImmutableSortedSet.Builder<Integer> answerLines = ImmutableSortedSet.naturalOrder();
  restOfLine = blockedLine;
  boolean needDiffAction = diffAction;
  for (LineAndWeight line : linesByWeight.build()) {
    int curLineNum = line.getLine();
    PermitAndDenyBdds curLine = bdds.get(curLineNum);
    boolean curDiff = takeDifferentActions(curLine, blockedLine);

    // The original line is still not blocked, or this is the first line with a different action.
    if (!restOfLine.isZero() || needDiffAction && curDiff) {
      restOfLine = restOfLine.diff(curLine.getMatchBdd());
      answerLines.add(curLineNum);
      needDiffAction = needDiffAction && !curDiff;
    }

    // The original line is blocked and we have a line with a different action (if such exists).
    if (restOfLine.isZero() && !needDiffAction) {
      break;
    }
  }

  return new BlockingProperties(answerLines.build(), diffAction);
}
 
Example 17
Source File: AutoFactoryProcessor.java    From auto with Apache License 2.0 4 votes vote down vote up
private static ImmutableSortedSet.Builder<TypeMirror> newTypeSetBuilder() {
  return ImmutableSortedSet.orderedBy(
      Comparator.comparing(t -> MoreTypes.asTypeElement(t).getQualifiedName().toString()));
}
 
Example 18
Source File: ConfigCommand.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Constructs a {@link ConfigurationForOutput} from the given input daata. */
private static ConfigurationForOutput getConfigurationForOutput(
    BuildConfigurationValue.Key skyKey,
    String configHash,
    BuildConfiguration config,
    ImmutableSortedMap<
            Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
        fragmentDefs) {

  ImmutableSortedSet.Builder<FragmentForOutput> fragments =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  for (Map.Entry<Class<? extends Fragment>, ImmutableSortedSet<Class<? extends FragmentOptions>>>
      entry : fragmentDefs.entrySet()) {
    fragments.add(
        new FragmentForOutput(
            entry.getKey().getName(),
            entry.getValue().stream().map(clazz -> clazz.getName()).collect(toList())));
  }
  fragmentDefs.entrySet().stream()
      .filter(entry -> config.hasFragment(entry.getKey()))
      .forEach(
          entry ->
              fragments.add(
                  new FragmentForOutput(
                      entry.getKey().getName(),
                      entry.getValue().stream()
                          .map(clazz -> clazz.getName())
                          .collect(toList()))));

  ImmutableSortedSet.Builder<FragmentOptionsForOutput> fragmentOptions =
      ImmutableSortedSet.orderedBy(comparing(e -> e.name));
  config.getOptions().getFragmentClasses().stream()
      .map(optionsClass -> config.getOptions().get(optionsClass))
      .forEach(
          fragmentOptionsInstance -> {
            fragmentOptions.add(
                new FragmentOptionsForOutput(
                    fragmentOptionsInstance.getClass().getName(),
                    getOrderedNativeOptions(fragmentOptionsInstance)));
          });
  fragmentOptions.add(
      new FragmentOptionsForOutput(
          UserDefinedFragment.DESCRIPTIVE_NAME, getOrderedUserDefinedOptions(config)));

  return new ConfigurationForOutput(
      skyKey.toString(),
      configHash,
      fragments.build().asList(),
      fragmentOptions.build().asList());
}
 
Example 19
Source File: AndroidBinaryBuildable.java    From buck with Apache License 2.0 4 votes vote down vote up
private void getStepsForNativeAssets(
    BuildContext context,
    ImmutableList.Builder<Step> steps,
    Path libSubdirectory,
    String metadataFilename,
    APKModule module) {

  steps.addAll(
      MakeCleanDirectoryStep.of(
          BuildCellRelativePath.fromCellRelativePath(
              context.getBuildCellRootPath(), getProjectFilesystem(), libSubdirectory)));

  // Input asset libraries are sorted in descending filesize order.
  ImmutableSortedSet.Builder<Path> inputAssetLibrariesBuilder =
      ImmutableSortedSet.orderedBy(
          (libPath1, libPath2) -> {
            try {
              ProjectFilesystem filesystem = getProjectFilesystem();
              int filesizeResult =
                  -Long.compare(
                      filesystem.getFileSize(libPath1), filesystem.getFileSize(libPath2));
              int pathnameResult = libPath1.compareTo(libPath2);
              return filesizeResult != 0 ? filesizeResult : pathnameResult;
            } catch (IOException e) {
              return 0;
            }
          });

  if (packageAssetLibraries || !module.isRootModule()) {
    // TODO(cjhopman): This block should probably all be handled by CopyNativeLibraries.
    // TODO(cjhopman): Why is this packaging native libs as assets even when native exopackage is
    // enabled?
    if (nativeFilesInfo.nativeLibsAssetsDirs.isPresent()
        && nativeFilesInfo.nativeLibsAssetsDirs.get().containsKey(module)) {
      // Copy in cxx libraries marked as assets. Filtering and renaming was already done
      // in CopyNativeLibraries.getBuildSteps().
      Path cxxNativeLibsSrc =
          context
              .getSourcePathResolver()
              .getRelativePath(nativeFilesInfo.nativeLibsAssetsDirs.get().get(module));
      steps.add(
          CopyStep.forDirectory(
              getProjectFilesystem(),
              cxxNativeLibsSrc,
              libSubdirectory,
              CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    // Step that populates a list of libraries and writes a metadata.txt to decompress.
    steps.add(
        createAssetLibrariesMetadataStep(
            libSubdirectory, metadataFilename, module, inputAssetLibrariesBuilder));
  }

  if (compressAssetLibraries || !module.isRootModule()) {
    ImmutableList.Builder<Path> outputAssetLibrariesBuilder = ImmutableList.builder();
    steps.add(
        createRenameAssetLibrariesStep(
            module, inputAssetLibrariesBuilder, outputAssetLibrariesBuilder));
    // Concat and xz compress.
    Path libOutputBlob = libSubdirectory.resolve("libraries.blob");
    steps.add(new ConcatStep(getProjectFilesystem(), outputAssetLibrariesBuilder, libOutputBlob));
    steps.add(
        CompressionAlgorithmCreator.createCompressionStep(
            assetCompressionAlgorithm.orElse(CompressionAlgorithm.XZ),
            getProjectFilesystem(),
            libOutputBlob,
            libSubdirectory,
            xzCompressionLevel));
  }
}
 
Example 20
Source File: ColumnRegistrar.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ColumnRegistrar(TableIdent tableIdent, RowGranularity rowGranularity) {
    this.tableIdent = tableIdent;
    this.rowGranularity = rowGranularity;
    this.infosBuilder = ImmutableSortedMap.naturalOrder();
    this.columnsBuilder = ImmutableSortedSet.orderedBy(ReferenceInfo.COMPARE_BY_COLUMN_IDENT);
}