Java Code Examples for com.google.common.collect.Ordering#from()

The following examples show how to use com.google.common.collect.Ordering#from() . 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: StreamSortHandlerTest.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Test
public void testSortedInPatient() throws InterruptedException {
    MockPartitionedCollector mockCollector = new MockPartitionedCollector();
    StreamTimeClockInLocalMemory timeClock = new StreamTimeClockInLocalMemory("sampleStream_1");
    Ordering<PartitionedEvent> timeOrdering = Ordering.from(PartitionedEventTimeOrderingComparator.INSTANCE);
    StreamSortWindowHandlerImpl sortHandler = new StreamSortWindowHandlerImpl();
    sortHandler.prepare("sampleStream_1", MockSampleMetadataFactory.createSampleStreamSortSpec("sampleStream_1", "PT1h", 5000), mockCollector);
    List<PartitionedEvent> sortedList = new LinkedList<>();

    int i = 0;
    while (i < 1000000) {
        PartitionedEvent event = MockSampleMetadataFactory.createRandomPartitionedEvent("sampleStream_1", System.currentTimeMillis() + i);
        sortHandler.nextEvent(event);
        sortedList.add(event);
        if (event.getTimestamp() > timeClock.getTime()) {
            timeClock.moveForward(event.getTimestamp());
        }
        sortHandler.onTick(timeClock, System.currentTimeMillis());
        i++;
    }
    sortHandler.close();
    Assert.assertTrue(timeOrdering.isOrdered(sortedList));
    Assert.assertTrue(timeOrdering.isOrdered(mockCollector.get()));
    Assert.assertEquals(1000000, mockCollector.get().size());
}
 
Example 2
Source File: OrderedResultIterator.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a comparator from the list of columns in ORDER BY clause.
 * @param orderByExpressions the columns in ORDER BY clause.
 * @return the comparator built from the list of columns in ORDER BY clause.
 */
// ImmutableBytesWritable.Comparator doesn't implement generics
@SuppressWarnings("unchecked")
private static Comparator<ResultEntry> buildComparator(List<OrderByExpression> orderByExpressions) {
    Ordering<ResultEntry> ordering = null;
    int pos = 0;
    for (OrderByExpression col : orderByExpressions) {
        Expression e = col.getExpression();
        Comparator<ImmutableBytesWritable> comparator = 
                e.getSortOrder() == SortOrder.DESC && !e.getDataType().isFixedWidth() 
                ? buildDescVarLengthComparator() 
                : new ImmutableBytesWritable.Comparator();
        Ordering<ImmutableBytesWritable> o = Ordering.from(comparator);
        if(!col.isAscending()) o = o.reverse();
        o = col.isNullsLast() ? o.nullsLast() : o.nullsFirst();
        Ordering<ResultEntry> entryOrdering = o.onResultOf(new NthKey(pos++));
        ordering = ordering == null ? entryOrdering : ordering.compound(entryOrdering);
    }
    return ordering;
}
 
Example 3
Source File: SimpleSearchProviderImplTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testSearchOrderByAuthorDescWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    // Add USER2 to two waves.
    if (i == 1 || i == 2) {
      WaveletOperation op1 = addParticipantToWavelet(USER1, name);
      WaveletOperation op2 = addParticipantToWavelet(USER2, name);
      submitDeltaToNewWavelet(name, USER1, op1, op2);
    } else {
      submitDeltaToNewWavelet(name, USER2, addParticipantToWavelet(USER2, name));
    }
  }
  SearchResult resultsAsc =
      searchProvider.search(USER2, "in:inbox orderby:creatordesc", 0, 10);
  assertEquals(10, resultsAsc.getNumResults());
  Ordering<SearchResult.Digest> descAuthorOrdering = Ordering.from(DESC_CREATOR_COMPARATOR);
  assertTrue(descAuthorOrdering.isOrdered(resultsAsc.getDigests()));
}
 
Example 4
Source File: DexAnnotator.java    From ZjDroid with Apache License 2.0 6 votes vote down vote up
public void writeAnnotations(Writer out) throws IOException {
    List<MapItem> mapItems = dexFile.getMapItems();
    // sort the map items based on the order defined by sectionAnnotationOrder
    Ordering<MapItem> ordering = Ordering.from(new Comparator<MapItem>() {
        @Override public int compare(MapItem o1, MapItem o2) {
            return Ints.compare(sectionAnnotationOrder.get(o1.getType()), sectionAnnotationOrder.get(o2.getType()));
        }
    });

    mapItems = ordering.immutableSortedCopy(mapItems);

    try {
        for (MapItem mapItem: mapItems) {
            SectionAnnotator annotator = annotators.get(mapItem.getType());
            annotator.annotateSection(this);
        }
    } finally {
        dexFile.writeAnnotations(out, this);
    }
}
 
Example 5
Source File: StreamSortHandlerTest.java    From eagle with Apache License 2.0 6 votes vote down vote up
/**
 * Used to debug window bucket lifecycle
 * <p>
 * Window period: PT1s, margin: 5s
 *
 * @throws InterruptedException
 */
@Test
public void testWithUnsortedEventsIn1MinuteWindow() throws InterruptedException {
    MockPartitionedCollector mockCollector = new MockPartitionedCollector();
    StreamTimeClockInLocalMemory timeClock = new StreamTimeClockInLocalMemory("sampleStream_1");
    Ordering<PartitionedEvent> timeOrdering = Ordering.from(PartitionedEventTimeOrderingComparator.INSTANCE);
    StreamSortWindowHandlerImpl sortHandler = new StreamSortWindowHandlerImpl();
    sortHandler.prepare("sampleStream_1", MockSampleMetadataFactory.createSampleStreamSortSpec("sampleStream_1", "PT1m", 5000), mockCollector);
    List<PartitionedEvent> unsortedList = new LinkedList<>();

    int i = 0;
    while (i < 1000) {
        PartitionedEvent event = MockSampleMetadataFactory.createRandomOutOfTimeOrderEventGroupedByName("sampleStream_1");
        sortHandler.nextEvent(event);
        unsortedList.add(event);
        if (event.getTimestamp() > timeClock.getTime()) {
            timeClock.moveForward(event.getTimestamp());
        }
        sortHandler.onTick(timeClock, System.currentTimeMillis());
        i++;
    }
    sortHandler.close();
    Assert.assertFalse(timeOrdering.isOrdered(unsortedList));
    Assert.assertTrue(timeOrdering.isOrdered(mockCollector.get()));
    Assert.assertTrue(mockCollector.get().size() > 0);
}
 
Example 6
Source File: ReplayPosition.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * Convenience method to compute the replay position for a group of SSTables.
 * @param sstables
 * @return the most recent (highest) replay position
 */
public static ReplayPosition getReplayPosition(Iterable<? extends SSTableReader> sstables)
{
    if (Iterables.isEmpty(sstables))
        return NONE;

    Function<SSTableReader, ReplayPosition> f = new Function<SSTableReader, ReplayPosition>()
    {
        public ReplayPosition apply(SSTableReader sstable)
        {
            return sstable.getReplayPosition();
        }
    };
    Ordering<ReplayPosition> ordering = Ordering.from(ReplayPosition.comparator);
    return ordering.max(Iterables.transform(sstables, f));
}
 
Example 7
Source File: QueryShuffleTransformation.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public List<TPatternMatch> shuffle(int nMatchesToModify) throws Exception {
	final Ordering<? super TPatternMatch> ordering = Ordering.from(comparator);

	// some tools, e.g. Neo4j require to be in a transaction to get properties
	// (used to get the ID properties for ordering)
	driver.beginTransaction();
	sortedMatches = ordering.sortedCopy(matches);
	driver.finishTransaction();

	final int size = sortedMatches.size();
	if (size < nMatchesToModify) {
		nMatchesToModify = size;
	}
	Collections.shuffle(sortedMatches, random);
	candidates = new ArrayList<>(nMatchesToModify);
	for (int i = 0; i < nMatchesToModify; i++) {
		final TPatternMatch candidate = sortedMatches.get(i);
		candidates.add(candidate);
	}

	return candidates;
}
 
Example 8
Source File: DexAnnotator.java    From AppTroy with Apache License 2.0 6 votes vote down vote up
public void writeAnnotations(Writer out) throws IOException {
    List<MapItem> mapItems = dexFile.getMapItems();
    // sort the map items based on the order defined by sectionAnnotationOrder
    Ordering<MapItem> ordering = Ordering.from(new Comparator<MapItem>() {
        @Override public int compare(MapItem o1, MapItem o2) {
            return Ints.compare(sectionAnnotationOrder.get(o1.getType()), sectionAnnotationOrder.get(o2.getType()));
        }
    });

    mapItems = ordering.immutableSortedCopy(mapItems);

    try {
        for (MapItem mapItem: mapItems) {
            SectionAnnotator annotator = annotators.get(mapItem.getType());
            annotator.annotateSection(this);
        }
    } finally {
        dexFile.writeAnnotations(out, this);
    }
}
 
Example 9
Source File: SimpleSearchProviderImplTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByCreatedDescWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:createddesc", 0, 10);
  Ordering<SearchResult.Digest> descOrdering = Ordering.from(DESC_CREATED_COMPARATOR);
  assertTrue(descOrdering.isOrdered(results.getDigests()));
}
 
Example 10
Source File: DagInfo.java    From tez with Apache License 2.0 5 votes vote down vote up
private Ordering<VertexInfo> getVertexOrdering() {
  return Ordering.from(new Comparator<VertexInfo>() {
    @Override public int compare(VertexInfo o1, VertexInfo o2) {
      return (o1.getTimeTaken() < o2.getTimeTaken()) ? -1 :
          ((o1.getTimeTaken() == o2.getTimeTaken()) ?
              0 : 1);
    }
  });
}
 
Example 11
Source File: SimpleSearchProviderImplTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByDescWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:datedesc", 0, 10);
  Ordering<SearchResult.Digest> descOrdering = Ordering.from(DESCENDING_DATE_COMPARATOR);
  assertTrue(descOrdering.isOrdered(results.getDigests()));
}
 
Example 12
Source File: SimpleSearchProviderImplTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByCreatedDescWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:createddesc", 0, 10);
  Ordering<SearchResult.Digest> descOrdering = Ordering.from(DESC_CREATED_COMPARATOR);
  assertTrue(descOrdering.isOrdered(results.getDigests()));
}
 
Example 13
Source File: SimpleSearchProviderImplTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByAscWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:dateasc", 0, 10);
  Ordering<SearchResult.Digest> ascOrdering = Ordering.from(ASCENDING_DATE_COMPARATOR);
  assertTrue(ascOrdering.isOrdered(results.getDigests()));
}
 
Example 14
Source File: OrderedResultIterator.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Builds a comparator from the list of columns in ORDER BY clause.
 * @param orderByExpressions the columns in ORDER BY clause.
 * @return the comparator built from the list of columns in ORDER BY clause.
 */
// ImmutableBytesWritable.Comparator doesn't implement generics
@SuppressWarnings("unchecked")
private static Comparator<ResultEntry> buildComparator(List<OrderByExpression> orderByExpressions) {
    Ordering<ResultEntry> ordering = null;
    int pos = 0;
    for (OrderByExpression col : orderByExpressions) {
        Ordering<ImmutableBytesWritable> o = Ordering.from(new ImmutableBytesWritable.Comparator());
        if(!col.isAscending()) o = o.reverse();
        o = col.isNullsLast() ? o.nullsLast() : o.nullsFirst();
        Ordering<ResultEntry> entryOrdering = o.onResultOf(new NthKey(pos++));
        ordering = ordering == null ? entryOrdering : ordering.compound(entryOrdering);
    }
    return ordering;
}
 
Example 15
Source File: ServiceCombDocumentationSwaggerMapper.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
private Multimap<String, ApiListing> filteringApiListings(Map.Entry<String, ApiListing> entry) {
  Multimap map = HashMultimap.create();
  ApiListing apiListing = entry.getValue();
  ApiListingBuilder apiListingBuilder = new ApiListingBuilder(Ordering.from(Orderings.apiPathCompatator()));
  apiListingBuilder.apiVersion(apiListing.getApiVersion())
      .basePath(apiListing.getBasePath())
      .resourcePath(apiListing.getResourcePath())
      .produces(validateContentType(apiListing.getProduces()
          , MediaType.APPLICATION_JSON)) // 02-02 only keep one produces
      .consumes(validateContentType(apiListing.getConsumes()
          , MediaType.APPLICATION_JSON))// 02-03 only keep one consumers
      .host(apiListing.getHost())
      .protocols(apiListing.getProtocols())
      .securityReferences(apiListing.getSecurityReferences())
      .models(apiListing.getModels())
      .description(apiListing.getDescription())
      .position(apiListing.getPosition())
      .tags(apiListing.getTags());

  List<ApiDescription> apiDescriptions = apiListing.getApis();
  List<ApiDescription> newApiDescriptions = new ArrayList<>(apiDescriptions.size());
  apiDescriptions.forEach(apiDescription -> newApiDescriptions.add(
      new ApiDescriptionBuilder(Ordering.from(Orderings.positionComparator()))
          .path(validatePath(apiDescription.getPath()))
          .description(apiDescription.getDescription())
          // 02-01 only keep the first operation and convert operation.
          .operations(Arrays.asList(validateOperation(apiDescription.getOperations().get(0))))
          .hidden(apiDescription.isHidden()).build())
  );

  apiListingBuilder.apis(newApiDescriptions);
  map.put(entry.getKey(), apiListingBuilder.build());
  return map;
}
 
Example 16
Source File: SimpleSearchProviderImplTest.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByCreatedAscWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:createdasc", 0, 10);
  Ordering<SearchResult.Digest> ascOrdering = Ordering.from(ASC_CREATED_COMPARATOR);
  assertTrue(ascOrdering.isOrdered(results.getDigests()));
}
 
Example 17
Source File: BasicBrooklynTypeRegistry.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Iterable<RegisteredType> getAllWithoutCatalog(Predicate<? super RegisteredType> filter) {
    // TODO optimisation? make indexes and look up?
    Ordering<RegisteredType> typeOrder = Ordering.from(RegisteredTypeNameThenBestFirstComparator.INSTANCE);
    return Locks.withLock(localRegistryLock.readLock(), 
        () -> localRegisteredTypesAndContainingBundles.values().stream().
            flatMap(m -> { return typeOrder.sortedCopy(m.values()).stream(); }).filter(filter::apply).collect(Collectors.toList()) );
}
 
Example 18
Source File: TaskInfo.java    From tez with Apache License 2.0 5 votes vote down vote up
private Ordering<TaskAttemptInfo> orderingOnAttemptStartTime() {
  return Ordering.from(new Comparator<TaskAttemptInfo>() {
    @Override public int compare(TaskAttemptInfo o1, TaskAttemptInfo o2) {
      return (o1.getStartTimeInterval() < o2.getStartTimeInterval()) ? -1 :
          ((o1.getStartTimeInterval() == o2.getStartTimeInterval()) ? 0 : 1);
    }
  });
}
 
Example 19
Source File: SimpleSearchProviderImplTest.java    From swellrt with Apache License 2.0 5 votes vote down vote up
public void testSearchOrderByCreatedAscWorks() throws Exception {
  for (int i = 0; i < 10; i++) {
    WaveletName name = WaveletName.of(WaveId.of(DOMAIN, String.valueOf(i)), WAVELET_ID);
    submitDeltaToNewWavelet(name, USER1, addParticipantToWavelet(USER1, name));
  }
  SearchResult results = searchProvider.search(USER1, "in:inbox orderby:createdasc", 0, 10);
  Ordering<SearchResult.Digest> ascOrdering = Ordering.from(ASC_CREATED_COMPARATOR);
  assertTrue(ascOrdering.isOrdered(results.getDigests()));
}
 
Example 20
Source File: Classification.java    From jpmml-evaluator with GNU Affero General Public License v3.0 4 votes vote down vote up
static
protected <K, V extends Number> Ordering<Map.Entry<K, Value<V>>> createOrdering(Type type){
	return Ordering.from((Map.Entry<K, Value<V>> left, Map.Entry<K, Value<V>> right) -> type.compareValues(left.getValue(), right.getValue()));
}