Java Code Examples for java.util.Optional#orElseGet()

The following examples show how to use java.util.Optional#orElseGet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericConfig.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 2
Source File: DeviceAnalyzer.java    From bundletool with Apache License 2.0 6 votes vote down vote up
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";
      });
}
 
Example 3
Source File: BtRuntime.java    From bt with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 4
Source File: ECDHKeyAgreement.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@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)
    );
}
 
Example 5
Source File: QueryableShipData.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
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;
    });
}
 
Example 6
Source File: MCRInfo.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@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());
}
 
Example 7
Source File: AvroFactory.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 8
Source File: FieldFactory.java    From beast with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 9
Source File: CompilerUtils.java    From presto with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 10
Source File: LoadBalancerTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 11
Source File: Components.java    From eventapis with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 12
Source File: CashBalance.java    From sample-boot-hibernate with MIT License 5 votes vote down vote up
/**
 * 指定口座の残高を取得します。(存在しない時は繰越保存後に取得します)
 * 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));
}
 
Example 13
Source File: PaymentMethod.java    From bisq-core with GNU Affero General Public License v3.0 4 votes vote down vote up
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")));
}
 
Example 14
Source File: TlsChannelImpl.java    From tls-channel with MIT License 4 votes vote down vote up
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);
}
 
Example 15
Source File: SupplierTest.java    From articles with Apache License 2.0 4 votes vote down vote up
@Test
void example_4() {
    Optional<Integer> foo = Optional.of(1);
    foo.orElseGet(() -> compute()); // lazy
}
 
Example 16
Source File: EncryptionUtility.java    From blackduck-alert with Apache License 2.0 4 votes vote down vote up
private String getGlobalSalt() {
    Optional<String> saltFromEnvironment = alertProperties.getAlertEncryptionGlobalSalt();
    return saltFromEnvironment.orElseGet(this::getGlobalSaltFromFile);
}
 
Example 17
Source File: Basic.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseGetNull() {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseGet(null);
}
 
Example 18
Source File: Basic.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void testEmptyOrElseGetNull() {
    Optional<Boolean> empty = Optional.empty();

    Boolean got = empty.orElseGet(null);
}
 
Example 19
Source File: V1_11_6__Missing_Entities.java    From hedera-mirror-node with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 20
Source File: ShipmentCandidateRow.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
private boolean qtyToDeliverCatchOverrideIsChanged()
{
	final Optional<Boolean> nullValuechanged = isNullValuesChanged(qtyToDeliverCatchOverrideInitial, qtyToDeliverCatchOverride);
	return nullValuechanged.orElseGet(() -> qtyToDeliverCatchOverrideInitial.compareTo(qtyToDeliverCatchOverride) != 0);
}