use of java.util.OptionalInt in project presto by prestodb.
the class AbstractTestHiveClient method readTable.
private MaterializedResult readTable(Transaction transaction, ConnectorTableHandle tableHandle, List<ColumnHandle> columnHandles, ConnectorSession session, TupleDomain<ColumnHandle> tupleDomain, OptionalInt expectedSplitCount, Optional<HiveStorageFormat> expectedStorageFormat) throws Exception {
List<ConnectorTableLayoutResult> tableLayoutResults = transaction.getMetadata().getTableLayouts(session, tableHandle, new Constraint<>(tupleDomain, bindings -> true), Optional.empty());
ConnectorTableLayoutHandle layoutHandle = getOnlyElement(tableLayoutResults).getTableLayout().getHandle();
List<ConnectorSplit> splits = getAllSplits(splitManager.getSplits(transaction.getTransactionHandle(), session, layoutHandle));
if (expectedSplitCount.isPresent()) {
assertEquals(splits.size(), expectedSplitCount.getAsInt());
}
ImmutableList.Builder<MaterializedRow> allRows = ImmutableList.builder();
for (ConnectorSplit split : splits) {
try (ConnectorPageSource pageSource = pageSourceProvider.createPageSource(transaction.getTransactionHandle(), session, split, columnHandles)) {
if (expectedStorageFormat.isPresent()) {
assertPageSourceType(pageSource, expectedStorageFormat.get());
}
MaterializedResult result = materializeSourceDataStream(session, pageSource, getTypes(columnHandles));
allRows.addAll(result.getMaterializedRows());
}
}
return new MaterializedResult(allRows.build(), getTypes(columnHandles));
}
use of java.util.OptionalInt in project 99-problems by shekhargulati.
the class Problem4_2 method maximize_unsorted.
public static IntPair maximize_unsorted(int[] numbers) {
OptionalInt min = IntStream.of(numbers).min();
OptionalInt max = IntStream.of(numbers).max();
return new IntPair(min.getAsInt(), max.getAsInt());
}
use of java.util.OptionalInt in project platform_frameworks_base by android.
the class NetdEventListenerServiceTest method verifyLoggedEvents.
void verifyLoggedEvents(int wait, DnsEvent... expectedEvents) {
verify(mLog, timeout(wait).times(expectedEvents.length)).log(mEvCaptor.capture());
for (DnsEvent got : mEvCaptor.getAllValues()) {
OptionalInt index = IntStream.range(0, expectedEvents.length).filter(i -> eventsEqual(expectedEvents[i], got)).findFirst();
// Don't match same expected event more than once.
index.ifPresent(i -> expectedEvents[i] = null);
assertTrue(index.isPresent());
}
}
use of java.util.OptionalInt in project torodb by torodb.
the class TopologyCoordinator method processHeartbeatResponse.
/**
* Processes a heartbeat response from "target" that arrived around "now", having spent
* "networkRoundTripTime" millis on the network.
* <p>
* Updates internal topology coordinator state, and returns instructions about what action to take
* next.
* <p>
* If the next action is {@link HeartbeatResponseAction#makeNoAction() "NoAction"} then nothing
* has to be done.
* <p>
* If the next action indicates {@link HeartbeatResponseAction#makeReconfigAction() "Reconfig"},
* the caller should verify the configuration in hbResponse is acceptable, perform any other
* reconfiguration actions it must, and call
* {@link #updateConfig(
* com.eightkdata.mongowp.mongoserver.api.safe.library.v3m0.pojos.ReplicaSetConfig,
* java.time.Instant, com.eightkdata.mongowp.OpTime) updateConfig}
* with the appropiate arguments.
* <p>
* This call should be paired (with intervening network communication) with a call to
* prepareHeartbeatRequest for the same "target".
*
* @param now the aproximated time when the response has been recived
* @param networkRoundTripTime the time spent on network
* @param target the host that send the respond
* @param hbResponse
*/
HeartbeatResponseAction processHeartbeatResponse(Instant now, Duration networkRoundTripTime, HostAndPort target, RemoteCommandResponse<ReplSetHeartbeatReply> hbResponse) {
PingStats hbStats = getPingOrDefault(target);
Preconditions.checkState(hbStats.getLastHeartbeatStartDate() != null, "It seems that a hb " + "response has been recived before it has been prepared");
if (!hbResponse.isOk()) {
hbStats.miss();
} else {
hbStats.hit(networkRoundTripTime);
}
boolean isUnauthorized = (hbResponse.getErrorCode() == ErrorCode.UNAUTHORIZED) || (hbResponse.getErrorCode() == ErrorCode.AUTHENTICATION_FAILED);
Duration alreadyElapsed = Duration.between(hbStats.getLastHeartbeatStartDate(), now);
Duration nextHeartbeatDelay;
// determine next start time
if (_rsConfig != null && (hbStats.getNumFailuresSinceLastStart() <= MAX_HEARTBEAT_RETRIES) && (alreadyElapsed.toMillis() < _rsConfig.getHeartbeatTimeoutPeriod())) {
if (isUnauthorized) {
nextHeartbeatDelay = HEARTBEAT_INTERVAL;
} else {
nextHeartbeatDelay = Duration.ZERO;
}
} else {
nextHeartbeatDelay = HEARTBEAT_INTERVAL;
}
Optional<ReplSetHeartbeatReply> commandReply = hbResponse.getCommandReply();
if (hbResponse.isOk() && commandReply.get().getConfig().isPresent()) {
long currentConfigVersion = _rsConfig != null ? _rsConfig.getConfigVersion() : -2;
ReplicaSetConfig newConfig = commandReply.get().getConfig().get();
assert newConfig != null;
if (newConfig.getConfigVersion() > currentConfigVersion) {
HeartbeatResponseAction nextAction = HeartbeatResponseAction.makeReconfigAction().setNextHeartbeatDelay(nextHeartbeatDelay);
return nextAction;
} else {
// target erroneously sent us one, even through it isn't newer.
if (newConfig.getConfigVersion() < currentConfigVersion) {
LOGGER.debug("Config version from heartbeat was older than ours.");
LOGGER.trace("Current config: {}. Config from heartbeat: {}", _rsConfig, newConfig);
} else {
LOGGER.trace("Config from heartbeat response was same as ours.");
}
}
}
// so return early.
if (_rsConfig == null) {
HeartbeatResponseAction nextAction = HeartbeatResponseAction.makeNoAction();
nextAction.setNextHeartbeatDelay(nextHeartbeatDelay);
return nextAction;
}
OptionalInt memberIndexOpt = _rsConfig.findMemberIndexByHostAndPort(target);
if (!memberIndexOpt.isPresent()) {
LOGGER.debug("replset: Could not find {} in current config so ignoring --" + " current config: {}", target, _rsConfig);
HeartbeatResponseAction nextAction = HeartbeatResponseAction.makeNoAction();
nextAction.setNextHeartbeatDelay(nextHeartbeatDelay);
return nextAction;
}
assert memberIndexOpt.isPresent();
int memberIndex = memberIndexOpt.getAsInt();
MemberHeartbeatData hbData = _hbdata.get(memberIndex);
assert hbData != null;
MemberConfig member = _rsConfig.getMembers().get(memberIndex);
if (!hbResponse.isOk()) {
if (isUnauthorized) {
LOGGER.debug("setAuthIssue: heartbeat response failed due to authentication" + " issue for member _id: {}", member.getId());
hbData.setAuthIssue(now);
} else if (hbStats.getNumFailuresSinceLastStart() > MAX_HEARTBEAT_RETRIES || alreadyElapsed.toMillis() >= _rsConfig.getHeartbeatTimeoutPeriod()) {
LOGGER.debug("setDownValues: heartbeat response failed for member _id:{}" + ", msg: {}", member.getId(), hbResponse.getErrorDesc());
hbData.setDownValues(now, hbResponse.getErrorDesc());
} else {
LOGGER.trace("Bad heartbeat response from {}; trying again; Retries left: {}; " + "{} ms have already elapsed", target, MAX_HEARTBEAT_RETRIES - hbStats.getNumFailuresSinceLastStart(), alreadyElapsed.toMillis());
}
} else {
ReplSetHeartbeatReply nonNullReply = commandReply.get();
LOGGER.trace("setUpValues: heartbeat response good for member _id:{}, msg: {}", member.getId(), nonNullReply.getHbmsg());
hbData.setUpValues(now, member.getHostAndPort(), nonNullReply);
}
HeartbeatResponseAction nextAction = updateHeartbeatDataImpl(memberIndex, now);
nextAction.setNextHeartbeatDelay(nextHeartbeatDelay);
return nextAction;
}
use of java.util.OptionalInt in project torodb by torodb.
the class TopologyCoordinator method shouldChangeSyncSource.
/**
* Determines if a new sync source should be chosen, if a better candidate sync source is
* available.
*
* It returns true if there exists a viable sync source member other than our current source,
* whose oplog has reached an optime greater than the max sync source lag later than current
* source's. It can return true in other scenarios (like if {@link #setForceSyncSourceIndex(int) }
* has been called or if we don't have a current sync source.
*
* @param now is used to skip over currently blacklisted sync sources.
* @return
*/
boolean shouldChangeSyncSource(HostAndPort currentSource, Instant now) {
// If the user requested a sync source change, return true.
if (_forceSyncSourceIndex != -1) {
return true;
}
OptionalInt currentMemberIndex = _rsConfig.findMemberIndexByHostAndPort(currentSource);
if (!currentMemberIndex.isPresent()) {
return true;
}
assert _hbdata.get(currentMemberIndex.getAsInt()) != null;
OpTime currentOpTime = _hbdata.get(currentMemberIndex.getAsInt()).getOpTime();
if (currentOpTime == null) {
// change.
return false;
}
long currentSecs = currentOpTime.getSecs();
long goalSecs = currentSecs + _maxSyncSourceLagSecs;
for (int i = 0; i < _hbdata.size(); i++) {
MemberHeartbeatData it = _hbdata.get(i);
MemberConfig candidateConfig = _rsConfig.getMembers().get(i);
OpTime itOpTime = it.getOpTime();
if (itOpTime != null && it.isUp() && it.getState().isReadable() && !isBlacklistedMember(candidateConfig, now) && goalSecs < itOpTime.getSecs()) {
LOGGER.info("changing sync target because current sync target's most recent OpTime " + "is {} which is more than {} seconds behind member {} whose most recent " + "OpTime is {} ", currentOpTime, _maxSyncSourceLagSecs, candidateConfig.getHostAndPort(), itOpTime);
return true;
}
}
return false;
}
Aggregations