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

The following examples show how to use com.google.common.collect.ImmutableSortedSet#copyOf() . 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: TestTimeZoneKey.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testZoneKeyData()
{
    Hasher hasher = Hashing.murmur3_128().newHasher();

    SortedSet<TimeZoneKey> timeZoneKeysSortedByKey = ImmutableSortedSet.copyOf(new Comparator<TimeZoneKey>()
    {
        @Override
        public int compare(TimeZoneKey left, TimeZoneKey right)
        {
            return Short.compare(left.getKey(), right.getKey());
        }
    }, TimeZoneKey.getTimeZoneKeys());

    for (TimeZoneKey timeZoneKey : timeZoneKeysSortedByKey) {
        hasher.putShort(timeZoneKey.getKey());
        hasher.putString(timeZoneKey.getId(), StandardCharsets.UTF_8);
    }
    // Zone file should not (normally) be changed, so let's make this more difficult
    assertEquals(hasher.hash().asLong(), -972834036790299986L, "zone-index.properties file contents changed!");
}
 
Example 2
Source File: TestrigText.java    From batfish with Apache License 2.0 6 votes vote down vote up
private static Map<String, byte[]> readTestrigResources(
    String testrigResourcePrefix, @Nullable String subfolder, Iterable<String> filenames) {
  if (filenames != null) {
    List<String> filenameList = ImmutableList.copyOf(filenames);
    SortedSet<String> filenameSet = ImmutableSortedSet.copyOf(filenames);
    if (filenameList.size() != filenameSet.size()) {
      throw new BatfishException("Duplicate filenames provided in: " + filenameList);
    }
    String subfolderText = subfolder != null ? String.format("/%s", subfolder) : "";
    return filenameList.stream()
        .collect(
            ImmutableMap.toImmutableMap(
                Function.identity(),
                filename ->
                    readResourceBytes(
                        String.format(
                            "%s%s/%s", testrigResourcePrefix, subfolderText, filename))));
  } else {
    return Collections.emptyMap();
  }
}
 
Example 3
Source File: IndexInfoTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntersection_NestedOrTermHasDocIdsInfiniteToSmall() {
    IndexInfo left = new IndexInfo(-1);
    List<JexlNode> children = new ArrayList<>();
    children.add(JexlNodeFactory.buildEQNode("FIELD1", "VALUE1"));
    children.add(JexlNodeFactory.buildEQNode("FIELD2", "VALUE2"));
    children.add(JexlNodeFactory.buildEQNode("FIELD3", "VALUE3"));
    
    left.applyNode(JexlNodeFactory.createOrNode(children));
    
    List<IndexMatch> rightMatches = buildIndexMatches("FIELD", "VALUE", "doc1");
    IndexInfo right = new IndexInfo(rightMatches);
    
    // build the query string before
    List<JexlNode> andChildren = new ArrayList<>();
    andChildren.add(left.getNode());
    andChildren.add(JexlNodeFactory.buildEQNode("FIELD", "VALUE"));
    
    JexlNode origQueryTree = JexlNodeFactory.createAndNode(andChildren);
    
    IndexInfo merged = left.intersect(right);
    
    // The intersection of left and right should be a set of 1 document ids
    List<IndexMatch> expectedDocs = buildIndexMatches("FIELD", "VALUE", "doc1");
    ImmutableSortedSet<IndexMatch> expectedSorted = ImmutableSortedSet.copyOf(expectedDocs);
    
    assertEquals(1, merged.uids().size());
    assertEquals(expectedSorted, merged.uids());
    
    assertTrue(TreeEqualityVisitor.isEqual(JexlNodeFactory.createScript(origQueryTree), JexlNodeFactory.createScript(merged.getNode()),
                    new TreeEqualityVisitor.Reason()));
}
 
Example 4
Source File: WorkMgr.java    From batfish with Apache License 2.0 5 votes vote down vote up
/** Return a {@link Container container} contains all snapshots directories inside it. */
public Container getContainer(String networkName) {
  Optional<NetworkId> networkIdOpt = _idManager.getNetworkId(networkName);
  checkArgument(networkIdOpt.isPresent(), "Network '%s' does not exist", networkName);
  SortedSet<String> testrigs =
      ImmutableSortedSet.copyOf(_idManager.listSnapshots(networkIdOpt.get()));
  return Container.of(networkName, testrigs);
}
 
Example 5
Source File: PropertySourcesProcessor.java    From apollo with Apache License 2.0 5 votes vote down vote up
private void initializePropertySources() {
  if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) {
    //already initialized
    return;
  }
  CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME);

  //sort by order asc
  ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
  Iterator<Integer> iterator = orders.iterator();

  while (iterator.hasNext()) {
    int order = iterator.next();
    for (String namespace : NAMESPACE_NAMES.get(order)) {
      Config config = ConfigService.getConfig(namespace);

      composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
    }
  }

  // clean up
  NAMESPACE_NAMES.clear();

  // add after the bootstrap property source or to the first
  if (environment.getPropertySources()
      .contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {

    // ensure ApolloBootstrapPropertySources is still the first
    ensureBootstrapPropertyPrecedence(environment);

    environment.getPropertySources()
        .addAfter(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, composite);
  } else {
    environment.getPropertySources().addFirst(composite);
  }
}
 
Example 6
Source File: ImmutableConverter.java    From ZjDroid with Apache License 2.0 5 votes vote down vote up
@Nonnull
public ImmutableSortedSet<ImmutableItem> toSortedSet(@Nonnull Comparator<? super ImmutableItem> comparator,
                                                     @Nullable final Iterable<? extends Item> iterable) {
    if (iterable == null) {
        return ImmutableSortedSet.of();
    }

    boolean needsCopy = false;
    if (iterable instanceof ImmutableSortedSet &&
            ((ImmutableSortedSet)iterable).comparator().equals(comparator)) {
        for (Item element: iterable) {
            if (!isImmutable(element)) {
                needsCopy = true;
                break;
            }
        }
    } else {
        needsCopy = true;
    }

    if (!needsCopy) {
        return (ImmutableSortedSet<ImmutableItem>)iterable;
    }

    final Iterator<? extends Item> iter = iterable.iterator();


    return ImmutableSortedSet.copyOf(comparator, new Iterator<ImmutableItem>() {
        @Override public boolean hasNext() { return iter.hasNext(); }
        @Override public ImmutableItem next() { return makeImmutable(iter.next()); }
        @Override public void remove() { iter.remove(); }
    });
}
 
Example 7
Source File: Profiler.java    From Quicksql with MIT License 5 votes vote down vote up
/** Creates a Distribution.
 *
 * @param columns Column or columns being described
 * @param values Values of columns, or null if there are too many
 * @param cardinality Number of distinct values
 * @param nullCount Number of rows where this column had a null value;
 * @param expectedCardinality Expected cardinality
 * @param minimal Whether the distribution is not implied by a unique
 *   or functional dependency
 */
public Distribution(SortedSet<Column> columns, SortedSet<Comparable> values,
    double cardinality, int nullCount, double expectedCardinality,
    boolean minimal) {
  this.columns = ImmutableSortedSet.copyOf(columns);
  this.values = values == null ? null : ImmutableSortedSet.copyOf(values);
  this.cardinality = cardinality;
  this.nullCount = nullCount;
  this.expectedCardinality = expectedCardinality;
  this.minimal = minimal;
}
 
Example 8
Source File: CiscoConfiguration.java    From batfish with Apache License 2.0 5 votes vote down vote up
/**
 * Get the {@link OspfNetwork} in the specified {@link OspfProcess} containing the specified
 * {@link Interface}'s address
 *
 * <p>Returns {@code null} if the interface address is {@code null} or the interface address does
 * not overlap with any {@link OspfNetwork} in the specified {@link OspfProcess}
 */
private static @Nullable OspfNetwork getOspfNetworkForInterface(
    Interface iface, OspfProcess process) {
  ConcreteInterfaceAddress interfaceAddress = iface.getAddress();
  if (interfaceAddress == null) {
    // Iface has no IP address / isn't associated with a network in this OSPF process
    return null;
  }

  // Sort networks with longer prefixes first, then lower start IPs and areas
  SortedSet<OspfNetwork> networks =
      ImmutableSortedSet.copyOf(
          Comparator.<OspfNetwork>comparingInt(n -> n.getPrefix().getPrefixLength())
              .reversed()
              .thenComparing(n -> n.getPrefix().getStartIp())
              .thenComparingLong(OspfNetwork::getArea),
          process.getNetworks());
  for (OspfNetwork network : networks) {
    Prefix networkPrefix = network.getPrefix();
    Ip networkAddress = networkPrefix.getStartIp();
    Ip maskedInterfaceAddress =
        interfaceAddress.getIp().getNetworkAddress(networkPrefix.getPrefixLength());
    if (maskedInterfaceAddress.equals(networkAddress)) {
      // Found a longest prefix match, so found the network in this OSPF process for the iface
      return network;
    }
  }
  return null;
}
 
Example 9
Source File: Bridge.java    From batfish with Apache License 2.0 5 votes vote down vote up
@JsonCreator
private static @Nonnull Bridge create(
    @JsonProperty(PROP_PORTS) @Nullable Set<String> ports,
    @JsonProperty(PROP_PVID) @Nullable Integer pvid,
    @JsonProperty(PROP_VIDS) @Nullable IntegerSpace vids) {
  checkArgument(pvid != null, "Missing %s", PROP_PVID);
  checkArgument(vids != null, "Missing %s", PROP_VIDS);
  return new Bridge(
      ImmutableSortedSet.copyOf(firstNonNull(ports, ImmutableSortedSet.of())), pvid, vids);
}
 
Example 10
Source File: PomIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
public PublishedViaMaven(
    String target,
    ProjectFilesystem filesystem,
    String coords,
    @Nullable SourcePath pomTemplate,
    BuildRule... deps) {
  super(BuildTargetFactory.newInstance(target), filesystem);
  this.coords = coords;
  this.pomTemplate = pomTemplate;
  this.deps = ImmutableSortedSet.copyOf(deps);
}
 
Example 11
Source File: UnskippedRulesTrackerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
private BuildRule createRule(
    String buildTarget, ImmutableSet<BuildRule> deps, ImmutableSet<BuildRule> runtimeDeps) {
  return new FakeBuildRuleWithRuntimeDeps(
      BuildTargetFactory.newInstance(buildTarget),
      ImmutableSortedSet.copyOf(deps),
      ImmutableSortedSet.copyOf(runtimeDeps));
}
 
Example 12
Source File: EndpointInfo.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance.
 */
EndpointInfo(String hostnamePattern, String pathMapping, @Nullable String regexPathPrefix,
             @Nullable String fragment, @Nullable MediaType defaultMimeType,
             Iterable<MediaType> availableMimeTypes) {

    this.hostnamePattern = requireNonNull(hostnamePattern, "hostnamePattern");
    this.pathMapping = requireNonNull(pathMapping, "pathMapping");
    this.regexPathPrefix = Strings.emptyToNull(regexPathPrefix);
    this.fragment = Strings.emptyToNull(fragment);
    this.defaultMimeType = defaultMimeType;

    this.availableMimeTypes = ImmutableSortedSet.copyOf(
            Comparator.comparing(MediaType::toString),
            requireNonNull(availableMimeTypes, "availableMimeTypes"));
}
 
Example 13
Source File: SimpleProfiler.java    From Quicksql with MIT License 4 votes vote down vote up
private ImmutableSortedSet<Column> toColumns(Iterable<Integer> ordinals) {
  return ImmutableSortedSet.copyOf(
      Iterables.transform(ordinals, columns::get));
}
 
Example 14
Source File: EventQueueBackingStoreFile.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
@Override
ImmutableSortedSet<Integer> getReferenceCounts() {
  return ImmutableSortedSet.copyOf(logFileIDReferenceCounts.keySet());
}
 
Example 15
Source File: HeaderSpace.java    From batfish with Apache License 2.0 4 votes vote down vote up
public Builder setNotIcmpCodes(Iterable<SubRange> notIcmpCodes) {
  _notIcmpCodes = ImmutableSortedSet.copyOf(notIcmpCodes);
  return this;
}
 
Example 16
Source File: HeaderSpace.java    From batfish with Apache License 2.0 4 votes vote down vote up
@JsonProperty(PROP_NOT_PACKET_LENGTHS)
public void setNotPacketLengths(Iterable<SubRange> notPacketLengths) {
  _notPacketLengths = ImmutableSortedSet.copyOf(notPacketLengths);
}
 
Example 17
Source File: CachingBuildEngineTest.java    From buck with Apache License 2.0 4 votes vote down vote up
public FakeHasRuntimeDeps(
    BuildTarget target, ProjectFilesystem filesystem, BuildRule... runtimeDeps) {
  super(target, filesystem);
  this.runtimeDeps = ImmutableSortedSet.copyOf(runtimeDeps);
}
 
Example 18
Source File: ServiceObjectGroupBean.java    From batfish with Apache License 2.0 4 votes vote down vote up
public ServiceObjectGroup toServiceObjectGroup() {
  return new ServiceObjectGroup(
      name, ImmutableSortedSet.copyOf(firstNonNull(services, ImmutableSet.of())));
}
 
Example 19
Source File: InvalidListPruningDebugTest.java    From phoenix-tephra with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdleRegions() throws Exception {
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  try (PrintWriter out = new PrintWriter(outputStream)) {
    // Get the list of regions that have the lowest prune upper bounds for the latest record time
    Long latestRecordTime = compactedRegions.asMap().lastKey();
    SortedSet<InvalidListPruningDebugTool.RegionPruneInfoPretty> latestExpected =
      ImmutableSortedSet.copyOf(pruneUpperBoundAndStringComparator(), compactedRegions.get(latestRecordTime));
    pruningDebug.execute(new String[]{"idle-regions", "-1"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with explicit time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime)}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with relative time
    outputStream.reset();
    pruningDebug.execute(new String[]{"idle-regions", "-1", "now-2s"}, out);
    out.flush();
    assertEquals(latestExpected, readOutputStream(outputStream));

    // Same command with reduced number of regions
    outputStream.reset();
    int limit = 2;
    pruningDebug.execute(new String[]{"idle-regions", String.valueOf(limit), String.valueOf(latestRecordTime)}, out);
    out.flush();
    Assert.assertEquals(GSON.toJson(subset(latestExpected, 0, limit)), readOutputStream(outputStream));

    // For a different time, this time only live regions that are compacted are returned
    outputStream.reset();
    Long secondLastRecordTime = Iterables.get(compactedRegions.keySet(), 1);
    Set<String> compactedRegionsTime =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(secondLastRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> compactedRegionsLatest =
      Sets.newTreeSet(Iterables.transform(compactedRegions.get(latestRecordTime), PRUNE_INFO_TO_STRING));
    Set<String> liveExpected = new TreeSet<>(Sets.intersection(compactedRegionsTime, compactedRegionsLatest));
    pruningDebug.execute(new String[]{"idle-regions", "-1", String.valueOf(latestRecordTime - 1)}, out);
    out.flush();
    List<RegionPruneInfo> actual = GSON.fromJson(readOutputStream(outputStream), PRUNE_INFO_LIST_TYPE);
    Assert.assertEquals(liveExpected, Sets.newTreeSet(Iterables.transform(actual, PRUNE_INFO_TO_STRING)));
  }
}
 
Example 20
Source File: AddressGroupBean.java    From batfish with Apache License 2.0 4 votes vote down vote up
public AddressGroup toAddressGroup() {
  return new AddressGroup(
      name,
      ImmutableSortedSet.copyOf(firstNonNull(addresses, ImmutableSet.of())),
      ImmutableSortedSet.copyOf(firstNonNull(childGroupNames, ImmutableSet.of())));
}