类java.util.OptionalInt源码实例Demo

下面列出了怎么用java.util.OptionalInt的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: presto   文件: TaskContext.java
public static TaskContext createTaskContext(
        QueryContext queryContext,
        TaskStateMachine taskStateMachine,
        GcMonitor gcMonitor,
        Executor notificationExecutor,
        ScheduledExecutorService yieldExecutor,
        Session session,
        MemoryTrackingContext taskMemoryContext,
        boolean perOperatorCpuTimerEnabled,
        boolean cpuTimerEnabled,
        OptionalInt totalPartitions)
{
    TaskContext taskContext = new TaskContext(queryContext, taskStateMachine, gcMonitor, notificationExecutor, yieldExecutor, session, taskMemoryContext, perOperatorCpuTimerEnabled, cpuTimerEnabled, totalPartitions);
    taskContext.initialize();
    return taskContext;
}
 
源代码2 项目: buck   文件: ExecutionOrderAwareFakeStepTest.java
@Test
public void eachStepHasIncrementingExecutionOrder() {
  AtomicInteger order = new AtomicInteger(0);
  ExecutionOrderAwareFakeStep step1 = new ExecutionOrderAwareFakeStep("name", "desc", 0, order);
  ExecutionOrderAwareFakeStep step2 = new ExecutionOrderAwareFakeStep("name", "desc", 0, order);
  ExecutionOrderAwareFakeStep step3 = new ExecutionOrderAwareFakeStep("name", "desc", 0, order);
  ExecutionContext context = TestExecutionContext.newInstance();
  step1.execute(context);
  step2.execute(context);
  step3.execute(context);
  assertThat(step1.getExecutionBeginOrder(), equalTo(OptionalInt.of(0)));
  assertThat(step1.getExecutionEndOrder(), equalTo(OptionalInt.of(1)));
  assertThat(step2.getExecutionBeginOrder(), equalTo(OptionalInt.of(2)));
  assertThat(step2.getExecutionEndOrder(), equalTo(OptionalInt.of(3)));
  assertThat(step3.getExecutionBeginOrder(), equalTo(OptionalInt.of(4)));
  assertThat(step3.getExecutionEndOrder(), equalTo(OptionalInt.of(5)));
}
 
源代码3 项目: presto   文件: TestCompactionSetCreator.java
private static ShardIndexInfo shardWithTemporalBucket(OptionalInt bucketNumber, Type type, Long start, Long end)
{
    if (type.equals(DATE)) {
        return new ShardIndexInfo(
                1,
                bucketNumber,
                UUID.randomUUID(),
                1,
                1,
                Optional.empty(),
                Optional.of(ShardRange.of(new Tuple(type, start.intValue()), new Tuple(type, end.intValue()))));
    }
    return new ShardIndexInfo(
            1,
            bucketNumber,
            UUID.randomUUID(),
            1,
            1,
            Optional.empty(),
            Optional.of(ShardRange.of(new Tuple(type, start), new Tuple(type, end))));
}
 
源代码4 项目: onos   文件: NetconfDeviceInfo.java
/**
 * Information for contacting the controller.
 *
 * @param name      the connection type
 * @param password  the password for the device
 * @param ipAddress the ip address
 * @param port      the tcp port
 * @param path      the path part
 */
public NetconfDeviceInfo(String name, String password, IpAddress ipAddress,
                         int port, String path) {
    checkArgument(!name.equals(""), "Empty device username");
    checkArgument(port > 0, "Negative port");
    checkNotNull(ipAddress, "Null ip address");
    this.name = name;
    this.password = password;
    this.ipAddress = ipAddress;
    this.port = port;
    if (path == null || path.isEmpty()) {
        this.path = Optional.empty();
    } else {
        this.path = Optional.of(path);
    }
    this.sshClientLib = Optional.empty();
    this.connectTimeoutSec = OptionalInt.empty();
    this.replyTimeoutSec = OptionalInt.empty();
    this.idleTimeoutSec = OptionalInt.empty();
}
 
源代码5 项目: KaellyBot   文件: GuildLeaveListener.java
public void onReady(GuildDeleteEvent event) {
    try {

        Optional<Guild> optionalGuild = event.getGuild().map(guildEvent -> Guild.getGuild(guildEvent, false));
        if (optionalGuild.isPresent()) {
            Guild guild = optionalGuild.get();
            guild.removeToDatabase();

            LOG.info("La guilde " + event.getGuildId().asString() + " - " + guild.getName()
                    + " a supprimé " + Constants.name);

            ClientConfig.DISCORD()
                    .flatMap(cli -> cli.getChannelById(Snowflake.of(Constants.chanReportID)))
                    .filter(chan -> chan instanceof TextChannel)
                    .map(chan -> (TextChannel) chan)
                    .distinct()
                    .flatMap(chan -> chan.createMessage("[LOSE] **" + optionalGuild.get().getName() + "**, -"
                                    + event.getGuild().map(discord4j.core.object.entity.Guild::getMemberCount)
                            .orElse(OptionalInt.empty()).orElse(0) +  " utilisateurs"))
                    .subscribe();
        }
    } catch(Exception e){
        Reporter.report(e, event.getGuild().orElse(null));
        LOG.error("onReady", e);
    }
}
 
源代码6 项目: besu   文件: PacketTest.java
@Test
public void shouldDecodeValidPongPacket() {
  final Packet packet = decode(VALID_PONG_PACKET);
  final PongPacketData packetData = packet.getPacketData(PongPacketData.class).get();

  assertThat(packet.getType()).isSameAs(PacketType.PONG);
  assertThat(packetData.getTo())
      .isEqualTo(new Endpoint("180.181.122.26", 1025, OptionalInt.of(30303)));
  assertThat(packetData.getPingHash())
      .isEqualTo(
          Bytes.fromHexString(
              "0x46896547d3b4259aa1a67bd26e7ec58ab4be650c5552ef0360caf9dae489d53b"));
  assertThat(packetData.getExpiration()).isEqualTo(1535585736);
  assertThat(packet.getNodeId())
      .isEqualTo(
          Bytes.fromHexString(
              "0x669f45b66acf3b804c26ce13cfdd1f7e3d0ff4ed85060841b9af3af6dbfbacd05181e1c9363161446a307f3ca24e707856a01e4bf1eed5e1aefc14011a5c1c1c"));
  assertThat(packet.getHash())
      .isEqualTo(
          Bytes.fromHexString(
              "0xa1581c1705e744976d0341011c4490b3ab0b48283407ae5cf7526b9487174896"));
}
 
源代码7 项目: streamex   文件: IntStreamEx.java
/**
 * Returns the maximum element of this stream according to the provided key
 * extractor function.
 *
 * <p>
 * This is a terminal operation.
 *
 * @param <V> the type of the {@code Comparable} sort key
 * @param keyExtractor a non-interfering, stateless function
 * @return an {@code OptionalInt} describing the first element of this
 *         stream for which the highest value was returned by key extractor,
 *         or an empty {@code OptionalInt} if the stream is empty
 * @since 0.1.2
 */
public <V extends Comparable<? super V>> OptionalInt maxBy(IntFunction<V> keyExtractor) {
    ObjIntBox<V> result = collect(() -> new ObjIntBox<>(null, 0), (box, i) -> {
        V val = Objects.requireNonNull(keyExtractor.apply(i));
        if (box.a == null || box.a.compareTo(val) < 0) {
            box.a = val;
            box.b = i;
        }
    }, (box1, box2) -> {
        if (box2.a != null && (box1.a == null || box1.a.compareTo(box2.a) < 0)) {
            box1.a = box2.a;
            box1.b = box2.b;
        }
    });
    return result.a == null ? OptionalInt.empty() : OptionalInt.of(result.b);
}
 
源代码8 项目: openjdk-8   文件: BasicInt.java
@Test(groups = "unit")
public void testEmpty() {
    OptionalInt empty = OptionalInt.empty();
    OptionalInt present = OptionalInt.of(1);

    // empty
    assertTrue(empty.equals(empty));
    assertTrue(empty.equals(OptionalInt.empty()));
    assertTrue(!empty.equals(present));
    assertTrue(0 == empty.hashCode());
    assertTrue(!empty.toString().isEmpty());
    assertTrue(!empty.isPresent());
    empty.ifPresent(v -> { fail(); });
    assertEquals(2, empty.orElse(2));
    assertEquals(2, empty.orElseGet(()-> 2));
}
 
源代码9 项目: hono   文件: FileBasedCredentialsServiceTest.java
/**
 * Verifies that the <em>modificationEnabled</em> property prevents updating an existing entry.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateCredentialsFailsIfModificationIsDisabled(final VertxTestContext ctx) {

    // GIVEN a registry that has been configured to not allow modification of entries
    credentialsConfig.setModificationEnabled(false);

    final CommonCredential secret = createPasswordCredential("myId", "bar", OptionalInt.empty());

    // containing a set of credentials
    setCredentials(getCredentialsManagementService(), "tenant", "device", Collections.singletonList(secret))
            .compose(ok -> {
                // WHEN trying to update the credentials
                final PasswordCredential newSecret = createPasswordCredential("myId", "baz", OptionalInt.empty());
                return svc.updateCredentials("tenant", "device",
                        Collections.singletonList(newSecret),
                        Optional.empty(),
                        NoopSpan.INSTANCE);
            })
            .onComplete(ctx.succeeding(s -> ctx.verify(() -> {
                // THEN the update fails with a 403
                assertThat(s.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN);
                ctx.completeNow();
            })));
}
 
源代码10 项目: Strata   文件: ResolvedCapitalIndexedBondTest.java
@Test
public void test_builder() {
  ResolvedCapitalIndexedBond test = sut();
  assertThat(test.getCurrency()).isEqualTo(USD);
  assertThat(test.getDayCount()).isEqualTo(ACT_ACT_ISDA);
  assertThat(test.getStartDate()).isEqualTo(PERIODIC[0].getStartDate());
  assertThat(test.getEndDate()).isEqualTo(PERIODIC[3].getEndDate());
  assertThat(test.getUnadjustedStartDate()).isEqualTo(PERIODIC[0].getUnadjustedStartDate());
  assertThat(test.getUnadjustedEndDate()).isEqualTo(PERIODIC[3].getUnadjustedEndDate());
  assertThat(test.getLegalEntityId()).isEqualTo(LEGAL_ENTITY);
  assertThat(test.getNominalPayment()).isEqualTo(NOMINAL);
  assertThat(test.getNotional()).isEqualTo(NOTIONAL);
  assertThat(test.getPeriodicPayments().toArray()).isEqualTo(PERIODIC);
  assertThat(test.getSettlementDateOffset()).isEqualTo(SETTLE_OFFSET);
  assertThat(test.getYieldConvention()).isEqualTo(US_IL_REAL);
  assertThat(test.hasExCouponPeriod()).isFalse();
  assertThat(test.getFirstIndexValue()).isEqualTo(RATE_CALC.getFirstIndexValue().getAsDouble());
  assertThat(test.findPeriod(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(Optional.of(test.getPeriodicPayments().get(0)));
  assertThat(test.findPeriod(LocalDate.MIN)).isEqualTo(Optional.empty());
  assertThat(test.findPeriodIndex(PERIODIC[0].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(0));
  assertThat(test.findPeriodIndex(PERIODIC[1].getUnadjustedStartDate())).isEqualTo(OptionalInt.of(1));
  assertThat(test.findPeriodIndex(LocalDate.MIN)).isEqualTo(OptionalInt.empty());
  assertThat(test.calculateSettlementDateFromValuation(date(2015, 6, 30), REF_DATA))
      .isEqualTo(SETTLE_OFFSET.adjust(date(2015, 6, 30), REF_DATA));
}
 
@Test
public void shouldSaveForFutureWhenStateIsNotAvailable() throws Exception {
  final SignedBlockAndState target = beaconChainUtil.createBlockAndStateAtSlot(ONE, true);
  final SignedAggregateAndProof aggregate = generator.validAggregateAndProof(target.toUnsigned());
  when(attestationValidator.singleOrAggregateAttestationChecks(
          aggregate.getMessage().getAggregate(), OptionalInt.empty()))
      .thenReturn(SAVE_FOR_FUTURE);

  assertThat(validator.validate(ValidateableAttestation.fromSignedAggregate(aggregate)))
      .isEqualTo(SAVE_FOR_FUTURE);
}
 
源代码12 项目: hadoop-ozone   文件: HddsServerUtil.java
/**
 * Retrieve the socket address that should be used by DataNodes to connect
 * to the SCM.
 *
 * @param conf
 * @return Target {@code InetSocketAddress} for the SCM service endpoint.
 */
public static InetSocketAddress getScmDataNodeBindAddress(
    ConfigurationSource conf) {
  final Optional<String> host = getHostNameFromConfigKeys(conf,
      ScmConfigKeys.OZONE_SCM_DATANODE_BIND_HOST_KEY);

  final OptionalInt port = getPortNumberFromConfigKeys(conf,
      ScmConfigKeys.OZONE_SCM_DATANODE_ADDRESS_KEY);

  return NetUtils.createSocketAddr(
      host.orElse(ScmConfigKeys.OZONE_SCM_DATANODE_BIND_HOST_DEFAULT) + ":" +
          port.orElse(ScmConfigKeys.OZONE_SCM_DATANODE_PORT_DEFAULT));
}
 
源代码13 项目: besu   文件: GraphQLDataFetchers.java
public GraphQLDataFetchers(final Set<Capability> supportedCapabilities) {
  final OptionalInt version =
      supportedCapabilities.stream()
          .filter(cap -> EthProtocol.NAME.equals(cap.getName()))
          .mapToInt(Capability::getVersion)
          .max();
  highestEthVersion = version.isPresent() ? version.getAsInt() : null;
}
 
源代码14 项目: presto   文件: IndexBuildDriverFactoryProvider.java
public DriverFactory createStreaming(PageBuffer pageBuffer, Page indexKeyTuple)
{
    ImmutableList.Builder<OperatorFactory> operatorFactories = ImmutableList.<OperatorFactory>builder()
            .addAll(coreOperatorFactories);

    if (dynamicTupleFilterFactory.isPresent()) {
        // Bind in a dynamic tuple filter if necessary
        operatorFactories.add(dynamicTupleFilterFactory.get().filterWithTuple(indexKeyTuple));
    }

    operatorFactories.add(new PageBufferOperatorFactory(outputOperatorId, planNodeId, pageBuffer));

    return new DriverFactory(pipelineId, inputDriver, false, operatorFactories.build(), OptionalInt.empty(), UNGROUPED_EXECUTION);
}
 
源代码15 项目: buck   文件: TestResultFormatterTest.java
private TestResultFormatter createFormatterWithMaxLogLines(int logLines) {
  return new TestResultFormatter(
      new Ansi(false),
      Verbosity.COMMANDS,
      TestResultSummaryVerbosity.of(false, false, OptionalInt.of(logLines)),
      Locale.US,
      Optional.of(logPath),
      TimeZone.getTimeZone("America/Los_Angeles"));
}
 
源代码16 项目: besu   文件: EnodeURL.java
public URI toURI() {
  final String uri =
      String.format(
          "enode://%[email protected]%s:%d",
          nodeId.toUnprefixedHexString(),
          InetAddresses.toUriString(ip),
          getListeningPortOrZero());
  final OptionalInt discPort = getDiscPortQueryParam();
  if (discPort.isPresent()) {
    return URI.create(uri + String.format("?discport=%d", discPort.getAsInt()));
  } else {
    return URI.create(uri);
  }
}
 
源代码17 项目: vespa   文件: UpgraderTest.java
@Test
public void testPinningMajorVersionInApplication() {
    Version version = Version.fromString("6.2");
    tester.controllerTester().upgradeSystem(version);

    // Setup applications
    var canary0 = createAndDeploy("canary", "canary");
    var default0 = tester.newDeploymentContext().submit().deploy();
    tester.applications().lockApplicationOrThrow(default0.application().id(),
                                                 a -> tester.applications().store(a.withMajorVersion(6)));
    assertEquals(OptionalInt.of(6), default0.application().majorVersion());

    // New major version is released
    version = Version.fromString("7.0");
    tester.controllerTester().upgradeSystem(version);
    assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber());
    tester.upgrader().maintain();
    tester.triggerJobs();

    // ... canary upgrade to it
    assertEquals(2, tester.jobs().active().size());
    canary0.deployPlatform(version);
    assertEquals(0, tester.jobs().active().size());
    tester.controllerTester().computeVersionStatus();

    // The other application does not because it has pinned to major version 6
    tester.upgrader().maintain();
    tester.triggerJobs();
    assertEquals(0, tester.jobs().active().size());
}
 
源代码18 项目: presto   文件: TestSqlTask.java
@Test
public void testEmptyQuery()
{
    SqlTask sqlTask = createInitialTask();

    TaskInfo taskInfo = sqlTask.updateTask(TEST_SESSION,
            Optional.of(PLAN_FRAGMENT),
            ImmutableList.of(),
            createInitialEmptyOutputBuffers(PARTITIONED)
                    .withNoMoreBufferIds(),
            OptionalInt.empty());
    assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);

    taskInfo = sqlTask.getTaskInfo();
    assertEquals(taskInfo.getTaskStatus().getState(), TaskState.RUNNING);

    taskInfo = sqlTask.updateTask(TEST_SESSION,
            Optional.of(PLAN_FRAGMENT),
            ImmutableList.of(new TaskSource(TABLE_SCAN_NODE_ID, ImmutableSet.of(), true)),
            createInitialEmptyOutputBuffers(PARTITIONED)
                    .withNoMoreBufferIds(),
            OptionalInt.empty());
    assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);

    taskInfo = sqlTask.getTaskInfo();
    assertEquals(taskInfo.getTaskStatus().getState(), TaskState.FINISHED);
}
 
源代码19 项目: hono   文件: VertxBasedAmqpProtocolAdapter.java
private Span newSpan(final String operationName, final Device authenticatedDevice,
        final OptionalInt traceSamplingPriority, final SpanContext context) {
    final Span span = TracingHelper.buildChildSpan(tracer, context, operationName, getTypeName())
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null)
            .start();

    if (authenticatedDevice != null) {
        TracingHelper.setDeviceTags(span, authenticatedDevice.getTenantId(), authenticatedDevice.getDeviceId());
    }
    traceSamplingPriority.ifPresent(prio -> {
        TracingHelper.setTraceSamplingPriority(span, prio);
    });
    return span;
}
 
源代码20 项目: presto   文件: LocalExecutionPlanner.java
private static void addLookupOuterDrivers(LocalExecutionPlanContext context)
{
    // For an outer join on the lookup side (RIGHT or FULL) add an additional
    // driver to output the unused rows in the lookup source
    for (DriverFactory factory : context.getDriverFactories()) {
        List<OperatorFactory> operatorFactories = factory.getOperatorFactories();
        for (int i = 0; i < operatorFactories.size(); i++) {
            OperatorFactory operatorFactory = operatorFactories.get(i);
            if (!(operatorFactory instanceof JoinOperatorFactory)) {
                continue;
            }

            JoinOperatorFactory lookupJoin = (JoinOperatorFactory) operatorFactory;
            Optional<OuterOperatorFactoryResult> outerOperatorFactoryResult = lookupJoin.createOuterOperatorFactory();
            if (outerOperatorFactoryResult.isPresent()) {
                // Add a new driver to output the unmatched rows in an outer join.
                // We duplicate all of the factories above the JoinOperator (the ones reading from the joins),
                // and replace the JoinOperator with the OuterOperator (the one that produces unmatched rows).
                ImmutableList.Builder<OperatorFactory> newOperators = ImmutableList.builder();
                newOperators.add(outerOperatorFactoryResult.get().getOuterOperatorFactory());
                operatorFactories.subList(i + 1, operatorFactories.size()).stream()
                        .map(OperatorFactory::duplicate)
                        .forEach(newOperators::add);

                context.addDriverFactory(false, factory.isOutputDriver(), newOperators.build(), OptionalInt.of(1), outerOperatorFactoryResult.get().getBuildExecutionStrategy());
            }
        }
    }
}
 
@Test
void moreThan() {
    final MarketplaceFilterCondition condition = CurrentDaysPastDueCondition.moreThan(0);
    final Wrapper<?> w = mock(Wrapper.class);
    when(w.getCurrentDpd()).thenReturn(OptionalInt.of(0));
    assertThat(condition).rejects(w);
    when(w.getCurrentDpd()).thenReturn(OptionalInt.of(1));
    assertThat(condition).accepts(w);
}
 
源代码22 项目: presto   文件: TestPageProcessor.java
@Test
public void testProjectNoColumns()
{
    PageProcessor pageProcessor = new PageProcessor(Optional.empty(), ImmutableList.of(), OptionalInt.of(MAX_BATCH_SIZE));

    Page inputPage = new Page(createLongSequenceBlock(0, 100));

    Iterator<Optional<Page>> output = processAndAssertRetainedPageSize(pageProcessor, inputPage);

    List<Optional<Page>> outputPages = ImmutableList.copyOf(output);
    assertEquals(outputPages.size(), 1);
    Page outputPage = outputPages.get(0).orElse(null);
    assertEquals(outputPage.getChannelCount(), 0);
    assertEquals(outputPage.getPositionCount(), inputPage.getPositionCount());
}
 
源代码23 项目: presto   文件: SqlTaskManager.java
@Override
public TaskInfo updateTask(Session session, TaskId taskId, Optional<PlanFragment> fragment, List<TaskSource> sources, OutputBuffers outputBuffers, OptionalInt totalPartitions)
{
    requireNonNull(session, "session is null");
    requireNonNull(taskId, "taskId is null");
    requireNonNull(fragment, "fragment is null");
    requireNonNull(sources, "sources is null");
    requireNonNull(outputBuffers, "outputBuffers is null");

    long sessionQueryMaxMemoryPerNode = getQueryMaxMemoryPerNode(session).toBytes();
    long sessionQueryTotalMaxMemoryPerNode = getQueryMaxTotalMemoryPerNode(session).toBytes();
    // Session property query_max_memory_per_node is used to only decrease memory limit
    if (sessionQueryMaxMemoryPerNode <= queryMaxMemoryPerNode) {
        queryContexts.getUnchecked(taskId.getQueryId()).setMaxUserMemory(sessionQueryMaxMemoryPerNode);
    }

    if (sessionQueryTotalMaxMemoryPerNode <= queryMaxTotalMemoryPerNode) {
        queryContexts.getUnchecked(taskId.getQueryId()).setMaxTotalMemory(sessionQueryTotalMaxMemoryPerNode);
    }

    if (resourceOvercommit(session)) {
        // TODO: This should have been done when the QueryContext was created. However, the session isn't available at that point.
        queryContexts.getUnchecked(taskId.getQueryId()).setResourceOvercommit();
    }

    SqlTask sqlTask = tasks.getUnchecked(taskId);
    sqlTask.recordHeartbeat();
    return sqlTask.updateTask(session, fragment, sources, outputBuffers, totalPartitions);
}
 
源代码24 项目: nifi   文件: LoadBalanceSession.java
private boolean receiveRecommendedProtocolVersion() throws IOException {
    logger.debug("Receiving Protocol Version from Peer {}", peerDescription);

    final OptionalInt recommendationResponse = channel.read();
    if (!recommendationResponse.isPresent()) {
        if (System.currentTimeMillis() > readTimeout) {
            throw new SocketTimeoutException("Timed out waiting for Peer " + peerDescription + " to recommend Protocol Version");
        }

        return false;
    }

    final int requestedVersion = recommendationResponse.getAsInt();
    if (requestedVersion < 0) {
        throw new EOFException("Encounter End-of-File with Peer " + peerDescription + " when expecting a Protocol Version Recommendation");
    }

    if (negotiator.isVersionSupported(requestedVersion)) {
        protocolVersion = requestedVersion;
        phase = TransactionPhase.SEND_CONNECTION_ID;
        logger.debug("Peer {} recommended Protocol Version of {}. Accepting version.", peerDescription, requestedVersion);

        return true;
    } else {
        final Integer preferred = negotiator.getPreferredVersion(requestedVersion);
        if (preferred == null) {
            logger.debug("Peer {} requested version {} of the Load Balance Protocol. This version is not acceptable. Aborting communications.", peerDescription, requestedVersion);
            phase = TransactionPhase.ABORT_PROTOCOL_NEGOTIATION;
            return true;
        } else {
            logger.debug("Peer {} requested version {} of the Protocol. Recommending version {} instead", peerDescription, requestedVersion, preferred);
            protocolVersion = preferred;
            phase = TransactionPhase.RECOMMEND_PROTOCOL_VERSION;
            return true;
        }
    }
}
 
源代码25 项目: smallrye-config   文件: Converters.java
public OptionalInt convert(final String value) {
    if (value.isEmpty()) {
        return OptionalInt.empty();
    } else {
        final Integer converted = getDelegate().convert(value);
        return converted == null ? OptionalInt.empty() : OptionalInt.of(converted.intValue());
    }
}
 
源代码26 项目: java-8-matchers   文件: OptionalMatchers.java
/**
 * Matches a non empty OptionalInt with the given content
 *
 * @param content Expected contents of the Optional
 */
public static Matcher<OptionalInt> containsInt(int content) {
    return new TypeSafeMatcher<OptionalInt>() {
        @Override
        protected boolean matchesSafely(OptionalInt item) {
            return item.isPresent() && item.getAsInt() == content;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Optional.of(content).toString());
        }
    };
}
 
源代码27 项目: buck   文件: PathListingTest.java
@Test
public void listsEmptyIncludeZeroSize() throws IOException {
  setupPaths(10);
  assertThat(
      PathListing.listMatchingPathsWithFilters(
          tmpDir.getRoot().toPath(),
          "*",
          PathListing.GET_PATH_MODIFIED_TIME,
          PathListing.FilterMode.INCLUDE,
          OptionalInt.empty(), // maxPathsFilter
          Optional.of(0L)), // maxSizeFilter
      empty());
}
 
源代码28 项目: amodeus   文件: IDGenerator.java
public IDGenerator(Population populationExisting) {
    this.usedIDs = populationExisting.getPersons().keySet();

    // find largest integer used in IDs
    largestInteger = usedIDs.stream().map(Id::toString).map(this::extractLargestInt) //
            .filter(OptionalInt::isPresent).mapToInt(OptionalInt::getAsInt).max().orElse(1);
}
 
源代码29 项目: twitch4j   文件: ChatModerationAction.java
/**
 * @return optional wrapper around the duration the user was timed out for, in seconds
 */
public OptionalInt getTimeoutDuration() {
    if (getModerationAction() == ModerationAction.TIMEOUT && args != null && args.size() > 1)
        return OptionalInt.of(Integer.parseInt(args.get(1)));

    return OptionalInt.empty();
}
 
源代码30 项目: luna   文件: AmountInputInterface.java
@Override
public final void applyInput(Player player, OptionalInt amount, Optional<String> name) {
    amount.ifPresent(value -> onAmountInput(player, value));
}
 
 类所在包
 同包方法