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.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public IBucketLogger getLogger(final Optional<DataBucketBean> bucket) {
    final DataBucketBean b = bucket.orElseGet(() -> _mutable_state.bucket.get());
    return _mutable_state.bucket_loggers.computeIfAbsent(b.full_name(), (k) -> _logging_service.getLogger(b));
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public String getTempOutputLocation(Optional<DataBucketBean> bucket) {
    return _globals.distributed_root_dir() + "/"
            + bucket.orElseGet(() -> _mutable_state.bucket.get()).full_name() + "/managed_bucket/import/temp/";
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public String getFinalOutputLocation(Optional<DataBucketBean> bucket) {
    return _globals.distributed_root_dir() + "/"
            + bucket.orElseGet(() -> _mutable_state.bucket.get()).full_name() + "/managed_bucket/import/ready/";
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.vmware.VMWareProvider.java

private Folder getDestinationFolderFromImage(String image, Folder rootFolder) {
    Optional<Folder> destinationFolder = Optional.empty();
    if (isMultiPartImage(image)) {
        String host = image.split(IMAGE_DELIMITER)[1];
        if (!host.equals(RANDOM_HOST)) {
            destinationFolder = vmWareProviderVirtualMachineUtil.searchVMFolderByHostname(host, rootFolder);
        }/*from  w ww. j  av  a  2s . com*/
    } else {
        destinationFolder = vmWareProviderVirtualMachineUtil.searchVMFolderFromVMName(image, rootFolder);
    }
    return destinationFolder.orElseGet(() -> vmWareProviderVirtualMachineUtil
            .searchFolderByName("VM", rootFolder).orElseThrow(() -> new RuntimeException(
                    "ERROR unable to retrieve a VM folder from image: '" + image + "'")));
}

From source file:com.vsct.dt.strowgr.admin.repository.consul.ConsulRepository.java

@Override
public Set<String> getEntryPointsId() {
    try {/* www  . j  ava2  s. c  om*/
        HttpGet listKeysURI = new HttpGet("http://" + host + ":" + port + "/v1/kv/admin?keys");
        Optional<Set<String>> allKeys = client.execute(listKeysURI, httpResponse -> consulReader
                .parseHttpResponseAccepting404(httpResponse, consulReader::parseKeysFromHttpEntity));
        return allKeys.orElseGet(HashSet::new).stream().filter(s -> !s.contains("lock"))
                .map(s -> s.replace("admin/", "")).map(s -> s.replace("/lock", ""))
                .map(s -> s.replace("/current", "")).map(s -> s.replace("/pending", ""))
                .map(s -> s.replace("/committing", "")).map(s -> s.replace("/disabled", "")) // @deprecated TODO remove
                .map(s -> s.replace("/autoreload", "")).map(s -> s.replace("/haproxyversion", ""))
                .filter(s -> !s.isEmpty()).distinct().collect(Collectors.toSet());

    } catch (IOException e) {
        LOGGER.error("error in consul repository", e);
        return new HashSet<>();
    }
}

From source file:com.bouncestorage.swiftproxy.v2.Identity.java

@Path("tokens")
@POST// w w w.jav a  2  s .com
@Produces(MediaType.APPLICATION_JSON)
public Response auth(AuthV2Request payload, @HeaderParam("Host") Optional<String> host,
        @Context Request request) {
    String tenant = payload.auth.tenantName;
    String identity = payload.auth.passwordCredentials.username;
    if (Strings.isNullOrEmpty(tenant)) {
        tenant = identity;
    }
    String credential = payload.auth.passwordCredentials.password;
    String authToken = null;
    try {
        authToken = ((BounceResourceConfig) application).authenticate(tenant + ":" + identity, credential);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    if (authToken == null) {
        return notAuthorized();
    }

    String storageURL = host.orElseGet(() -> request.getLocalAddr() + ":" + request.getLocalPort());
    String scheme = request.getScheme();
    tenant = "AUTH_" + tenant;
    storageURL = scheme + "://" + storageURL + "/v1/" + tenant;

    AuthV2Response resp = new AuthV2Response();
    resp.access.token.id = authToken;
    resp.access.token.expires = Instant.now().plusSeconds(InfoResource.CONFIG.tempauth.token_life);
    resp.access.token.tenant = new IDAndName(tenant, tenant);
    resp.access.user = new AuthV2Response.Access.User(identity, identity);
    resp.access.user.roles.add(new IDAndName(identity, identity));
    if (!identity.equals(tenant)) {
        resp.access.user.roles.add(new IDAndName(tenant, tenant));
    }

    AuthV2Response.Access.ServiceCatalog.Endpoint endpoint = new AuthV2Response.Access.ServiceCatalog.Endpoint();
    try {
        endpoint.publicURL = new URL(storageURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw propagate(e);
    }
    endpoint.tenantId = tenant;
    resp.access.serviceCatalog[0].endpoints.add(endpoint);
    org.jclouds.Context c = getBlobStore(authToken).get().getContext().unwrap();
    resp.access.serviceCatalog[0].name += String.format(" (%s %s)", c.getId(),
            c.getProviderMetadata().getEndpoint());
    return Response.ok(resp).build();
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public void sendObjectToStreamingPipeline(Optional<DataBucketBean> bucket,
        Either<JsonNode, Map<String, Object>> object) {

    final DataBucketBean this_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

    final boolean streaming_pipeline_disabled = (MasterEnrichmentType.none == Optional
            .ofNullable(this_bucket.master_enrichment_type()).orElse(MasterEnrichmentType.none));

    final String topic = _distributed_services.generateTopicName(this_bucket.full_name(), Optional.empty());

    final boolean emit_to_pipeline = Lambdas.get(() -> {
        if (streaming_pipeline_disabled) {
            this.emitObject(bucket, object);
            return (_distributed_services.doesTopicExist(topic));
        } else/*w w  w .  j ava2  s  . co  m*/
            return true;
    });

    if (emit_to_pipeline) {
        final String obj_str = object.either(JsonNode::toString,
                map -> _mapper.convertValue(map, JsonNode.class).toString());

        if (_batch_intermed_storage_service.isPresent()) {
            _batch_intermed_storage_service.get().storeObject(obj_str);
        } else if (_crud_intermed_storage_service.isPresent()) { // (super slow)
            _crud_intermed_storage_service.get().storeObject(obj_str);
        }
        _distributed_services.produce(topic, obj_str);
    }
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

@Override
public CompletableFuture<Map<String, String>> getHarvestLibraries(final Optional<DataBucketBean> bucket) {
    if (_state_name == State.IN_TECHNOLOGY) {

        final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

        final SingleQueryComponent<SharedLibraryBean> tech_query = CrudUtils.anyOf(SharedLibraryBean.class)
                .when(SharedLibraryBean::_id, my_bucket.harvest_technology_name_or_id())
                .when(SharedLibraryBean::path_name, my_bucket.harvest_technology_name_or_id());

        final List<SingleQueryComponent<SharedLibraryBean>> other_libs = Optionals
                .ofNullable(my_bucket.harvest_configs()).stream()
                .flatMap(hcfg -> Optionals.ofNullable(hcfg.library_names_or_ids()).stream()).map(name -> {
                    return CrudUtils.anyOf(SharedLibraryBean.class).when(SharedLibraryBean::_id, name)
                            .when(SharedLibraryBean::path_name, name);
                }).collect(Collector.of(LinkedList::new, LinkedList::add, (left, right) -> {
                    left.addAll(right);// w  w  w.  ja v  a 2 s . c  o m
                    return left;
                }));

        @SuppressWarnings("unchecked")
        final MultiQueryComponent<SharedLibraryBean> spec = CrudUtils.<SharedLibraryBean>anyOf(tech_query,
                other_libs.toArray(new SingleQueryComponent[other_libs.size()]));

        // Get the names or ids, get the shared libraries, get the cached ids (must be present)

        return this._core_management_db.readOnlyVersion().getSharedLibraryStore()
                .getObjectsBySpec(spec, Arrays.asList(JsonUtils._ID, "path_name"), true).thenApply(cursor -> {
                    return StreamSupport.stream(cursor.spliterator(), false)
                            .collect(Collectors.<SharedLibraryBean, String, String>toMap(lib -> lib.path_name(),
                                    lib -> _globals.local_cached_jar_dir() + "/"
                                            + JarCacheUtils.buildCachedJarName(lib)));
                });
    } else {
        throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE);
    }
}

From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java

@Override
public Validation<BasicMessageBean, JsonNode> emitObject(final Optional<DataBucketBean> bucket,
        final AnalyticThreadJobBean job, final Either<JsonNode, Map<String, Object>> object,
        final Optional<AnnotationBean> annotations) {
    final DataBucketBean this_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

    if (annotations.isPresent()) {
        throw new RuntimeException(ErrorUtils.NOT_YET_IMPLEMENTED);
    }/*  w ww .j  av  a 2  s.  c  o m*/
    final JsonNode obj_json = object.either(__ -> __,
            map -> (JsonNode) _mapper.convertValue(map, JsonNode.class));

    if (_batch_index_service.isPresent()) {
        _batch_index_service.get().storeObject(obj_json);
    } else if (_crud_index_service.isPresent()) { // (super slow)
        _crud_index_service.get().storeObject(obj_json);
    }
    if (_batch_storage_service.isPresent()) {
        _batch_storage_service.get().storeObject(obj_json);
    } else if (_crud_storage_service.isPresent()) { // (super slow)
        _crud_storage_service.get().storeObject(obj_json);
    }

    final String topic = _distributed_services.generateTopicName(this_bucket.full_name(),
            ICoreDistributedServices.QUEUE_END_NAME);
    if (_distributed_services.doesTopicExist(topic)) {
        // (ie someone is listening in on our output data, so duplicate it for their benefit)
        _distributed_services.produce(topic, obj_json.toString());
    }
    //(else nothing to do)

    return Validation.success(obj_json);
}

From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java

/** Sets up the writers for optional output (not normally needed - only if enrichment is disabled)
 * @param bucket/*from   w w w.ja  v  a2s . c  om*/
 */
protected void initializeOptionalOutput(final Optional<DataBucketBean> bucket) {

    if (_mutable_state.initialized_direct_output.isSet()) {
        return;
    }
    final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());
    synchronized (this) {
        _mutable_state.initialized_direct_output.trySet(true);
        _multi_writer.set(MultiDataService.getMultiWriter(my_bucket, _service_context));
    }
}