Java Code Examples for com.google.common.collect.ImmutableList#sortedCopyOf()

The following examples show how to use com.google.common.collect.ImmutableList#sortedCopyOf() . 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: CreateNullEntity.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Finds an available connect points among edge ports of the specified device.
 *
 * @param deviceId device identifier
 * @return list of connect points available for link or host attachments
 */
protected List<ConnectPoint> findAvailablePorts(DeviceId deviceId) {
    EdgePortService eps = get(EdgePortService.class);

    // As there may be a slight delay in edge service getting updated, retry a few times
    for (int i = 0; i < MAX_EDGE_PORT_TRIES; i++) {
        List<ConnectPoint> points = ImmutableList
                .sortedCopyOf((l, r) -> Longs.compare(l.port().toLong(), r.port().toLong()),
                              eps.getEdgePoints(deviceId));
        if (!points.isEmpty()) {
            return points;
        }
        Tools.delay(100);
    }
    return ImmutableList.of();
}
 
Example 2
Source File: DynamicEndpointGroup.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the specified {@link Endpoint}s as current {@link Endpoint} list.
 */
protected final void setEndpoints(Iterable<Endpoint> endpoints) {
    final List<Endpoint> oldEndpoints = this.endpoints;
    final List<Endpoint> newEndpoints = ImmutableList.sortedCopyOf(endpoints);

    if (!hasChanges(oldEndpoints, newEndpoints)) {
        return;
    }

    endpointsLock.lock();
    try {
        this.endpoints = newEndpoints;
    } finally {
        endpointsLock.unlock();
    }

    notifyListeners(newEndpoints);
    completeInitialEndpointsFuture(newEndpoints);
}
 
Example 3
Source File: ShTestIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void resourcesAreMarkedAsInputs() throws IOException {
  Assume.assumeTrue(ImmutableSet.of(Platform.MACOS, Platform.LINUX).contains(Platform.detect()));
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "sh_test_resources", tmp);
  workspace.setUp();
  ProcessResult result = workspace.runBuckCommand("audit", "inputs", "//:test");
  result.assertSuccess();
  ImmutableList<String> lines =
      ImmutableList.sortedCopyOf(
          Comparator.naturalOrder(), Splitter.on("\n").split(result.getStdout().trim()));

  ImmutableList<String> expected =
      ImmutableList.of(
          "as_path/resource_file_as_path",
          "resources/BUCK",
          "resources/subdir/resource_file",
          "test.sh");
  Assert.assertEquals(expected, lines);
}
 
Example 4
Source File: GenerateDnsReportCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private void write(DomainBase domain) {
  ImmutableList<String> nameservers =
      ImmutableList.sortedCopyOf(domain.loadNameserverHostNames());
  ImmutableList<Map<String, ?>> dsData =
      domain
          .getDsData()
          .stream()
          .map(
              dsData1 ->
                  ImmutableMap.of(
                      "keyTag", dsData1.getKeyTag(),
                      "algorithm", dsData1.getAlgorithm(),
                      "digestType", dsData1.getDigestType(),
                      "digest", base16().encode(dsData1.getDigest())))
          .collect(toImmutableList());
  ImmutableMap.Builder<String, Object> mapBuilder = new ImmutableMap.Builder<>();
  mapBuilder.put("domain", domain.getDomainName());
  if (!nameservers.isEmpty()) {
    mapBuilder.put("nameservers", nameservers);
  }
  if (!dsData.isEmpty()) {
    mapBuilder.put("dsData", dsData);
  }
  writeJson(mapBuilder.build());
}
 
Example 5
Source File: FileUtils.java    From startup-os with Apache License 2.0 5 votes vote down vote up
/** Gets subfolder names in path. Throws IllegalStateException if path is not a folder. */
public ImmutableList<String> listSubfolders(String path) throws IOException {
  if (!folderExists(path)) {
    throw new IllegalStateException("Folder does not exist");
  }
  return ImmutableList.sortedCopyOf(
      listContents(path)
          .stream()
          .filter(x -> folderExists(joinPaths(path, x)))
          .collect(Collectors.toList()));
}
 
Example 6
Source File: FileUtils.java    From startup-os with Apache License 2.0 5 votes vote down vote up
/**
 * Gets file and folder absolute paths recursively. Throws NoSuchFileException if directory
 * doesn't exist.
 */
public ImmutableList<String> listContentsRecursively(String path) throws IOException {
  try (Stream<Path> paths =
      Files.find(
          fileSystem.getPath(expandHomeDirectory(path)),
          100000, // Folder depth
          (unused, unused2) -> true)) {
    return ImmutableList.sortedCopyOf(paths.map(Path::toString).collect(Collectors.toList()));
  }
}
 
Example 7
Source File: DynamicEndpointGroup.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the specified {@link Endpoint} to current {@link Endpoint} list.
 */
protected final void addEndpoint(Endpoint e) {
    final List<Endpoint> newEndpoints;
    endpointsLock.lock();
    try {
        final List<Endpoint> newEndpointsUnsorted = Lists.newArrayList(endpoints);
        newEndpointsUnsorted.add(e);
        endpoints = newEndpoints = ImmutableList.sortedCopyOf(newEndpointsUnsorted);
    } finally {
        endpointsLock.unlock();
    }

    notifyListeners(newEndpoints);
    completeInitialEndpointsFuture(newEndpoints);
}
 
Example 8
Source File: ResourceFilterFactory.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts filters from an AttributeMap, as a list of strings.
 *
 * <p>In BUILD files, string lists can be represented as a list of strings, a single
 * comma-separated string, or a combination of both. This method outputs a single list of
 * individual string values, which can then be passed directly to resource processing actions.
 *
 * @return the values of this attribute contained in the {@link AttributeMap}, as a list.
 */
private static ImmutableList<String> extractFilters(List<String> rawValues) {
  if (rawValues.isEmpty()) {
    return ImmutableList.of();
  }

  /*
   * To deal with edge cases involving placement of whitespace and multiple strings inside a
   * single item of the given list, manually build the list here rather than call something like
   * {@link RuleContext#getTokenizedStringListAttr}.
   *
   * Filter out all empty values, even those that were explicitly provided. Paying attention to
   * empty values is never helpful: even if code handled them correctly (and not all of it does)
   * empty filter values result in all resources matching the empty filter, meaning that filtering
   * does nothing (even if non-empty filters were also provided).
   */

  // Use an ImmutableSet to remove duplicate values
  ImmutableSet.Builder<String> builder = ImmutableSet.builder();

  for (String rawValue : rawValues) {
    if (rawValue.contains(",")) {
      for (String token : rawValue.split(",")) {
        if (!token.trim().isEmpty()) {
          builder.add(token.trim());
        }
      }
    } else if (!rawValue.isEmpty()) {
      builder.add(rawValue);
    }
  }

  // Create a sorted copy so that ResourceFilterFactory objects with the same filters are treated
  // the same regardless of the ordering of those filters.
  return ImmutableList.sortedCopyOf(builder.build());
}
 
Example 9
Source File: CodeGenUtil.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the fields sorted in order of field number. By default, they are sorted in order of
 * definition in the proto file.
 */
static List<FieldDescriptor> sorted(List<FieldDescriptor> fields) {
  return ImmutableList.sortedCopyOf(
      new Comparator<FieldDescriptor>() {
        @Override
        public int compare(FieldDescriptor o1, FieldDescriptor o2) {
          return Integer.compare(o1.getNumber(), o2.getNumber());
        }
      },
      fields);
}
 
Example 10
Source File: ViolationLevelManagement.java    From AACAdditionPro with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create a new {@link ViolationLevelManagement}
 *
 * @param moduleType the {@link ModuleType} of the module this {@link ViolationLevelManagement} is being used by.
 * @param decayTicks the time in ticks until the vl of a player is decreased by one. If this is negative no decrease will happen.
 */
public ViolationLevelManagement(final ModuleType moduleType, final long decayTicks)
{
    // The ModuleType of the check
    this.moduleType = moduleType;

    ModuleType.VL_MODULETYPES.add(moduleType);

    this.violationLevels = new ViolationLevelMap(decayTicks);
    // Listener registration as of the PlayerQuitEvent
    AACAdditionPro.getInstance().registerListener(this.violationLevels);

    // Load the thresholds and sort them.
    switch (ServerVersion.getActiveServerVersion()) {
        case MC188:
            final List<Threshold> temp = Threshold.loadThresholds(moduleType.getConfigString() + ".thresholds");
            Collections.sort(temp);
            thresholds = ImmutableList.copyOf(temp);
            break;
        case MC112:
        case MC113:
        case MC114:
        case MC115:
            thresholds = ImmutableList.sortedCopyOf(Threshold.loadThresholds(moduleType.getConfigString() + ".thresholds"));
            break;
        default:
            throw new UnknownMinecraftVersion();
    }
}
 
Example 11
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaId() {
  // All TLDs have the same data, so just keep trying until one works
  // (the expectation is that all / any should work)
  ImmutableList<String> tlds = ImmutableList.sortedCopyOf(Registries.getTldsOfType(TldType.REAL));
  checkArgument(!tlds.isEmpty(), "There must exist at least one REAL TLD.");
  Throwable finalThrowable = null;
  for (String tld : tlds) {
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    String id;
    try {
      id = loginAndGetId(requestFactory, tld);
    } catch (Throwable e) {
      // Login failures are bad but not unexpected for certain TLDs. We shouldn't store those
      // but rather should only store useful Throwables.
      logger.atWarning().log("Error logging in to MoSAPI server: " + e.getMessage());
      continue;
    }
    try {
      return getRdapBaseUrlsPerIanaIdWithTld(tld, id, requestFactory);
    } catch (Throwable throwable) {
      logger.atWarning().log(
          String.format(
              "Error retrieving RDAP urls with TLD %s: %s", tld, throwable.getMessage()));
      finalThrowable = throwable;
    }
  }
  throw new RuntimeException(
      String.format("Error contacting MosAPI server. Tried TLDs %s", tlds), finalThrowable);
}
 
Example 12
Source File: ResultCollector.java    From bazel with Apache License 2.0 4 votes vote down vote up
public ImmutableList<MissingMember> getSortedMissingMembers() {
  return ImmutableList.sortedCopyOf(missingMembers);
}
 
Example 13
Source File: BlazeTypeScriptConfigTest.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Test
public void testDifferentOptions() {
  TypeScriptConfig blazeConfig = blazeConfigService.getConfigs().get(0);
  assertThat(blazeConfig.getBaseUrl()).isEqualTo(vf("/src/out/execroot/bin/project/foo"));
  assertThat(blazeConfig.getDependencies())
      .containsExactly(vf("/src/out/execroot/bin/project/foo/tsconfig_editor.json"));

  ImmutableList<JSModulePathSubstitution> paths =
      ImmutableList.sortedCopyOf(
          Comparator.comparing(JSModulePathSubstitution::getMappedName), blazeConfig.getPaths());
  assertThat(paths).hasSize(2);
  JSModulePathSubstitution projectPath = paths.get(0);
  assertThat(projectPath.getMappedName()).isEqualTo("workspace");
  assertThat(projectPath.getMappings())
      .containsExactly(
          "../../../../../workspace/*",
          "../../../../../workspace/blaze-bin/*",
          "../../../../../workspace/blaze-genfiles/*",
          "../../*",
          "../../../genfiles/*",
          "./tsconfig.runfiles/workspace/*")
      .inOrder();

  JSModulePathSubstitution projectFooPath = paths.get(1);
  assertThat(projectFooPath.getMappedName()).isEqualTo("workspace/project/foo");
  assertThat(projectFooPath.getMappings())
      .containsExactly(
          "../../../../../workspace/project/foo/*",
          "../../../../../workspace/blaze-bin/project/foo/*",
          "../../../../../workspace/blaze-genfiles/project/foo/*",
          "../../project/foo/*",
          "../../../genfiles/project/foo/*",
          "./tsconfig.runfiles/workspace/project/foo/*")
      .inOrder();

  assertThat(ReadAction.compute(blazeConfig::getRootDirsFiles))
      .containsExactly(
          vf("/src/workspace/project/foo"),
          vf("/src/out/execroot/bin/project/foo/tsconfig.runfiles/workspace"),
          vf("/src/out/execroot/bin/project/foo/tsconfig.runfiles/workspace/project/foo"));
  assertThat(ReadAction.compute(blazeConfig::getRootDirs))
      .containsExactly(
          psi("/src/workspace/project/foo"),
          psi("/src/out/execroot/bin/project/foo/tsconfig.runfiles/workspace"),
          psi("/src/out/execroot/bin/project/foo/tsconfig.runfiles/workspace/project/foo"));
}
 
Example 14
Source File: BuildOptions.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static OptionsDiffForReconstruction createDiffForReconstruction(
    BuildOptions first, BuildOptions second) {
  OptionsDiff diff = diff(first, second);
  if (diff.areSame()) {
    first.maybeInitializeFingerprintAndHashCode();
    return OptionsDiffForReconstruction.getEmpty(first.fingerprint, second.computeChecksum());
  }
  LinkedHashMap<Class<? extends FragmentOptions>, Map<String, Object>> differingOptions =
      new LinkedHashMap<>(diff.differingOptions.keySet().size());
  for (Class<? extends FragmentOptions> clazz :
      diff.differingOptions.keySet().stream()
          .sorted(lexicalFragmentOptionsComparator)
          .collect(Collectors.toList())) {
    Collection<OptionDefinition> fields = diff.differingOptions.get(clazz);
    LinkedHashMap<String, Object> valueMap = new LinkedHashMap<>(fields.size());
    for (OptionDefinition optionDefinition :
        fields.stream()
            .sorted(Comparator.comparing(o -> o.getField().getName()))
            .collect(Collectors.toList())) {
      Object secondValue;
      try {
        secondValue = Iterables.getOnlyElement(diff.second.get(optionDefinition));
      } catch (IllegalArgumentException e) {
        // TODO(janakr): Currently this exception should never be thrown since diff is never
        // constructed using the diff method that takes in a preexisting OptionsDiff. If this
        // changes, add a test verifying this error catching works properly.
        throw new IllegalStateException(
            "OptionsDiffForReconstruction can only handle a single first BuildOptions and a "
                + "single second BuildOptions and has encountered multiple second BuildOptions",
            e);
      }
      valueMap.put(optionDefinition.getField().getName(), secondValue);
    }
    differingOptions.put(clazz, valueMap);
  }
  first.maybeInitializeFingerprintAndHashCode();
  return new OptionsDiffForReconstruction(
      differingOptions,
      diff.extraFirstFragments.stream()
          .sorted(lexicalFragmentOptionsComparator)
          .collect(ImmutableSet.toImmutableSet()),
      ImmutableList.sortedCopyOf(
          Comparator.comparing(o -> o.getClass().getName()), diff.extraSecondFragments),
      first.fingerprint,
      second.computeChecksum(),
      diff.starlarkSecond,
      diff.extraStarlarkOptionsFirst,
      diff.extraStarlarkOptionsSecond,
      second);
}
 
Example 15
Source File: StackedFileHashCache.java    From buck with Apache License 2.0 4 votes vote down vote up
public StackedFileHashCache(ImmutableList<? extends ProjectFileHashCache> caches) {
  this.caches = ImmutableList.sortedCopyOf(new FileHashCacheComparator(), caches);
}
 
Example 16
Source File: BuildLanguageInfoItem.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Returns a byte array containing a proto-buffer describing the build language. */
private static byte[] getBuildLanguageDefinition(RuleClassProvider provider) {
  BuildLanguage.Builder resultPb = BuildLanguage.newBuilder();
  ImmutableList<RuleClass> sortedRuleClasses =
      ImmutableList.sortedCopyOf(
          Comparator.comparing(RuleClass::getName), provider.getRuleClassMap().values());
  for (RuleClass ruleClass : sortedRuleClasses) {
    if (isAbstractRule(ruleClass)) {
      continue;
    }

    RuleDefinition.Builder rulePb = RuleDefinition.newBuilder();
    rulePb.setName(ruleClass.getName());

    ImmutableList<Attribute> sortedAttributeDefinitions =
        ImmutableList.sortedCopyOf(
            Comparator.comparing(Attribute::getName), ruleClass.getAttributes());
    for (Attribute attr : sortedAttributeDefinitions) {
      Type<?> t = attr.getType();
      AttributeDefinition.Builder attrPb = AttributeDefinition.newBuilder();
      attrPb.setName(attr.getName());
      attrPb.setType(ProtoUtils.getDiscriminatorFromType(t));
      attrPb.setMandatory(attr.isMandatory());
      attrPb.setAllowEmpty(!attr.isNonEmpty());
      attrPb.setAllowSingleFile(attr.isSingleArtifact());
      attrPb.setConfigurable(attr.isConfigurable());
      attrPb.setCfgIsHost(attr.getTransitionFactory().isHost());

      // Encode default value, if simple.
      Object v = attr.getDefaultValueUnchecked();
      if (!(v == null
          || v instanceof Attribute.ComputedDefault
          || v instanceof StarlarkComputedDefaultTemplate
          || v instanceof Attribute.LateBoundDefault
          || v == t.getDefaultValue())) {
        attrPb.setDefault(convertAttrValue(t, v));
      }
      attrPb.setExecutable(attr.isExecutable());
      if (BuildType.isLabelType(t)) {
        attrPb.setAllowedRuleClasses(getAllowedRuleClasses(sortedRuleClasses, attr));
        attrPb.setNodep(t.getLabelClass() == Type.LabelClass.NONDEP_REFERENCE);
      }
      rulePb.addAttribute(attrPb);
    }

    resultPb.addRule(rulePb);
  }

  return resultPb.build().toByteArray();
}
 
Example 17
Source File: AaTool.java    From startup-os with Apache License 2.0 4 votes vote down vote up
public ImmutableList<String> getCommands() {
  return ImmutableList.sortedCopyOf(commands.keySet());
}
 
Example 18
Source File: ResultCollector.java    From bazel with Apache License 2.0 4 votes vote down vote up
public ImmutableList<Path> getSortedIndirectDeps() {
  return ImmutableList.sortedCopyOf(indirectDeps);
}
 
Example 19
Source File: StarlarkProvider.java    From bazel with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an unexported {@link StarlarkProvider} with a schema.
 *
 * <p>The resulting object needs to be exported later (via {@link #export}).
 *
 * @param schema the allowed field names for instances of this provider
 * @param location the location of the Starlark definition for this provider (tests may use {@link
 *     Location#BUILTIN})
 */
// TODO(adonovan): in what sense is this "schemaful" if schema may be null?
public static StarlarkProvider createUnexportedSchemaful(
    @Nullable Collection<String> schema, Location location) {
  return new StarlarkProvider(
      /*key=*/ null, schema == null ? null : ImmutableList.sortedCopyOf(schema), location);
}
 
Example 20
Source File: StarlarkProvider.java    From bazel with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an exported {@link StarlarkProvider} with no schema.
 *
 * @param key the key that identifies this provider
 * @param schema the allowed field names for instances of this provider
 * @param location the location of the Starlark definition for this provider (tests may use {@link
 *     Location#BUILTIN})
 */
// TODO(adonovan): in what sense is this "schemaful" if schema may be null?
public static StarlarkProvider createExportedSchemaful(
    Key key, @Nullable Collection<String> schema, Location location) {
  return new StarlarkProvider(
      key, schema == null ? null : ImmutableList.sortedCopyOf(schema), location);
}