下面列出了java.util.Optional#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void processPodUpdate(String podName, WorkflowInstance instance) {
LOG.debug("Processing pod update: {}: {}", podName, instance);
var podOpt = client.getPod(podName);
if (podOpt.isEmpty()) {
return;
}
var pod = podOpt.orElseThrow();
final Optional<RunState> runState = lookupPodRunState(pod, instance);
if (runState.isEmpty()) {
return;
}
emitPodEvents(pod, runState.get());
}
private void validateLog(AzureClient client, PagedList<RoleAssignmentInner> roleAssignments, Identity identity, CloudAdlsGen2View cloudFileSystem,
ValidationResultBuilder resultBuilder) {
LOGGER.debug(String.format("Validating logger identity %s", identity.principalId()));
List<StorageLocationBase> locations = cloudFileSystem.getLocations();
if (Objects.nonNull(locations) && !locations.isEmpty()) {
AdlsGen2Config adlsGen2Config = adlsGen2ConfigGenerator.generateStorageConfig(locations.get(0).getValue());
String storageAccountName = adlsGen2Config.getAccount();
Optional<String> storageAccountIdOptional = azureStorage.findStorageAccountIdInVisibleSubscriptions(client, storageAccountName);
if (storageAccountIdOptional.isEmpty()) {
LOGGER.debug("Storage account {} not found or insufficient permission to list subscriptions and / or storage accounts.", storageAccountName);
addError(resultBuilder, String.format("Storage account with name %s not found.", storageAccountName));
return;
}
ResourceId storageAccountResourceId = ResourceId.fromString(storageAccountIdOptional.get());
PagedList<RoleAssignmentInner> roleAssignmentsForSubscription =
getRoleAssignmentsOfSubscription(roleAssignments, storageAccountResourceId.subscriptionId(), client);
validateRoleAssigmentAndScope(roleAssignmentsForSubscription, resultBuilder, identity,
List.of(storageAccountName, storageAccountResourceId.resourceGroupName(), storageAccountResourceId.subscriptionId()));
} else {
LOGGER.debug("There is no storage location set for logger identity, this should not happen!");
}
LOGGER.info("Validating logger identity is finished");
}
/**
* Authenticates the given {@link RequestContext request context}.
*
* @param requestContext the request context to authenticate.
* @param dittoHeaders the (potentially not completely set) DittoHeaders of the request.
* @return the authentication result.
*/
@Override
protected AuthenticationResult tryToAuthenticate(final RequestContext requestContext,
final DittoHeaders dittoHeaders) {
final Optional<JsonWebToken> jwtOptional = extractJwtFromRequest(requestContext);
if (jwtOptional.isEmpty()) {
LOGGER.withCorrelationId(dittoHeaders).debug("JWT is missing.");
return DefaultAuthenticationResult.failed(dittoHeaders, buildMissingJwtException(dittoHeaders));
}
final CompletableFuture<AuthenticationResult> authenticationResultFuture =
getAuthenticationResult(jwtOptional.get(), dittoHeaders)
.exceptionally(throwable -> toFailedAuthenticationResult(throwable, dittoHeaders));
return waitForResult(authenticationResultFuture, dittoHeaders);
}
/**
* Obtains the property value for the given key
* @param key - the key of the property
* @return the value for the given key
* @throws IllegalArgumentException - if the key is not valid or we don't have a value for it
*/
public String get (String key) {
if (StringUtils.isEmpty(key)) {
throw new IllegalArgumentException("A configuration key is required");
}
key = AmforeasProperty.PREFIX + key;
l.debug("Getting configuration for key {}", key);
Optional<AmforeasProperty> p = this.getProperty(key);
if (p.isEmpty()) {
throw new IllegalArgumentException("The provided configuration key " + key + " is not valid");
}
return p.get().getValue();
}
private static Optional<DoubleRange> toRange(Optional<Object> min, Optional<Object> max, Type columnType)
{
if (columnType instanceof VarcharType || columnType instanceof CharType || columnType.equals(TIME)) {
return Optional.empty();
}
if (min.isEmpty() || max.isEmpty()) {
return Optional.empty();
}
return Optional.of(new DoubleRange(toDouble(min.get(), columnType), toDouble(max.get(), columnType)));
}
private boolean matches(final Any<?> any, final AttrCond cond, final boolean not) {
PlainSchema schema = plainSchemaDAO.find(cond.getSchema());
if (schema == null) {
LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
return false;
}
@SuppressWarnings("unchecked")
Optional<PlainAttr<?>> attr = (Optional<PlainAttr<?>>) any.getPlainAttr(cond.getSchema());
boolean found;
switch (cond.getType()) {
case ISNULL:
found = attr.isEmpty();
break;
case ISNOTNULL:
found = attr.isPresent();
break;
default:
PlainAttrValue attrValue = anyUtilsFactory.getInstance(any).newPlainAttrValue();
try {
if (cond.getType() != AttrCond.Type.LIKE
&& cond.getType() != AttrCond.Type.ILIKE
&& cond.getType() != AttrCond.Type.ISNULL
&& cond.getType() != AttrCond.Type.ISNOTNULL) {
((JPAPlainSchema) schema).validator().validate(cond.getExpression(), attrValue);
}
} catch (ValidationException e) {
LOG.error("Could not validate expression '" + cond.getExpression() + '\'', e);
return false;
}
found = attr.isPresent() && matches(attr.get().getValues(), attrValue, schema, cond);
}
return not ? !found : found;
}
private List<DiscoveryPeer> getPeersFromNeighborsPacket(final Packet packet) {
final Optional<NeighborsPacketData> maybeNeighborsData =
packet.getPacketData(NeighborsPacketData.class);
if (maybeNeighborsData.isEmpty()) {
return Collections.emptyList();
}
final NeighborsPacketData neighborsData = maybeNeighborsData.get();
return neighborsData.getNodes().stream()
.map(p -> peerTable.get(p).orElse(p))
.collect(Collectors.toList());
}
/**
* Create an .eps file that corresponds to the compiled latex document containing the pstricks drawing.
* @param pathExportEPS The path of the .eps file to create (MUST ends with .eps).
* @return The create file or nothing.
* @throws SecurityException In case of problem while accessing files.
*/
public Optional<File> createEPSFile(final String pathExportEPS) {
final Optional<File> optDir = SystemUtils.getInstance().createTempDir();
if(optDir.isEmpty()) {
BadaboomCollector.INSTANCE.add(new FileNotFoundException("Cannot create a tmp dir"));
return Optional.empty();
}
final File tmpDir = optDir.get();
final Optional<File> optFile = createPSFile(tmpDir.getAbsolutePath() + SystemUtils.getInstance().fileSep + "tmpPSFile.ps", tmpDir); //NON-NLS
if(optFile.isEmpty()) {
return Optional.empty();
}
final File psFile = optFile.get();
final OperatingSystem os = OperatingSystem.getSystem().orElse(OperatingSystem.LINUX);
final File finalFile = new File(pathExportEPS);
final File fileEPS = new File(psFile.getAbsolutePath().replace(".ps", ExportFormat.EPS_LATEX.getFileExtension())); //NON-NLS
final String[] paramsLatex = {os.getPS2EPSBinPath(), psFile.getAbsolutePath(), fileEPS.getAbsolutePath()};
final String log = SystemUtils.getInstance().execute(paramsLatex, tmpDir).b;
if(!fileEPS.exists()) {
BadaboomCollector.INSTANCE.add(new IllegalAccessException(getDocumentCode() + SystemUtils.getInstance().eol + log));
return Optional.empty();
}
try {
Files.copy(fileEPS.toPath(), finalFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}catch(final IOException ex) {
BadaboomCollector.INSTANCE.add(ex);
return Optional.empty();
}
SystemUtils.getInstance().removeDirWithContent(tmpDir.getPath());
return Optional.of(finalFile);
}
@Override
public ListenableFuture<?> execute(RenameView statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters)
{
Session session = stateMachine.getSession();
QualifiedObjectName viewName = createQualifiedObjectName(session, statement, statement.getSource());
Optional<ConnectorViewDefinition> viewDefinition = metadata.getView(session, viewName);
if (viewDefinition.isEmpty()) {
throw semanticException(TABLE_NOT_FOUND, statement, "View '%s' does not exist", viewName);
}
QualifiedObjectName target = createQualifiedObjectName(session, statement, statement.getTarget());
if (metadata.getCatalogHandle(session, target.getCatalogName()).isEmpty()) {
throw semanticException(CATALOG_NOT_FOUND, statement, "Target catalog '%s' does not exist", target.getCatalogName());
}
if (metadata.getView(session, target).isPresent()) {
throw semanticException(TABLE_ALREADY_EXISTS, statement, "Target view '%s' already exists", target);
}
if (!viewName.getCatalogName().equals(target.getCatalogName())) {
throw semanticException(NOT_SUPPORTED, statement, "View rename across catalogs is not supported");
}
accessControl.checkCanRenameView(session.toSecurityContext(), viewName, target);
metadata.renameView(session, viewName, target);
return immediateFuture(null);
}
private int getSelectedCharges(Equipment equip)
{
int minCharges = equip.getMinCharges();
int maxCharges = equip.getMaxCharges();
Optional<String> selectedValue = delegate.showInputDialog(equip.toString(),
LanguageBundle.getFormattedString("in_igNumCharges", //$NON-NLS-1$
Integer.toString(minCharges), Integer.toString(maxCharges)),
Integer.toString(equip.getRemainingCharges()));
if (selectedValue.isEmpty())
{
return -1;
}
int charges;
try
{
charges = Integer.parseInt(selectedValue.get().trim());
}
catch (NumberFormatException e)
{
charges = minCharges - 1;
}
if ((charges < minCharges) || (charges > maxCharges))
{
ShowMessageDelegate.showMessageDialog(LanguageBundle.getString("in_igValueOutOfRange"),
Constants.APPLICATION_NAME, MessageType.ERROR);
return getSelectedCharges(equip);
}
return charges;
}
private void updateNodeLivenessEventsForReadyNodes(Mutex lock) {
// Update node last request events through ZooKeeper to collect request to all config servers.
// We do this here ("lazily") to avoid writing to zk for each config request.
for (Node node : nodeRepository().getNodes(Node.State.ready)) {
Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname());
if (lastLocalRequest.isEmpty()) continue;
if (! node.history().hasEventAfter(History.Event.Type.requested, lastLocalRequest.get())) {
History updatedHistory = node.history()
.with(new History.Event(History.Event.Type.requested, Agent.NodeFailer, lastLocalRequest.get()));
nodeRepository().write(node.with(updatedHistory), lock);
}
}
}
/**
* Returns the transaction receipt associated with the given transaction hash.
*
* @param transactionHash The hash of the transaction that corresponds to the receipt to retrieve.
* @return The transaction receipt associated with the referenced transaction.
*/
public Optional<TransactionReceiptWithMetadata> transactionReceiptByTransactionHash(
final Hash transactionHash) {
final Optional<TransactionLocation> maybeLocation =
blockchain.getTransactionLocation(transactionHash);
if (maybeLocation.isEmpty()) {
return Optional.empty();
}
// getTransactionLocation should not return if the TX or block doesn't exist, so throwing
// on a missing optional is appropriate.
final TransactionLocation location = maybeLocation.get();
final BlockBody blockBody = blockchain.getBlockBody(location.getBlockHash()).orElseThrow();
final Transaction transaction = blockBody.getTransactions().get(location.getTransactionIndex());
final Hash blockhash = location.getBlockHash();
final BlockHeader header = blockchain.getBlockHeader(blockhash).orElseThrow();
final List<TransactionReceipt> transactionReceipts =
blockchain.getTxReceipts(blockhash).orElseThrow();
final TransactionReceipt transactionReceipt =
transactionReceipts.get(location.getTransactionIndex());
long gasUsed = transactionReceipt.getCumulativeGasUsed();
if (location.getTransactionIndex() > 0) {
gasUsed =
gasUsed
- transactionReceipts.get(location.getTransactionIndex() - 1).getCumulativeGasUsed();
}
return Optional.of(
TransactionReceiptWithMetadata.create(
transactionReceipt,
transaction,
transactionHash,
location.getTransactionIndex(),
gasUsed,
blockhash,
header.getNumber()));
}
@Override
public Optional<User> getUserFromAccessToken(String accessToken) throws UserValidationException {
if (StringUtils.isBlank(accessToken)) {
return Optional.empty();
}
final User local = users.getIfPresent(accessToken);
if (local != null) {
return Optional.of(local);
}
try {
final Optional<UserInfo> userInfoOpt = openIdClient.getUserInfo(accessToken);
if (userInfoOpt.isEmpty()) {
return Optional.empty();
}
final UserInfo userInfo = userInfoOpt.get();
final String subject = userInfo.getSubject().getValue();
final Optional<User> user = userStore.userFor(subject);
if (user.isPresent()) {
user.ifPresent(value -> users.put(accessToken, value));
return user;
} else {
final User newUser = userStore.saveNew(userInfo.getNickname(), subject);
users.put(subject, newUser);
return Optional.of(newUser);
}
} catch (AuthenticationUnavailableException | IOException | ParseException e) {
throw new UserValidationException(e);
}
}
@Override
public Optional<ErrorResponse> filter(DiscFilterRequest request) {
try {
Optional<ResourceNameAndAction> resourceMapping =
requestResourceMapper.getResourceNameAndAction(request.getMethod(), request.getRequestURI(), request.getQueryString());
log.log(Level.FINE, () -> String.format("Resource mapping for '%s': %s", request, resourceMapping));
if (resourceMapping.isEmpty()) {
incrementAcceptedMetrics(request, false);
return Optional.empty();
}
Result result = checkAccessAllowed(request, resourceMapping.get());
AuthorizationResult.Type resultType = result.zpeResult.type();
setAttribute(request, RESULT_ATTRIBUTE, resultType.name());
if (resultType == AuthorizationResult.Type.ALLOW) {
populateRequestWithResult(request, result);
incrementAcceptedMetrics(request, true);
return Optional.empty();
}
log.log(Level.FINE, () -> String.format("Forbidden (403) for '%s': %s", request, resultType.name()));
incrementRejectedMetrics(request, FORBIDDEN, resultType.name());
return Optional.of(new ErrorResponse(FORBIDDEN, "Access forbidden: " + resultType.getDescription()));
} catch (IllegalArgumentException e) {
log.log(Level.FINE, () -> String.format("Unauthorized (401) for '%s': %s", request, e.getMessage()));
incrementRejectedMetrics(request, UNAUTHORIZED, "Unauthorized");
return Optional.of(new ErrorResponse(UNAUTHORIZED, e.getMessage()));
}
}
private CompletionStage<Collection<OutboundSignalWithId>> enrichAndFilterSignal(
final Pair<OutboundSignalWithId, FilteredTopic> outboundSignalWithExtraFields) {
final OutboundSignalWithId outboundSignal = outboundSignalWithExtraFields.first();
final FilteredTopic filteredTopic = outboundSignalWithExtraFields.second();
final Optional<JsonFieldSelector> extraFieldsOptional =
Optional.ofNullable(filteredTopic).flatMap(FilteredTopic::getExtraFields);
if (extraFieldsOptional.isEmpty()) {
return CompletableFuture.completedFuture(Collections.singletonList(outboundSignal));
}
final JsonFieldSelector extraFields = extraFieldsOptional.get();
final Target target = outboundSignal.getTargets().get(0);
final ThingId thingId = ThingId.of(outboundSignal.getEntityId());
final DittoHeaders headers = DittoHeaders.newBuilder()
.authorizationContext(target.getAuthorizationContext())
// schema version is always the latest for connectivity signal enrichment.
.schemaVersion(JsonSchemaVersion.LATEST)
.build();
final CompletionStage<JsonObject> extraFuture =
signalEnrichmentFacade.retrievePartialThing(thingId, extraFields, headers, outboundSignal.getSource());
return extraFuture.thenApply(outboundSignal::setExtra)
.thenApply(outboundSignalWithExtra -> applyFilter(outboundSignalWithExtra, filteredTopic))
.exceptionally(error -> {
logger.withCorrelationId(outboundSignal.getSource())
.warning("Could not retrieve extra data due to: {} {}",
error.getClass().getSimpleName(), error.getMessage());
// recover from all errors to keep message-mapping-stream running despite enrichment failures
return Collections.singletonList(recoverFromEnrichmentError(outboundSignal, target, error));
});
}
private Flavor asFlavor(String flavorString, NodeType type) {
Optional<Flavor> flavor = nodeFlavors.getFlavor(flavorString);
if (flavor.isEmpty()) {
// TODO: Remove the need for this by always adding hosts with a given capacity
if (type == NodeType.tenant) // Tenant nodes can have any (docker) flavor
flavor = Optional.of(new Flavor(NodeResources.fromLegacyName(flavorString)));
else
throw new IllegalArgumentException("No flavor '" + flavorString + "'");
}
return flavor.get();
}
@Override
public Network convertToLegacyNetwork(EnvironmentNetworkResponse source, String availabilityZone) {
Network result = new Network();
result.setName(missingResourceNameGenerator.generateName(APIResourceType.NETWORK));
result.setSubnetCIDR(null);
result.setOutboundInternetTraffic(source.getOutboundInternetTraffic());
result.setNetworkCidrs(source.getNetworkCidrs());
Map<String, Object> attributes = new HashMap<>();
Optional<CloudSubnet> cloudSubnet;
if (StringUtils.isNotBlank(source.getPreferedSubnetId())) {
LOGGER.debug("Choosing subnet by prefered subnet Id {}", source.getPreferedSubnetId());
cloudSubnet = Optional.of(source.getSubnetMetas().get(source.getPreferedSubnetId()));
} else if (StringUtils.isNotEmpty(availabilityZone)) {
LOGGER.debug("Choosing subnet by availability zone {}", availabilityZone);
cloudSubnet = source.getSubnetMetas().values().stream()
.filter(s -> StringUtils.isNotEmpty(s.getAvailabilityZone()) &&
s.getAvailabilityZone().equals(availabilityZone))
.findFirst();
} else {
LOGGER.debug("Fallback to choose random subnet");
cloudSubnet = source.getSubnetMetas().values().stream().findFirst();
}
if (cloudSubnet.isEmpty()) {
throw new BadRequestException("No subnet for the given availability zone: " + availabilityZone);
}
LOGGER.debug("Chosen subnet: {}", cloudSubnet.get());
attributes.put("subnetId", cloudSubnet.get().getId());
attributes.put("cloudPlatform", getCloudPlatform().name());
attributes.putAll(getAttributesForLegacyNetwork(source));
try {
result.setAttributes(new Json(attributes));
} catch (IllegalArgumentException e) {
LOGGER.debug("Environment's network could not be converted to network.", e);
}
return result;
}
ModificationType getModification(PathArgument id) {
Optional<TerminalDataTreeCandidateNode> node = getNode(id);
return (node.isEmpty() ? ModificationType.UNMODIFIED : node.get().getModificationType());
}
private Optional<Boolean> childAsBoolean(Optional<ModelElement> element, String childTagName) {
if (element.isEmpty()) return Optional.empty();
return Optional.ofNullable(element.get().childAsBoolean(childTagName));
}
String validateCanal(
final Route route,
final Collection<Unit> units,
final Map<Unit, Collection<Unit>> newDependents,
final GamePlayer player) {
// Check each unit 1 by 1 to see if they can move through necessary canals on route
String result = null;
final Set<Unit> unitsThatFailCanal = new HashSet<>();
final Set<Unit> setWithNull = new HashSet<>();
setWithNull.add(null);
final Collection<Unit> unitsWithoutDependents =
(units == null) ? setWithNull : findNonDependentUnits(units, route, newDependents);
for (final Unit unit : unitsWithoutDependents) {
for (final Territory t : route.getAllTerritories()) {
Optional<String> failureMessage = Optional.empty();
for (final CanalAttachment canalAttachment : CanalAttachment.get(t)) {
if (!CanalAttachment.isCanalOnRoute(canalAttachment.getCanalName(), route)) {
continue; // Only check canals that are on the route
}
failureMessage = canPassThroughCanal(canalAttachment, unit, player);
final boolean canPass = failureMessage.isEmpty();
if ((!Properties.getControlAllCanalsBetweenTerritoriesToPass(data) && canPass)
|| (Properties.getControlAllCanalsBetweenTerritoriesToPass(data) && !canPass)) {
break; // If need to control any canal and can pass OR need to control all canals and
// can't pass
}
}
if (failureMessage.isPresent()) {
result = failureMessage.get();
unitsThatFailCanal.add(unit);
}
}
}
if (result == null || units == null) {
return result;
}
// If any units failed canal check then try to land transport them
final Set<Unit> potentialLandTransports =
unitsWithoutDependents.stream()
.filter(
unit ->
!unitsThatFailCanal.contains(unit)
&& Matches.unitHasEnoughMovementForRoute(route).test(unit))
.collect(Collectors.toSet());
final Set<Unit> unitsToLandTransport =
unitsWithoutDependents.stream()
.filter(
unit ->
unitsThatFailCanal.contains(unit)
|| !Matches.unitHasEnoughMovementForRoute(route).test(unit))
.collect(Collectors.toSet());
return checkLandTransports(player, potentialLandTransports, unitsToLandTransport).isEmpty()
? null
: result;
}