下面列出了怎么用java.util.function.LongSupplier的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
Predicate predicate = Predicate.create(mappingContext, example);
StatementBuilder.OngoingReadingAndReturn returning = predicate
.useWithReadingFragment(cypherGenerator::prepareMatchOf)
.returning(asterisk());
BuildableStatement returningWithPaging = addPagingParameter(predicate.getNeo4jPersistentEntity(), pageable,
returning);
Statement statement = returningWithPaging.build();
List<S> page = this.neo4jOperations.findAll(statement, predicate.getParameters(), example.getProbeType());
LongSupplier totalCountSupplier = () -> this.count(example);
return PageableExecutionUtils.getPage(page, pageable, totalCountSupplier);
}
private static LongSupplier blocksOfVariousBPV() {
final long mul = TestUtil.nextInt(random(), 1, 100);
final long min = random().nextInt();
return new LongSupplier() {
int i = Lucene80DocValuesFormat.NUMERIC_BLOCK_SIZE;
int maxDelta;
@Override
public long getAsLong() {
if (i == Lucene80DocValuesFormat.NUMERIC_BLOCK_SIZE) {
maxDelta = 1 << random().nextInt(5);
i = 0;
}
i++;
return min + mul * random().nextInt(maxDelta);
}
};
}
private DocumentsWriterDeleteQueue(InfoStream infoStream, long generation, long startSeqNo, LongSupplier previousMaxSeqId) {
this.infoStream = infoStream;
this.globalBufferedUpdates = new BufferedUpdates("global");
this.generation = generation;
this.nextSeqNo = new AtomicLong(startSeqNo);
this.startSeqNo = startSeqNo;
this.previousMaxSeqId = previousMaxSeqId;
long value = previousMaxSeqId.getAsLong();
assert value <= startSeqNo : "illegal max sequence ID: " + value + " start was: " + startSeqNo;
/*
* we use a sentinel instance as our initial tail. No slice will ever try to
* apply this tail since the head is always omitted.
*/
tail = new Node<>(null); // sentinel
globalSlice = new DeleteSlice(tail);
}
private static long[] getSorted(List<FollowerInfo> followers, boolean includeSelf,
ToLongFunction<FollowerInfo> getFollowerIndex, LongSupplier getLogIndex) {
final int length = includeSelf ? followers.size() + 1 : followers.size();
if (length == 0) {
throw new IllegalArgumentException("followers.size() == "
+ followers.size() + " and includeSelf == " + includeSelf);
}
final long[] indices = new long[length];
for (int i = 0; i < followers.size(); i++) {
indices[i] = getFollowerIndex.applyAsLong(followers.get(i));
}
if (includeSelf) {
// note that we also need to wait for the local disk I/O
indices[length - 1] = getLogIndex.getAsLong();
}
Arrays.sort(indices);
return indices;
}
public void testFullLongRange() throws Exception {
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(1, new LongSupplier() {
@Override
public long getAsLong() {
int thingToDo = r.nextInt(3);
switch (thingToDo) {
case 0: return Long.MIN_VALUE;
case 1: return Long.MAX_VALUE;
default: return TestUtil.nextLong(r, Long.MIN_VALUE, Long.MAX_VALUE);
}
}
});
}
}
private long[] getSorted(List<RaftPeerId> followerIDs, boolean includeSelf,
ToLongFunction<FollowerInfo> getFollowerIndex, LongSupplier getLogIndex) {
final int length = includeSelf ? followerIDs.size() + 1 : followerIDs.size();
if (length == 0) {
throw new IllegalArgumentException("followers.size() == "
+ followerIDs.size() + " and includeSelf == " + includeSelf);
}
final long[] indices = new long[length];
List<FollowerInfo> followerInfos = getFollowerInfos(followerIDs);
for (int i = 0; i < followerInfos.size(); i++) {
indices[i] = getFollowerIndex.applyAsLong(followerInfos.get(i));
}
if (includeSelf) {
// note that we also need to wait for the local disk I/O
indices[length - 1] = getLogIndex.getAsLong();
}
Arrays.sort(indices);
return indices;
}
public void testSparseFullLongRange() throws Exception {
assumeTrue("Requires sparse norms support", codecSupportsSparsity());
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(random().nextDouble(), new LongSupplier() {
@Override
public long getAsLong() {
int thingToDo = r.nextInt(3);
switch (thingToDo) {
case 0: return Long.MIN_VALUE;
case 1: return Long.MAX_VALUE;
default: return TestUtil.nextLong(r, Long.MIN_VALUE, Long.MAX_VALUE);
}
}
});
}
}
@SuppressWarnings("unchecked")
@Test
public void testForceRefresh() {
LongSupplier currentTimeSupplier = Mockito.mock(LongSupplier.class);
Mockito.when(currentTimeSupplier.getAsLong())
.thenReturn(0L, toMillis(5), toMillis(10), toMillis(15), toMillis(25));
Supplier<String> refreshFunction = Mockito.mock(Supplier.class);
Mockito.when(refreshFunction.get())
.thenReturn("a", "b", "c");
CachedObject<String> cachedName = new CachedObject<>(20, currentTimeSupplier);
assertEquals("a", cachedName.get(refreshFunction));
assertEquals("a", cachedName.get(refreshFunction));
assertEquals("b", cachedName.forceRefresh(refreshFunction));
assertEquals("b", cachedName.get(refreshFunction));
}
@Test
public void testSize() throws IOException {
sizeControllableFile = new SizeControllableFile(file, new FileSize() {
@Override
public long getSize(LongSupplier realSizeProvider) {
return realSizeProvider.getAsLong() - 100;
}
});
long totalLen = 0;
for (int i = 0; i < testCount; i++) {
int dataLen = randomInt(1, 1024);
sizeControllableFile.getFileChannel().write(ByteBuffer.wrap(randomString(dataLen).getBytes()));
totalLen += dataLen;
Assert.assertEquals(totalLen - 100, sizeControllableFile.size());
}
}
ReaderPool(Directory directory, Directory originalDirectory, SegmentInfos segmentInfos,
FieldInfos.FieldNumbers fieldNumbers, LongSupplier completedDelGenSupplier, InfoStream infoStream,
String softDeletesField, StandardDirectoryReader reader) throws IOException {
this.directory = directory;
this.originalDirectory = originalDirectory;
this.segmentInfos = segmentInfos;
this.fieldNumbers = fieldNumbers;
this.completedDelGenSupplier = completedDelGenSupplier;
this.infoStream = infoStream;
this.softDeletesField = softDeletesField;
if (reader != null) {
// Pre-enroll all segment readers into the reader pool; this is necessary so
// any in-memory NRT live docs are correctly carried over, and so NRT readers
// pulled from this IW share the same segment reader:
List<LeafReaderContext> leaves = reader.leaves();
assert segmentInfos.size() == leaves.size();
for (int i=0;i<leaves.size();i++) {
LeafReaderContext leaf = leaves.get(i);
SegmentReader segReader = (SegmentReader) leaf.reader();
SegmentReader newReader = new SegmentReader(segmentInfos.info(i), segReader, segReader.getLiveDocs(),
segReader.getHardLiveDocs(), segReader.numDocs(), true);
readerMap.put(newReader.getOriginalSegmentInfo(), new ReadersAndUpdates(segmentInfos.getIndexCreatedVersionMajor(),
newReader, newPendingDeletes(newReader, newReader.getOriginalSegmentInfo())));
}
}
}
/**
* Measures execution time of {@code supplier#getAsLong} and logs it via the
* given {@code logger}.
* @return the same value as returned by {@code supplier#getAsLong}
*/
protected static long time(LongSupplier supplier, Logger logger) {
long start = Time.monotonicNow();
long result = supplier.getAsLong();
long end = Time.monotonicNow();
long elapsed = end - start;
logger.debug("Completed check in {} ms, result: {}", elapsed, result);
return result;
}
public void testFewValues() throws Exception {
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(1, new LongSupplier() {
@Override
public long getAsLong() {
return r.nextBoolean() ? 20 : 3;
}
});
}
}
public void testOutliers() throws Exception {
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
final long commonValue = TestUtil.nextLong(r, Byte.MIN_VALUE, Byte.MAX_VALUE);
doTestNormsVersusDocValues(1, new LongSupplier() {
@Override
public long getAsLong() {
return r.nextInt(100) == 0 ? TestUtil.nextLong(r, Byte.MIN_VALUE, Byte.MAX_VALUE) : commonValue;
}
});
}
}
public void testSparseByteRange() throws Exception {
assumeTrue("Requires sparse norms support", codecSupportsSparsity());
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(random().nextDouble(), new LongSupplier() {
@Override
public long getAsLong() {
return TestUtil.nextLong(r, Byte.MIN_VALUE, Byte.MAX_VALUE);
}
});
}
}
public void testShortRange() throws Exception {
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(1, new LongSupplier() {
@Override
public long getAsLong() {
return TestUtil.nextLong(r, Short.MIN_VALUE, Short.MAX_VALUE);
}
});
}
}
@Override
public Page<T> findAll(Pageable pageable) {
OngoingReadingAndReturn returning = cypherGenerator.prepareMatchOf(entityMetaData)
.returning(cypherGenerator.createReturnStatementForMatch(entityMetaData));
StatementBuilder.BuildableStatement returningWithPaging =
addPagingParameter(entityMetaData, pageable, returning);
Statement statement = returningWithPaging.build();
List<T> allResult = this.neo4jOperations.findAll(statement, entityInformation.getJavaType());
LongSupplier totalCountSupplier = this::count;
return PageableExecutionUtils.getPage(allResult, pageable, totalCountSupplier);
}
public void testZeroOrMin() throws Exception {
// try to make GCD compression fail if the format did not anticipate that
// the GCD of 0 and MIN_VALUE is negative
int numIterations = atLeast(1);
for (int i = 0; i < numIterations; i++) {
final LongSupplier longs = () -> {
return random().nextBoolean() ? 0 : Long.MIN_VALUE;
};
doTestNumericsVsStoredFields(1, longs);
}
}
public void testAllZeros() throws Exception {
int iterations = atLeast(1);
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(1, new LongSupplier() {
@Override
public long getAsLong() {
return 0;
}
});
}
}
private void doTestSparseNumericBlocksOfVariousBitsPerValue(double density) throws Exception {
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(new MockAnalyzer(random()));
conf.setMaxBufferedDocs(atLeast(Lucene80DocValuesFormat.NUMERIC_BLOCK_SIZE));
conf.setRAMBufferSizeMB(-1);
conf.setMergePolicy(newLogMergePolicy(random().nextBoolean()));
IndexWriter writer = new IndexWriter(dir, conf);
Document doc = new Document();
Field storedField = newStringField("stored", "", Field.Store.YES);
Field dvField = new NumericDocValuesField("dv", 0);
doc.add(storedField);
doc.add(dvField);
final int numDocs = atLeast(Lucene80DocValuesFormat.NUMERIC_BLOCK_SIZE*3);
final LongSupplier longs = blocksOfVariousBPV();
for (int i = 0; i < numDocs; i++) {
if (random().nextDouble() > density) {
writer.addDocument(new Document());
continue;
}
long value = longs.getAsLong();
storedField.setStringValue(Long.toString(value));
dvField.setLongValue(value);
writer.addDocument(doc);
}
writer.forceMerge(1);
writer.close();
// compare
assertDVIterate(dir);
assertDVAdvance(dir, 1); // Tests all jump-lengths from 1 to maxDoc (quite slow ~= 1 minute for 200K docs)
dir.close();
}
FromBlockingIterablePublisher(final BlockingIterable<? extends T> iterable,
final LongSupplier timeoutSupplier,
final TimeUnit unit) {
this.iterable = requireNonNull(iterable);
this.timeoutSupplier = requireNonNull(timeoutSupplier);
this.unit = requireNonNull(unit);
}
private Optional<MinMajorityMax> getMajorityMin(ToLongFunction<FollowerInfo> followerIndex, LongSupplier logIndex) {
final RaftPeerId selfId = server.getId();
final RaftConfiguration conf = server.getRaftConf();
final List<FollowerInfo> followers = voterLists.get(0);
final boolean includeSelf = conf.containsInConf(selfId);
if (followers.isEmpty() && !includeSelf) {
return Optional.empty();
}
final long[] indicesInNewConf = getSorted(followers, includeSelf, followerIndex, logIndex);
final MinMajorityMax newConf = MinMajorityMax.valueOf(indicesInNewConf);
if (!conf.isTransitional()) {
return Optional.of(newConf);
} else { // configuration is in transitional state
final List<FollowerInfo> oldFollowers = voterLists.get(1);
final boolean includeSelfInOldConf = conf.containsInOldConf(selfId);
if (oldFollowers.isEmpty() && !includeSelfInOldConf) {
return Optional.empty();
}
final long[] indicesInOldConf = getSorted(oldFollowers, includeSelfInOldConf, followerIndex, logIndex);
final MinMajorityMax oldConf = MinMajorityMax.valueOf(indicesInOldConf);
return Optional.of(newConf.combine(oldConf));
}
}
private void doTestGCDCompression(double density) throws Exception {
int numIterations = atLeast(1);
for (int i = 0; i < numIterations; i++) {
final long min = - (((long) random().nextInt(1 << 30)) << 32);
final long mul = random().nextInt() & 0xFFFFFFFFL;
final LongSupplier longs = () -> {
return min + mul * random().nextInt(1 << 20);
};
doTestNumericsVsStoredFields(density, longs);
}
}
public default Optional<Merge> getMergeAction(
final long from,
final long into,
final LongSupplier newSegmentId)
{
return Optional.empty();
}
@Test
public void testLazyOpen() throws IOException {
sizeControllableFile = new SizeControllableFile(file, new FileSize() {
@Override
public long getSize(LongSupplier realSizeProvider) {
return realSizeProvider.getAsLong();
}
}) {
@Override
protected void doOpen() throws IOException {
openCount.incrementAndGet();
super.doOpen();
}
};
Assert.assertEquals(0, openCount.get());
for (int i = 0; i < testCount; i++) {
sizeControllableFile.getFileChannel();
sizeControllableFile.size();
Assert.assertEquals(1, openCount.get());
}
sizeControllableFile.close();
for (int i = 0; i < testCount; i++) {
sizeControllableFile.getFileChannel();
sizeControllableFile.size();
Assert.assertEquals(2, openCount.get());
}
}
private void record(LongSupplier sampleSupplier) {
rotate();
long sample = sampleSupplier.getAsLong();
for (AtomicLong max : ringBuffer) {
updateMax(max, sample);
}
}
ClientSideState(final Edition edition, final LongSupplier timeSource, final Supplier<byte[]> ivSource,
final Function<Object, byte[]> serialization, final BiFunction<Class<?>, byte[], Object> deserialization, final int timeout) {
this.edition = edition;
this.timeSource = timeSource;
this.ivSource = ivSource;
this.serialization = serialization;
this.deserialization = deserialization;
this.timeout = timeout;
}
public static StateMachineMetrics getStateMachineMetrics(
RaftServerImpl server, RaftLogIndex appliedIndex,
StateMachine stateMachine) {
String serverId = server.getMemberId().toString();
LongSupplier getApplied = appliedIndex::get;
LongSupplier getApplyCompleted =
() -> (stateMachine.getLastAppliedTermIndex() == null) ? -1
: stateMachine.getLastAppliedTermIndex().getIndex();
return new StateMachineMetrics(serverId, getApplied, getApplyCompleted);
}
private StateMachineMetrics(String serverId, LongSupplier getApplied,
LongSupplier getApplyCompleted) {
registry = getMetricRegistryForStateMachine(serverId);
registry.gauge(STATEMACHINE_APPLIED_INDEX_GAUGE,
() -> () -> getApplied.getAsLong());
registry.gauge(STATEMACHINE_APPLY_COMPLETED_GAUGE,
() -> () -> getApplyCompleted.getAsLong());
}
private Optional<MinMajorityMax> getMajorityMin(ToLongFunction<FollowerInfo> followerIndex, LongSupplier logIndex) {
final RaftPeerId selfId = server.getId();
final RaftConfiguration conf = server.getRaftConf();
final List<RaftPeerId> followers = voterLists.get(0);
final boolean includeSelf = conf.containsInConf(selfId);
if (followers.isEmpty() && !includeSelf) {
return Optional.empty();
}
final long[] indicesInNewConf = getSorted(followers, includeSelf, followerIndex, logIndex);
final MinMajorityMax newConf = MinMajorityMax.valueOf(indicesInNewConf);
if (!conf.isTransitional()) {
return Optional.of(newConf);
} else { // configuration is in transitional state
final List<RaftPeerId> oldFollowers = voterLists.get(1);
final boolean includeSelfInOldConf = conf.containsInOldConf(selfId);
if (oldFollowers.isEmpty() && !includeSelfInOldConf) {
return Optional.empty();
}
final long[] indicesInOldConf = getSorted(oldFollowers, includeSelfInOldConf, followerIndex, logIndex);
final MinMajorityMax oldConf = MinMajorityMax.valueOf(indicesInOldConf);
return Optional.of(newConf.combine(oldConf));
}
}
public void testSparseLongRange() throws Exception {
assumeTrue("Requires sparse norms support", codecSupportsSparsity());
int iterations = atLeast(1);
final Random r = random();
for (int i = 0; i < iterations; i++) {
doTestNormsVersusDocValues(random().nextDouble(), new LongSupplier() {
@Override
public long getAsLong() {
return TestUtil.nextLong(r, Long.MIN_VALUE, Long.MAX_VALUE);
}
});
}
}