下面列出了怎么用java.util.OptionalInt的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
@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)));
}
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))));
}
/**
* 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();
}
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);
}
}
@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"));
}
/**
* 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);
}
@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));
}
/**
* 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();
})));
}
@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);
}
/**
* 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));
}
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;
}
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);
}
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"));
}
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);
}
}
@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());
}
@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);
}
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;
}
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);
}
@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());
}
@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);
}
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;
}
}
}
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());
}
}
/**
* 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());
}
};
}
@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());
}
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);
}
/**
* @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();
}
@Override
public final void applyInput(Player player, OptionalInt amount, Optional<String> name) {
amount.ifPresent(value -> onAmountInput(player, value));
}