Example usage for java.util Optional orElseGet

List of usage examples for java.util Optional orElseGet

Introduction

In this page you can find the example usage for java.util Optional orElseGet.

Prototype

public T orElseGet(Supplier<? extends T> supplier) 

Source Link

Document

If a value is present, returns the value, otherwise returns the result produced by the supplying function.

Usage

From source file:org.apache.ambari.view.web.service.PackageScannerServiceImpl.java

private void updateApplication(Application application, Registry registry) {
    Optional<Package> packageOptional = packageRepository.findByName(application.getName());

    Package pack = packageOptional.orElseGet(() -> {
        Package pac = new Package();
        pac.setName(application.getName());
        pac.setRegistry(registry);/*from   w w  w.j a  va  2 s.  c  o m*/
        packageRepository.save(pac);
        return pac;
    });

    Map<String, Application.Version> versionMap = application.getVersions().stream()
            .collect(Collectors.toMap(Application.Version::getVersion, Function.identity()));

    Set<String> versionsFromRepo = pack.getVersions().stream().map(PackageVersion::getVersion)
            .collect(Collectors.toSet());
    versionMap.keySet().forEach(x -> {
        if (!versionsFromRepo.contains(x)) {
            PackageVersion packageVersion = new PackageVersion();
            Application.Version version = versionMap.get(x);
            packageVersion.setVersion(version.getVersion());
            packageVersion.setDeploymentDefinition(version.getApplicationConfig());
            packageVersion.setViewPackage(pack);
            pack.getVersions().add(packageVersion);
            versionRepository.save(packageVersion);
        }
    });

}

From source file:io.divolte.server.recordmapping.DslRecordMapping.java

private static Optional<ValidationError> validateTrivialUnion(final Schema targetSchema,
        final Function<Schema, Boolean> validator, final String messageIfInvalid, Object... messageParameters) {
    final Optional<Schema> resolvedSchema = unpackNullableUnion(targetSchema);
    final Optional<Optional<ValidationError>> unionValidation = resolvedSchema
            .map(s -> validator.apply(s) ? Optional.empty()
                    : validationError(String.format(messageIfInvalid, messageParameters), targetSchema));
    return unionValidation.orElseGet(() -> validationError(
            "mapping to non-trivial unions (" + targetSchema + ") is not supported", targetSchema));
}

From source file:com.rcn.controller.ResourceController.java

@RequestMapping(value = "/resources", method = RequestMethod.GET)
public String resources(@RequestParam(value = "t", required = false) Optional<String> resourceType,
        Model model) {//w w w. java 2s .  c o  m
    model.addAttribute("resourceType", resourceType.orElseGet(() -> ""));
    return "resources";
}

From source file:com.spotify.heroic.metric.astyanax.AstyanaxMetricModule.java

@JsonCreator
public AstyanaxMetricModule(@JsonProperty("id") Optional<String> id,
        @JsonProperty("seeds") Optional<Set<String>> seeds, @JsonProperty("keyspace") Optional<String> keyspace,
        @JsonProperty("maxConnectionsPerHost") Optional<Integer> maxConnectionsPerHost,
        @JsonProperty("groups") Optional<Groups> groups,
        @JsonProperty("pools") Optional<ReadWriteThreadPools.Config> pools) {
    this.id = id;
    this.groups = groups.orElseGet(Groups::empty).or(DEFAULT_GROUP);
    this.keyspace = keyspace.orElse(DEFAULT_KEYSPACE);
    this.seeds = seeds.orElse(DEFAULT_SEEDS);
    this.maxConnectionsPerHost = maxConnectionsPerHost.orElse(DEFAULT_MAX_CONNECTIONS_PER_HOST);
    this.pools = pools.orElseGet(ReadWriteThreadPools.Config::buildDefault);
}

From source file:org.apache.ambari.view.registry.web.service.ApplicationService.java

@Transactional
public ApplicationVersion saveApplicationConfig(ApplicationConfig config) {
    Optional<Application> applicationOptional = applicationRepository.findByName(config.getName());

    Application application = applicationOptional.orElseGet(() -> {
        Application app = new Application();
        app = new Application();
        app.setName(config.getName());/*from   w ww  .  j  av  a2 s.com*/
        return app;
    });

    application.setDescription(config.getDescription());
    application.setLabel(config.getLabel());
    application.setUpdatedAt(new Date());

    validateVersionIsGreater(config, application);

    ApplicationVersion version = new ApplicationVersion();
    version.setApplication(application);
    try {
        version.setApplicationConfig(getJsonString(config));
    } catch (JsonProcessingException e) {
        log.error("Failed to serialize configuration to JSON string for {}", config);
        throw new ConfigSerializationException(e);
    }

    version.setVersion(config.getVersion());
    version.setCreatedAt(new Date());

    application.getVersions().add(version);
    applicationRepository.save(application);

    return applicationVersionRepository.save(version);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Returns the base index name (before any date strings, splits etc) have been appended
 *  Generated by taking 1-3 directories from the path and then appening the end of a UUID
 * @param bucket/*  w ww  .  j  a  v a  2  s. c  o  m*/
 * @param secondary_buffer - for "ping pong" buffers
 * @return
 */
public static String getBaseIndexName(final DataBucketBean bucket, final Optional<String> secondary_buffer) {

    final Optional<String> override_string = Optionals
            .<String>of(() -> ((String) bucket.data_schema().search_index_schema().technology_override_schema()
                    .get(SearchIndexSchemaDefaultBean.index_name_override_)));

    return override_string.orElseGet(() -> {
        return BucketUtils.getUniqueSignature(bucket.full_name(), secondary_buffer);
    });
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Returns a readable copy of the base name  (before any date strings, splits etc)
 *  Uses the read alias that all non-overridden indexes have
 * @param bucket/*from  w w  w.j  a v  a2  s  .  com*/
 * @return
 */
public static String getReadableBaseIndexName(final DataBucketBean bucket) {
    final Optional<String> override_string = Optionals
            .<String>of(() -> ((String) bucket.data_schema().search_index_schema().technology_override_schema()
                    .get(SearchIndexSchemaDefaultBean.index_name_override_)));

    return override_string.orElseGet(() -> {
        return ElasticsearchContext.READ_PREFIX
                + BucketUtils.getUniqueSignature(bucket.full_name(), Optional.empty());
    });
}

From source file:ch.wisv.areafiftylan.integration.ConsumptionIntegrationTest.java

private Consumption getOrPersistConsumption(String consumption) {
    Optional<Consumption> consumptionOptional = consumptionsRepository.findByName(consumption);

    return consumptionOptional.orElseGet(() -> consumptionService.addPossibleConsumption(consumption));
}

From source file:io.cloudslang.intellij.lang.annotator.ExecutableAnnotator.java

private YAMLPsiElement findChildRecursively(YAMLPsiElement element, String[] possibleName) {
    List<YAMLPsiElement> yamlElements = element.getYAMLElements();
    if (yamlElements.isEmpty()) {
        return null;
    }/*from  ww  w  .  jav a  2s .  c  o m*/
    Optional<YAMLPsiElement> matchingNode = yamlElements.stream().filter(e -> hasAcceptedName(e, possibleName))
            .findFirst();
    return matchingNode.orElseGet(() -> yamlElements.stream().map(e -> findChildRecursively(e, possibleName))
            .filter(Objects::nonNull).findFirst().orElse(null));
}

From source file:com.epam.dlab.backendapi.dao.ExploratoryLibDAO.java

private Document findLibraries(String user, String exploratoryName, Bson include) {
    Optional<Document> opt = findOne(USER_INSTANCES, exploratoryCondition(user, exploratoryName),
            fields(excludeId(), include));

    return opt.orElseGet(Document::new);

}