List of usage examples for java.util Optional orElseGet
public T orElseGet(Supplier<? extends T> supplier)
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
@Override public String getAnalyticsContextSignature(final Optional<DataBucketBean> bucket, final Optional<Set<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>>> services) { if (_state_name == State.IN_TECHNOLOGY) { final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get()); final Config full_config = setupServices(bucket, services); if (_mutable_state.signature_override.isSet()) { // only run once... (this is important because can do ping/pong buffer type stuff below) //(note only doing this here so I can quickly check that I'm not being called multiple times with different services - ie in this case I error...) return this.getClass().getName() + ":" + _mutable_state.signature_override.get(); }//from w w w. j a va 2 s . c om final Optional<Config> service_config = PropertiesUtils.getSubConfig(full_config, "service"); final Config config_no_services = full_config.withoutPath("service"); // Ugh need to add: core deps, core + underlying management db to this list // Service interface/implementation: final Config service_defn_subset = _mutable_state.service_manifest_override.get().stream() // DON'T MAKE PARALLEL SEE BELOW .map(clazz_name -> { final String config_path = clazz_name._2() .orElse(clazz_name._1().getSimpleName().substring(1)); return Lambdas .wrap_u(__ -> service_config.get().hasPath(config_path) ? Tuples._2T(config_path, service_config.get().getConfig(config_path)) : null) //(could add extra transforms here if we wanted) .apply(Unit.unit()); }).filter(cfg -> null != cfg).reduce(ConfigFactory.empty(), (acc, k_v) -> acc.withValue(k_v._1(), k_v._2().root()), (acc1, acc2) -> acc1 // (This will never be called as long as the above stream is not parallel) ); // Service configuration: final Config service_cfgn_subset = _mutable_state.service_manifest_override.get().stream() // DON'T MAKE PARALLEL SEE BELOW .reduce(config_no_services, // (leave other configurations, we just transform service specific configuration) (acc, clazz_name) -> { final Optional<? extends IUnderlyingService> underlying_service = _service_context .getService(clazz_name._1(), clazz_name._2()); return underlying_service .map(ds -> ds.createRemoteConfig(Optional.of(my_bucket), acc)).orElse(acc); }, (acc1, acc2) -> acc1 // (This will never be called as long as the above stream is not parallel) ); final Config config_subset_services = service_cfgn_subset.withValue("service", service_defn_subset.root()); final Config last_call = Lambdas .<Config, Config>wrap_u( config_pipeline -> _mutable_state.library_configs.isSet() ? config_pipeline.withValue( __MY_MODULE_LIBRARY_ID, ConfigValueFactory.fromAnyRef(BeanTemplateUtils .toJson(new LibraryContainerBean(_mutable_state.library_configs .get().entrySet().stream() .filter(kv -> kv.getValue().path_name() .equals(kv.getKey())) .map(kv -> kv.getValue()).collect(Collectors.toList()))) .toString())) : config_pipeline) .andThen(Lambdas.wrap_u(config_pipeline -> getJob().isPresent() ? config_pipeline .withValue(__MY_JOB_ID, ConfigValueFactory.fromAnyRef(getJob().get().name()) //(exists by above "if") ) : config_pipeline)).apply(config_subset_services) .withValue(__MY_BUCKET_ID, ConfigValueFactory.fromAnyRef(BeanTemplateUtils.toJson(my_bucket).toString())) .withValue(__MY_TECH_LIBRARY_ID, ConfigValueFactory.fromAnyRef( BeanTemplateUtils.toJson(_mutable_state.technology_config.get()).toString())); final String ret1 = last_call.root().render(ConfigRenderOptions.concise()); _mutable_state.signature_override.set(ret1); _mutable_serializable_signature = ret1; final String ret = this.getClass().getName() + ":" + ret1; // Finally this is a good central (central per-job, NOT per-bucket or per-bucket-and-tech (*)) place to sort out deleting ping pong buffers // (*) though there's some logic that attempts to simulate running once-per-bucket-and-tech // which should work for the moment - though will disable that functionality still because it _doesn't_ work for tidying up at the end getJob().ifPresent(job -> { centralPerJobOutputSetup(my_bucket, job); centralPerBucketOutputSetup(my_bucket); }); return ret; } else { throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE); } }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
@Override public CompletableFuture<?> flushBatchOutput(Optional<DataBucketBean> bucket, AnalyticThreadJobBean job) { _mutable_state.has_unflushed_data = false; // (just means that the shutdown hook will do nothing) // (this can safely be run for multiple jobs since it only applies to the outputter we're using in this process anyway, plus multiple // flushes don't have any functional side effects) final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get()); _logger.info(ErrorUtils.get("Flushing output for bucket:job {0}:{1}", my_bucket.full_name(), job.name())); //first flush loggers final Stream<CompletableFuture<?>> flush_loggers = _mutable_state.bucket_loggers.values().stream() .map(l -> l.flush());//from w w w. j av a 2 s. c o m // Flush external and sub-buckets: final Stream<CompletableFuture<?>> flush_external = _mutable_state.external_buckets.values().stream() .map(e -> { return e.<CompletableFuture<?>>either(ee -> ee.<CompletableFuture<?>>either(batch -> { return batch.flushOutput(); // flush external output }, slow -> { //(nothing to do) return (CompletableFuture<?>) CompletableFuture.completedFuture(Unit.unit()); }), topic -> { //(nothing to do) return (CompletableFuture<?>) CompletableFuture.completedFuture(Unit.unit()); }); }); final Stream<CompletableFuture<?>> flush_sub = _mutable_state.sub_buckets.values().stream() .map(sub_context -> sub_context.flushBatchOutput(bucket, job)); final Stream<CompletableFuture<?>> flush_writer = Stream .of(_multi_writer.optional().<CompletableFuture<?>>map(writer -> writer.flushBatchOutput()) .orElseGet(() -> (CompletableFuture<?>) CompletableFuture.completedFuture(Unit.unit()))); // Important: this is the line that actually executes all the flushes, so need to ensure each of the above is added here: return CompletableFuture.allOf(Stream.of(flush_loggers, flush_external, flush_sub, flush_writer) .flatMap(__ -> __).toArray(CompletableFuture[]::new)); }
From source file:alfio.manager.PaymentManager.java
TransactionAndPaymentInfo getInfo(TicketReservation reservation, Event event) { Optional<TransactionAndPaymentInfo> maybeTransaction = transactionRepository .loadOptionalByReservationId(reservation.getId()).map(transaction -> { switch (reservation.getPaymentMethod()) { case PAYPAL: return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, paypalManager.getInfo(transaction, event).orElse(null)); case STRIPE: return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, stripeManager.getInfo(transaction, event).orElse(null)); default: return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, new PaymentInformation(reservation.getPaidAmount(), null, String.valueOf(transaction.getGatewayFee()), String.valueOf(transaction.getPlatformFee()))); }//from ww w.ja va2s .c o m }); maybeTransaction.ifPresent(info -> { try { Transaction transaction = info.getTransaction(); String transactionId = transaction.getTransactionId(); PaymentInformation paymentInformation = info.getPaymentInformation(); if (paymentInformation != null) { transactionRepository.updateFees(transactionId, reservation.getId(), safeParseLong(paymentInformation.getPlatformFee()), safeParseLong(paymentInformation.getFee())); } } catch (Exception e) { log.warn("cannot update fees", e); } }); return maybeTransaction.orElseGet(() -> new TransactionAndPaymentInfo(reservation.getPaymentMethod(), null, new PaymentInformation(reservation.getPaidAmount(), null, null, null))); }
From source file:org.haiku.haikudepotserver.job.LocalJobServiceImpl.java
private String validateAndCoalesceOrCreateJob(JobSpecification specification, Set<JobSnapshot.Status> coalesceForStatuses, Function<JobSpecification, Job> createJobFunction) { Preconditions.checkState(null != executor, "the executor has not been configured; was this service started correctly?"); Preconditions.checkArgument(null != specification); Preconditions.checkArgument(null != coalesceForStatuses, "the statuses over which coalescing should occur must be supplied"); getJobRunner(specification.getJobTypeCode()).orElseThrow(() -> new IllegalStateException( "unable to run a job runner for the job type code; " + specification.getJobTypeCode())); for (String guid : specification.getSuppliedDataGuids()) { if (!tryGetData(guid).isPresent()) { throw new IllegalStateException("unable to run a job specification because the specified data " + guid + " was not able to be found"); }/*from w w w . j a va2 s. c o m*/ } if (null == specification.getGuid()) { specification.setGuid(UUID.randomUUID().toString()); } else { synchronized (this) { if (tryGetJob(specification.getGuid()).isPresent()) { throw new IllegalStateException( "a specification has been submitted for which there is already a job running; " + specification.getGuid()); } } } // first clear out any expired jobs clearExpiredInternalJobs(); // if there is an existing report that can be used then use it; otherwise make a new one. // The use of sorting below is to get the best job to re-use (the most recent) from all // of the possible ones. Optional<String> firstMatchingJobGuidOptional; synchronized (this) { firstMatchingJobGuidOptional = ImmutableList.copyOf(jobs.values()).stream() .filter((j) -> coalesceForStatuses.contains(j.getStatus())) .filter((j) -> specification.isEquivalent(j.getJobSpecification())) .sorted((j1, j2) -> ComparisonChain.start() .compare(j1.getStatus(), j2.getStatus(), Ordering.explicit(JobSnapshot.Status.FINISHED, JobSnapshot.Status.STARTED, JobSnapshot.Status.QUEUED)) .compare(j1.getFinishTimestamp(), j2.getFinishTimestamp(), Ordering.natural().nullsLast()) .compare(j1.getStartTimestamp(), j2.getStartTimestamp(), Ordering.natural().nullsLast()) .compare(j1.getQueuedTimestamp(), j2.getQueuedTimestamp(), Ordering.natural().nullsLast()) .compare(j1.getFailTimestamp(), j2.getFailTimestamp(), Ordering.natural().nullsLast()) .compare(j1.getCancelTimestamp(), j2.getCancelTimestamp(), Ordering.natural().nullsLast()) .result()) .map(Job::getGuid).findFirst(); } return firstMatchingJobGuidOptional.orElseGet(() -> createJobFunction.apply(specification).getGuid()); }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
@Override public <T extends IAnalyticsAccessContext<?>> Optional<T> getServiceInput(final Class<T> clazz, final Optional<DataBucketBean> bucket, final AnalyticThreadJobBean job, final AnalyticThreadJobInputBean job_input) { if (_mutable_state.service_manifest_override.isSet()) { // Can't call getServiceInput after getContextSignature/getContextLibraries throw new RuntimeException(ErrorUtils.get(ErrorUtils.SERVICE_RESTRICTIONS)); }//from ww w . j a v a 2 s . c om //TODO: should support "" as myself (clone or something?) - also check if null works in getInputPaths/Queues //TODO: what happens if I external emit to myself (again supporting "") .. not sure if the output services will be set up? // First off, check we have permissions: final DataBucketBean my_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get()); final AuthorizationBean auth_bean = new AuthorizationBean(my_bucket.owner_id()); final ICrudService<DataBucketBean> secured_bucket_crud = _core_management_db.readOnlyVersion() .getDataBucketStore().secured(_service_context, auth_bean); final String resource_or_name = Optional.ofNullable(job_input.resource_name_or_id()).orElse("/unknown"); final String data_service = Optional.ofNullable(job_input.data_service()).orElse("unknown.unknown"); final boolean found_bucket = Lambdas.wrap_u(() -> { return resource_or_name.startsWith(BucketUtils.EXTERNAL_BUCKET_PREFIX) ? true // (in this case we delegate the checking to the data service) : secured_bucket_crud.getObjectBySpec( CrudUtils.allOf(DataBucketBean.class).when(DataBucketBean::full_name, job_input.resource_name_or_id()), Collections.emptyList(), // (don't want any part of the bucket, just whether it exists or not) true).get().isPresent(); }).get(); if (!found_bucket) { throw new RuntimeException( ErrorUtils.get(ErrorUtils.BUCKET_NOT_FOUND_OR_NOT_READABLE, job_input.resource_name_or_id())); } // Now try to get the technology driver // the job config is in the format owner_id:bucket_name:{input_config} final Optional<String> job_config = Optional.of(my_bucket.owner_id() + ":" + my_bucket.full_name() + ":" + BeanTemplateUtils.toJson(job_input).toString()); final String[] other_service = data_service.split("[.]"); final Optional<T> ret_val = getUnderlyingService(_service_context, other_service[0], Optionals.of(() -> other_service[1])) .flatMap(service -> service.getUnderlyingPlatformDriver(clazz, job_config)); // Add to list of extra services to add automatically if (ret_val.isPresent()) { // only if we managed to load the analytics access context DataServiceUtils.getUnderlyingServiceInterface(other_service[0]) .ifPresent(ds -> _mutable_state.extra_auto_context_libs .add(Tuples._2T(ds, Optionals.of(() -> other_service[1]).filter(s -> !s.isEmpty())))); } return ret_val; }
From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.ElasticsearchCrudService.java
/** Utility function for deleting an object * @param rw_context/*w w w . j a v a 2s. co m*/ * @param id * @param obj_to_delete * @param bulk * @return */ private DeleteRequestBuilder singleObjectDeleteRequest( final Either<ReadWriteContext, Tuple2<String, String>> rw_context, final String id, final Either<O, Tuple2<String, String>> obj_to_delete, final boolean bulk) { final Either<JsonNode, Tuple2<String, String>> json_object = obj_to_delete.left().map(left -> { return ((JsonNode.class.isAssignableFrom(_state.clazz)) ? (JsonNode) left : BeanTemplateUtils.toJson(left)); }); final Optional<String> maybe_preferred_index = rw_context.<Optional<String>>either( left -> Optional.of(left.indexContext().getWritableIndex(Optional.of(json_object.left().value()))), right -> Optional.empty()); // Get and remove some built-in fields if present final Optional<String> maybe_type = json_object.<Optional<String>>either( json -> Optional.ofNullable(((ObjectNode) json).get(ElasticsearchUtils._TYPE)).map(j -> j.asText()), json_str -> Optional.empty()); // For security reasons this needs to be a substring of the primary segment final Optional<String> maybe_index = json_object.<Optional<String>>either(json -> Optional .ofNullable(((ObjectNode) json).get(ElasticsearchUtils._INDEX)).map(j -> j.asText()), json_str -> Optional.empty()).filter(index -> { final String preferred_index = maybe_preferred_index.get(); // (exists by construction) final int id_index = preferred_index.lastIndexOf("__"); if (id_index > 0) { final String reqd_base = preferred_index.substring(0, id_index + 14); // 2 for __ + 12 for UUID return index.startsWith(reqd_base); } else return false; }); return Optional.of(rw_context .<DeleteRequestBuilder>either( left -> _state.client.prepareDelete() .setIndex(maybe_index.orElseGet(() -> maybe_preferred_index.get())) //(exists by construction) .setType(maybe_type.orElseGet(() -> left.typeContext().getWriteType())), right -> _state.client.prepareDelete().setIndex(right._1()).setType(right._2())) .setConsistencyLevel(WriteConsistencyLevel.ONE) .setRefresh(!bulk && CreationPolicy.OPTIMIZED != _state.creation_policy).setId(id)).get(); }
From source file:com.ikanow.aleph2.shared.crud.elasticsearch.services.ElasticsearchCrudService.java
/** Utility function for adding a set of objects to a single index * @param rw_context - either the index/type context, or just (index,type) for retries * @param new_object - either the object to insert/save, or (id, string source) (must be the object(left) if the index/type context (ie left) is used for "rw_context") * @param replace_if_present - replace the existing object (else error) * @param bulk - whether being called as part of a bulk operation * @return/* www. j av a 2 s. co m*/ */ private IndexRequestBuilder singleObjectIndexRequest( final Either<ReadWriteContext, Tuple2<String, String>> rw_context, final Either<O, Tuple2<String, String>> new_object, final boolean replace_if_present, final boolean bulk) { final Either<JsonNode, Tuple2<String, String>> json_object = new_object.left().map(left -> { return ((JsonNode.class.isAssignableFrom(_state.clazz)) ? (JsonNode) left : BeanTemplateUtils.toJson(left)); }); final Optional<String> maybe_preferred_index = rw_context.<Optional<String>>either( left -> Optional.of(left.indexContext().getWritableIndex(Optional.of(json_object.left().value()))), right -> Optional.empty()); // Get and remove some built-in fields if present final Optional<String> maybe_id = json_object.<Optional<String>>either( json -> Optional.ofNullable(((ObjectNode) json).remove(JsonUtils._ID)).map(j -> j.asText()), json_str -> Optional.empty()); final Optional<String> maybe_type = json_object.<Optional<String>>either(json -> Optional .ofNullable(((ObjectNode) json).remove(ElasticsearchUtils._TYPE)).map(j -> j.asText()), json_str -> Optional.empty()); // For security reasons this needs to be a substring of the primary segment final Optional<String> maybe_index = json_object.<Optional<String>>either(json -> Optional .ofNullable(((ObjectNode) json).remove(ElasticsearchUtils._INDEX)).map(j -> j.asText()), json_str -> Optional.empty()).filter(index -> { final String preferred_index = maybe_preferred_index.get(); // (exists by construction) final int id_index = preferred_index.lastIndexOf("__"); if (id_index > 0) { final String reqd_base = preferred_index.substring(0, id_index + 14); // 2 for __ + 12 for UUID return index.startsWith(reqd_base); } else return false; }); return Optional .of(rw_context .<IndexRequestBuilder>either( left -> _state.client.prepareIndex( maybe_index.orElseGet(() -> maybe_preferred_index.get()), //(exists by construction) maybe_type.orElseGet(() -> left.typeContext().getWriteType())), right -> _state.client.prepareIndex(right._1(), right._2())) .setOpType(replace_if_present ? OpType.INDEX : OpType.CREATE) .setConsistencyLevel(WriteConsistencyLevel.ONE) .setRefresh(!bulk && CreationPolicy.OPTIMIZED != _state.creation_policy) .setSource(json_object.<String>either(left -> left.toString(), right -> right._2()))) .map(i -> json_object.<IndexRequestBuilder>either(left -> maybe_id.map(id -> i.setId(id)).orElse(i), right -> i.setId(right._1()))) //DEBUG //.map(irb -> { System.out.println("REQUEST INDICES = " + Arrays.toString(irb.request().indices())); return irb; }) .get(); }
From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java
@Override public String getAnalyticsContextSignature(final Optional<DataBucketBean> bucket, final Optional<Set<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>>> services) { if (_state_name == State.IN_TECHNOLOGY) { // Returns a config object containing: // - set up for any of the services described // - all the rest of the configuration // - the bucket bean ID final Config full_config = ModuleUtils.getStaticConfig() .withoutPath(DistributedServicesPropertyBean.APPLICATION_NAME) .withoutPath("MongoDbManagementDbService.v1_enabled") // (special workaround for V1 sync service) ;/*from w ww . j av a2s . c o m*/ final Optional<Config> service_config = PropertiesUtils.getSubConfig(full_config, "service"); final ImmutableSet<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>> complete_services_set = ImmutableSet .<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>>builder() .addAll(services.orElse(Collections.emptySet())) .add(Tuples._2T(ICoreDistributedServices.class, Optional.empty())) .add(Tuples._2T(IManagementDbService.class, Optional.empty())) .add(Tuples._2T(ISearchIndexService.class, Optional.empty())) .add(Tuples._2T(ISecurityService.class, Optional.empty())) .add(Tuples._2T(IStorageService.class, Optional.empty())) .add(Tuples._2T(IManagementDbService.class, IManagementDbService.CORE_MANAGEMENT_DB)).build(); if (_mutable_state.service_manifest_override.isSet()) { if (!complete_services_set.equals(_mutable_state.service_manifest_override.get())) { throw new RuntimeException(ErrorUtils.SERVICE_RESTRICTIONS); } } else { _mutable_state.service_manifest_override.set(complete_services_set); } final Config config_no_services = full_config.withoutPath("service"); // Ugh need to add: core deps, core + underlying management db to this list final Config service_subset = complete_services_set.stream() // DON'T MAKE PARALLEL SEE BELOW .map(clazz_name -> { final String config_path = clazz_name._2() .orElse(clazz_name._1().getSimpleName().substring(1)); return service_config.get().hasPath(config_path) ? Tuples._2T(config_path, service_config.get().getConfig(config_path)) : null; }).filter(cfg -> null != cfg).reduce(ConfigFactory.empty(), (acc, k_v) -> acc.withValue(k_v._1(), k_v._2().root()), (acc1, acc2) -> acc1 // (This will never be called as long as the above stream is not parallel) ); final Config config_subset_services = config_no_services.withValue("service", service_subset.root()); final Config last_call = Lambdas .get(() -> _mutable_state.library_configs.isSet() ? config_subset_services .withValue(__MY_MODULE_LIBRARY_ID, ConfigValueFactory .fromAnyRef(BeanTemplateUtils .toJson(new LibraryContainerBean( _mutable_state.library_configs.get().entrySet() .stream() .filter(kv -> kv.getValue().path_name() .equals(kv.getKey())) .map(kv -> kv.getValue()) .collect(Collectors.toList()))) .toString())) : config_subset_services) .withValue(__MY_BUCKET_ID, ConfigValueFactory.fromAnyRef(BeanTemplateUtils .toJson(bucket.orElseGet(() -> _mutable_state.bucket.get())).toString())) .withValue(__MY_TECH_LIBRARY_ID, ConfigValueFactory.fromAnyRef( BeanTemplateUtils.toJson(_mutable_state.technology_config.get()).toString())); final String ret1 = last_call.root().render(ConfigRenderOptions.concise()); _mutable_state.signature_override.set(ret1); final String ret = this.getClass().getName() + ":" + ret1; this.overrideSavedContext(); // (FOR TESTING ONLY - ie BECAUSE THIS IS MOCK ANALYTIC CONTEXT) return ret; } else { throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE); } }