Java Code Examples for java.util.OptionalLong#isPresent()

The following examples show how to use java.util.OptionalLong#isPresent() . 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: TabletRowAdapter.java    From timely with Apache License 2.0 6 votes vote down vote up
public static String toDebugOutput(TabletId tid) {
    StringJoiner joiner = new StringJoiner(", ", "[", "]");
    Text endRow = tid.getEndRow();
    if (null != endRow) {
        Optional<String> prefix = decodeRowPrefix(endRow);
        OptionalLong offset = decodeRowOffset(endRow);
        prefix.ifPresent(s -> joiner.add("prefix: " + s));
        if (offset.isPresent()) {
            LocalDateTime date = Instant.ofEpochMilli(offset.getAsLong()).atZone(ZoneId.of("UTC"))
                    .toLocalDateTime();
            joiner.add("date: " + date.toString());
            joiner.add("millis: " + offset.getAsLong());
        }
    }

    return joiner.toString();
}
 
Example 2
Source File: AbstractBlockParameterMethod.java    From besu with Apache License 2.0 6 votes vote down vote up
protected Object findResultByParamType(final JsonRpcRequestContext request) {
  final BlockParameter blockParam = blockParameter(request);

  final Object result;
  final OptionalLong blockNumber = blockParam.getNumber();
  if (blockNumber.isPresent()) {
    result = resultByBlockNumber(request, blockNumber.getAsLong());
  } else if (blockParam.isLatest()) {
    result = latestResult(request);
  } else {
    // If block parameter is not numeric or latest, it is pending.
    result = pendingResult(request);
  }

  return result;
}
 
Example 3
Source File: JsonGenesisConfigOptions.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public OptionalLong getBerlinBlockNumber() {
  if (ExperimentalEIPs.berlinEnabled) {
    final OptionalLong berlinBlock = getOptionalLong("berlinblock");
    final OptionalLong yolov1Block = getOptionalLong("yolov1block");
    if (yolov1Block.isPresent()) {
      if (berlinBlock.isPresent()) {
        throw new RuntimeException(
            "Genesis files cannot specify both berlinblock and yoloV1Block.");
      }
      return yolov1Block;
    }
    return berlinBlock;
  }
  return OptionalLong.empty();
}
 
Example 4
Source File: Boolean2ScorerSupplier.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private long computeCost() {
  OptionalLong minRequiredCost = Stream.concat(
      subs.get(Occur.MUST).stream(),
      subs.get(Occur.FILTER).stream())
      .mapToLong(ScorerSupplier::cost)
      .min();
  if (minRequiredCost.isPresent() && minShouldMatch == 0) {
    return minRequiredCost.getAsLong();
  } else {
    final Collection<ScorerSupplier> optionalScorers = subs.get(Occur.SHOULD);
    final long shouldCost = MinShouldMatchSumScorer.cost(
        optionalScorers.stream().mapToLong(ScorerSupplier::cost),
        optionalScorers.size(), minShouldMatch);
    return Math.min(minRequiredCost.orElse(Long.MAX_VALUE), shouldCost);
  }
}
 
Example 5
Source File: DateTieredCompactor.java    From hbase with Apache License 2.0 5 votes vote down vote up
private boolean needEmptyFile(CompactionRequestImpl request) {
  // if we are going to compact the last N files, then we need to emit an empty file to retain the
  // maxSeqId if we haven't written out anything.
  OptionalLong maxSeqId = StoreUtils.getMaxSequenceIdInList(request.getFiles());
  OptionalLong storeMaxSeqId = store.getMaxSequenceId();
  return maxSeqId.isPresent() && storeMaxSeqId.isPresent() &&
      maxSeqId.getAsLong() == storeMaxSeqId.getAsLong();
}
 
Example 6
Source File: CachingHiveMetastore.java    From presto with Apache License 2.0 5 votes vote down vote up
private static CacheBuilder<Object, Object> newCacheBuilder(OptionalLong expiresAfterWriteMillis, OptionalLong refreshMillis, long maximumSize)
{
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (expiresAfterWriteMillis.isPresent()) {
        cacheBuilder = cacheBuilder.expireAfterWrite(expiresAfterWriteMillis.getAsLong(), MILLISECONDS);
    }
    if (refreshMillis.isPresent() && (expiresAfterWriteMillis.isEmpty() || expiresAfterWriteMillis.getAsLong() > refreshMillis.getAsLong())) {
        cacheBuilder = cacheBuilder.refreshAfterWrite(refreshMillis.getAsLong(), MILLISECONDS);
    }
    cacheBuilder = cacheBuilder.maximumSize(maximumSize);
    return cacheBuilder;
}
 
Example 7
Source File: SqlStandardAccessControlMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private Set<RoleGrant> getRoleGrantsByRoles(Set<String> roles, OptionalLong limit)
{
    ImmutableSet.Builder<RoleGrant> roleGrants = ImmutableSet.builder();
    int count = 0;
    for (String role : roles) {
        if (limit.isPresent() && count >= limit.getAsLong()) {
            break;
        }
        for (RoleGrant grant : metastore.listGrantedPrincipals(role)) {
            count++;
            roleGrants.add(grant);
        }
    }
    return roleGrants.build();
}
 
Example 8
Source File: ISortedSet.java    From bifurcan with MIT License 5 votes vote down vote up
/**
 * @return the entry whose key is either equal to {@code key}, or just above it. If {@code key} is greater than the
 * maximum value in the map, returns {@code null}.
 */
default V ceil(V val) {
  OptionalLong idx = ceilIndex(val);
  return idx.isPresent()
      ? nth(idx.getAsLong())
      : null;
}
 
Example 9
Source File: ReplicationTracker.java    From crate with Apache License 2.0 5 votes vote down vote up
private static long inSyncCheckpointStates(
        final Map<String, CheckpointState> checkpoints,
        ToLongFunction<CheckpointState> function,
        Function<LongStream, OptionalLong> reducer) {
    final OptionalLong value =
            reducer.apply(
                    checkpoints
                            .values()
                            .stream()
                            .filter(cps -> cps.inSync)
                            .mapToLong(function)
                            .filter(v -> v != SequenceNumbers.PRE_60_NODE_CHECKPOINT && v != SequenceNumbers.UNASSIGNED_SEQ_NO));
    return value.isPresent() ? value.getAsLong() : SequenceNumbers.UNASSIGNED_SEQ_NO;
}
 
Example 10
Source File: ResourceRegionEncoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private byte[] getContentRangeHeader(ResourceRegion region) {
	long start = region.getPosition();
	long end = start + region.getCount() - 1;
	OptionalLong contentLength = contentLength(region.getResource());
	if (contentLength.isPresent()) {
		long length = contentLength.getAsLong();
		return getAsciiBytes("Content-Range: bytes " + start + '-' + end + '/' + length + "\r\n\r\n");
	}
	else {
		return getAsciiBytes("Content-Range: bytes " + start + '-' + end + "\r\n\r\n");
	}
}
 
Example 11
Source File: ISortedMap.java    From bifurcan with MIT License 5 votes vote down vote up
/**
 * @return the entry whose key is either equal to {@code key}, or just above it. If {@code key} is greater than the
 * maximum value in the map, returns {@code null}.
 */
default IEntry<K, V> ceil(K key) {
  OptionalLong idx = ceilIndex(key);
  return idx.isPresent()
      ? nth(idx.getAsLong())
      : null;
}
 
Example 12
Source File: ThriftMetastoreUtil.java    From presto with Apache License 2.0 5 votes vote down vote up
public static OptionalLong getTotalSizeInBytes(OptionalDouble averageColumnLength, OptionalLong rowCount, OptionalLong nullsCount)
{
    if (averageColumnLength.isPresent() && rowCount.isPresent() && nullsCount.isPresent()) {
        long nonNullsCount = rowCount.getAsLong() - nullsCount.getAsLong();
        if (nonNullsCount < 0) {
            return OptionalLong.empty();
        }
        return OptionalLong.of(round(averageColumnLength.getAsDouble() * nonNullsCount));
    }
    return OptionalLong.empty();
}
 
Example 13
Source File: OptionalMatchers.java    From java-8-matchers with MIT License 5 votes vote down vote up
/**
 * Matches a non empty OptionalLong with the given content
 *
 * @param content Expected contents of the Optional
 */
public static Matcher<OptionalLong> containsLong(long content) {
    return new TypeSafeMatcher<OptionalLong>() {
        @Override
        protected boolean matchesSafely(OptionalLong item) {
            return item.isPresent() && item.getAsLong() == content;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Optional.of(content).toString());
        }
    };
}
 
Example 14
Source File: Configurator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the last WUM updated timestamp from the wum summary file in the 'wumDir' path
 *
 * @return last WUM updated timestamp
 */
private static String getLastWumUpdatedTimestamp() {
    String lastWumUpdateTimestamp = "-1";
    Path wumDir = Paths.get(carbonHome, ConfigConstants.UPDATES_DIR, ConfigConstants.WUM_DIR);
    if (Files.exists(wumDir)) {
        OptionalLong max = OptionalLong.empty();
        try {
            // List files in WUM directory, filter file names for numbers and get the
            // timestamps from file names, then get the maximum timestamp as the
            // the last wum updated timestamp.
            max = Files.list(wumDir).filter(path -> !Files.isDirectory(path))
                    .map(path -> path.getFileName().toString()).filter(StringUtils::isNumeric)
                    .mapToLong(Long::parseLong).max();
        } catch (IOException e) {
            log.error("An error occurred when retrieving last wum update time.", e);
        }
        if (max.isPresent()) {
            lastWumUpdateTimestamp = String.valueOf(max.getAsLong());
        } else {
            log.warn("No WUM update information found in the file path: " + wumDir.toString());
        }
    } else {
        log.warn("WUM directory not found in the file path: " + wumDir.toString());
    }
    return lastWumUpdateTimestamp;
}
 
Example 15
Source File: JsonGenesisConfigOptions.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public OptionalLong getConstantinopleFixBlockNumber() {
  final OptionalLong petersburgBlock = getOptionalLong("petersburgblock");
  final OptionalLong constantinopleFixBlock = getOptionalLong("constantinoplefixblock");
  if (constantinopleFixBlock.isPresent()) {
    if (petersburgBlock.isPresent()) {
      throw new RuntimeException(
          "Genesis files cannot specify both petersburgBlock and constantinopleFixBlock.");
    }
    return constantinopleFixBlock;
  }
  return petersburgBlock;
}
 
Example 16
Source File: JsonGenesisConfigOptions.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public OptionalLong getDaoForkBlock() {
  final OptionalLong block = getOptionalLong("daoforkblock");
  if (block.isPresent() && block.getAsLong() <= 0) {
    return OptionalLong.empty();
  }
  return block;
}
 
Example 17
Source File: ConcatSortedMap.java    From bifurcan with MIT License 5 votes vote down vote up
@Override
public ConcatSortedMap<K, V> remove(K key) {
  OptionalLong oIdx = floorIndex(key);
  if (oIdx.isPresent() && keyEquality().test(key, nth(oIdx.getAsLong()).key())) {
    ConcatSortedMap<K, V> result = from(comparator, belowExclusive(oIdx.getAsLong()), aboveExclusive(oIdx.getAsLong()));
    if (isLinear) {
      this.segments = result.segments;
      this.segmentOffsets = result.segmentOffsets;
    } else {
      return result;
    }
  }

  return this;
}
 
Example 18
Source File: Policy.java    From caffeine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the duration until the entry should be automatically removed. The expiration policy
 * determines when the entry's duration is reset.
 *
 * @param key the key for the entry being queried
 * @return the duration if the entry is present in the cache
 */
@NonNull
default Optional<Duration> getExpiresAfter(@NonNull K key) {
  // This method will be abstract in version 3.0.0
  OptionalLong duration = getExpiresAfter(key, TimeUnit.NANOSECONDS);
  return duration.isPresent()
      ? Optional.of(Duration.ofNanos(duration.getAsLong()))
      : Optional.empty();
}
 
Example 19
Source File: SemiTransactionalHiveMetastore.java    From presto with Apache License 2.0 4 votes vote down vote up
private static OptionalLong firstPresent(OptionalLong first, OptionalLong second)
{
    return first.isPresent() ? first : second;
}
 
Example 20
Source File: CaffeineConfiguration.java    From caffeine with Apache License 2.0 4 votes vote down vote up
/**
 * Set the maximum weight.
 *
 * @param maximumWeight the maximum weighted size
 */
public void setMaximumWeight(OptionalLong maximumWeight) {
  this.maximumWeight = maximumWeight.isPresent()
      ? maximumWeight.getAsLong()
      : null;
}