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:com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest.KubernetesApiVersion.java

@JsonCreator
public static KubernetesApiVersion fromString(String name) {
    if (StringUtils.isEmpty(name)) {
        return null;
    }/*from w  w  w .  j  av  a  2s . c o  m*/

    synchronized (values) {
        Optional<KubernetesApiVersion> versionOptional = values.stream()
                .filter(v -> v.name.equalsIgnoreCase(name)).findAny();

        // separate from the above chain to avoid concurrent modification of the values list
        return versionOptional.orElseGet(() -> new KubernetesApiVersion(name));
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.description.manifest.KubernetesKind.java

@JsonCreator
public static KubernetesKind fromString(String name) {
    if (StringUtils.isEmpty(name)) {
        return null;
    }//from   w  ww  .  j  ava  2  s .  c  o m

    synchronized (values) {
        Optional<KubernetesKind> kindOptional = values.stream().filter(
                v -> v.name.equalsIgnoreCase(name) || (v.alias != null && v.alias.equalsIgnoreCase(name)))
                .findAny();

        // separate from the above chain to avoid concurrent modification of the values list
        return kindOptional.orElseGet(() -> {
            KubernetesKind result = new KubernetesKind(name);
            result.isDynamic = true;
            return result;
        });
    }
}

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

/** Handles the prefix and suffix of the full hive schema
 *  https://www.elastic.co/guide/en/elasticsearch/hadoop/current/hive.html
 * @param table_name - if empty then "main_table"
 * @param bucket/* ww  w  .j  av  a 2 s  .  co m*/
 * @param schema
 * @param partial_hive_schema
 * @return
 */
public static Validation<String, String> generateFullHiveSchema(final Optional<String> table_name,
        final DataBucketBean bucket, final DataSchemaBean.DataWarehouseSchemaBean schema,
        Optional<Client> maybe_client, ElasticsearchIndexServiceConfigBean config) {
    // (ignore views for the moment)

    final String prefix = ErrorUtils.get("CREATE EXTERNAL TABLE {0} ", getTableName(bucket, schema));

    final DataSchemaBean.DataWarehouseSchemaBean.Table table = table_name.flatMap(t -> Optionals
            .ofNullable(schema.views()).stream().filter(v -> t.equals(v.database_name())).findFirst())
            .orElse(schema.main_table());

    final JsonNode user_schema = _mapper.convertValue(table.table_format(), JsonNode.class);

    final Validation<String, String> partial_table = generatePartialHiveSchema(prefix, user_schema, true);

    // (for the main table, just going to be the full alias - for views will need to be cleverer)
    final String index = Optionals
            .of(() -> bucket.data_schema().search_index_schema().technology_override_schema()
                    .get(SearchIndexSchemaDefaultBean.index_name_override_).toString())
            .orElseGet(() -> "r__" + BucketUtils.getUniqueSignature(bucket.full_name(), Optional.empty()));

    final Optional<ElasticsearchHiveOverrideBean> maybe_override = Optionals
            .of(() -> schema.technology_override_schema())
            .map(m -> BeanTemplateUtils.from(m, ElasticsearchHiveOverrideBean.class).get());

    // OK all this horrible code is intended to sort out the list of types to apply in the hive query
    final Optional<ElasticsearchHiveOverrideBean.TableOverride> table_override = maybe_override
            .map(cfg -> cfg.table_overrides().get(table_name.orElse(MAIN_TABLE_NAME)));
    final Optional<Set<String>> user_type_overrides = table_override.map(t -> t.types())
            .filter(l -> !l.isEmpty()).map(l -> new TreeSet<String>(l));
    final Set<String> mutable_type_set = user_type_overrides.orElseGet(() -> {
        return new TreeSet<String>(
                maybe_client.map(client -> ElasticsearchIndexUtils.getTypesForIndex(client, index).values())
                        .orElse(Collections.emptySet()));
    });

    final ElasticsearchIndexServiceConfigBean schema_config = ElasticsearchIndexConfigUtils
            .buildConfigBeanFromSchema(bucket, config, _mapper);
    final CollidePolicy collide_policy = Optionals
            .of(() -> schema_config.search_technology_override().collide_policy())
            .orElse(CollidePolicy.new_type);

    Optionals.of(() -> schema_config.search_technology_override().type_name_or_prefix()).map(Optional::of)
            .orElseGet(() -> Optional.of((collide_policy == CollidePolicy.new_type)
                    ? ElasticsearchContext.TypeContext.ReadWriteTypeContext.AutoRwTypeContext.DEFAULT_PREFIX
                    : ElasticsearchIndexServiceConfigBean.DEFAULT_FIXED_TYPE_NAME))
            .ifPresent(type_or_prefix -> {
                if (!user_type_overrides.isPresent()) { // leave alone if manually specified
                    if (collide_policy == CollidePolicy.new_type) { // add a few types
                        //TODO (ALEPH-17): need to make this get auto populated as new types are added, see the ALEPH-17 comment in ElasticsearchIndexService
                        if (mutable_type_set.size() < 10) {
                            IntStream.rangeClosed(1, 10).boxed().map(i -> type_or_prefix + i.toString())
                                    .forEach(type -> mutable_type_set.add(type));
                        }
                    } else { // OK in this case just make sure the default type is represented
                        mutable_type_set.add(type_or_prefix);
                    }
                }
            });

    final String suffix = Optional.of(" STORED BY 'org.elasticsearch.hadoop.hive.EsStorageHandler' ")
            .map(s -> s + ErrorUtils.get(
                    "TBLPROPERTIES(''es.index.auto.create'' = ''false'', ''es.resource'' = ''{0}/{1}''", index,
                    mutable_type_set.stream().collect(Collectors.joining(","))))
            .map(s -> table_override.map(t -> t.name_mappings()).filter(m -> !m.isEmpty())
                    .map(m -> s + ", 'es.mapping.names' = '"
                            + m.entrySet().stream().map(kv -> kv.getKey() + ":" + kv.getValue())
                                    .collect(Collectors.joining(","))
                            + "'")
                    .orElse(s))
            .map(s -> table_override
                    .flatMap(t -> Optional.ofNullable(t.url_query()).map(ss -> "?" + ss).map(Optional::of)
                            .orElseGet(() -> Optional.ofNullable(t.json_query())
                                    .map(jq -> _mapper.convertValue(jq, JsonNode.class).toString())))
                    .map(ss -> s + ", 'es.query' = '" + ss + "'").orElse(s))
            .map(s -> s + ") ").get();

    return partial_table.map(s -> s + suffix);
}

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

/** Registers the hive table
 *  NOT SURE HOW TO TEST THIS?/*from ww  w. j ava2 s.c o  m*/
 * @param config
 * @param delete_prev
 * @param create_new
 * @return
 * @throws SQLException
 * @throws ClassNotFoundException 
 */
public static Validation<String, Boolean> registerHiveTable(final Optional<Connection> maybe_hive_cxn,
        final Configuration config, Optional<String> delete_prev, Optional<String> create_new) {

    final Tuple3<String, String, String> params = getParamsFromHiveConfig(config);
    final String connection_url = params._1();
    final String user_name = params._2();
    final String password = params._3();

    try {
        Class.forName("org.apache.hive.jdbc.HiveDriver");

        final Connection hive_cxn = maybe_hive_cxn.orElseGet(
                Lambdas.wrap_u(() -> DriverManager.getConnection(connection_url, user_name, password)));

        final Validation<String, Boolean> delete_prev_results = delete_prev
                .<Validation<String, Boolean>>map(sql -> {
                    try {
                        return Validation.success(hive_cxn.createStatement().execute(sql));
                    } catch (Throwable t) {
                        return Validation.fail(ErrorUtils.getLongForm("delete hive table, error = {0}", t));
                    }
                }).orElse(Validation.success(true));

        final Validation<String, Boolean> create_new_results = delete_prev_results.bind(b -> {
            return create_new.<Validation<String, Boolean>>map(sql -> {
                try {
                    return Validation.success(hive_cxn.createStatement().execute(sql));
                } catch (Throwable t) {
                    return Validation.fail(ErrorUtils.getLongForm("create hive table, error = {0}", t));
                }
            }).orElse(Validation.success(b));
        });

        return create_new_results;
    } catch (Throwable t) {
        return Validation.fail(ErrorUtils.getLongForm("connect to hive, error = {0}", t));
    }
}

From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

public static <T> Response createFunction(IServiceContext service_context, String service_type,
        String access_level, String service_identifier, Optional<String> bucket_full_names,
        final FileDescriptor file_upload, Optional<String> json) {
    //TODO some validation that we are getting back a file crud service (so we cant send the wrong args)
    final Either<String, Tuple2<ICrudService<T>, Class<T>>> crud_service_either = RestUtils
            .getCrudService(service_context, service_type, access_level, service_identifier, bucket_full_names);
    if (crud_service_either.isLeft())
        return Response.status(Status.BAD_REQUEST).entity(crud_service_either.left().value()).build();

    final Optional<CompletableFuture<Supplier<Object>>> maybe_fut = json
            .<CompletableFuture<Supplier<Object>>>map(j -> {
                //TODO exception when this isn't a shared lib bean
                final SharedLibraryBean slb = BeanTemplateUtils.from(j, SharedLibraryBean.class).get();
                final ICrudService<Tuple2<ICrudService<T>, Class<T>>> crud_service = (ICrudService<Tuple2<ICrudService<T>, Class<T>>>) crud_service_either
                        .right().value()._1();
                return (CompletableFuture<Supplier<Object>>) crud_service
                        .storeObject(new Tuple2(slb, file_upload));
            });/*from ww w.  j  av  a2 s .co m*/

    final CompletableFuture<Supplier<Object>> fut = maybe_fut // (sun didn't like this in one statement so split into 2 for compile reasons)
            .orElseGet(() -> {
                final ICrudService<FileDescriptor> crud_service = (ICrudService<FileDescriptor>) crud_service_either
                        .right().value()._1();
                return (CompletableFuture<Supplier<Object>>) crud_service.storeObject(file_upload);
            });

    try {
        final Tuple3<String, Boolean, String> id_or_error = fut.handle((ok, ex) -> {
            if (ok != null)
                return new Tuple3<String, Boolean, String>(ok.get().toString(), true, "ok");
            else if (ex != null)
                return new Tuple3<String, Boolean, String>(null, false,
                        ErrorUtils.getLongForm("Exception storing object: {0}", ex));
            else
                return new Tuple3<String, Boolean, String>(null, false,
                        "something went very wrong, shouldn't have reached this piece of code");
        }).get();
        return Response.ok(RestUtils
                .convertObjectToJson(new CreateResponse(id_or_error._1(), id_or_error._2(), id_or_error._3()))
                .toString()).build();
    } catch (Exception e) {
        return Response.status(Status.BAD_REQUEST).entity(ErrorUtils.getLongForm("Error: {0}", e)).build();
    }
}

From source file:com.netflix.spinnaker.igor.admin.AdminController.java

@Autowired
public AdminController(Optional<List<CommonPollingMonitor>> pollingMonitors) {
    this.pollingMonitors = pollingMonitors.orElseGet(ArrayList::new);
}

From source file:ru.mera.samples.infrastructure.aop.AroundCacheValidationAdvice.java

protected Object getCachedObject(ProceedingJoinPoint pjp, String key, Supplier<Optional<ImageEntity>> suplier) {
    String funcName = pjp.getSignature().getName();
    logger.info("Around method: " + funcName);
    Optional<ImageEntity> image = suplier.get();
    ImageEntity bufferedImage = image.orElseGet(() -> {
        try {/*from   w  w w . ja v  a2 s.c  o m*/
            logger.info("Around method: not found cached image " + key);
            return (ImageEntity) pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    });
    return bufferedImage;
}

From source file:me.ferrybig.javacoding.webmapper.requests.JSONSessionProvider.java

@Override
public EndpointResult<?> handleHttpRequest(WebServerRequest req) throws RouteException {
    Optional<JSONObject> data = req.getDataAs(JSONObject.class);
    LazySessionSupplier s = new LazySessionSupplier(() -> sessions.findOrCreateSession(
            Optional.ofNullable(data.orElseGet(JSONObject::new).optString("session", null))));
    req.setSessionSupplier(s);// ww w  .  ja  v  a 2 s . c om
    EndpointResult<?> upper = upstream.handleHttpRequest(req);
    if (upper.getContentType() == JSON) {
        JSONObject obj = (JSONObject) upper.getData();
        obj.put("session", s.getSession().getKey());
        return new EndpointResult<>(upper.getResult(), obj, JSON);
    }
    return upper;
}

From source file:org.geowebcache.diskquota.storage.TilePageCalculator.java

private Collection<String> getParameterIds(String layerName, Optional<Collection<String>> parameterIds) {
    return parameterIds.orElseGet(() -> {
        try {// w ww. ja  v a 2  s .c om
            return sb.getCachedParameterIds(layerName);
        } catch (StorageException e) {
            log.error("Error while retreiving cached parameter IDs for layer " + layerName, e);
            return Collections.emptySet();
        }
    });
}

From source file:de.speexx.csv.table.app.Application.java

void exportResult(final Configuration conf, final RowReader rows) throws Exception {
    assert Objects.nonNull(rows) : "Rows are null";
    assert Objects.nonNull(conf) : "configuration is null";

    final CSVPrinter printer = createCsvPrinter(rows, conf);

    for (final Row row : rows) {
        final List<String> recordEntries = new ArrayList<>();
        for (final Entry entry : row) {
            final EntryDescriptor.Type type = entry.getDescriptor().getType();
            final TypeTransformer transformer = TypeTransformer.of(type, EntryDescriptor.Type.STRING);
            final Optional<String> opt = transformer.transform(entry.getValue());
            recordEntries.add(opt.orElseGet(() -> ""));
        }//  ww w  .j a v a  2 s.c  om
        printer.printRecord(recordEntries);
    }
}