下面列出了java.util.Optional#orElseGet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String getMainLocaleViaProperties(Device device) {
Optional<String> locale = Optional.empty();
int apiLevel = device.getVersion().getApiLevel();
if (apiLevel < Versions.ANDROID_M_API_VERSION) {
Optional<String> language = device.getProperty(LEGACY_LANGUAGE_PROPERTY);
Optional<String> region = device.getProperty(LEGACY_REGION_PROPERTY);
if (language.isPresent() && region.isPresent()) {
locale = Optional.of(language.get() + "-" + region.get());
}
} else {
locale = device.getProperty(LOCALE_PROPERTY_SYS);
if (!locale.isPresent()) {
locale = device.getProperty(LOCALE_PROPERTY_PRODUCT);
}
}
return locale.orElseGet(
() -> {
System.err.println("Warning: Can't detect device locale, will use 'en-US'.");
return "en-US";
});
}
/**
* Note that:
*
* <pre>
* If no annotation matches the specified parameter, the property will be ignored.
* </pre>
*
* @param key
* @param expectedType
* @return the configured value
*/
private <U> U lookup(String key, Class<U> expectedType) {
Config config = getConfig();
Optional<U> value;
if (ElementType.METHOD.equals(annotationSource)) {
// <classname>/<methodname>/<annotation>/<parameter>
value = config.getOptionalValue(getConfigKeyForMethod() + key, expectedType);
} else {
// <classname>/<annotation>/<parameter>
value = config.getOptionalValue(getConfigKeyForClass() + key, expectedType);
}
if (!value.isPresent()) {
// <annotation>/<parameter>
value = config.getOptionalValue(annotationType.getSimpleName() + "/" + key, expectedType);
}
// annotation values
return value.orElseGet(() -> getConfigFromAnnotation(key));
}
private String createErrorMessage(LifecycleEvent event, LifecycleBinding binding) {
Optional<String> descriptionOptional = binding.getDescription();
String errorMessage = "Failed to execute " + event.name().toLowerCase() + " hook: ";
errorMessage += ": " + (descriptionOptional.orElseGet(() -> binding.getRunnable().toString()));
return errorMessage;
}
/**
* 指定口座の残高を取得します。(存在しない時は繰越保存後に取得します)
* low: 複数通貨の適切な考慮や細かい審査は本筋でないので割愛。
*/
public static CashBalance getOrNew(final OrmRepository rep, String accountId, String currency) {
LocalDate baseDay = rep.dh().time().day();
Optional<CashBalance> m = rep.tmpl().get(
"from CashBalance c where c.accountId=?1 and c.currency=?2 and c.baseDay=?3 order by c.baseDay desc",
accountId, currency, baseDay);
return m.orElseGet(() -> create(rep, accountId, currency));
}
@Bean
AggregateListener snapshotRecorder(
ViewQuery<Stock> stockViewRepository,
EventRepository stockEventRepository,
StockRepository stockRepository,
Optional<List<RollbackSpec>> rollbackSpecs
) {
return new AggregateListener(stockViewRepository, stockEventRepository, stockRepository, rollbackSpecs.orElseGet(ArrayList::new), objectMapper);
}
@Test
public void requireThatLoadBalancerServesMultiGroupSetups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 1);
SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null, null);
LoadBalancer lb = new LoadBalancer(cluster, true);
Optional<Group> grp = lb.takeGroup(null);
Group group = grp.orElseGet(() -> {
throw new AssertionFailedError("Expected a SearchCluster.Group");
});
assertThat(group.nodes().size(), equalTo(1));
}
public static ParameterizedType makeClassName(String baseName, Optional<String> suffix)
{
String className = baseName
+ "_" + suffix.orElseGet(() -> Instant.now().atZone(UTC).format(TIMESTAMP_FORMAT))
+ "_" + CLASS_ID.incrementAndGet();
return typeFromJavaClassName("io.prestosql.$gen." + toJavaIdentifierString(className));
}
public static ProtoField getField(Descriptors.FieldDescriptor descriptor, Object fieldValue) {
List<ProtoField> protoFields = Arrays.asList(
new TimestampField(descriptor, fieldValue),
new EnumField(descriptor, fieldValue),
new ByteField(descriptor, fieldValue),
new StructField(descriptor, fieldValue),
new NestedField(descriptor, fieldValue)
);
Optional<ProtoField> first = protoFields
.stream()
.filter(ProtoField::matches)
.findFirst();
return first.orElseGet(() -> new DefaultProtoField(descriptor, fieldValue));
}
/**
* Extracts an Avro {@link Schema} from a {@link SpecificRecord}. We do this either via {@link
* SpecificData} or by instantiating a record and extracting the schema from the instance.
*/
static <T> Schema extractAvroSpecificSchema(
Class<T> type,
SpecificData specificData) {
Optional<Schema> newSchemaOptional = tryExtractAvroSchemaViaInstance(type);
return newSchemaOptional.orElseGet(() -> specificData.getSchema(type));
}
@GET
@Path("version")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Operation(description = "get MyCoRe version information",
responses = {
@ApiResponse(content = @Content(schema = @Schema(implementation = GitInfo.class)))
},
tags = MCRRestUtils.TAG_MYCORE_ABOUT)
public Response getVersion() {
Optional<Response> cachedResponse = MCRRestUtils.getCachedResponse(request, INIT_TIME);
return cachedResponse.orElseGet(
() -> Response.ok(new GitInfo(MCRCoreVersion.getVersionProperties())).lastModified(INIT_TIME).build());
}
public ShipData getOrCreateShip(PhysicsWrapperEntity wrapperEntity) {
Optional<ShipData> data = getShip(wrapperEntity.getPersistentID());
return data.orElseGet(() -> {
ShipData shipData = new ShipData.Builder(wrapperEntity).build();
allShips.add(shipData);
return shipData;
});
}
@Override
protected byte[] engineGenerateSecret() throws IllegalStateException {
if ((privateKey == null) || (publicKey == null)) {
throw new IllegalStateException("Not initialized correctly");
}
Optional<byte[]> resultOpt = deriveKeyImpl(privateKey, publicKey);
return resultOpt.orElseGet(
() -> deriveKeyNative(privateKey, publicKey)
);
}
private boolean qtyToDeliverCatchOverrideIsChanged()
{
final Optional<Boolean> nullValuechanged = isNullValuesChanged(qtyToDeliverCatchOverrideInitial, qtyToDeliverCatchOverride);
return nullValuechanged.orElseGet(() -> qtyToDeliverCatchOverrideInitial.compareTo(qtyToDeliverCatchOverride) != 0);
}
public TlsChannelImpl(
ReadableByteChannel readChannel,
WritableByteChannel writeChannel,
SSLEngine engine,
Optional<BufferHolder> inEncrypted,
Consumer<SSLSession> initSessionCallback,
boolean runTasks,
TrackingAllocator plainBufAllocator,
TrackingAllocator encryptedBufAllocator,
boolean releaseBuffers,
boolean waitForCloseConfirmation) {
// @formatter:on
this.readChannel = readChannel;
this.writeChannel = writeChannel;
this.engine = engine;
this.inEncrypted =
inEncrypted.orElseGet(
() ->
new BufferHolder(
"inEncrypted",
Optional.empty(),
encryptedBufAllocator,
buffersInitialSize,
maxTlsPacketSize,
false /* plainData */,
releaseBuffers));
this.initSessionCallback = initSessionCallback;
this.runTasks = runTasks;
this.plainBufAllocator = plainBufAllocator;
this.encryptedBufAllocator = encryptedBufAllocator;
this.waitForCloseConfirmation = waitForCloseConfirmation;
inPlain =
new BufferHolder(
"inPlain",
Optional.empty(),
plainBufAllocator,
buffersInitialSize,
maxTlsPacketSize,
true /* plainData */,
releaseBuffers);
outEncrypted =
new BufferHolder(
"outEncrypted",
Optional.empty(),
encryptedBufAllocator,
buffersInitialSize,
maxTlsPacketSize,
false /* plainData */,
releaseBuffers);
}
public static PaymentMethod getPaymentMethodById(String id) {
Optional<PaymentMethod> paymentMethodOptional = getAllValues().stream().filter(e -> e.getId().equals(id)).findFirst();
return paymentMethodOptional.orElseGet(() -> new PaymentMethod(Res.get("shared.na")));
}
@Test
void example_4() {
Optional<Integer> foo = Optional.of(1);
foo.orElseGet(() -> compute()); // lazy
}
private String getGlobalSalt() {
Optional<String> saltFromEnvironment = alertProperties.getAlertEncryptionGlobalSalt();
return saltFromEnvironment.orElseGet(this::getGlobalSaltFromFile);
}
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseGetNull() {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseGet(null);
}
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseGetNull() {
Optional<Boolean> empty = Optional.empty();
Boolean got = empty.orElseGet(null);
}
private void updateAccount(String line) throws Exception {
byte[] data = Base64.decodeBase64(line);
AccountInfo accountInfo = AccountInfo.parseFrom(data);
EntityId accountEntityId = EntityId.of(accountInfo.getAccountID());
Optional<Entities> entityExists = entityRepository.findById(accountEntityId.getId());
if (entityExists.isPresent() && hasCreateTransaction(entityExists.get())) {
return;
}
Entities entity = entityExists.orElseGet(() -> accountEntityId.toEntity());
if (entity.getExpiryTimeNs() == null && accountInfo.hasExpirationTime()) {
try {
entity.setExpiryTimeNs(Utility.timeStampInNanos(accountInfo.getExpirationTime()));
} catch (ArithmeticException e) {
log.warn("Invalid expiration time for account {}: {}", entity.getEntityNum(),
StringUtils.trim(e.getMessage()));
}
}
if (entity.getAutoRenewPeriod() == null && accountInfo.hasAutoRenewPeriod()) {
entity.setAutoRenewPeriod(accountInfo.getAutoRenewPeriod().getSeconds());
}
if (entity.getKey() == null && accountInfo.hasKey()) {
entity.setKey(accountInfo.getKey().toByteArray());
}
if (entity.getProxyAccountId() == null && accountInfo.hasProxyAccountID()) {
EntityId proxyAccountEntityId = EntityId.of(accountInfo.getProxyAccountID());
// Persist if doesn't exist
entityRepository.findById(proxyAccountEntityId.getId())
.orElseGet(() -> entityRepository.save(proxyAccountEntityId.toEntity()));
entity.setProxyAccountId(proxyAccountEntityId);
}
if (accountInfo.getDeleted()) {
entity.setDeleted(accountInfo.getDeleted());
}
if (entityExists.isPresent()) {
log.debug("Updating entity {} for account {}", entity.getEntityNum(), accountEntityId);
} else {
log.debug("Creating entity for account {}", accountEntityId);
}
entityRepository.save(entity);
}