Пример #1
0
 @Override
 public ImmutableSortedSet<Path> getSortedMatchingDirectoryContents(
     final Path pathRelativeToProjectRoot, String globPattern) throws IOException {
   Preconditions.checkState(isDirectory(pathRelativeToProjectRoot));
   final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + globPattern);
   return FluentIterable.from(fileContents.keySet())
       .filter(
           new Predicate<Path>() {
             @Override
             public boolean apply(Path input) {
               return input.getParent().equals(pathRelativeToProjectRoot)
                   && pathMatcher.matches(input.getFileName());
             }
           })
       .toSortedSet(
           Ordering.natural()
               .onResultOf(
                   new Function<Path, FileTime>() {
                     @Override
                     public FileTime apply(Path path) {
                       try {
                         return getLastModifiedTimeFetcher().getLastModifiedTime(path);
                       } catch (IOException e) {
                         throw new RuntimeException(e);
                       }
                     }
                   })
               .compound(Ordering.natural())
               .reverse());
 }
Пример #2
0
  /** Constructor */
  public TreeMapStore() {
    /*
     * For the start times index, the "key comparator" will compare the
     * start times as longs directly. This is the primary comparator for its
     * tree map.
     *
     * The secondary "value" comparator will check the end times first, and
     * in the event of a tie, defer to the ISegment's Comparable
     * implementation, a.k.a. its natural ordering.
     *
     * The same is done for the end times index, but swapping the first two
     * comparators instead.
     */
    fStartTimesIndex =
        checkNotNull(
            TreeMultimap.<Long, T>create(
                SegmentComparators.LONG_COMPARATOR,
                Ordering.from(SegmentComparators.INTERVAL_END_COMPARATOR)
                    .compound(Ordering.natural())));

    fEndTimesIndex =
        checkNotNull(
            TreeMultimap.<Long, T>create(
                SegmentComparators.LONG_COMPARATOR,
                Ordering.from(SegmentComparators.INTERVAL_START_COMPARATOR)
                    .compound(Ordering.natural())));

    fSize = 0;
  }
Пример #3
0
  @Override
  public int compareTo(Employee o) {
    int diff =
        ComparisonChain.start()
            .compare(lastName, o.lastName, Ordering.from(String.CASE_INSENSITIVE_ORDER))
            .compare(firstName, o.firstName, Ordering.from(String.CASE_INSENSITIVE_ORDER))
            .compare(title, o.title, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                titleCourtesy,
                o.titleCourtesy,
                Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(birthDate, o.birthDate, Ordering.natural().nullsFirst())
            .compare(hireDate, o.hireDate, Ordering.natural().nullsFirst())
            .compare(address, o.address, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(city, o.city, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(region, o.region, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                postalCode, o.postalCode, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(country, o.country, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                homePhone, o.homePhone, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(
                extension, o.extension, Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsFirst())
            .compare(reportsTo, o.reportsTo, Ordering.natural().nullsFirst())
            .result();
    if (diff != 0) return diff;

    if (photo == null) return o.photo == null ? 0 : -1;
    if (o.photo == null) return 1;
    return UnsignedBytes.lexicographicalComparator().compare(photo, o.photo);
  }
 private String makeSubjectString(
     String httpMethod, String host, String path, final Map<String, List<String>> parameters)
     throws UnsupportedEncodingException {
   parameters.remove("");
   StringBuilder sb = new StringBuilder();
   sb.append(httpMethod);
   sb.append("\n");
   sb.append(host);
   sb.append("\n");
   sb.append(path);
   sb.append("\n");
   String prefix = sb.toString();
   sb = new StringBuilder();
   boolean addedParam = false;
   for (final String paramName : Ordering.natural().sortedCopy(parameters.keySet())) {
     if (SecurityParameter.Signature.parameter().equals(paramName)) continue;
     List<String> paramValues = parameters.get(paramName);
     if (paramValues.isEmpty()) paramValues = Lists.newArrayList("");
     for (final String value : Ordering.natural().sortedCopy(paramValues)) {
       sb.append(urlencode(paramName)).append("=").append(urlencode(value)).append("&");
       addedParam = true;
     }
   }
   if (addedParam) sb.setLength(sb.length() - 1);
   String subject = prefix + sb.toString();
   LOG.trace("VERSION2: " + subject);
   return subject;
 }
Пример #5
0
  private static void verifyMergeSorted(
      Iterable<Iterable<Integer>> iterables, Iterable<Integer> unsortedExpected) {
    Iterable<Integer> expected = Ordering.natural().sortedCopy(unsortedExpected);

    Iterable<Integer> mergedIterator = Iterables.mergeSorted(iterables, Ordering.natural());

    assertEquals(Lists.newLinkedList(expected), Lists.newLinkedList(mergedIterator));
  }
Пример #6
0
 public void testBuilder_orderEntriesByValue_usedTwiceFails() {
   ImmutableBiMap.Builder<String, Integer> builder =
       new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
   try {
     builder.orderEntriesByValue(Ordering.natural());
     fail("Expected IllegalStateException");
   } catch (IllegalStateException expected) {
   }
 }
Пример #7
0
  public void testNullsLast() {
    Ordering<Integer> ordering = Ordering.natural().nullsLast();
    Helpers.testComparator(ordering, 0, 1, Integer.MAX_VALUE, null);

    new EqualsTester()
        .addEqualityGroup(ordering, Ordering.natural().nullsLast())
        .addEqualityGroup(numberOrdering.nullsLast())
        .addEqualityGroup(Ordering.natural())
        .testEquals();
  }
Пример #8
0
 @SuppressWarnings("unchecked")
 @Test
 public void testGroupSortNoEffect() {
   List<Tuple2<Integer, Integer>> pairs =
       Lists.newArrayList(tuple2(1, 2), tuple2(2, 3), tuple2(1, 3), tuple2(3, 1), tuple2(2, 1));
   JavaPairRDD<Integer, Integer> p = jsc().parallelizePairs(pairs);
   GroupSorted<Integer, Integer> gs =
       new GroupSorted(p, new HashPartitioner(2), Ordering.natural());
   GroupSorted<Integer, Integer> gs1 =
       new GroupSorted(gs, new HashPartitioner(2), Ordering.natural());
   Assert.assertTrue(JavaPairRDD.toRDD(gs) == JavaPairRDD.toRDD(gs1));
 }
Пример #9
0
  public void testFrom() {
    Ordering<String> caseInsensitiveOrdering = Ordering.from(String.CASE_INSENSITIVE_ORDER);
    assertEquals(0, caseInsensitiveOrdering.compare("A", "a"));
    assertTrue(caseInsensitiveOrdering.compare("a", "B") < 0);
    assertTrue(caseInsensitiveOrdering.compare("B", "a") > 0);

    @SuppressWarnings("deprecation") // test of deprecated method
    Ordering<String> orderingFromOrdering = Ordering.from(Ordering.<String>natural());
    new EqualsTester()
        .addEqualityGroup(caseInsensitiveOrdering, Ordering.from(String.CASE_INSENSITIVE_ORDER))
        .addEqualityGroup(orderingFromOrdering, Ordering.natural())
        .testEquals();
  }
  @Override
  public void validate(
      final ValidationContext context, final ValidationReport report, final JsonNode instance) {
    final Set<String> fields = Sets.newHashSet(instance.fieldNames());
    final Set<String> missing = Sets.difference(required, fields);

    if (missing.isEmpty()) return;

    final Message.Builder msg =
        newMsg()
            .addInfo("required", Ordering.natural().sortedCopy(required))
            .addInfo("missing", Ordering.natural().sortedCopy(missing))
            .setMessage("required property(ies) not found");
    report.addMessage(msg.build());
  }
Пример #11
0
  public void testOnResultOf_natural() {
    Comparator<String> comparator =
        Ordering.natural().onResultOf(StringLengthFunction.StringLength);
    assertTrue(comparator.compare("to", "be") == 0);
    assertTrue(comparator.compare("or", "not") < 0);
    assertTrue(comparator.compare("that", "to") > 0);

    new EqualsTester()
        .addEqualityGroup(
            comparator, Ordering.natural().onResultOf(StringLengthFunction.StringLength))
        .addEqualityGroup(DECREASING_INTEGER)
        .testEquals();
    reserializeAndAssert(comparator);
    assertEquals("Ordering.natural().onResultOf(StringLength)", comparator.toString());
  }
Пример #12
0
 /**
  * Returns the minimal range that {@linkplain Range#contains(Comparable) contains} all of the
  * given values. The returned range is {@linkplain BoundType#CLOSED closed} on both ends.
  *
  * @throws ClassCastException if the parameters are not <i>mutually comparable</i>
  * @throws NoSuchElementException if {@code values} is empty
  * @throws NullPointerException if any of {@code values} is null
  */
 public static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) {
   checkNotNull(values);
   if (values instanceof ContiguousSet) {
     return ((ContiguousSet<C>) values).range();
   }
   Iterator<C> valueIterator = values.iterator();
   C min = checkNotNull(valueIterator.next());
   C max = min;
   while (valueIterator.hasNext()) {
     C value = checkNotNull(valueIterator.next());
     min = Ordering.natural().min(min, value);
     max = Ordering.natural().max(max, value);
   }
   return closed(min, max);
 }
Пример #13
0
 public Weight(String feature, Vector weights, int n) {
   this.feature = feature;
   // pick out the weight with the largest abs value, but don't forget the sign
   Queue<Category> biggest = new PriorityQueue<Category>(n + 1, Ordering.natural());
   for (Vector.Element element : weights.all()) {
     biggest.add(new Category(element.index(), element.get()));
     while (biggest.size() > n) {
       biggest.poll();
     }
   }
   categories = Lists.newArrayList(biggest);
   Collections.sort(categories, Ordering.natural().reverse());
   value = categories.get(0).weight;
   maxIndex = categories.get(0).index;
 }
Пример #14
0
 public static <E extends Object & Comparable<? super E>> ImmutableSortedSet<E> of(E var0) {
   Object[] var1 = new Object[1];
   Object var2 = Preconditions.checkNotNull(var0);
   var1[0] = var2;
   Ordering var3 = Ordering.natural();
   return new RegularImmutableSortedSet(var1, var3);
 }
Пример #15
0
  private void serverAddedSegment(final DruidServerMetadata server, final DataSegment segment) {

    String segmentId = segment.getIdentifier();
    synchronized (lock) {
      log.debug("Adding segment[%s] for server[%s]", segment, server);

      ServerSelector selector = selectors.get(segmentId);
      if (selector == null) {
        selector = new ServerSelector(segment, tierSelectorStrategy);

        VersionedIntervalTimeline<String, ServerSelector> timeline =
            timelines.get(segment.getDataSource());
        if (timeline == null) {
          timeline = new VersionedIntervalTimeline<>(Ordering.natural());
          timelines.put(segment.getDataSource(), timeline);
        }

        timeline.add(
            segment.getInterval(),
            segment.getVersion(),
            segment.getShardSpec().createChunk(selector));
        selectors.put(segmentId, selector);
      }

      QueryableDruidServer queryableDruidServer = clients.get(server.getName());
      if (queryableDruidServer == null) {
        queryableDruidServer = addServer(baseView.getInventoryValue(server.getName()));
      }
      selector.addServerAndUpdateSegment(queryableDruidServer, segment);
    }
  }
Пример #16
0
 @Override
 public String errorMessage(String name) {
   String suffix =
       "Available attributes: "
           + Joiner.on(", ").join(Ordering.natural().sortedCopy(values.keySet()));
   return String.format(errorMessage, name) + "\n" + suffix;
 }
Пример #17
0
  @Override
  public void serializeInto(XcodeprojSerializer s) {
    super.serializeInto(s);

    s.addField("mainGroup", mainGroup);

    Collections.sort(
        targets,
        Ordering.natural()
            .onResultOf(
                new Function<PBXTarget, String>() {
                  @Override
                  public String apply(PBXTarget input) {
                    return input.getName();
                  }
                }));
    s.addField("targets", targets);
    s.addField("buildConfigurationList", buildConfigurationList);
    s.addField("compatibilityVersion", compatibilityVersion);

    NSDictionary d = new NSDictionary();
    d.put("LastUpgradeCheck", "0600");

    s.addField("attributes", d);
  }
Пример #18
0
  @Override
  @SuppressWarnings("StringEquality")
  public DefaultBuildInvocations buildAll(String modelName, Project project) {
    if (!canBuild(modelName)) {
      throw new GradleException("Unknown model name " + modelName);
    }

    DefaultProjectIdentifier projectIdentifier = getProjectIdentifier(project);
    // construct task selectors
    List<LaunchableGradleTaskSelector> selectors = Lists.newArrayList();
    Map<String, LaunchableGradleTaskSelector> selectorsByName = Maps.newTreeMap(Ordering.natural());
    Set<String> visibleTasks = Sets.newLinkedHashSet();
    findTasks(project, selectorsByName, visibleTasks);
    for (String selectorName : selectorsByName.keySet()) {
      LaunchableGradleTaskSelector selector = selectorsByName.get(selectorName);
      selectors.add(
          selector
              .setName(selectorName)
              .setTaskName(selectorName)
              .setProjectIdentifier(projectIdentifier)
              .setDisplayName(selectorName + " in " + project + " and subprojects.")
              .setPublic(visibleTasks.contains(selectorName)));
    }

    // construct project tasks
    List<LaunchableGradleTask> projectTasks = tasks(project);

    // construct build invocations from task selectors and project tasks
    return new DefaultBuildInvocations()
        .setSelectors(selectors)
        .setTasks(projectTasks)
        .setProjectIdentifier(projectIdentifier);
  }
Пример #19
0
 /**
  * Returns an immutable sorted multiset containing the given elements sorted by their natural
  * ordering.
  *
  * <p>This method is not type-safe, as it may be called on elements that are not mutually
  * comparable.
  *
  * @throws ClassCastException if the elements are not mutually comparable
  * @throws NullPointerException if any of {@code elements} is null
  */
 public static <E> ImmutableSortedMultiset<E> copyOf(Iterator<? extends E> elements) {
   // Hack around E not being a subtype of Comparable.
   // Unsafe, see ImmutableSortedMultisetFauxverideShim.
   @SuppressWarnings("unchecked")
   Ordering<E> naturalOrder = (Ordering<E>) Ordering.<Comparable>natural();
   return copyOf(naturalOrder, elements);
 }
Пример #20
0
  /** Remove completed queries after a waiting period */
  public void removeExpiredQueries() {
    List<QueryExecution> sortedQueries =
        IterableTransformer.on(queries.values())
            .select(compose(not(isNull()), endTimeGetter()))
            .orderBy(Ordering.natural().onResultOf(endTimeGetter()))
            .list();

    int toRemove = Math.max(sortedQueries.size() - maxQueryHistory, 0);
    DateTime oldestAllowedQuery = DateTime.now().minus(maxQueryAge.toMillis());

    for (QueryExecution queryExecution : sortedQueries) {
      try {
        DateTime endTime = queryExecution.getQueryInfo().getQueryStats().getEndTime();
        if ((endTime.isBefore(oldestAllowedQuery) || toRemove > 0) && isAbandoned(queryExecution)) {
          removeQuery(queryExecution.getQueryInfo().getQueryId());
          --toRemove;
        }
      } catch (RuntimeException e) {
        log.warn(
            e,
            "Error while inspecting age of query %s",
            queryExecution.getQueryInfo().getQueryId());
      }
    }
  }
  public void testDeterministic() {
    // A pentagon.
    Graph<String, String> graph = LinkedUndirectedGraph.create();
    graph.createNode("A");
    graph.createNode("B");
    graph.createNode("C");
    graph.createNode("D");
    graph.createNode("E");
    graph.connect("A", "-->", "B");
    graph.connect("B", "-->", "C");
    graph.connect("C", "-->", "D");
    graph.connect("D", "-->", "E");
    graph.connect("E", "-->", "A");

    GraphColoring<String, String> coloring =
        new GreedyGraphColoring<>(graph, Ordering.<String>natural());
    assertThat(coloring.color()).isEqualTo(3);
    validateColoring(graph);
    assertThat(coloring.getPartitionSuperNode("A")).isEqualTo("A");
    assertThat(coloring.getPartitionSuperNode("C")).isEqualTo("A");

    Comparator<String> biasD =
        new Comparator<String>() {
          @Override
          public int compare(String o1, String o2) {
            return o1.replace('D', '@').compareTo(o2.replace('D', '@'));
          }
        };

    coloring = new GreedyGraphColoring<>(graph, biasD);
    assertThat(coloring.color()).isEqualTo(3);
    validateColoring(graph);
    assertThat(coloring.getPartitionSuperNode("A")).isEqualTo("A");
    assertThat("A".equals(coloring.getPartitionSuperNode("C"))).isFalse();
  }
Пример #22
0
 private static ImmutableSortedSet<Method> findAllBenchmarkMethods(
     Class<?> benchmarkClass, Instrument instrument) throws InvalidBenchmarkException {
   ImmutableSortedSet.Builder<Method> result =
       ImmutableSortedSet.orderedBy(
           Ordering.natural()
               .onResultOf(
                   new Function<Method, String>() {
                     @Override
                     public String apply(Method method) {
                       return method.getName();
                     }
                   }));
   Set<String> benchmarkMethodNames = new HashSet<String>();
   Set<String> overloadedMethodNames = new TreeSet<String>();
   for (Method method : benchmarkClass.getDeclaredMethods()) {
     if (instrument.isBenchmarkMethod(method)) {
       method.setAccessible(true);
       result.add(method);
       if (!benchmarkMethodNames.add(method.getName())) {
         overloadedMethodNames.add(method.getName());
       }
     }
   }
   if (!overloadedMethodNames.isEmpty()) {
     throw new InvalidBenchmarkException(
         "Overloads are disallowed for benchmark methods, found overloads of %s in benchmark %s",
         overloadedMethodNames, benchmarkClass);
   }
   return result.build();
 }
  public void testOrderedPermutationSetRepeatedElementsSize() {
    List<Integer> list = newArrayList(1, 1, 1, 1, 2, 2, 3);
    Collection<List<Integer>> permutations =
        Collections2.orderedPermutations(list, Ordering.natural());

    assertPermutationsCount(105, permutations);
  }
  @Override
  public Iterator<? extends T> iterator(long first, long count) {
    Collection<T> data = dataModel.getObject();
    if (data == null || data.size() == 0) return Iterators.emptyIterator();
    Iterator<T> it;
    final SortParam<S> sortParam = getSort();
    if (sortParam != null && sortParam.getProperty() != null) {
      Ordering<T> ordering =
          Ordering.natural()
              .nullsFirst()
              .onResultOf(
                  new Function<T, Comparable<?>>() {

                    @Override
                    public Comparable<?> apply(T input) {
                      return comparableValue(input, sortParam.getProperty());
                    }
                  });
      if (!sortParam.isAscending()) ordering = ordering.reverse();
      it = ordering.sortedCopy(data).iterator();
    } else {
      it = data.iterator();
    }
    if (first > 0) Iterators.advance(it, (int) first);
    return count >= 0 ? Iterators.limit(it, (int) count) : it;
  }
Пример #25
0
 public int compareToGuava(Person that) {
   return ComparisonChain.start()
       .compare(this.lastName, that.lastName)
       .compare(this.firstName, that.firstName)
       .compare(this.zipCode, that.zipCode, Ordering.natural().nullsLast())
       .result();
 }
Пример #26
0
  protected void nmerge(String... witnessContents) throws Exception {
    final Collation<String> collation = new Collation<String>("Test", Ordering.<String>natural());

    final List<Witness> witnesses = Lists.newArrayListWithExpectedSize(witnessContents.length);
    int sigil = 0;
    for (String witness : witnessContents) {
      witnesses.add(
          collation.add(new SimpleWitness("W" + Integer.toString(++sigil)), tokenize(witness)));
    }

    for (Match<String> m : collation.getMatches()) {
      LOG.debug(m.toString());
    }

    final Converter<String> converter = new Converter<String>();
    final VariantGraph<String> graph =
        converter.create(collation.getMatches(), collation.getWitnesses());
    LOG.debug("\n" + graph.toString());

    for (Witness w : collation.getWitnesses()) {
      LOG.debug("{}: {}", w, Iterables.toString(collation.getVersion(w)));
    }

    final Witness base = witnesses.get(0);
    for (Chunk<String> ch : collation.compare(base, witnesses.get(1), ChunkState.ADDED)) {
      LOG.debug(ch.toString());
    }

    for (Variant<String> v : collation.getApparatus(base, 0, collation.getVersion(base).size())) {
      LOG.debug(v.toString());
    }
  }
Пример #27
0
  private void logEndpoints() {
    final StringBuilder stringBuilder = new StringBuilder(1024).append("\n\n");

    final ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    for (Object o : config.getSingletons()) {
      if (o.getClass().isAnnotationPresent(Path.class)) {
        builder.add(o.getClass());
      }
    }
    for (Class<?> klass : config.getClasses()) {
      if (klass.isAnnotationPresent(Path.class)) {
        builder.add(klass);
      }
    }

    for (Class<?> klass : builder.build()) {
      final String path = klass.getAnnotation(Path.class).value();
      final ImmutableList.Builder<String> endpoints = ImmutableList.builder();
      for (AnnotatedMethod method : annotatedMethods(klass)) {
        for (HttpMethod verb : method.getMetaMethodAnnotations(HttpMethod.class)) {
          endpoints.add(
              String.format("    %-7s %s (%s)", verb.value(), path, klass.getCanonicalName()));
        }
      }

      for (String line : Ordering.natural().sortedCopy(endpoints.build())) {
        stringBuilder.append(line).append('\n');
      }
    }

    LOG.info(stringBuilder.toString());
  }
Пример #28
0
 @Override
 public int compareTo(PluginInfo that) {
   return ComparisonChain.start()
       .compare(this.name, that.name)
       .compare(this.version, that.version, Ordering.natural().nullsFirst())
       .result();
 }
Пример #29
0
 @Override
 public int compareTo(ObjectDemo that) {
   return ComparisonChain.start()
       .compare(this.propertiesOne, that.propertiesOne)
       .compare(this.propertiesTwo, that.propertiesTwo, Ordering.<String>natural().nullsLast())
       .result();
 }
Пример #30
0
    @Override
    public Set<DataSegment> findUsedSegments(Set<SegmentIdentifier> identifiers)
        throws IOException {
      final VersionedIntervalTimeline<String, DataSegment> timeline =
          new VersionedIntervalTimeline<>(Ordering.natural());
      for (DataSegment dataSegment : appenderatorTester.getPushedSegments()) {
        timeline.add(
            dataSegment.getInterval(),
            dataSegment.getVersion(),
            dataSegment.getShardSpec().createChunk(dataSegment));
      }

      final Set<DataSegment> retVal = Sets.newHashSet();
      for (SegmentIdentifier identifier : identifiers) {
        for (TimelineObjectHolder<String, DataSegment> holder :
            timeline.lookup(identifier.getInterval())) {
          for (PartitionChunk<DataSegment> chunk : holder.getObject()) {
            if (identifiers.contains(SegmentIdentifier.fromDataSegment(chunk.getObject()))) {
              retVal.add(chunk.getObject());
            }
          }
        }
      }

      return retVal;
    }