List of usage examples for java.util Optional map
public <U> Optional<U> map(Function<? super T, ? extends U> mapper)
From source file:alfio.manager.AdminReservationManager.java
private void assignTickets(Event event, List<Attendee> attendees, int categoryId, List<Integer> reservedForUpdate, List<SpecialPrice> codes, String reservationId, String userLanguage, int srcPriceCts) { Optional<Iterator<SpecialPrice>> specialPriceIterator = Optional.of(codes).filter(c -> !c.isEmpty()) .map(Collection::iterator); for (int i = 0; i < reservedForUpdate.size(); i++) { Attendee attendee = attendees.get(i); if (!attendee.isEmpty()) { Integer ticketId = reservedForUpdate.get(i); ticketRepository.updateTicketOwnerById(ticketId, attendee.getEmailAddress(), attendee.getFullName(), attendee.getFirstName(), attendee.getLastName()); if (StringUtils.isNotBlank(attendee.getReference()) || attendee.isReassignmentForbidden()) { updateExtRefAndLocking(categoryId, attendee, ticketId); }//from w ww. j a va 2 s . co m if (!attendee.getAdditionalInfo().isEmpty()) { ticketFieldRepository.updateOrInsert(attendee.getAdditionalInfo(), ticketId, event.getId()); } specialPriceIterator.map(Iterator::next).ifPresent(code -> ticketRepository .reserveTicket(reservationId, ticketId, code.getId(), userLanguage, srcPriceCts)); } } }
From source file:alfio.controller.api.ReservationApiController.java
@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest") public Map<String, Object> assignTicketToPerson(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, @RequestParam(value = "single-ticket", required = false, defaultValue = "false") boolean singleTicket, UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, HttpServletRequest request, Model model, Authentication authentication) throws Exception { Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal) .filter(UserDetails.class::isInstance).map(UserDetails.class::cast); Optional<Triple<ValidationResult, Event, Ticket>> assignmentResult = ticketHelper.assignTicket(eventName, ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, t -> { Locale requestLocale = RequestContextUtils.getLocale(request); model.addAttribute("ticketFieldConfiguration", ticketHelper.findTicketFieldConfigurationAndValue(t.getMiddle().getId(), t.getRight(), requestLocale)); model.addAttribute("value", t.getRight()); model.addAttribute("validationResult", t.getLeft()); model.addAttribute("countries", TicketHelper.getLocalizedCountries(requestLocale)); model.addAttribute("event", t.getMiddle()); model.addAttribute("useFirstAndLastName", t.getMiddle().mustUseFirstAndLastName()); model.addAttribute("availableLanguages", i18nManager.getEventLanguages(eventName).stream() .map(ContentLanguage.toLanguage(requestLocale)).collect(Collectors.toList())); String uuid = t.getRight().getUuid(); model.addAttribute("urlSuffix", singleTicket ? "ticket/" + uuid + "/view" : uuid); model.addAttribute("elementNamePrefix", ""); }, userDetails);/*from ww w . ja va 2 s. c o m*/ Map<String, Object> result = new HashMap<>(); Optional<ValidationResult> validationResult = assignmentResult.map(Triple::getLeft); if (validationResult.isPresent() && validationResult.get().isSuccess()) { result.put("partial", templateManager.renderServletContextResource("/WEB-INF/templates/event/assign-ticket-result.ms", model.asMap(), request, TemplateManager.TemplateOutput.HTML)); } result.put("validationResult", validationResult.orElse( ValidationResult.failed(new ValidationResult.ErrorDescriptor("fullName", "error.fullname")))); return result; }
From source file:com.ikanow.aleph2.data_import.services.HarvestContext.java
@Override public String getHarvestContextSignature(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 www.j a v a 2s . co m final Optional<Config> service_config = PropertiesUtils.getSubConfig(full_config, "service"); final Optional<DataBucketBean> maybe_bucket = bucket.map(Optional::of) .orElseGet(() -> _mutable_state.bucket.optional()); final ImmutableSet<Tuple2<Class<? extends IUnderlyingService>, Optional<String>>> complete_services_set = Optional .of(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(IStorageService.class, Optional.empty())) .add(Tuples._2T(ISecurityService.class, Optional.empty())) .add(Tuples._2T(ILoggingService.class, Optional.empty())) //doesn't pull in ES via getUnderlyingArtefacts, relies on the one here .add(Tuples._2T(IManagementDbService.class, IManagementDbService.CORE_MANAGEMENT_DB))) // Optional services: //TODO (ALEPH-19): 1) should port this across to the more comprehensive/centralized CSL, 2) Do I need a "support direct output" flag, and not do this if not set? // seems like a waste to stick these JARs on the classpath when the Harvester is normally only writing to real-time/file-based queue? // (see AnalyticsContext/DataServiceUtils for more details on point #1) .map(sb -> (maybe_bucket.map(b -> hasSearchIndexOutput(b)).orElse(false)) ? sb.add(Tuples._2T(ISearchIndexService.class, Optional.empty())) .add(Tuples._2T(ITemporalService.class, Optional.empty())).add( Tuples._2T(IColumnarService.class, Optional.empty())) : sb) .map(sb -> (maybe_bucket.map(b -> hasDocumentOutput(b)).orElse(false)) ? sb.add(Tuples._2T(IDocumentService.class, Optional.empty())) : sb) .map(sb -> sb.build()).get(); final Config config_no_services = full_config.withoutPath("service"); 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); } // Ugh need to add: core deps, core + underlying management db to this list final Config service_defn_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 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(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 .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( maybe_bucket.map(b -> BeanTemplateUtils.toJson(b).toString()).orElse("{}"))) .withValue(__MY_TECH_LIBRARY_ID, ConfigValueFactory.fromAnyRef(_mutable_state.technology_config .optional().map(l -> BeanTemplateUtils.toJson(l).toString()).orElse("{}"))); return this.getClass().getName() + ":" + last_call.root().render(ConfigRenderOptions.concise()); } else { throw new RuntimeException(ErrorUtils.TECHNOLOGY_NOT_MODULE); } }
From source file:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java
/** Checks if an index/set-of-indexes spawned from a bucket * @param bucket// w w w.j a v a 2s .co m */ protected Optional<JsonNode> handlePotentiallyNewIndex(final DataBucketBean bucket, final Optional<String> secondary_buffer, final boolean is_primary, final ElasticsearchIndexServiceConfigBean schema_config, final String index_type) { try { // Will need the current mapping regardless (this is just some JSON parsing so should be pretty quick): final XContentBuilder mapping = ElasticsearchIndexUtils.createIndexMapping(bucket, secondary_buffer, is_primary, schema_config, _mapper, index_type); final JsonNode user_mapping = _mapper.readTree(mapping.bytes().toUtf8()); final String cache_key = bucket._id() + secondary_buffer.map(s -> ":" + s).orElse("") + ":" + Boolean.toString(is_primary); final Date current_template_time = _bucket_template_cache.getIfPresent(cache_key); if ((null == current_template_time) || current_template_time.before(Optional.ofNullable(bucket.modified()).orElse(new Date()))) { try { final GetIndexTemplatesRequest gt = new GetIndexTemplatesRequest() .names(ElasticsearchIndexUtils.getBaseIndexName(bucket, secondary_buffer)); final GetIndexTemplatesResponse gtr = _crud_factory.getClient().admin().indices() .getTemplates(gt).actionGet(); if (gtr.getIndexTemplates().isEmpty() || !mappingsAreEquivalent(gtr.getIndexTemplates().get(0), user_mapping, _mapper)) { // If no template, or it's changed, then update final String base_name = ElasticsearchIndexUtils.getBaseIndexName(bucket, secondary_buffer); _crud_factory.getClient().admin().indices().preparePutTemplate(base_name).setSource(mapping) .execute().actionGet(); _logger.info(ErrorUtils.get("Updated mapping for bucket={0}, base_index={1}", bucket.full_name(), base_name)); } } catch (Exception e) { _logger.error(ErrorUtils.getLongForm("Error updating mapper bucket={1} err={0}", e, bucket.full_name())); } _bucket_template_cache.put(cache_key, bucket.modified()); } return Optional.of(user_mapping); } catch (Exception e) { return Optional.empty(); } }
From source file:alfio.manager.TicketReservationManager.java
void sendReminderForOfflinePayments() { Date expiration = truncate(// w w w . j av a 2 s . co m addHours(new Date(), configurationManager .getIntConfigValue(Configuration.getSystemConfiguration(OFFLINE_REMINDER_HOURS), 24)), Calendar.DATE); ticketReservationRepository.findAllOfflinePaymentReservationForNotification(expiration).stream() .map(reservation -> { Optional<Ticket> ticket = ticketRepository.findFirstTicketInReservation(reservation.getId()); Optional<Event> event = ticket.map(t -> eventRepository.findById(t.getEventId())); Optional<Locale> locale = ticket.map(t -> Locale.forLanguageTag(t.getUserLanguage())); return Triple.of(reservation, event, locale); }).filter(p -> p.getMiddle().isPresent()).filter(p -> { Event event = p.getMiddle().get(); return truncate( addHours(new Date(), configurationManager.getIntConfigValue(Configuration.from( event.getOrganizationId(), event.getId(), OFFLINE_REMINDER_HOURS), 24)), Calendar.DATE).compareTo(p.getLeft().getValidity()) >= 0; }).map(p -> Triple.of(p.getLeft(), p.getMiddle().get(), p.getRight().get())).forEach(p -> { TicketReservation reservation = p.getLeft(); Event event = p.getMiddle(); Map<String, Object> model = prepareModelForReservationEmail(event, reservation); Locale locale = p.getRight(); ticketReservationRepository.flagAsOfflinePaymentReminderSent(reservation.getId()); notificationManager.sendSimpleEmail(event, reservation.getEmail(), messageSource.getMessage("reservation.reminder.mail.subject", new Object[] { getShortReservationID(event, reservation.getId()) }, locale), () -> templateManager.renderTemplate(event, TemplateResource.REMINDER_EMAIL, model, locale)); }); }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
@SuppressWarnings("unchecked") /* (non-Javadoc)/* ww w. j a v a2s . c o m*/ * @see com.ikanow.aleph2.data_model.interfaces.shared_services.IUnderlyingService#getUnderlyingPlatformDriver(java.lang.Class, java.util.Optional) */ @Override public <T> Optional<T> getUnderlyingPlatformDriver(final Class<T> driver_class, final Optional<String> driver_options) { if (IEnrichmentModuleContext.class.isAssignableFrom(driver_class)) { return driver_options.map(batch_str -> { return (Optional<T>) Optional.of( new BatchEnrichmentContext(new BatchEnrichmentContext(this), Integer.parseInt(batch_str))); }).orElseGet(() -> (Optional<T>) Optional.of(new BatchEnrichmentContext(this))); } else return Optional.empty(); }
From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java
@Override public Validation<BasicMessageBean, JsonNode> sendObjectToStreamingPipeline( final Optional<DataBucketBean> bucket, final AnalyticThreadJobBean job, final Either<JsonNode, Map<String, Object>> object, final Optional<AnnotationBean> annotations) { if (annotations.isPresent()) { throw new RuntimeException(ErrorUtils.NOT_YET_IMPLEMENTED); }//from w ww .ja v a 2 s.co m final JsonNode obj_json = object.either(__ -> __, map -> (JsonNode) _mapper.convertValue(map, JsonNode.class)); return this.getOutputTopic(bucket, job).<Validation<BasicMessageBean, JsonNode>>map(topic -> { 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()); return Validation.success(obj_json); } else { return Validation.fail(ErrorUtils.buildSuccessMessage(this.getClass().getSimpleName(), "sendObjectToStreamingPipeline", "Bucket:job {0}:{1} topic {2} has no listeners", bucket.map(b -> b.full_name()).orElse("(unknown)"), job.name(), topic)); } }).orElseGet(() -> { return Validation.fail(ErrorUtils.buildErrorMessage(this.getClass().getSimpleName(), "sendObjectToStreamingPipeline", "Bucket:job {0}:{1} has no output topic", bucket.map(b -> b.full_name()).orElse("(unknown)"), job.name())); }); }
From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java
@Override public <S> ICrudService<S> getBucketObjectStore(final Class<S> clazz, final Optional<DataBucketBean> bucket, final Optional<String> collection, final Optional<StateDirectoryType> type) { final Optional<DataBucketBean> this_bucket = bucket.map(x -> Optional.of(x)).orElseGet( () -> _mutable_state.bucket.isSet() ? Optional.of(_mutable_state.bucket.get()) : Optional.empty()); return Patterns.match(type).<ICrudService<S>>andReturn() .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.enrichment == t.get(), __ -> _core_management_db.getBucketEnrichmentState(clazz, this_bucket.get(), collection)) .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.harvest == t.get(), __ -> _core_management_db.getBucketHarvestState(clazz, this_bucket.get(), collection)) // assume this is the technology context, most likely usage .when(t -> t.isPresent() && AssetStateDirectoryBean.StateDirectoryType.library == t.get(), __ -> _core_management_db.getPerLibraryState(clazz, this.getTechnologyConfig(), collection)) // default: analytics or not specified: analytics .otherwise(__ -> _core_management_db.getBucketAnalyticThreadState(clazz, this_bucket.get(), collection));/*w ww. j av a2s .c om*/ }
From source file:alfio.controller.api.user.RestEventApiController.java
@RequestMapping(value = "events/{shortName}/reserve-tickets", method = RequestMethod.POST) public ResponseEntity<Result<String>> reserveTickets(@PathVariable("shortName") String shortName, @RequestBody ReservationForm reservation, BindingResult bindingResult, Locale locale) { return eventRepository.findOptionalByShortName(shortName).map(event -> { Optional<String> reservationUrl = reservation.validate(bindingResult, ticketReservationManager, additionalServiceRepository, eventManager, event).flatMap(selected -> { Date expiration = DateUtils.addMinutes(new Date(), ticketReservationManager.getReservationTimeout(event)); try { String reservationId = ticketReservationManager.createTicketReservation(event, selected.getLeft(), selected.getRight(), expiration, Optional.ofNullable(reservation.getPromoCode()), //FIXME check Optional.ofNullable(reservation.getPromoCode()), //FIXME check locale, false); return Optional.of("/event/" + shortName + "/reservation/" + reservationId + "/book"); } catch (TicketReservationManager.NotEnoughTicketsException nete) { bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS); } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) { bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED); } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) { bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND); }// w ww . j a v a 2s . com return Optional.empty(); }); Result<String> result = reservationUrl.map(url -> Result.success(url)) .orElseGet(() -> Result.validationError(bindingResult.getAllErrors())); return new ResponseEntity<>(result, HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
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 ava 2 s . c o m*/ 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); } }