java.util.Optional#orElseGet ( )源码实例Demo

下面列出了java.util.Optional#orElseGet ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: bundletool   文件: DeviceAnalyzer.java
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";
      });
}
 
源代码2 项目: smallrye-fault-tolerance   文件: GenericConfig.java
/**
 * 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));
}
 
源代码3 项目: bt   文件: BtRuntime.java
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;
}
 
源代码4 项目: sample-boot-hibernate   文件: CashBalance.java
/**
 * 指定口座の残高を取得します。(存在しない時は繰越保存後に取得します)
 * 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));
}
 
源代码5 项目: eventapis   文件: Components.java
@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);
}
 
源代码6 项目: vespa   文件: LoadBalancerTest.java
@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));
}
 
源代码7 项目: presto   文件: CompilerUtils.java
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));
}
 
源代码8 项目: beast   文件: FieldFactory.java
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));
}
 
源代码9 项目: flink   文件: AvroFactory.java
/**
 * 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));
}
 
源代码10 项目: mycore   文件: MCRInfo.java
@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());
}
 
源代码11 项目: Valkyrien-Skies   文件: QueryableShipData.java
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;
    });
}
 
源代码12 项目: jdk8u_jdk   文件: ECDHKeyAgreement.java
@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);
}
 
源代码14 项目: tls-channel   文件: TlsChannelImpl.java
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);
}
 
源代码15 项目: bisq-core   文件: PaymentMethod.java
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")));
}
 
源代码16 项目: articles   文件: SupplierTest.java
@Test
void example_4() {
    Optional<Integer> foo = Optional.of(1);
    foo.orElseGet(() -> compute()); // lazy
}
 
源代码17 项目: blackduck-alert   文件: EncryptionUtility.java
private String getGlobalSalt() {
    Optional<String> saltFromEnvironment = alertProperties.getAlertEncryptionGlobalSalt();
    return saltFromEnvironment.orElseGet(this::getGlobalSaltFromFile);
}
 
源代码18 项目: jdk8u-jdk   文件: Basic.java
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseGetNull() {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseGet(null);
}
 
源代码19 项目: jdk8u_jdk   文件: Basic.java
@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);
}