Java Code Examples for java.util.OptionalInt#of()

The following examples show how to use java.util.OptionalInt#of() . 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: BlockchainUtil.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * General utility to process a list of headers and a blockchain, sussing out which header in the
 * input list is simultaneously the highest order block number and a direct match with one of the
 * headers of the local chain. The purpose of which being to determine the point of departure in
 * fork scenarios.
 *
 * @param blockchain our local copy of the blockchain
 * @param headers the list of remote headers
 * @param ascendingHeaderOrder whether the headers are sorted in ascending or descending order
 * @return index of the highest known header, or an empty value if no header is known
 */
public static OptionalInt findHighestKnownBlockIndex(
    final Blockchain blockchain,
    final List<BlockHeader> headers,
    final boolean ascendingHeaderOrder) {
  final int offset = ascendingHeaderOrder ? -1 : 0;
  final Comparator<BlockHeader> comparator =
      knownBlockComparator(blockchain, ascendingHeaderOrder);

  final int insertionIndex = -Collections.binarySearch(headers, null, comparator) - 1;
  final int ancestorIndex = insertionIndex + offset;
  if (ancestorIndex < 0 || ancestorIndex >= headers.size()) {
    return OptionalInt.empty();
  }
  return OptionalInt.of(ancestorIndex);
}
 
Example 2
Source File: TcpKeepaliveOption.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Converts the wire format of an EDNS Option (the option data only) into the type-specific
 * format.
 *
 * @param in The input stream.
 */
@Override
void optionFromWire(DNSInput in) throws IOException {
  int length = in.remaining();

  switch (length) {
    case 0:
      timeout = OptionalInt.empty();
      break;
    case 2:
      timeout = OptionalInt.of(in.readU16());
      break;
    default:
      throw new WireParseException(
          "invalid length (" + length + ") of the data in the edns_tcp_keepalive option");
  }
}
 
Example 3
Source File: LockedApplication.java    From vespa with Apache License 2.0 5 votes vote down vote up
/** Set a major version for this, or set to null to remove any major version override */
public LockedApplication withMajorVersion(Integer majorVersion) {
    return new LockedApplication(lock, id, createdAt, deploymentSpec, validationOverrides,
                                 deploymentIssueId, ownershipIssueId, owner,
                                 majorVersion == null ? OptionalInt.empty() : OptionalInt.of(majorVersion),
                                 metrics, deployKeys, projectId, latestVersion, instances);
}
 
Example 4
Source File: AggregationMode.java    From buck with Apache License 2.0 5 votes vote down vote up
AggregationMode(int minimumDepth) {
  if (minimumDepth <= 0) {
    throw new HumanReadableException(
        "Aggregation level must be a positive integer (got " + minimumDepth + ")");
  }

  this.minimumDepth = OptionalInt.of(minimumDepth);
}
 
Example 5
Source File: TestDictionaryCompressionOptimizer.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public OptionalInt tryConvertToDirect(int maxDirectBytes)
{
    assertFalse(direct);
    long directBytes = (long) (rowCount * valuesPerRow * bytesPerEntry);
    if (directBytes <= maxDirectBytes) {
        direct = true;
        return OptionalInt.of(toIntExact(directBytes));
    }
    else {
        return OptionalInt.empty();
    }
}
 
Example 6
Source File: AmountInputMessageReader.java    From luna with MIT License 5 votes vote down vote up
@Override
public Event read(Player player, GameMessage msg) throws Exception {
    OptionalInt number = OptionalInt.of(msg.getPayload().getInt());
    AbstractInterfaceSet interfaces = player.getInterfaces();

    Optional<InputInterface> inputOptional = interfaces.getCurrentInput();
    if (inputOptional.isPresent()) {
        inputOptional.get().applyInput(player, number, Optional.empty());
        interfaces.resetCurrentInput();
    }
    return null;
}
 
Example 7
Source File: CellPositioner.java    From Flowless with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public OptionalInt firstVisibleAfter(int position) {
    MemoizationList<C> cells = cellManager.getLazyCellList();
    int presentBefore = cells.getMemoizedCountBefore(position);
    int present = cells.getMemoizedCount();
    for(int i = presentBefore; i < present; ++i) {
        C cell = cells.memoizedItems().get(i);
        if(cell.getNode().isVisible()) {
            return OptionalInt.of(cells.indexOfMemoizedItem(i));
        }
    }
    return OptionalInt.empty();
}
 
Example 8
Source File: MySqlExtension.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetches the database ID of the given name from the database.
 *
 * @param name the name to get the ID for
 * @param con connection to the sql table
 * @return id of the playerAuth, or empty OptionalInt if the name is not registered
 * @throws SQLException .
 */
protected OptionalInt retrieveIdFromTable(String name, Connection con) throws SQLException {
    String sql = "SELECT " + col.ID + " FROM " + tableName + " WHERE " + col.NAME + "=?;";
    try (PreparedStatement pst = con.prepareStatement(sql)) {
        pst.setString(1, name);
        try (ResultSet rs = pst.executeQuery()) {
            if (rs.next()) {
                return OptionalInt.of(rs.getInt(col.ID));
            }
        }
    }
    return OptionalInt.empty();
}
 
Example 9
Source File: EnodeURL.java    From besu with Apache License 2.0 5 votes vote down vote up
public static EnodeURL fromURI(final URI uri) {
  checkArgument(uri != null, "URI cannot be null");
  checkStringArgumentNotEmpty(uri.getScheme(), "Missing 'enode' scheme.");
  checkStringArgumentNotEmpty(uri.getHost(), "Missing or invalid ip address.");
  checkStringArgumentNotEmpty(uri.getUserInfo(), "Missing node ID.");

  checkArgument(
      uri.getScheme().equalsIgnoreCase("enode"), "Invalid URI scheme (must equal \"enode\").");
  checkArgument(
      NODE_ID_PATTERN.matcher(uri.getUserInfo()).matches(),
      "Invalid node ID: node ID must have exactly 128 hexadecimal characters and should not include any '0x' hex prefix.");

  final Bytes id = Bytes.fromHexString(uri.getUserInfo());
  String host = uri.getHost();
  int tcpPort = uri.getPort();

  // Parse discport if it exists
  OptionalInt discoveryPort = OptionalInt.empty();
  String query = uri.getQuery();
  if (query != null) {
    final Matcher discPortMatcher = DISCPORT_QUERY_STRING_REGEX.matcher(query);
    if (discPortMatcher.matches()) {
      Integer discPort = Ints.tryParse(discPortMatcher.group(1));
      discoveryPort = discPort == null ? discoveryPort : OptionalInt.of(discPort);
    }
    checkArgument(discoveryPort.isPresent(), "Invalid discovery port: '" + query + "'.");
  } else {
    discoveryPort = OptionalInt.of(tcpPort);
  }

  return builder()
      .ipAddress(host)
      .nodeId(id)
      .listeningPort(tcpPort)
      .discoveryPort(discoveryPort)
      .build();
}
 
Example 10
Source File: ServiceRuntimeAdapter.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
/**
 * Notifies the runtime of the block commit event.
 *
 * @param snapshotHandle a handle to the native snapshot object
 * @param validatorId a validator id. Negative if this node is not a validator
 * @param height the current blockchain height
 * @throws CloseFailuresException if there was a failure in destroying some native peers
 * @see ServiceRuntime#afterCommit(Snapshot, OptionalInt, long)
 */
void afterCommit(long snapshotHandle, int validatorId, long height)
    throws CloseFailuresException {
  try (Cleaner cleaner = new Cleaner("afterCommit")) {
    Snapshot snapshot = accessFactory.createSnapshot(snapshotHandle, cleaner);
    OptionalInt optionalValidatorId = validatorId >= 0
        ? OptionalInt.of(validatorId)
        : OptionalInt.empty();
    serviceRuntime.afterCommit(snapshot, optionalValidatorId, height);
  } catch (CloseFailuresException e) {
    handleCloseFailure(e);
  }
}
 
Example 11
Source File: OptionalIntScalar.java    From doma with Apache License 2.0 4 votes vote down vote up
@Override
public OptionalInt get() {
  Integer value = wrapper.get();
  return value != null ? OptionalInt.of(value) : OptionalInt.empty();
}
 
Example 12
Source File: BehindStatus.java    From GitToolBox with Apache License 2.0 4 votes vote down vote up
public OptionalInt delta() {
  return delta != null ? OptionalInt.of(delta) : OptionalInt.empty();
}
 
Example 13
Source File: FindOps.java    From Java8CN with Apache License 2.0 4 votes vote down vote up
@Override
public OptionalInt get() {
    return hasValue ? OptionalInt.of(value) : null;
}
 
Example 14
Source File: HivePageSinkProvider.java    From presto with Apache License 2.0 4 votes vote down vote up
private ConnectorPageSink createPageSink(HiveWritableTableHandle handle, boolean isCreateTable, ConnectorSession session, Map<String, String> additionalTableParameters)
{
    OptionalInt bucketCount = OptionalInt.empty();
    List<SortingColumn> sortedBy = ImmutableList.of();

    if (handle.getBucketProperty().isPresent()) {
        bucketCount = OptionalInt.of(handle.getBucketProperty().get().getBucketCount());
        sortedBy = handle.getBucketProperty().get().getSortedBy();
    }

    HiveWriterFactory writerFactory = new HiveWriterFactory(
            fileWriterFactories,
            handle.getSchemaName(),
            handle.getTableName(),
            isCreateTable,
            handle.getInputColumns(),
            handle.getTableStorageFormat(),
            handle.getPartitionStorageFormat(),
            additionalTableParameters,
            bucketCount,
            sortedBy,
            handle.getLocationHandle(),
            locationService,
            session.getQueryId(),
            new HivePageSinkMetadataProvider(
                    handle.getPageSinkMetadata(),
                    new HiveMetastoreClosure(memoizeMetastore(metastore, perTransactionMetastoreCacheMaximumSize)),
                    new HiveIdentity(session)),
            typeManager,
            hdfsEnvironment,
            pageSorter,
            writerSortBufferSize,
            maxOpenSortFiles,
            immutablePartitions,
            session,
            nodeManager,
            eventClient,
            hiveSessionProperties,
            hiveWriterStats);

    return new HivePageSink(
            writerFactory,
            handle.getInputColumns(),
            handle.getBucketProperty(),
            pageIndexerFactory,
            hdfsEnvironment,
            maxOpenPartitions,
            writeVerificationExecutor,
            partitionUpdateCodec,
            session);
}
 
Example 15
Source File: FindOps.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@Override
public OptionalInt get() {
    return hasValue ? OptionalInt.of(value) : null;
}
 
Example 16
Source File: FindOps.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
@Override
public OptionalInt get() {
    return hasValue ? OptionalInt.of(value) : null;
}
 
Example 17
Source File: PeerPermissionsDenylist.java    From besu with Apache License 2.0 4 votes vote down vote up
public static PeerPermissionsDenylist create(final int maxSize) {
  return new PeerPermissionsDenylist(OptionalInt.of(maxSize));
}
 
Example 18
Source File: FailedToMovePartitionEvent.java    From java-dcp-client with Apache License 2.0 4 votes vote down vote up
/**
 * The partition ID which has caused issue
 */
public OptionalInt partition() {
  return OptionalInt.of(partition);
}
 
Example 19
Source File: Artist.java    From gplaymusic with MIT License 4 votes vote down vote up
public OptionalInt getTotalAlbums() {
  return OptionalInt.of(totalAlbums);
}
 
Example 20
Source File: OneInputOperatorTransformation.java    From flink with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the maximum parallelism of this operator.
 *
 * <p>The maximum parallelism specifies the upper bound for dynamic scaling. It also defines the
 * number of key groups used for partitioned state.
 *
 * @param maxParallelism Maximum parallelism
 * @return The operator with set maximum parallelism
 */
@PublicEvolving
public OneInputOperatorTransformation<T> setMaxParallelism(int maxParallelism) {
	this.operatorMaxParallelism = OptionalInt.of(maxParallelism);
	return this;
}