Java Code Examples for java.util.function.LongSupplier

The following examples show how to use java.util.function.LongSupplier. These examples are extracted from open source projects. 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 Project: sdn-rx   Source File: SimpleQueryByExampleExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source Project: lucene-solr   Source File: TestLucene80DocValuesFormat.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
  };
}
 
Example 3
Source Project: lucene-solr   Source File: DocumentsWriterDeleteQueue.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source Project: ratis   Source File: LeaderState.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 6 votes vote down vote up
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);
        }
      }
    });
  }
}
 
Example 6
Source Project: incubator-ratis   Source File: LeaderState.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 6 votes vote down vote up
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);
        }
      }
    });
  }
}
 
Example 8
Source Project: multiapps-controller   Source File: CachedObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 9
Source Project: x-pipe   Source File: SizeControllableFileTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
	}
}
 
Example 10
Source Project: lucene-solr   Source File: ReaderPool.java    License: Apache License 2.0 6 votes vote down vote up
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())));
    }
  }
}
 
Example 11
Source Project: hadoop-ozone   Source File: AbstractSpaceUsageSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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;
      }
    });
  }
}
 
Example 13
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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;
      }
    });
  }
}
 
Example 14
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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);
      }
    });
  }
}
 
Example 15
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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);
      }
    });
  }
}
 
Example 16
Source Project: sdn-rx   Source File: SimpleNeo4jRepository.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 17
Source Project: lucene-solr   Source File: BaseDocValuesFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 18
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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;
      }
    });
  }
}
 
Example 19
Source Project: lucene-solr   Source File: TestLucene80DocValuesFormat.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 20
Source Project: servicetalk   Source File: FromBlockingIterablePublisher.java    License: Apache License 2.0 5 votes vote down vote up
FromBlockingIterablePublisher(final BlockingIterable<? extends T> iterable,
                              final LongSupplier timeoutSupplier,
                              final TimeUnit unit) {
    this.iterable = requireNonNull(iterable);
    this.timeoutSupplier = requireNonNull(timeoutSupplier);
    this.unit = requireNonNull(unit);
}
 
Example 21
Source Project: ratis   Source File: LeaderState.java    License: Apache License 2.0 5 votes vote down vote up
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));
  }
}
 
Example 22
Source Project: lucene-solr   Source File: BaseDocValuesFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 23
public default Optional<Merge> getMergeAction(
		final long from,
		final long into,
		final LongSupplier newSegmentId)
{
	return Optional.empty();
}
 
Example 24
Source Project: x-pipe   Source File: SizeControllableFileTest.java    License: Apache License 2.0 5 votes vote down vote up
@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());
	}
}
 
Example 25
Source Project: micrometer   Source File: TimeWindowMax.java    License: Apache License 2.0 5 votes vote down vote up
private void record(LongSupplier sampleSupplier) {
    rotate();
    long sample = sampleSupplier.getAsLong();
    for (AtomicLong max : ringBuffer) {
        updateMax(max, sample);
    }
}
 
Example 26
Source Project: syndesis   Source File: ClientSideState.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 27
Source Project: incubator-ratis   Source File: StateMachineMetrics.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 28
Source Project: incubator-ratis   Source File: StateMachineMetrics.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 29
Source Project: incubator-ratis   Source File: LeaderState.java    License: Apache License 2.0 5 votes vote down vote up
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));
  }
}
 
Example 30
Source Project: lucene-solr   Source File: BaseNormsFormatTestCase.java    License: Apache License 2.0 5 votes vote down vote up
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);
      }
    });
  }
}